Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
+15
@@ -0,0 +1,15 @@
|
|||||||
|
target/
|
||||||
|
**/module/*/front/dist/
|
||||||
|
core.[0-9]*
|
||||||
|
/build/documentation-*/
|
||||||
|
**/config/setting.json
|
||||||
|
/.release-key.*/
|
||||||
|
/.agents/
|
||||||
|
/.codex/
|
||||||
|
**/__pycache__/
|
||||||
|
**/*.pyc
|
||||||
|
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
/sdk/python/*.egg-info/
|
||||||
|
/sdk/python/build/
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Dever 核心开发
|
||||||
|
|
||||||
|
开始任务前先读取 `/dm/AGENTS.md`,再读取目标路径适用的子级规则。适用于整个仓库。这里维护编译器、运行库和标准库;Dever 应用开发使用 [随包 Skill](skills/dever/SKILL.md)。
|
||||||
|
|
||||||
|
## 核心开发要求
|
||||||
|
|
||||||
|
- **同时验收两层代码:实现 Dever 的 Rust 代码,以及使用 Dever 的项目代码。两层都必须简单、直接、好读、好维护;编译器能运行不足以证明设计合格。** 本节是重构的首要工程门槛,不以赶进度、凑行数或局部性能为理由放宽,不替代根规则的数据保护。
|
||||||
|
- **禁止防御性冗余和垃圾代码。** 不重复判空、重复验证已保证的条件,不猜类型、不试多种格式、不乱补默认值、不吞错或层层兜底;不保留无调用方的抽象、占位实现、兼容路径和备用实现。外部输入、安全、可变业务状态与资源释放在所属边界正确处理,内部直接使用已建立的保证。
|
||||||
|
- **语言承担简化业务代码的责任。** Model 使用 type,保留 rule、flow、loop 表;同一类型、约束和默认值只声明一次,错误默认传播,分支和步骤集中表达。不强制每个 Model 配 DTO、View、转换函数、Service;不能把编译器缺失的能力转嫁为每个项目重复编写的样板。
|
||||||
|
- **先明确合同,再写最小实现。** 每批代码必须对应已定下的语言行为、实际调用和验收用例;语义未定时先补齐合同,不猜测协议、不临时加默认值“修到能跑”。优先标准库和成熟依赖,必要中文注释说明原因;不靠压缩写法或删正确性处理减行数。
|
||||||
|
- **构建不得依赖备份目录。** 同级 bak/core 仅用于查阅历史实现和运行对照测试,不作为源码、依赖或运行时回退路径。复用具体代码须确认职责清楚、无多余依赖且真实测试通过。
|
||||||
|
- **每批交付检查真实业务和真实成本。** 同时检查生成 Rust 与 Dever 业务样例的重复检查、无用包装、错误传播和资源责任,运行对应真实测试与性能对照。未测不算通过;缺少用途的代码删除,未满足本节不得标阶段完成。
|
||||||
|
|
||||||
|
## 工作规则
|
||||||
|
|
||||||
|
- 首条回复和最终回复称呼用户为“主人”。先读适用规则、相关源码和测试,再修改;已读且未变的文件不重复读取。
|
||||||
|
- 落实用户已授权的工作,不用方案或记录代替实施。讨论方案时只读;安装、部署、重启、提交、推送和重写 Git 历史须在授权范围内。
|
||||||
|
- 在 `/dm` 工作时遵守根 AGENTS。构建和程序运行使用已有开发容器,不往宿主机安装环境;保留用户改动、数据和凭据。
|
||||||
|
- 版本号以 rust/Cargo.toml 的编译器版本为准,没有生产数据,不做旧语法、接口、配置或数据的兼容层。公开行为改动须说明,并同步调用方、测试和文档。
|
||||||
|
|
||||||
|
## 实现规则
|
||||||
|
|
||||||
|
- 保留 Dever 语法与约束。固定路线:Dever → 具体类型 Rust → 官方 Cargo/rustc → 原生程序。不开新后端,不 fork rustc。
|
||||||
|
- 优先复用 Rust 标准库和已有成熟库。只实现 Dever 自身规则与必要适配,不重复造解析器、调度器、网络栈或数值算法。
|
||||||
|
- 不预建扩展点、占位层或没有调用方的抽象。函数用于消除真实重复或表达清楚的职责,不包装每次库调用。
|
||||||
|
- 不添加无依据的判空、类型猜测、备用实现或静默兜底。外部输入在所属入口验证,内部不重复检查已保证的条件;鉴权、数据隔离、协议和资源释放必须正确。
|
||||||
|
- 错误沿现有路径传播,保留原因,不用空值或默认成功掩盖失败。重试、锁、缓存和补偿只用于当前真实需求。
|
||||||
|
- 每次复制、扫描、分配、加锁或调度交接都要有用途。只读优先借用,能移动就移动,不用 clone 代替所有权分析。
|
||||||
|
- 普通调用生成直接函数调用,只有需要挂起的函数才生成异步调用。具体类型直接传递,集合直接遍历,不套动态值或中间容器。
|
||||||
|
- 环境地址、端口、路径和凭据走既有配置;身份及数据归属来自可信上下文。不按账号、租户、测试名称或固定答案写特例。协议常量和局部算法常量可留在代码中。
|
||||||
|
- Rust 和 Dever 只写必要的中文注释,解释原因和约束;领域业务说明写在 `doc/`。Dever 源文件使用 `.dv`;函数用 lowerCamelCase,字段、局部值和目录用 snake_case。
|
||||||
|
- 沿用目录结构,只保留工具包和运行库两份 Cargo 清单。每目录最多八个手写 `.rs` 文件,通常每文件 100–300 行,接近 400 行审查,超过 500 行拆分;小模块可直接放在 mod.rs。
|
||||||
|
|
||||||
|
## 验证与交付
|
||||||
|
|
||||||
|
- 先比较生成代码、运行库调用和独立 Rust 实现,找到多余操作再改。保留已有优化,不为某个性能样例添加特殊路径。
|
||||||
|
- 性能对照使用相同语义、输入、精度、依赖和编译选项。共享 Dever 运行库的对照只检验生成层,不能证明运行库追平。
|
||||||
|
- 提前固定轮次,保留全部原始结果及源码、二进制对应关系。报告绝对耗时、修改前后变化和对 Rust 的差距,不挑选样本或隐瞒退化。
|
||||||
|
- 每个独立改动先做相关功能和性能验证,再继续下一项;每批结束检查相关矩阵。验收出口、已知差距与停止规则以 [REMAINING.md](REMAINING.md) 为准;2% 只作观测目标,差距小于该基准自身波动时不据此改代码,也不为凑数字增加代码。
|
||||||
|
- 新增复杂度没有稳定收益就撤回。删去重复实现且性能没有退化,可以保留;只有实测提速才报告性能提升。
|
||||||
|
- 复用现有检查和测试,不造自证逻辑、不削弱断言。已通过的检查仅在相关内容变化或证据不足时补验。
|
||||||
|
- 说明只写当前用法和必要规则,不写对话、开发日志或占位描述。修改代码同步相关说明;调用图由工具生成,见 [说明写法](DOCUMENTATION.md)。
|
||||||
|
- 交付前检查差异、错误处理、冗余、引用和临时文件。未执行、失败或未测项目如实说明,不以构建成功代替业务通过。
|
||||||
|
|
||||||
|
源码布局、构建和测试命令见 [rust/README.md](rust/README.md)。语言行为见 [LANGUAGE.md](LANGUAGE.md)。
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Dever 源码架构
|
||||||
|
|
||||||
|
Dever 把应用编译成原生程序。编译器负责读懂和检查 .dv 文件,再把业务函数写成 Rust,由 rustc 生成可执行文件。应用启动后执行的是这个文件,不需要解释 .dv 源码。
|
||||||
|
|
||||||
|
## 一条 build 命令经过哪里
|
||||||
|
|
||||||
|
以快速上手中的问候项目为例,执行 `dever build . --output ./greeting`:
|
||||||
|
|
||||||
|
| 步骤 | 源码入口 | 以问候函数为例 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 1. 找文件 | [命令入口](rust/src/cli/main.rs) → [项目加载](rust/src/compiler/project/mod.rs) | 根据目录识别 hello 组件、greeting 领域,以及业务函数和 CMD 入口所在的文件。加载器也会加入项目依赖和用到的标准库。 |
|
||||||
|
| 2. 读语法 | [词法分析](rust/src/syntax/lex) → [语法分析](rust/src/syntax/parse) → [语法树](rust/src/syntax/ast) | 解析函数的名字、输入、输出和函数体,保留它们在原文件里的位置。此时能读懂表达式的结构,还没有判断它的类型是否正确。 |
|
||||||
|
| 3. 检查含义 | [格式检查](rust/src/compiler/format) → [程序检查](rust/src/compiler/check/program/mod.rs) | 确认 CMD 绑定的函数存在,参数和返回值的类型正确。检查结果存入 [Program](rust/src/compiler/model/program.rs)。例如,问候函数声明返回 Text,却给输出赋了 Int,编译器会在这里报错,不会进入原生编译。 |
|
||||||
|
| 4. 生成 Rust | [构建入口](rust/src/compiler/build/mod.rs) → [所有权分析](rust/src/compiler/check/ownership) → [代码生成](rust/src/compiler/emit/mod.rs) | 构建入口核对项目的 API 快照(如有),准备前端资源。编译器再判断参数能借用还是要移交所有权,生成问候函数和调用它的命令入口。 |
|
||||||
|
| 5. 生成可执行文件 | [单文件发行的内置编译](rust/src/compiler/build/local.rs)、[源码开发的 Cargo 构建](rust/src/compiler/build/cargo.rs) | 发行命令使用随文件提供的编译器、链接器和预编译运行库。源码开发使用 Cargo。构建成功后写入可执行文件;目标文件已存在时会报错。 |
|
||||||
|
|
||||||
|
`dever check` 完成项目检查,不构建二进制。`dever run` 与 `build` 共用原生编译步骤:run 启动生成的程序,build 将它写入指定路径。有本地组件前端时,run 读取开发资源,build 准备要随程序交付的资源。`dever inspect` 使用[源码索引](rust/src/compiler/inspect/mod.rs)生成符号和调用关系,不启动应用。
|
||||||
|
|
||||||
|
## 标准库、运行库和编译器有什么区别
|
||||||
|
|
||||||
|
- [lib/](lib/README.md) 是应用能调用的 Dever 标准库。要查函数名、参数和返回类型,从这里读对应的 .dv 声明。
|
||||||
|
- [rust/src/runtime/](rust/src/runtime/lib.rs) 是 Rust 运行库。数据库连接、HTTP 服务、任务调度等能力在应用运行时由这里实现。构建器按程序使用的能力选择运行库功能。
|
||||||
|
- [rust/src/compiler/model/](rust/src/compiler/model) 是编译器内部的类型和程序结构,用于检查和生成代码。这个目录不是应用项目里的 data/,也不负责执行数据库查询。
|
||||||
|
- [build/](build/README.md) 用于组装 Dever 发行文件;上表的 [compiler/build/](rust/src/compiler/build/mod.rs) 用于构建用户应用。
|
||||||
|
|
||||||
|
## 修改源码时从哪里开始
|
||||||
|
|
||||||
|
| 要解决的问题 | 先看哪里 | 对应测试 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 一段代码解析不了,或格式化结果不对 | syntax/parse、compiler/format | [语法测试](test/rust/syntax.rs) |
|
||||||
|
| 程序接受了错误类型,或拒绝了合法表达式 | compiler/check 及 compiler/model | [编译器测试](test/rust/compiler.rs)、[程序检查测试](test/rust/program.rs) |
|
||||||
|
| 类型检查正确,但生成的程序结果不对 | compiler/emit;涉及数据库、网络等操作时再查 runtime 对应模块 | [原生执行测试](test/rust/native.rs)、[运行库测试](test/rust/runtime.rs) |
|
||||||
|
| 命令、前端打包、依赖或构建输出不对 | cli、compiler/project、compiler/package、compiler/build | [构建测试](test/rust/build.rs) |
|
||||||
|
|
||||||
|
具体的构建命令和性能测试方法见[编译器与运行库开发说明](rust/README.md)。
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# 源码说明与流程图
|
||||||
|
|
||||||
|
领域文档面向使用该领域的开发者。`README.md` 说明职责和入口;`doc/<主题>.md` 说明操作的前提、状态变化和失败结果。说明文件的二级标题绑定完整符号,例如 `## shop.order.app.shipping`。同一符号只写一处业务说明;签名、行号和调用关系由工具生成。`.dv` 中用 `#` 或 `/* ... */` 简短说明局部实现的原因。调用流程页的业务说明来自 `doc/`。
|
||||||
|
|
||||||
|
## 常用命令
|
||||||
|
|
||||||
|
| 命令 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| `dever inspect . --links` | 根据已保存的源码与说明生成各领域的 `link.md`。 |
|
||||||
|
| `dever inspect . --links --check` | 检查已有流程图是否与源码和说明一致。 |
|
||||||
|
| `dever inspect . --json` | 输出符号、调用关系、范围和诊断,供编辑器或工具使用。 |
|
||||||
|
| `dever inspect . --json --symbol shop.order.app.quote --depth 0` | 查看指定定义的控制图;增加深度可包含相邻调用。 |
|
||||||
|
|
||||||
|
生成流程图时,源码和符号绑定必须通过检查。手写的同名 `link.md` 不会被覆盖。控制图展示可能的分支、调用、失败和资源收尾;定位一次真实请求需要运行日志或追踪。
|
||||||
|
|
||||||
|
VS Code 使用同一索引提供定义、引用、调用层级、悬浮信息和流程页。保存源码后再使用导航;未保存时插件会提示索引已过期。详细操作见插件自带说明。
|
||||||
|
|
||||||
|
## 索引字段
|
||||||
|
|
||||||
|
- 位置是零起始的 `[file, start_line, start_character, end_line, end_character]`;列按 UTF-16 计数。局部诊断不会隐藏独立有效定义,也不会为无效调用生成连线。
|
||||||
|
- 省略 `source_name` 时使用 `name`。具体 handler 实例可用 `template` 引用同一索引中的模板 ID,共享声明和签名;签名中的定义名替换为实例名。若局部查询没有包含模板,则直接输出实例的完整元数据。编译器与插件应配套使用。
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
# Dever 快速上手
|
||||||
|
|
||||||
|
本教程实现一个问候函数,分别通过命令行和 HTTP 调用,并验证其返回值。示例不依赖数据库或外部服务。
|
||||||
|
|
||||||
|
## 创建项目
|
||||||
|
|
||||||
|
下载 Linux x86_64 的 `dever`,执行 `chmod +x dever`,再把它放到 `PATH` 中的目录。这个文件包含编译所需的工具,可以直接运行项目和生成可执行文件。执行 `dever --help` 查看命令。
|
||||||
|
|
||||||
|
~~~sh
|
||||||
|
dever new greeting_app
|
||||||
|
cd greeting_app
|
||||||
|
dever check .
|
||||||
|
dever run . -- hello.greeting.greet '{"name":"Dever"}'
|
||||||
|
~~~
|
||||||
|
|
||||||
|
`dever new` 要求目标目录不存在。`dever run` 执行入口 `hello.greeting.greet`,返回:
|
||||||
|
|
||||||
|
~~~json
|
||||||
|
{"code":0,"message":"ok","data":"Hello, Dever"}
|
||||||
|
~~~
|
||||||
|
|
||||||
|
如果传入 `{}`,命令会报告缺少必填字段 `name`,并以非零状态退出。
|
||||||
|
|
||||||
|
用 `dever build . --output ./greeting` 生成应用程序。生成后可以直接执行 `./greeting hello.greeting.greet '{"name":"Dever"}'`。应用程序不依赖项目源码或 `dever` 命令。
|
||||||
|
|
||||||
|
## 业务函数与入口
|
||||||
|
|
||||||
|
项目目录 `module/hello/greeting/` 表示 `hello` 组件的 `greeting` 领域。`flow/greeting.dv` 负责生成问候语;`api/greeting.dv` 定义调用它的命令。函数接收文本参数 `name`,把问候语写入输出 `message`:
|
||||||
|
|
||||||
|
~~~dever
|
||||||
|
greet(name: Text) (message: Text) {
|
||||||
|
message = "Hello, " + name
|
||||||
|
}
|
||||||
|
~~~
|
||||||
|
|
||||||
|
`api/greeting.dv` 中的 `cmd greet = app.greet` 将命令 `greet` 绑定到本领域函数。完整命令名 `hello.greeting.greet` 依次由组件名、领域名和入口名组成。CMD 和 HTTP 可以绑定同一个函数,问候逻辑只需实现一次。
|
||||||
|
|
||||||
|
## 添加 HTTP 入口
|
||||||
|
|
||||||
|
创建目录 `module/hello/greeting/api/web/`,在其中新建 `greeting.dv`。HTTP 入口复用同一个业务函数:
|
||||||
|
|
||||||
|
~~~dever
|
||||||
|
public get greet = app.greet
|
||||||
|
~~~
|
||||||
|
|
||||||
|
在项目根创建 `config/setting.json`(如无 `config/` 目录,先创建)。配置监听地址和站点:
|
||||||
|
|
||||||
|
~~~json
|
||||||
|
{
|
||||||
|
"http": { "host": "127.0.0.1", "port": 8080 },
|
||||||
|
"sites": { "web": { "path": "web", "hosts": ["127.0.0.1"] } }
|
||||||
|
}
|
||||||
|
~~~
|
||||||
|
|
||||||
|
添加 HTTP 入口后,即使只运行 CMD,也需要这份 `config/setting.json`。
|
||||||
|
|
||||||
|
用 `dever run . -- api` 启动服务。在另一终端发起请求:
|
||||||
|
|
||||||
|
~~~sh
|
||||||
|
curl --fail --get --data-urlencode 'name=Dever' \
|
||||||
|
http://127.0.0.1:8080/hello/greeting/web/greeting/greet
|
||||||
|
~~~
|
||||||
|
|
||||||
|
响应的 `data` 字段为 `"Hello, Dever"`。路径由组件、领域、API 文件相对路径和入口名组成。`public` 允许匿名访问;`get` 从查询参数读取具名输入。用 `Ctrl+C` 停止服务。若端口已被占用,同时修改配置和请求地址。
|
||||||
|
|
||||||
|
如果组件需要网页,把公开文件放在 `module/hello/front/src/`,再按[组件前端说明](LANGUAGE.md#组件前端与-typescript-客户端)挂载。
|
||||||
|
|
||||||
|
## 测试和阅读代码
|
||||||
|
|
||||||
|
新建 `test/hello/greeting/greeting.dv`。测试函数名与文件名对应,不接收输入,也不返回业务值:
|
||||||
|
|
||||||
|
~~~dever
|
||||||
|
greeting() () {
|
||||||
|
assertEq(app.greet("Dever"), "Hello, Dever")
|
||||||
|
}
|
||||||
|
~~~
|
||||||
|
|
||||||
|
~~~sh
|
||||||
|
dever fmt .
|
||||||
|
dever check .
|
||||||
|
dever test . --filter hello.greeting.greeting
|
||||||
|
dever inspect . --links
|
||||||
|
dever inspect . --links --check
|
||||||
|
~~~
|
||||||
|
|
||||||
|
`test` 验证业务函数的返回值;HTTP 请求验证这个地址是否能接收 `name` 并返回同一句问候语。`inspect --links` 根据源码和领域说明生成 `module/hello/greeting/link.md`。
|
||||||
|
|
||||||
|
分支用 `rule`,多步操作用 `flow`,遍历和聚合用 `loop`,持久化用 `type` 数据模型。语法和边界见[语言参考](LANGUAGE.md),库函数见[标准库](lib/README.md),领域说明和导航见[源码说明与流程图](DOCUMENTATION.md)。
|
||||||
|
|
||||||
|
## 使用 AI 开发
|
||||||
|
|
||||||
|
按[应用开发规范](skills/dever/SKILL.md)为开发工具提供项目目录,以及与 `dever --version` 对应的语言参考和标准库说明。
|
||||||
+1309
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,12 @@
|
|||||||
|
# Dever v0.0.2
|
||||||
|
|
||||||
|
Dever 是一门面向业务应用的语言。业务代码用普通函数表达计算,用 `rule` 描述判断、`flow` 组织操作、`loop` 遍历数据。应用通过数据模型、HTTP 入口、Job 和 Port/Adapter 接入存储及外部能力。编译器将代码生成具体类型的 Rust,并构建为原生程序。
|
||||||
|
|
||||||
|
- **开始开发:**[快速上手](GETTING_STARTED.md)从新建项目开始,依次运行命令、开放 HTTP 入口和添加测试。
|
||||||
|
- **查用法:**[语言参考](LANGUAGE.md)、[标准库](lib/README.md)、[源码说明与流程图](DOCUMENTATION.md)。
|
||||||
|
- **查看示例:**[文字游戏、CMS 与 Agent](examples/next/README.md),分别展示规则、数据业务和外部模型调用。
|
||||||
|
- **使用 AI 或编辑器:**[应用开发 Skill](skills/dever/SKILL.md)、[VS Code 插件](editor/vscode/README.md)。
|
||||||
|
- **阅读 Dever 源码:**[源码架构](ARCHITECTURE.md)以一次构建为例,说明编译器、标准库和运行库各自负责什么。
|
||||||
|
- **构建和发行:**[编译器构建](rust/README.md)、[单文件发行](build/README.md)、[SDK](sdk/README.md)。
|
||||||
|
|
||||||
|
核心验收标准、实测结果和部署边界见[完成定义](REMAINING.md)。
|
||||||
+180
@@ -0,0 +1,180 @@
|
|||||||
|
# Dever 0.0.1 完成定义
|
||||||
|
|
||||||
|
状态:2026-11-20。本文件定义当前验收标准、剩余事项和停止规则。语言合同见 [LANGUAGE.md](LANGUAGE.md)。
|
||||||
|
|
||||||
|
Dever v0.0.1 已通过第 2 节的核心功能和大型多实例验收。SQLite 单实例和 PostgreSQL 双实例的一小时负载均为 60/60 窗口达标,双实例 Job 接手和最终 x86_64 离线包已验证。SQLite 长稳成绩对应基线 `e6ec8aa`;已知性能差距和待环境验收项见第 5 节。
|
||||||
|
|
||||||
|
基线之后修复多实例请求 ID,清理编译与数据库重复代码。PostgreSQL 双实例接手、迁移和 Worker 定向回归通过。公开 API 七轮同场复验(每轮 25 万请求):基线与当前分别为 57120/57937 请求每秒、服务端 CPU 4.02/3.93 秒,应用二进制同为 2722912 字节。此用例不读取请求 ID;原始数据见 target/performance/redundancy-api-20261118/results.json,当前离线包见 4.7。
|
||||||
|
|
||||||
|
## 1. v0.0.1 验收范围
|
||||||
|
|
||||||
|
下列条件是本次发行的验收依据。出现冲突时须由项目负责人确认,不得自行更改。
|
||||||
|
|
||||||
|
| 编号 | 决定(2026-11-17) |
|
||||||
|
| --- | --- |
|
||||||
|
| D1 | 0.0.1 只验收核心:语言与三表、Model/事务、HTTP/REST、认证权限租户、Job、CMD、格式化/检查、VS Code 导航。Worker 三生态打包、WebSocket/SSE、上传存储、ARM、GPU、多实现 Port 的代码保留,不进 0.0.1 出口 |
|
||||||
|
| D2 | 稳定性看趋势,不看最大/最小比:一小时负载中,后 30 分钟 RSS 中位数不超过前 30 分钟的 1.10 倍,且 RSS 峰值、FD、线程数门槛不变(见 4.2) |
|
||||||
|
| D3 | 构建规模的正式输入是 `owned`(万函数、调用深度 100);`deep`(万函数 10000 层单链)只作压力用例单列,不进 30 秒门槛。原因:深链耗时来自 rustc 内联环路检查随调用深度平方增长(单态化收集 14.9 秒,深度 100 时 1.6 秒),不是函数数量 |
|
||||||
|
| D4 | Job、CRUD、读取、HTTP 对同责任独立 Rust 的 5%~7% 差距登记为已知差距,不进 0.0.1 出口,但不得扩大;2% 只作观测目标 |
|
||||||
|
| D5 | 允许提交基线与清理可再生构建产物;不推送、不部署、不切换系统 dever |
|
||||||
|
|
||||||
|
## 2. 0.0.1 出口(全部满足才报告完成)
|
||||||
|
|
||||||
|
**正确性**
|
||||||
|
- `cargo test --workspace --all-features` 全部通过;17 个 ignored 的 PostgreSQL 与外部 Worker 用例用各自入口单独跑通;`clippy -D warnings`、`fmt` 全绿。
|
||||||
|
- 新增两类测试:语法与格式化的随机输入测试(解析不崩溃、`fmt` 幂等);rule 互斥穷尽证明的反例测试。
|
||||||
|
- 真实业务用例:`examples/next/cms` 仅用于验证语言写法与性能,不扩展为业务产品。以内容、分类、评论验证 Model 与三表;身份、租户、事务、Job 复用已有综合负载。SQLite 与 PostgreSQL 均验证;四方对比逐项列明共同语义与资源责任。
|
||||||
|
|
||||||
|
**稳定性**:一小时负载(32 租户、1048576 初始记录、128 客户端)60 个窗口各至少 1000 成功请求/秒、成功 p99 ≤ 200ms、错误 0、数据与隔离正确、Job 在结束后 60 秒内完成、关闭后无遗留进程;RSS 峰值 ≤ 256MiB、FD ≤ 512、线程 ≤ 32、RSS 趋势满足 D2。
|
||||||
|
|
||||||
|
**性能**
|
||||||
|
- 构建(见下方规模预算):`owned` 万函数 release ≤ 30 秒,dev 改函数体 ≤ 10 秒,冷 inspect ≤ 1.5 秒,索引体积 ≤ 5MiB,规则证明与峰值内存也须达标。
|
||||||
|
- 无回归:对上一个提交,任何已达标基准稳定慢超过 5% 必须修复或撤回;L2 已有的文本/List/Map 读取退化必须修回,Text 连接达标版本必须保住。
|
||||||
|
- 业务级必须快于冻结基线与 Go;CRUD 与公开自动 API 已满足,见 4.6。对独立 Rust 的差距见 D4 与第 5 节。
|
||||||
|
|
||||||
|
**代码**
|
||||||
|
- 没有超过 200 行的生产 Rust 函数(基线 20 个,当前 0 个);`unwrap`/`expect("checked …")` 能用类型表达的改为类型,原定门槛 474 处。排除注释、生成字符串和测试后,用同一脚本复数 `f584a9b` 与当前代码为 958 → 420,达标。
|
||||||
|
- 删除已撤回的实验候选与无调用方代码;Markdown 只保留每个领域一页,`LANGUAGE.md` 为唯一语言规范。
|
||||||
|
- 同一规则只写一次,不增加防御性冗余;每次改动的净增行数必须有对应的功能或测试。
|
||||||
|
|
||||||
|
**交付**:最终源码的 x86_64 离线包与 VSIX,干净离线构建、搬移后运行通过。ARM 实机、GPU、真实身份/模型/支付通知列为"待环境验收",不计入 0.0.1。
|
||||||
|
|
||||||
|
## 3. 防转圈规则
|
||||||
|
|
||||||
|
1. 每个性能或稳定性问题**最多两轮实验**;第三轮必须有新证据(已定位的根因、硬件计数器、可复现差异)。没有就登记为已知问题,转下一项。
|
||||||
|
2. 不新增出口:新发现的问题写入第 5 节,经项目负责人确认后才进入第 2 节。
|
||||||
|
3. 同一源码身份的结果不重复测;一小时压测必须在有修复后才重跑。
|
||||||
|
4. 微基准的差距小于该基准自身的波动(同一变体多次运行之间)时,不据此改代码。本机共享主机实测波动 ±5%~10%。
|
||||||
|
5. 每完成一个步骤提交一次,提交信息写明验证结果;不在一个提交里混合无关改动。
|
||||||
|
6. 不降低优化级别、不放宽已定义的正确性与安全断言。
|
||||||
|
|
||||||
|
## 4. 执行步骤与状态
|
||||||
|
|
||||||
|
| 步骤 | 内容 | 状态 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 0 | 提交基线、写完成定义、清理构建产物 | 已完成:基线 f584a9b;清理释放约 46GiB(保留发行包、bak、R0 基线、next-cargo、文档引用的测试目录) |
|
||||||
|
| 1 | 正确性:全量测试、两类新增测试、cms 用例 | 最终源码 476 项常规测试、PostgreSQL 18 项、外部 SDK 5 项通过。双实例共享、撤权、隔离和未完成 Job 续领通过,见 4.3 |
|
||||||
|
| 2 | 稳定性:压测判定改为 D2 趋势;结束后检查 RSS 趋势、错误、Job、进程 | SQLite 单实例、PostgreSQL 双实例均为 60/60 窗口达标,资源、数据、隔离、Job 排空和退出检查全通过,见 4.2 |
|
||||||
|
| 3 | 性能:handler 索引体积、构建预算矩阵、记录累加/Map/Bytes 读取退化 | 索引、导航、集合/CRUD/API 与四方构建已收齐;最终编译器 owned 万函数 release 首次中位 16.92 秒、dev 改体 2.86 秒、冷 inspect 0.624 秒,模块变更与干净构建核对通过。公开 API 两批较长对照均领先冻结基线与 Go;宽入口压力结果单列于第 5 节 |
|
||||||
|
| 4 | 代码瘦身:超长函数、`expect`、文档合并、删除废弃代码 | 剩余 17 个超长函数按真实职责整理后为 0 个;入口直接传递已检查函数,非空值与记录缓冲类型不再重复匹配。生成 Rust 的 529 处内存格式化检查由具体 `String` 写入统一处理;剩 420 处,通过减半门槛 |
|
||||||
|
| 5 | 发行:最终包与 VSIX,目标环境单列 | x86_64 离线包已更新,17555 文件校验及空环境搬移、修改后重建、独立运行和缺工具拒绝均通过;VSIX 保留,见 4.7 |
|
||||||
|
|
||||||
|
### 4.1 步骤 3 的具体项
|
||||||
|
- 构建:最终编译器的 owned 万函数各三轮,release 首次 16.92 秒、改体 16.60 秒,dev 首次 6.06 秒、改体 2.86 秒;两种模式 12 个构建及执行正确,峰值 RSS 517100KiB。摘要与输入在 `target/acceptance-20261118/{owned-release,owned-dev}/results.json`。上一候选的签名改动、无修改及独立 Rust/Go 同场对照见 4.6。
|
||||||
|
- 整理前候选矩阵:owned 的 100/1000/10000 函数 dev 首次中位数 1.00/1.98/12.57 秒,改体 0.37/0.73/4.62 秒,改签名 0.39/0.84/5.78 秒,无修改 0.11/0.16/0.61 秒;小两档 release 首次 5.29/7.02 秒、改体 4.82/6.52 秒、改签名 5.14/6.55 秒,全部执行结果正确。固定三轮,4 CPU/8Gi、Cargo 单任务;规则证明 45 个布尔/区间/预算样本全部正确,最长 0.027 秒。证据:`target/performance/{scale-dev-review,scale-release-review,rule-proof-review,rule-numeric-review}-20261117/results.json`。
|
||||||
|
- 模块变更:dev/release 各 36 个增量样本、27 个干净构建对照全部正确,覆盖 100/1000/10000 函数下的新增、重命名与删除。万函数 dev 首次 13.87 秒、三种增量 5.84–6.91 秒;release 首次 28.21 秒、三种增量 28.38–28.84 秒,峰值 RSS 876196KiB。夹具含 CMD/JSON,100/1000 函数 release 首次 6.42/8.32 秒,不能用来判断短入口是否达到 6/8 秒预算。证据:`target/performance/module-{dev,release}-review-20261117/results.json`。
|
||||||
|
- Model 构建:查询执行与自动 API 入口的泛型实例化已集中到运行库;cms 改一行 release 重建 92 → 73 秒,增加 60 个流程为 154 → 101.8 秒。每请求多一次装箱,自动 API 七轮未测到总耗时回归,见 4.6。fat LTO 与单代码生成单元保持不变;放宽优化级别的候选因执行退化已撤回,见 4.5。
|
||||||
|
- handler 索引去重已完成:万函数 19,998 个符号、19,996 条边全部保留,JSON 约 9,055,890 → 4,208,886 字节(−53.5%),最终编译器冷查询三轮中位数 0.624 秒、4208869 字节;路径长度会影响少量字节。整理前 100/1000/10000 的 owned、handler 共 18 项均通过;真实插件七轮冷加载 701ms、保存后刷新 715ms、缓存命中 0.016ms,绑定签名、源码跳转与缓存失效通过。最终编译器的真实导航与浏览器测试通过。证据:`target/performance/{inspect-readable-review-20261117,inspect-review-20261117,editor-handler-review-20261117}/results.json`。
|
||||||
|
- 记录累加、Map、Bytes 读取:用一次通用的所有权/原地更新变换替代逐形状识别(`emit/body/record.rs`、`bytes.rs`),最终编译器在原对照上补验 68 档,4352 个运行组结果全部正确,未见稳定超过 5% 的退化。证据:`target/acceptance-20261118/kernel/results.json`。
|
||||||
|
|
||||||
|
### 4.2 一小时长稳
|
||||||
|
|
||||||
|
SQLite(2026-11-18)在 4 CPU/8 GiB 开发容器运行:32 租户、1048576 初始记录、128 客户端、HTTP 在途 8、SQLite 每连接缓存 64KiB。预热一分钟后,60/60 个一分钟窗口满足原门槛,未启用分配采样。服务绑定三个核,驱动绑定另一个核。
|
||||||
|
|
||||||
|
| 指标 | 实测 |
|
||||||
|
| --- | ---: |
|
||||||
|
| 成功请求/预期 409/非预期错误 | 9112843/1012505/0 |
|
||||||
|
| 成功请求/秒,平均/最低窗口 | 2531.35/1704.40 |
|
||||||
|
| 成功 p99,整体/最差窗口 | 64.65ms/113.87ms |
|
||||||
|
| 服务端平均 CPU | 2.48 核 |
|
||||||
|
| RSS 峰值/FD 峰值/线程峰值 | 30868KiB/183/9 |
|
||||||
|
| 前/后半程 RSS 中位数 | 28468/28768KiB,比例 1.01054 |
|
||||||
|
| Job 排空 | 0.138 秒 |
|
||||||
|
| 综合应用 release 二进制 | 8133448 字节(7.76MiB) |
|
||||||
|
|
||||||
|
完整数据、唯一性、租户隔离、回滚拒绝和物理队列核对通过,服务进程已退出。测试退出码 0,`functional_verified` 与 `slo_passed` 均为 true。摘要和逐请求原样本:`target/next-build-tests/189363-api-tenant-large/{load-results.json,load-samples.json}`;测试日志和 CPU、I/O 采样:`target/acceptance-20261118/hour-isolated{.log,-environment.jsonl}`。多实例使用 PostgreSQL,见 4.3。
|
||||||
|
|
||||||
|
首轮同预算复验有 7 个 p99 超标,最低 738.6 成功请求/秒、最差 p99 305.18ms;最差窗口服务实际占用 0.90 核,相邻达标窗口为 2.47/2.35 核。证据保留在 `target/next-build-tests/162466-api-tenant-large/`;等待来源未证实。调整测试端 CPU 放置后,320 万初始记录短测先通过,随后按原负载和原门槛完成这次验收。
|
||||||
|
|
||||||
|
PostgreSQL 双实例(2026-11-19,隔离节点,4 CPU/8 GiB):同为 32 租户、1048576 初始记录、128 客户端。60/60 达标,最低 2476.27 成功请求/秒,最差 p99 108.92ms,非预期错误 0。两实例合计 RSS 峰值 20788KiB,前后半程中位数比例 1.00193,FD 峰值 226、线程峰值 2;Job 在 0.030 秒排空。隔离、数据核对和进程退出通过,验收结果(本地结果:target/pg-history-ab-20261119.8itimh8_/storage-results/next-build-tests/13477-api-tenant-postgres-replica-soak/load-results.json)。
|
||||||
|
|
||||||
|
### 4.3 正确性(2026-11-18,开发容器 4 CPU/8Gi)
|
||||||
|
|
||||||
|
- `cargo fmt --check` 与全工作区严格 Clippy 通过;常规测试 476 项全部通过。首次 build 测试的诊断夹具仍匹配已不生成的旧运算符;修正注入点后通过,源码位置及错误断言保留。启用全部特性,41 个 ignored 不计入常规通过数。日志:`target/acceptance-20261118/`。
|
||||||
|
- PostgreSQL 17.11 实库专项 18/18;两实例共用数据库,验证跨实例读写、实时撤权、租户隔离和活跃 Job 幂等。终止一个已领取任务的实例后,另一个在租约到期后接手,业务写入只提交一次。
|
||||||
|
- 原生生态与 SDK 五个专项(Go、npm、Python、原生包、C/C++ SDK)5/5 通过。
|
||||||
|
- CMS、Agent、文字游戏的 fmt/check/test 已实测;Agent 使用声明的测试替身。workflows 是设计夹具,缺真实 Adapter 时不计作通过。最终编译器的真实导航和高亮 14 项通过;离线流程图共 269 张、16 页已验证。
|
||||||
|
|
||||||
|
### 4.4 cms 试点记录(2026-11-17)
|
||||||
|
范围:在 `content.article` 领域增加 `model/category`、`model/comment`,业务为分类、评论(默认待审核)、规则表审核、公开评论分页;Dever 测试 `discussion` 与既有 `publishing` 均在真实 SQLite 上通过,`fmt/check/inspect --links --check` 通过。
|
||||||
|
|
||||||
|
| 发现 | 状态 |
|
||||||
|
| --- | --- |
|
||||||
|
| 添加外键后原有 Model 无法直接跨接口 | 已按确认的合同修改:普通 CMD、HTTP、JSON 只编解码存储字段,解码关系为 Unloaded,拒绝客户端提交关系。私有存储字段与 Secret 输出限制保留;显式嵌套输出才声明结果记录 |
|
||||||
|
| CMS 字段命名绕路 | 已恢复 `category_id`、`article_id`,不增加 DTO/View。评论与撤回通过条件更新串行,撤回后不公开评论 |
|
||||||
|
| 后续范围 | 自动 API 真实路径性能、四方同业务与源码量;不扩账号、订单、支付产品功能 |
|
||||||
|
|
||||||
|
### 4.5 未采用的构建候选
|
||||||
|
认证三件套擦除无稳定收益(增加 60 个流程时 101.8 → 102.5 秒);应用包 16 个代码生成单元使内核几何平均慢 7%–10%,`record_inspect` 慢 1.9 倍;thin LTO 或关闭 LTO 使内核几何平均慢 16%–27%。均已撤回,不加开关保留第二条发行路径。
|
||||||
|
|
||||||
|
### 4.6 当前四方对照(2026-11-18)
|
||||||
|
|
||||||
|
表中的“冻结基线”指为对照测试保留的 Dever 编译器构建。各实现先预热一次,再轮流测试七轮,保留所有原样本、源码与二进制摘要。CMS 只用于验证项目写法;基准分别隔离集合、事务 CRUD 和公开 JSON API,轻量参考程序的成绩只代表该测试路径。
|
||||||
|
|
||||||
|
| 用例与单位 | Dever v0.0.1 | 冻结基线 | 独立 Rust | Go |
|
||||||
|
| --- | ---: | ---: | ---: | ---: |
|
||||||
|
| 1024 条完整 CRUD,整批 ms | 65.51 | 77.29 | 63.33(有界资源版) | 99.34 |
|
||||||
|
| 公开自动 JSON API,请求/秒 | 57517 | 53876 | 70393(公开成功路径) | 31898 |
|
||||||
|
| 公开 API 服务端 CPU,秒/50 万请求 | 8.10 | 8.57 | 6.60 | 15.68 |
|
||||||
|
| 公开 API RSS 峰值中位数,KiB | 4032 | 4524 | 2856 | 14332 |
|
||||||
|
| Map 文本键查询,4096 项 ns | 82097 | 90131 | 82464(输入所有权与结果收集版) | 117945 |
|
||||||
|
|
||||||
|
CRUD:Dever v0.0.1比冻结基线耗时少 15.24%、比 Go 少 34.05%,对独立资源 Rust 慢 3.44%;同步轻量 Rust 为 14.33ms,仍单列保存,不覆盖其缺少异步资源责任的差异。48 项提交、拒绝、回滚与完整数据核对全部通过。手写业务非空行:Dever v0.0.1 25、冻结基线 22、Rust 93(资源版含资源实现 362)、Go 128;非空行包含注释,不当作去注释后的有效代码行。
|
||||||
|
|
||||||
|
自动 API:固定七轮、每轮 50 万逐条校验请求,吞吐中位数比冻结基线高 6.8%、比 Go 高 80.3%,分别赢 6/7 轮;此前 25 万/轮对照分别赢 5/7 和 7/7。冻结基线与Dever v0.0.1在个别轮次交叉,全部保留。原始样本见 `target/performance/api-gate-20261118/{controlled-final,json-body-confirm}/results.json`。独立 Rust/Go 比较覆盖公开 JSON 成功路径,不包含完整鉴权、取消、故障与排空的责任。
|
||||||
|
|
||||||
|
集合:68 档全部核对通过。List 读取对资源 Rust 为 −3.46%~−0.19%,记录 List 读取 −4.51%~+1.44%,Map 读取 −1.87%~+4.19%,文本键查询 −3.55%~−0.45%,Text 连接保住。部分轻量 Rust 仍快;`text_equal/1024` 对前版中位数 +9.89%,本变体轮间波动 12.2%,小规模 Bytes 波动更大,尚无稳定回归证据,不据噪声叠加实现。
|
||||||
|
|
||||||
|
证据:`target/performance/{kernel-review-20261117,model-review-20261117,api-four-way-20261117}/results.json`。核心生产源码物理行 67189 → 55421(−17.52%),非空行 64058 → 53701;其中编译器/CLI 40213 行、运行库 15208 行。按同一分类和冻结旧清单统计,测试、依赖、生成物另计。明细:`target/source-lines-old-review-20261117.json`、`target/source-lines-readable-review-20261117.json`。六组关键程序的生成 Rust 与二进制摘要均未变,见 `target/review-readability-20261117/codegen-equivalence.json`;原七轮运行成绩保留,不重复测同一业务二进制。功能覆盖须结合 D1,不用行数替代。
|
||||||
|
|
||||||
|
万函数 owned 构建采用同一百层分段调用图、固定三轮、相同优化与溢出检查;下表为中位秒数。独立 Rust/Go 不链接 Dever 运行库,结果不代表所有业务的构建速度。
|
||||||
|
|
||||||
|
| release 构建 | Dever v0.0.1 | 冻结基线 | 独立 Rust | Go |
|
||||||
|
| --- | ---: | ---: | ---: | ---: |
|
||||||
|
| 首次 | 25.442 | 30.028 | 56.119 | 9.404 |
|
||||||
|
| 改函数体 | 24.825 | 30.007 | 56.946 | 9.511 |
|
||||||
|
| 改签名 | 24.703 | 29.663 | 56.615 | 9.466 |
|
||||||
|
| 无修改 | 0.624 | 1.257 | 0.031 | 0.483 |
|
||||||
|
|
||||||
|
三方对端各 36 项、最终Dever v0.0.1万函数每种 profile 各 12 项构建及执行全部正确。原始成绩:`target/performance/{owned-readability-release,owned-old,owned-rust-release,owned-go-release}-review-20261117/results.json`;整理前 1302f432 候选的万函数 release 成绩另存 `owned-next-release-final-review-20261117`,不覆盖。
|
||||||
|
|
||||||
|
### 4.7 已验收交付(2026-11-19)
|
||||||
|
|
||||||
|
`target/closeout-20261119.QDFCr5/dever-0.0.1-linux-x86_64.tar.gz`(272787477 字节)及同名 .sha256。插件源码未变,`target/dever-language-0.0.1-review-20261117.vsix` 完整性已核验。
|
||||||
|
|
||||||
|
17555 个文件的摘要、长度与执行权限全部通过。空环境搬移后离线构建、改源码重建、独立运行和缺工具拒绝通过,见 `target/closeout-20261119.QDFCr5/verify.log`。宿主在隔离工作区发现包内 dever Skill,同版本文档可读。包不含三生态外部附件与 ARM。
|
||||||
|
|
||||||
|
## 5. 已知问题与已知差距(不进出口,不得扩大)
|
||||||
|
|
||||||
|
| 项 | 现状与证据 |
|
||||||
|
| --- | --- |
|
||||||
|
| CRUD | 1024 条记录的测试中,Dever 比有资源约束的独立 Rust 实现慢 3.44%(此前 5.5%~6.7%),同场比前版快 3.82%;固定成本与逐行成本继续分开记录,见 4.6 |
|
||||||
|
| Job | 1024 个 System Job 对完整 System Rust 慢约 5.5%~7.1%;入队每条多约 2µs |
|
||||||
|
| Model 分页与关系读取 | 直接整段写入 JSON 缓冲区,保留字节、值数与深度限制。72 档同场耗时中位数相对带入口核验的 Rust 从慢 5.99% 收窄为慢 4.46%,未见稳定超过 5% 的回归。计时含进程启动。实测(本地结果:target/closeout-20261119.QDFCr5/model/results.json) |
|
||||||
|
| HTTP | 公开 JSON 成功路径的四方结果见 4.6。独立 Rust 的吞吐中位数仍高,CPU 和 RSS 仍低;轻量成功路径不代表完整鉴权、取消、故障与排空责任。 |
|
||||||
|
| 宽入口构建压力 | 2026-11-18 同一开发容器三轮:万函数 layered release 首次 20.65 → 16.60 秒、改体 20.59 → 16.56 秒;独立 Rust 9.06/8.81 秒、Go 8.71/8.40 秒,冻结基线拒绝同输入(C015)。运算集中到内联函数,复用 Rust checked 操作并沿用静态故障信息。正式 owned 万函数 release 首次 18.02 秒、dev 改体 2.97 秒;18 次构建及执行正确,68 档运行对照未见稳定超过 5% 的退化。改用值载荷的候选虽达到 14.29/13.25 秒,但记录读取与 Text 连接退化,未保留。证据见 `target/performance/wide-rustc-phases-20261118/release-breakdown/`;D3 范围不变,宽入口仍未追平 Rust/Go |
|
||||||
|
| SQL 线程交接 | 每条 SQL 约 20µs 属平台线程唤醒延迟,是 Dever 与参考的共同下限;专用线程变体只快约 12%,且未含取消与期限责任,不采用。同进程对照 Dever 对参考在 ±3% 内(诊断源码 `target/diagnose-job-crud-20261117/bench`) |
|
||||||
|
| PostgreSQL 部署环境 | 隔离节点双实例长稳和同步主备跨节点手动切换(本地结果:target/deploy-failover-20261119/results.json)通过。单开发 Pod 内两应用、128 客户端的自动切换(本地结果:target/ha-check-20261119.PeYUHH/dever-ha-runtime-ixu5oz_f/results.json)通过:19.237 秒升主,两应用未重启并恢复写入;6719 笔已确认写入全部保留,Job 接手只写一次,旧主以只读备库回归。故障注入后有 1174 次连接错误或超时、36 次 HTTP 500,另有 3 笔写入成功但客户端未收到成功响应。正式 PostgreSQL 仍为单实例;目标持久存储、整节点故障与实际网络分区下的旧主隔离待验。原节点同步写尾延迟未达标,原节点证据(本地结果:target/performance/pg-replica-20261118.xzXi5k/)。 |
|
||||||
|
| 目标环境 | 集群只有 amd64 节点,开发 Pod 无 GPU;ARM 实机、GPU、真实外部服务无法验收 |
|
||||||
|
| 诊断环境 | 诊断使用入口分段计时和隔离 Callgrind 追踪,未使用硬件计数器。 |
|
||||||
|
|
||||||
|
## 6. 入口
|
||||||
|
|
||||||
|
构建、测试与严格检查:[rust/README.md](rust/README.md);规模对照:`test/performance/scale.py --shapes owned deep`;业务对照:`test/performance/{kernel,model,job,http_resources,http_server}.py`;综合负载:`test/rust/build/api/tenant/load.rs`;语言规范:[LANGUAGE.md](LANGUAGE.md);发行流程:[build/README.md](build/README.md)。
|
||||||
|
|
||||||
|
## 7. 规模验收预算
|
||||||
|
|
||||||
|
依赖已构建,应用输出缓存按场景新建。每种形状独立取三轮中位数,全部执行结果须正确。
|
||||||
|
|
||||||
|
| 指标 | 100 函数 | 1,000 函数 | 10,000 函数 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| dev 首次应用构建 | ≤ 5 秒 | ≤ 8 秒 | ≤ 20 秒 |
|
||||||
|
| dev 修改单函数体 | ≤ 2 秒 | ≤ 4 秒 | ≤ 10 秒 |
|
||||||
|
| release 首次/改函数体/改签名 | ≤ 6 秒 | ≤ 8 秒 | ≤ 30 秒 |
|
||||||
|
| 无修改构建,两种 profile | ≤ 0.15 秒 | ≤ 0.25 秒 | ≤ 1.5 秒 |
|
||||||
|
| 冷 inspect,包括序列化 | ≤ 0.05 秒 | ≤ 0.12 秒 | ≤ 1.5 秒 |
|
||||||
|
| 完整 inspect 索引 | ≤ 0.5MiB | ≤ 1MiB | ≤ 5MiB |
|
||||||
|
|
||||||
|
固定沿用 4 CPU/8Gi Pod、规模子进程 6Gi 虚拟地址限制和 Cargo 单任务;这些短入口夹具的构建峰值 RSS 不超过 1.5GiB。两种 profile 的签名变更、模块增删和干净构建必须结果一致,开发模式签名变更按首次构建预算验收。小型标量夹具的发行程序本体不超过 400KiB,不能以运行库不必要的 feature 膨胀换取方便实现。宽入口需在同一资源限制内成功,仍保留每次 900 秒终止上限,并与独立 Rust 同输入构建成本比较;不得提高分析上限后就宣称性能问题解决。
|
||||||
|
|
||||||
|
rule_proof.py 固定完整布尔组合与宽条件样例。Dever v0.0.1每条规则最多执行 1,000,000 次候选条件比较/分区展开,超过时返回未完成证明诊断;计数必须覆盖实际组合工作,不能只统计源码行数。完整 10 列/1,024 行与单行 20 列无约束规则均须在 1 秒内检查,遗漏与重叠须给出反例;另用确实超过预算的输入验证失败,而不是将有效简单规则误判为超预算。该预算不允许跳过输入类型、失败分支或范围边界。
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# Dever 发行构建
|
||||||
|
|
||||||
|
## 单文件 dever
|
||||||
|
|
||||||
|
Linux x86_64 的发行文件为原生可执行文件 `dever`。复制到目标机器并赋予执行权限后,即可用 `dever run` 运行项目,用 `dever build` 生成应用程序。开发者无需另装 Rust、Cargo 或链接器。当前发行在 Debian 13(glibc 2.41)上验证。构建使用 Linux 的 `/proc` 和可执行的内存文件,需有可写、可执行的临时目录。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
chmod +x dever
|
||||||
|
./dever new hello
|
||||||
|
./dever run hello -- hello.greeting.greet '{"name":"Dever"}'
|
||||||
|
./dever build hello --output ./hello-app
|
||||||
|
./hello-app hello.greeting.greet '{"name":"Dever"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
发布者在 Debian 13 x86_64 开发容器中用固定工具链构建。输出目录须已存在,输出文件须是新路径:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
export CARGO_TARGET_DIR="$PWD/target/next-cargo"
|
||||||
|
cargo +1.95.0 build --manifest-path rust/Cargo.toml --locked --offline --release --bin dever
|
||||||
|
mkdir target/linux-x86_64
|
||||||
|
python3 build/local.py --compiler "$CARGO_TARGET_DIR/release/dever" \
|
||||||
|
--output target/linux-x86_64/dever > target/linux-x86_64/dever.sha256
|
||||||
|
(cd target/linux-x86_64 && sha256sum -c dever.sha256)
|
||||||
|
```
|
||||||
|
|
||||||
|
Cargo 只编译 CLI;上面的 Python 命令生成可以单独分发的成品。它预编译运行库,并把标准库、编译和链接资源放入 `dever`。每次原生编译把所需资源加载到匿名内存文件,未安装工具链的机器也能构建普通 Dever 应用。前端构建脚本使用项目配置的工具。开发 Go、npm、Python Worker 时,请使用下文的平台工具包及其 SDK。跨架构构建也使用平台工具包。随文件的第三方许可声明可用 `dever --licenses` 查看;发布时同时按所带组件的条款提供相应源码或源码获取方式。
|
||||||
|
|
||||||
|
## 平台开发工具包
|
||||||
|
|
||||||
|
平台维护及交叉构建所用工具包包含源码、SDK 和完整的离线工具链。它与面向应用开发者的 `dever` 是不同的发行物。
|
||||||
|
|
||||||
|
在现有 Debian 13 x86_64 开发容器内组装,复用官方 Rust 1.95.0、Cargo vendor 和 Debian GCC/binutils。不会安装或替换系统 dever,不写用户 Cargo 配置。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 build/development.py --compiler target/next-cargo/release/dever \
|
||||||
|
--work target/release-stage --output target/dever-0.0.2-linux-x86_64.tar.xz
|
||||||
|
```
|
||||||
|
|
||||||
|
work、归档及校验文件必须是新路径。包含编译器、运行库源码、标准库、SDK、Skill、离线 Cargo 依赖、Rust 和 C 编译工具及其许可证。不会复制用户 Cargo home、项目配置、业务数据或 SDK 开发依赖目录。编译器自身没有新增开放许可声明。
|
||||||
|
|
||||||
|
解压归档后从 `dever/bin/dever` 启动。启动器从自身位置设置 `DEVER_ROOT`,工具包可整体移动。目标环境需提供 Linux x86_64、glibc 2.41 以及 shell 和常规系统工具。
|
||||||
|
|
||||||
|
manifest.json 列出交付文件的相对路径、长度、SHA-256 和执行权限;归档另附 SHA-256。Cargo 保留原始 vendor 校验与依赖许可证,Rust 和 Debian 工具许可证在 toolchain/licenses。构建缓存只在首次实际构建时产生,不打入归档。
|
||||||
|
|
||||||
|
外部 Python/npm/Go 依赖按 `dever lib install` 准备原生锁及缓存;应用 build 离线使用已准备资源,解释器和动态依赖内嵌在应用产物中。需要交付这些工具和依赖时,先在独立 DEVER_HOME 中准备实际项目,再给组装命令增加 `--external-home <该目录>`。仅打包固定官方工具与 Go/npm/uv 下载缓存,不复制配置、日志、业务源码和构建缓存;缓存内的符号链接不得越出准备目录。第三方依赖的原始许可证随缓存保留,发布者仍须核对实际依赖的分发条件。
|
||||||
|
|
||||||
|
应用源码与 dever.lock、原生锁文件可以直接搬移;target 中的并发锁由构建建立,无需复制历史 target。三生态离线验证从不带 target 的源码副本构建,确保这一行为。
|
||||||
|
|
||||||
|
带外部附件的启动器在未设置 DEVER_HOME 时使用包内 external 目录;显式设置时使用指定目录,不混用两套缓存。离线能力覆盖已准备的原生锁,不能离线获取未打包的版本。验证入口为 `test/release.py` 和 `test/release_external.py`,后者用空 HOME、不可达代理和搬移后的工具链构建三种生态,并在移走项目源码后运行真实第三方处理函数。aarch64 发行和真实目标执行仍需对应环境验收。
|
||||||
|
|
||||||
|
交叉构建附件由组装时显式选择:增加 --aarch64-native <Debian 13 交叉 GCC 解包根> 与 --aarch64-std <Rust 1.95.0 的 rustlib/aarch64-unknown-linux-gnu>。两者必须同时提供;只纳入官方目标标准库、交叉 GCC/binutils、目标头文件/库及许可证,不复制旧 Dever 运行库或测试 QEMU。随包 Cargo 使用包内目标链接器,搬移后无需系统交叉工具。编译目标用 dever build 的 --target linux-aarch64,外部 Worker 的目标限制见 LANGUAGE。
|
||||||
|
|
||||||
|
可用 test/release.py 的 --aarch64-runner <QEMU 路径> 验证搬移后的离线交叉构建与仿真执行;这项结果必须标作 QEMU,不能算 aarch64 实机或 aarch64 安装包验收。
|
||||||
@@ -0,0 +1,301 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""在 Debian 13 开发容器内组装 Linux x86_64 完整离线开发包。"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import tomllib
|
||||||
|
|
||||||
|
|
||||||
|
SOURCE = Path(__file__).resolve().parents[1]
|
||||||
|
TRIPLE = "x86_64-unknown-linux-gnu"
|
||||||
|
PACKAGES = (
|
||||||
|
"gcc-14-x86-64-linux-gnu", "cpp-14-x86-64-linux-gnu", "libgcc-14-dev",
|
||||||
|
"libc6-dev", "linux-libc-dev", "binutils-x86-64-linux-gnu", "libc6", "libgcc-s1",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def native_input(path):
|
||||||
|
"""只保留原生 C 构建所需工具;Rust LTO 使用包内 LLVM,不需要 GCC LTO。"""
|
||||||
|
name = str(path)
|
||||||
|
if name.startswith("/usr/include/"):
|
||||||
|
return True
|
||||||
|
if path.parent == Path("/usr/bin"):
|
||||||
|
return path.name in {
|
||||||
|
"x86_64-linux-gnu-gcc-14", "x86_64-linux-gnu-as",
|
||||||
|
"x86_64-linux-gnu-ld", "x86_64-linux-gnu-ar", "x86_64-linux-gnu-ranlib",
|
||||||
|
}
|
||||||
|
if name.startswith("/usr/libexec/gcc/"):
|
||||||
|
return path.name in {"cc1", "collect2", "liblto_plugin.so", "lto-wrapper"}
|
||||||
|
if name.startswith("/usr/lib/gcc/"):
|
||||||
|
return "/include/" in name or path.name in {
|
||||||
|
"libgcc.a", "libgcc_eh.a", "libgcc_s.so", "crtbegin.o", "crtbeginS.o",
|
||||||
|
"crtbeginT.o", "crtend.o", "crtendS.o",
|
||||||
|
"liblto_plugin.so",
|
||||||
|
}
|
||||||
|
return path.parent in {Path("/usr/lib/x86_64-linux-gnu"), Path("/usr/lib64")}
|
||||||
|
|
||||||
|
|
||||||
|
def output(*arguments, **options):
|
||||||
|
return subprocess.check_output(arguments, text=True, **options).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def digest(path):
|
||||||
|
with path.open("rb") as stream:
|
||||||
|
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def copy(source, destination):
|
||||||
|
"""只解引用作者明确选定的工具文件,不复制 Cargo home 或用户配置。"""
|
||||||
|
if source.is_dir():
|
||||||
|
shutil.copytree(source, destination, dirs_exist_ok=True)
|
||||||
|
else:
|
||||||
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copyfile(source, destination)
|
||||||
|
destination.chmod(0o755 if os.access(source, os.X_OK) else 0o644)
|
||||||
|
|
||||||
|
|
||||||
|
def script(path, body):
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_text('#!/bin/sh\nset -eu\ntools=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)\n' + body)
|
||||||
|
path.chmod(0o755)
|
||||||
|
|
||||||
|
|
||||||
|
def native_tools(tools):
|
||||||
|
"""保留 Debian 工具的相对安装布局;glibc 只进链接 sysroot,不覆盖宿主加载器。"""
|
||||||
|
base = {str(Path(path).resolve()) for path in output("dpkg-query", "-L", "libc6").splitlines()}
|
||||||
|
packages = set(PACKAGES)
|
||||||
|
executables = []
|
||||||
|
for package in PACKAGES:
|
||||||
|
for name in output("dpkg-query", "-L", package).splitlines():
|
||||||
|
path = Path(name)
|
||||||
|
if not path.is_file() or not native_input(path):
|
||||||
|
continue
|
||||||
|
copy(path, tools / "native" / path.relative_to("/"))
|
||||||
|
# Debian 的链接脚本使用 /lib;发行包展开 usrmerge 别名,不改写官方库文件。
|
||||||
|
if package == "libc6":
|
||||||
|
copy(path, tools / "native" / path.relative_to("/usr"))
|
||||||
|
if os.access(path, os.X_OK):
|
||||||
|
with path.open("rb") as stream:
|
||||||
|
if stream.read(4) == b"\x7fELF":
|
||||||
|
executables.append(path)
|
||||||
|
for name in ("as", "ld", "ar"):
|
||||||
|
copy(Path(f"/usr/bin/x86_64-linux-gnu-{name}"), tools / "native/usr/bin" / name)
|
||||||
|
libraries = set()
|
||||||
|
for executable in executables:
|
||||||
|
listing = subprocess.run(["ldd", str(executable)], text=True, capture_output=True)
|
||||||
|
if listing.returncode and "not a dynamic executable" not in listing.stderr + listing.stdout:
|
||||||
|
raise RuntimeError(f"ldd {executable}: {listing.stderr}{listing.stdout}")
|
||||||
|
for line in listing.stdout.splitlines():
|
||||||
|
if "=> not found" in line:
|
||||||
|
raise RuntimeError(line)
|
||||||
|
fields = line.split()
|
||||||
|
if "=>" in fields and fields[2].startswith("/"):
|
||||||
|
library = Path(fields[2])
|
||||||
|
if str(library.resolve()) not in base:
|
||||||
|
libraries.add(library)
|
||||||
|
for library in sorted(libraries):
|
||||||
|
copy(library, tools / "lib" / library.name)
|
||||||
|
owner = output("dpkg-query", "-S", str(library.resolve())).splitlines()[0].split(": ", 1)[0]
|
||||||
|
packages.add(owner)
|
||||||
|
copy(Path("/usr/lib/x86_64-linux-gnu/libgcc_s.so.1"), tools / "lib/libgcc_s.so.1")
|
||||||
|
packages.add("libgcc-s1")
|
||||||
|
for package in sorted(packages):
|
||||||
|
name = package.split(":", 1)[0]
|
||||||
|
copy(Path("/usr/share/doc") / name / "copyright", tools / "licenses" / name / "copyright")
|
||||||
|
copy(Path("/usr/share/common-licenses"), tools / "licenses/common")
|
||||||
|
(tools / "native-packages.txt").write_text(output("dpkg-query", "-W", *sorted(packages)) + "\n")
|
||||||
|
script(tools / "bin/cc", '''export LD_LIBRARY_PATH="$tools/lib"
|
||||||
|
exec "$tools/native/usr/bin/x86_64-linux-gnu-gcc-14" \\
|
||||||
|
--sysroot="$tools/native" \\
|
||||||
|
-B"$tools/native/usr/lib/gcc/x86_64-linux-gnu/14/" \\
|
||||||
|
-B"$tools/native/usr/libexec/gcc/x86_64-linux-gnu/14/" \\
|
||||||
|
-B"$tools/native/usr/bin/" \\
|
||||||
|
-B"$tools/native/usr/lib/x86_64-linux-gnu/" "$@"
|
||||||
|
''')
|
||||||
|
|
||||||
|
|
||||||
|
def rust_tools(tools, version, vendor):
|
||||||
|
rust = Path(output("rustc", f"+{version}", "--print", "sysroot"))
|
||||||
|
if f"host: {TRIPLE}" not in output("rustc", f"+{version}", "-vV"):
|
||||||
|
raise RuntimeError(f"this package requires the official {TRIPLE} toolchain")
|
||||||
|
for name in ("cargo", "rustc"):
|
||||||
|
copy(rust / "bin" / name, tools / "rust/bin" / name)
|
||||||
|
for library in (rust / "lib").glob("*.so*"):
|
||||||
|
if not library.is_symlink():
|
||||||
|
copy(library, tools / "rust/lib" / library.name)
|
||||||
|
for name in ("lib", "bin"):
|
||||||
|
copy(rust / "lib/rustlib" / TRIPLE / name, tools / "rust/lib/rustlib" / TRIPLE / name)
|
||||||
|
# 只裁剪已链接的工具;标准库 rlib/rmeta 中的符号、类型元数据与位码仍用于编译。
|
||||||
|
binaries = [*(tools / "rust/bin").iterdir(), *(tools / "rust/lib").glob("*.so*")]
|
||||||
|
binaries.extend(path for path in (tools / "rust/lib/rustlib" / TRIPLE / "bin").rglob("*")
|
||||||
|
if path.is_file())
|
||||||
|
for binary in binaries:
|
||||||
|
# 官方 .so 目录也含链接脚本,按原样保留,只处理 ELF 文件。
|
||||||
|
with binary.open("rb") as stream:
|
||||||
|
if stream.read(4) == b"\x7fELF":
|
||||||
|
subprocess.run(["strip", "--strip-unneeded", str(binary)], check=True)
|
||||||
|
copy(rust / "share/doc/rust", tools / "licenses/rust")
|
||||||
|
if vendor:
|
||||||
|
copy(vendor, tools / "vendor")
|
||||||
|
else:
|
||||||
|
subprocess.run([
|
||||||
|
"cargo", f"+{version}", "vendor", "--locked", "--offline", "--versioned-dirs",
|
||||||
|
str(tools / "vendor"),
|
||||||
|
], cwd=SOURCE / "rust", check=True)
|
||||||
|
config = tools / ".cargo/config.toml"
|
||||||
|
config.parent.mkdir()
|
||||||
|
config.write_text('''[source.crates-io]
|
||||||
|
replace-with = "vendored-sources"
|
||||||
|
|
||||||
|
[source.vendored-sources]
|
||||||
|
directory = "vendor"
|
||||||
|
''')
|
||||||
|
script(tools / "bin/cargo", '''export CARGO_HOME="$tools/.cargo"
|
||||||
|
export RUSTC="$tools/rust/bin/rustc"
|
||||||
|
export CC="$tools/bin/cc"
|
||||||
|
export AR="$tools/native/usr/bin/x86_64-linux-gnu-ar"
|
||||||
|
export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER="$CC"
|
||||||
|
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER="$tools/bin/aarch64-linux-gnu-gcc"
|
||||||
|
export CC_aarch64_unknown_linux_gnu="$tools/bin/aarch64-linux-gnu-gcc"
|
||||||
|
export AR_aarch64_unknown_linux_gnu="$tools/cross/usr/bin/aarch64-linux-gnu-ar"
|
||||||
|
export LD_LIBRARY_PATH="$tools/cross/usr/lib/x86_64-linux-gnu:$tools/lib"
|
||||||
|
export PATH="$tools/native/usr/bin:/usr/bin:/bin"
|
||||||
|
exec "$tools/rust/bin/cargo" --config "$tools/.cargo/config.toml" "$@"
|
||||||
|
''')
|
||||||
|
script(tools / "bin/rustc", '''export LD_LIBRARY_PATH="$tools/lib"
|
||||||
|
exec "$tools/rust/bin/rustc" "$@"
|
||||||
|
''')
|
||||||
|
|
||||||
|
|
||||||
|
def prepare(compiler, work):
|
||||||
|
work.mkdir()
|
||||||
|
bundle = work / "dever"
|
||||||
|
bundle.mkdir()
|
||||||
|
for name in ("rust/Cargo.toml", "rust/Cargo.lock", "rust/src", "lib",
|
||||||
|
"skills/dever/SKILL.md", "GETTING_STARTED.md", "LANGUAGE.md",
|
||||||
|
"DOCUMENTATION.md", "sdk/README.md",
|
||||||
|
"test/rust/native/combinations.dever"):
|
||||||
|
copy(SOURCE / name, bundle / name)
|
||||||
|
for language in ("python", "javascript", "go", "c"):
|
||||||
|
for path in sorted((SOURCE / "sdk" / language).iterdir()):
|
||||||
|
if path.is_file():
|
||||||
|
copy(path, bundle / path.relative_to(SOURCE))
|
||||||
|
copy(compiler, bundle / "bin/dever-core")
|
||||||
|
script(bundle / "bin/dever", '''export DEVER_ROOT="$tools"
|
||||||
|
exec "$tools/bin/dever-core" "$@"
|
||||||
|
''')
|
||||||
|
return bundle
|
||||||
|
|
||||||
|
|
||||||
|
def aarch64_tools(tools, native, standard):
|
||||||
|
"""复用已准备的 Debian 交叉工具与官方目标标准库,不带旧 Dever 运行库。"""
|
||||||
|
copy(standard, tools / "rust/lib/rustlib/aarch64-unknown-linux-gnu")
|
||||||
|
for name in ("usr/aarch64-linux-gnu", "usr/lib/gcc-cross/aarch64-linux-gnu",
|
||||||
|
"usr/libexec/gcc-cross/aarch64-linux-gnu", "usr/lib/x86_64-linux-gnu"):
|
||||||
|
# libcc1 是 GDB 的表达式求值插件;包内 Rust/C 构建不包含调试器。
|
||||||
|
shutil.copytree(native / name, tools / "cross" / name,
|
||||||
|
ignore=shutil.ignore_patterns("libcc1.so"))
|
||||||
|
for name in ("gcc-14", "as", "ld", "ar", "ranlib"):
|
||||||
|
copy(native / "usr/bin" / f"aarch64-linux-gnu-{name}",
|
||||||
|
tools / "cross/usr/bin" / f"aarch64-linux-gnu-{name}")
|
||||||
|
for path in (native / "usr/share/doc").iterdir():
|
||||||
|
if any(name in path.name for name in ("aarch64", "arm64", "cross-base")):
|
||||||
|
copy(path / "copyright", tools / "licenses/cross" / path.name / "copyright")
|
||||||
|
script(tools / "bin/aarch64-linux-gnu-gcc", '''export LD_LIBRARY_PATH="$tools/cross/usr/lib/x86_64-linux-gnu:$tools/lib"
|
||||||
|
exec "$tools/cross/usr/bin/aarch64-linux-gnu-gcc-14" \\
|
||||||
|
--sysroot="$tools/cross" \\
|
||||||
|
-B"$tools/cross/usr/lib/gcc-cross/aarch64-linux-gnu/14/" \\
|
||||||
|
-B"$tools/cross/usr/libexec/gcc-cross/aarch64-linux-gnu/14/" \\
|
||||||
|
-B"$tools/cross/usr/bin/" "$@"
|
||||||
|
''')
|
||||||
|
|
||||||
|
|
||||||
|
def record(bundle, compiler):
|
||||||
|
files = []
|
||||||
|
for path in sorted(bundle.rglob("*")):
|
||||||
|
if path.is_symlink():
|
||||||
|
raise RuntimeError(f"release contains a symlink: {path}")
|
||||||
|
if path.is_file():
|
||||||
|
files.append({"path": path.relative_to(bundle).as_posix(),
|
||||||
|
"bytes": path.stat().st_size, "sha256": digest(path),
|
||||||
|
"executable": os.access(path, os.X_OK)})
|
||||||
|
version = tomllib.loads((bundle / "rust/Cargo.toml").read_text())["package"]["version"]
|
||||||
|
if output(str(compiler), "--version") != f"dever {version}":
|
||||||
|
raise RuntimeError("compiler version differs from release sources")
|
||||||
|
manifest = {"format": "dever-development-1", "version": version, "target": TRIPLE,
|
||||||
|
"rust": "1.95.0", "compiler_sha256": digest(compiler), "files": files}
|
||||||
|
(bundle / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
|
||||||
|
return manifest
|
||||||
|
|
||||||
|
|
||||||
|
def external_tools(home, bundle):
|
||||||
|
"""只选独立准备目录中的工具和下载缓存;不带日志、配置或编译缓存。"""
|
||||||
|
home = home.resolve(strict=True)
|
||||||
|
selected = ["tools/go", "tools/node", "tools/uv", "tools/python", "tools/patchelf",
|
||||||
|
"go/modules", "npm/_cacache", "uv/archive-v0", "uv/wheels-v5",
|
||||||
|
"uv/simple-v18", "uv/sdists-v9"]
|
||||||
|
for name in selected:
|
||||||
|
source = home / name
|
||||||
|
if not source.is_dir():
|
||||||
|
raise RuntimeError(f"external distribution input is not prepared: {name}")
|
||||||
|
for path in source.rglob("*"):
|
||||||
|
if path.is_symlink() and not path.resolve(strict=True).is_relative_to(home):
|
||||||
|
raise RuntimeError(f"external cache link escapes its prepared directory: {path}")
|
||||||
|
copy(source, bundle / "external" / name)
|
||||||
|
script(bundle / "bin/dever", '''export DEVER_ROOT="$tools"
|
||||||
|
export DEVER_HOME="${DEVER_HOME:-$tools/external}"
|
||||||
|
exec "$tools/bin/dever-core" "$@"
|
||||||
|
''')
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--compiler", required=True, type=Path)
|
||||||
|
parser.add_argument("--work", required=True, type=Path, help="new staging directory")
|
||||||
|
parser.add_argument("--output", required=True, type=Path, help="new .tar.xz or .tar.gz archive")
|
||||||
|
parser.add_argument("--external-home", type=Path, help="isolated prepared DEVER_HOME to include official tools and dependency download caches")
|
||||||
|
parser.add_argument("--aarch64-native", type=Path, help="prepared Debian 13 cross-GCC root; paired with --aarch64-std")
|
||||||
|
parser.add_argument("--aarch64-std", type=Path, help="official Rust 1.95 rustlib/aarch64-unknown-linux-gnu directory")
|
||||||
|
args = parser.parse_args()
|
||||||
|
if bool(args.aarch64_native) != bool(args.aarch64_std):
|
||||||
|
parser.error("--aarch64-native and --aarch64-std must be provided together")
|
||||||
|
system = Path("/etc/os-release").read_text()
|
||||||
|
if 'ID=debian\n' not in system or 'VERSION_ID="13"' not in system:
|
||||||
|
parser.error("prepare this package in the Debian 13 development container")
|
||||||
|
args.compiler = args.compiler.resolve(strict=True)
|
||||||
|
args.work = args.work.absolute()
|
||||||
|
args.output = args.output.absolute()
|
||||||
|
if not args.output.name.endswith((".tar.xz", ".tar.gz")):
|
||||||
|
parser.error("output must end in .tar.xz or .tar.gz")
|
||||||
|
checksum = Path(str(args.output) + ".sha256")
|
||||||
|
if args.output.exists() or checksum.exists():
|
||||||
|
parser.error("output archive and checksum must not exist")
|
||||||
|
bundle = prepare(args.compiler, args.work)
|
||||||
|
tools = bundle / "toolchain"
|
||||||
|
tools.mkdir()
|
||||||
|
native_tools(tools)
|
||||||
|
rust_tools(tools, "1.95.0", None)
|
||||||
|
if args.aarch64_native:
|
||||||
|
aarch64_tools(tools, args.aarch64_native.resolve(strict=True), args.aarch64_std.resolve(strict=True))
|
||||||
|
if args.external_home:
|
||||||
|
external_tools(args.external_home, bundle)
|
||||||
|
copy(SOURCE / "build/README.md", bundle / "DEVELOPMENT.md")
|
||||||
|
manifest = record(bundle, args.compiler)
|
||||||
|
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
compressor = "xz -3 -T4" if args.output.suffix == ".xz" else "gzip -6"
|
||||||
|
with args.output.open("xb") as stream:
|
||||||
|
subprocess.run(["tar", "-C", str(args.work), "-I", compressor, "-cf", "-", "dever"],
|
||||||
|
stdout=stream, check=True)
|
||||||
|
with checksum.open("x") as stream:
|
||||||
|
stream.write(f"{digest(args.output)} {args.output.name}\n")
|
||||||
|
print(json.dumps({"archive": str(args.output), "bytes": args.output.stat().st_size,
|
||||||
|
"files": len(manifest["files"]), "compiler_sha256": digest(args.compiler)}))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+169
@@ -0,0 +1,169 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""生成内置原生构建能力的 Linux x86_64 dever。"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import struct
|
||||||
|
import subprocess
|
||||||
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import tomllib
|
||||||
|
|
||||||
|
from development import SOURCE, TRIPLE, digest, output
|
||||||
|
|
||||||
|
|
||||||
|
FOOTER = b"DVRLOC01"
|
||||||
|
RUST = "+1.95.0"
|
||||||
|
MANIFEST = str(SOURCE / "rust/Cargo.toml")
|
||||||
|
NATIVE_PACKAGES = ("libc6", "libc6-dev", "libgcc-s1", "zlib1g")
|
||||||
|
|
||||||
|
|
||||||
|
def runtime(work):
|
||||||
|
command = ["cargo", RUST, "build", "--manifest-path", MANIFEST,
|
||||||
|
"-p", "dever-runtime", "--all-features", "--locked", "--offline", "--release",
|
||||||
|
"--message-format=json"]
|
||||||
|
with (work / "runtime.jsonl").open("w+") as events:
|
||||||
|
subprocess.run(command, stdout=events, check=True)
|
||||||
|
events.seek(0)
|
||||||
|
for line in events:
|
||||||
|
event = json.loads(line)
|
||||||
|
if event["reason"] == "compiler-artifact":
|
||||||
|
for name in event["filenames"]:
|
||||||
|
path = Path(name)
|
||||||
|
if path.suffix in {".rlib", ".so"}:
|
||||||
|
yield f"crates/{path.name}", path
|
||||||
|
elif event["reason"] == "build-script-executed" and event["linked_libs"]:
|
||||||
|
for path in Path(event["out_dir"]).glob("*.a"):
|
||||||
|
yield f"native/{path.name}", path
|
||||||
|
|
||||||
|
|
||||||
|
def licenses(rust, work):
|
||||||
|
notices = work / "THIRD-PARTY.txt"
|
||||||
|
docs = rust / "share/doc/rust"
|
||||||
|
packages = json.loads(output(
|
||||||
|
"cargo", RUST, "metadata", "--manifest-path", MANIFEST, "--locked", "--offline",
|
||||||
|
"--all-features", "--filter-platform", TRIPLE, "--format-version", "1",
|
||||||
|
))["packages"]
|
||||||
|
with notices.open("wb") as stream:
|
||||||
|
def copy_notice(name, path):
|
||||||
|
stream.write(f"\n=== {name} ===\n".encode())
|
||||||
|
with path.open("rb") as notice:
|
||||||
|
shutil.copyfileobj(notice, stream)
|
||||||
|
stream.write(b"\n")
|
||||||
|
|
||||||
|
stream.write(b"Dever distribution: third-party notices\n")
|
||||||
|
for path in sorted(docs.rglob("*")):
|
||||||
|
if path.is_file():
|
||||||
|
copy_notice(f"Rust {RUST[1:]}/{path.relative_to(docs)}", path)
|
||||||
|
for name, version in (line.split("\t") for line in output(
|
||||||
|
"dpkg-query", "-W", *NATIVE_PACKAGES).splitlines()):
|
||||||
|
copy_notice(f"Debian {name} {version}",
|
||||||
|
Path("/usr/share/doc") / name.split(":")[0] / "copyright")
|
||||||
|
for path in sorted(Path("/usr/share/common-licenses").iterdir()):
|
||||||
|
if path.is_file() and not path.is_symlink():
|
||||||
|
copy_notice(f"Debian common licenses/{path.name}", path)
|
||||||
|
for package in packages:
|
||||||
|
if not package["source"]:
|
||||||
|
continue
|
||||||
|
name = f'{package["name"]} {package["version"]}'
|
||||||
|
stream.write(f'\n{name}: {package["license"]}\n'.encode())
|
||||||
|
directory = Path(package["manifest_path"]).parent
|
||||||
|
files = {path for path in directory.iterdir() if path.is_file() and
|
||||||
|
path.name.upper().startswith(("LICENSE", "LICENCE", "COPYING", "COPYRIGHT", "NOTICE", "UNLICENSE"))}
|
||||||
|
if package["license_file"]:
|
||||||
|
files.add(directory / package["license_file"])
|
||||||
|
for path in sorted(files):
|
||||||
|
copy_notice(f"{name}/{path.name}", path)
|
||||||
|
return notices
|
||||||
|
|
||||||
|
|
||||||
|
def inputs(work):
|
||||||
|
rust = Path(output("rustc", RUST, "--print", "sysroot"))
|
||||||
|
if f"host: {TRIPLE}" not in output("rustc", RUST, "-vV"):
|
||||||
|
raise RuntimeError(f"expected a {TRIPLE} release environment")
|
||||||
|
standard = rust / "lib/rustlib" / TRIPLE
|
||||||
|
engine, = (rust / "lib").glob("librustc_driver-*.so")
|
||||||
|
backend, = (rust / "lib").glob("libLLVM.so.*")
|
||||||
|
native = Path("/usr/lib/x86_64-linux-gnu")
|
||||||
|
selected = {
|
||||||
|
"THIRD-PARTY.txt": licenses(rust, work),
|
||||||
|
"bin/compile": rust / "bin/rustc",
|
||||||
|
"bin/link": standard / "bin/rust-lld",
|
||||||
|
"lib/engine": engine,
|
||||||
|
"lib/backend": backend,
|
||||||
|
"lib/zlib": native / "libz.so.1",
|
||||||
|
}
|
||||||
|
for path in (standard / "lib").iterdir():
|
||||||
|
if path.suffix in {".rlib", ".rmeta"}:
|
||||||
|
selected[f"sysroot/lib/rustlib/{TRIPLE}/lib/{path.name}"] = path
|
||||||
|
for name in ("Scrt1.o", "crti.o", "crtn.o", "libc_nonshared.a", "libdl.a", "librt.a",
|
||||||
|
"libpthread.a", "libutil.a"):
|
||||||
|
selected[f"crt/{name}"] = native / name
|
||||||
|
for library in ("libc", "libm", "libgcc_s"):
|
||||||
|
suffix = "1" if library == "libgcc_s" else "6"
|
||||||
|
selected[f"crt/{library}.so"] = native / f"{library}.so.{suffix}"
|
||||||
|
for name, path in runtime(work):
|
||||||
|
previous = selected.setdefault(name, path)
|
||||||
|
if previous != path:
|
||||||
|
raise RuntimeError(f"conflicting build resource {name}: {previous} and {path}")
|
||||||
|
return selected
|
||||||
|
|
||||||
|
|
||||||
|
def append_resources(destination, selected, work):
|
||||||
|
with subprocess.Popen(["xz", "-3", "-T2"], stdin=subprocess.PIPE, stdout=destination) as xz:
|
||||||
|
with tarfile.open(fileobj=xz.stdin, mode="w|") as archive:
|
||||||
|
for name, path in sorted(selected.items()):
|
||||||
|
if name.startswith(("bin/", "lib/")) or path.suffix == ".so":
|
||||||
|
stripped = work / "elf"
|
||||||
|
shutil.copyfile(path, stripped)
|
||||||
|
subprocess.run(["strip", "--strip-unneeded", str(stripped)], check=True)
|
||||||
|
path = stripped
|
||||||
|
path = path.resolve(strict=True)
|
||||||
|
info = archive.gettarinfo(str(path), arcname=name)
|
||||||
|
info.mode, info.mtime, info.uid, info.gid = 0o600, 0, 0, 0
|
||||||
|
info.uname = info.gname = ""
|
||||||
|
with path.open("rb") as source:
|
||||||
|
archive.addfile(info, source)
|
||||||
|
xz.stdin.close()
|
||||||
|
if xz.wait():
|
||||||
|
raise RuntimeError("compressing native build resources failed")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--compiler", type=Path, required=True)
|
||||||
|
parser.add_argument("--output", type=Path, required=True)
|
||||||
|
args = parser.parse_args()
|
||||||
|
compiler = args.compiler.resolve(strict=True)
|
||||||
|
destination = args.output.absolute()
|
||||||
|
version = tomllib.loads((SOURCE / "rust/Cargo.toml").read_text())["package"]["version"]
|
||||||
|
if output(str(compiler), "--version") != f"dever {version}":
|
||||||
|
parser.error("compiler and source versions differ")
|
||||||
|
with compiler.open("rb") as source:
|
||||||
|
if source.read(4) != b"\x7fELF":
|
||||||
|
parser.error("expected a native ELF compiler")
|
||||||
|
source.seek(-len(FOOTER), os.SEEK_END)
|
||||||
|
if source.read() == FOOTER:
|
||||||
|
parser.error("compiler already contains a native build image")
|
||||||
|
if destination.exists():
|
||||||
|
parser.error("output must be a new path")
|
||||||
|
with tempfile.TemporaryDirectory(prefix="dever-native-", dir=destination.parent) as work:
|
||||||
|
work = Path(work)
|
||||||
|
selected = inputs(work)
|
||||||
|
stage = work / "dever"
|
||||||
|
shutil.copyfile(compiler, stage)
|
||||||
|
with stage.open("r+b", buffering=0) as stream:
|
||||||
|
start = stream.seek(0, os.SEEK_END)
|
||||||
|
append_resources(stream, selected, work)
|
||||||
|
end = stream.seek(0, os.SEEK_END)
|
||||||
|
stream.write(struct.pack("<Q", end - start) + FOOTER)
|
||||||
|
stage.chmod(0o755)
|
||||||
|
os.link(stage, destination)
|
||||||
|
print(f"{digest(destination)} {destination.name}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
node_modules/
|
||||||
|
*.vsix
|
||||||
|
dist/
|
||||||
|
/core.[0-9]*
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
**/*
|
||||||
|
!package.json
|
||||||
|
!README.md
|
||||||
|
!language-configuration.json
|
||||||
|
!syntaxes/**
|
||||||
|
!extension.cjs
|
||||||
|
!graph.cjs
|
||||||
|
!workflow.cjs
|
||||||
|
!inspection.cjs
|
||||||
|
!navigation.cjs
|
||||||
|
!reading.cjs
|
||||||
|
!hover.cjs
|
||||||
|
!dist/**
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Dever 源码与流程阅读
|
||||||
|
|
||||||
|
插件使用项目编译器的 inspect,提供定义、引用、双向调用层级、CodeLens、诊断、悬浮说明和可点击流程。Dever: Show Calls 显示当前能力的流程及调用关系,子调用可以原地展开、折叠。流程页先显示业务说明和流程图;入口未单独写说明时,使用它绑定的处理函数说明。展开「实现细节」可查看签名、调用关系与长节点原文。Dever: Open Domain Links 打开由 inspect --links 生成且仍有效的领域文档。
|
||||||
|
|
||||||
|
在 VS Code 设置 dever.command 为编译器的绝对路径数组;远程工作区使用远程主机可执行的路径。检查命令不经过 shell,不会自动安装或替换编译器。未信任工作区不能启动源码检查。
|
||||||
|
|
||||||
|
导航依据磁盘已保存内容及 SHA-256;未保存修改显示状态提示并拒绝旧位置跳转。局部错误时仍可导航独立有效定义。当前支持普通函数、rule、flow、loop、CMD、HTTP、Job 与具名 SQL;步骤种类、守卫失败出口和具体调用均来自已检查程序。loop 展示来源、take/累积状态初始化、过滤、排序键、每行短路、循环回边、稳定排序后截取及 index 重复键失败;foldUntil 先更新状态再判断 stop,结束本行后仍走向下一输出行。同步 walk 展示 Next/Done、状态推进和停止拉取;Bytes 来源沿用逐元素循环图。随包标准库函数可以按真实调用展开并跳转源码。并发任务和流展示实际分支、汇合、取消与资源释放路径。HTTP 入口展示站点、认证、可信租户选库、实时权限和事务成功/失败出口;Job 入队是单独的队列边,不画成同步调用。
|
||||||
|
|
||||||
|
在既有 dev 容器的 editor/vscode 目录中执行 npm run build。依赖由 package-lock.json 固定,构建产物位于 dist;不手工修改产物。测试命令为 npm test、npm run test:navigation、npm run test:flows。
|
||||||
|
|
||||||
|
高亮测试额外传入 --markdown-grammar <现有 VS Code Markdown grammar>;导航和流程测试设置 DEVER_TEST_BIN 为本次编译器。浏览器测试设置 DEVER_BROWSER_TOOLS 为已有 playwright-core、@sparticuz/chromium 的依赖目录,并加载该浏览器的动态库及字体配置。共享 dev 当前使用 /cache/node/manage-browser/native/lib 和 /tmp/fonts,对应 LD_LIBRARY_PATH、FONTCONFIG_PATH。测试调用真实编译器,并在真实浏览器中核对渲染、源码点击及子流程展开;VS Code API 边界使用替身。
|
||||||
|
|
||||||
|
插件没有第二套语言解析器、后台编译服务或拖拽改源码能力。流程图描述静态调用关系;实际请求的执行顺序需通过运行日志或追踪确认。
|
||||||
|
|
||||||
|
静态 handler 的阅读名称包含具体绑定,不显示编译器的生成摘要。相同源码的不同绑定分别展开实际目标;文档仍绑定原始完整函数名,只写一份。未绑定模板可导航到声明,不生成执行图。
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
const esbuild = require('esbuild');
|
||||||
|
const fs = require('node:fs/promises');
|
||||||
|
|
||||||
|
async function build() {
|
||||||
|
await fs.mkdir('dist', { recursive: true });
|
||||||
|
await Promise.all([
|
||||||
|
fs.copyFile(require.resolve('@mermaid-js/tiny'), 'dist/mermaid.js'),
|
||||||
|
fs.copyFile('flow-browser.js', 'dist/flow-browser.js'),
|
||||||
|
esbuild.build({ entryPoints: ['flow-preview.cjs'], bundle: true, outfile: 'dist/flow-preview.cjs', minify: true, legalComments: 'eof', platform: 'node', external: ['vscode'] })
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
build().catch(error => { console.error(error); process.exitCode = 1; });
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
const { registerNavigation } = require('./navigation.cjs');
|
||||||
|
|
||||||
|
function activate(context) {
|
||||||
|
registerNavigation(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { activate };
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
(() => {
|
||||||
|
const mermaid = globalThis.mermaid;
|
||||||
|
const vscode = acquireVsCodeApi();
|
||||||
|
mermaid.initialize({ startOnLoad: false, securityLevel: 'loose', theme: document.body.classList.contains('vscode-dark') ? 'dark' : 'default', flowchart: { htmlLabels: false } });
|
||||||
|
let sequence = 0;
|
||||||
|
let request = 0;
|
||||||
|
const pending = new Map();
|
||||||
|
// Mermaid 维护全局图状态;串行渲染,避免展开多个调用时争用临时节点。
|
||||||
|
let rendering = Promise.resolve();
|
||||||
|
function render(root) {
|
||||||
|
rendering = rendering.then(async () => {
|
||||||
|
for (const code of root.querySelectorAll('pre > code.language-mermaid')) {
|
||||||
|
try {
|
||||||
|
const { svg } = await mermaid.render('dever-flow-' + sequence++, code.textContent);
|
||||||
|
const container = document.createElement('div');
|
||||||
|
container.className = 'dever-flow';
|
||||||
|
container.innerHTML = svg;
|
||||||
|
code.parentElement.replaceWith(container);
|
||||||
|
} catch (error) {
|
||||||
|
const message = document.createElement('p');
|
||||||
|
message.className = 'dever-flow-error';
|
||||||
|
message.textContent = '流程图渲染失败:' + error.message;
|
||||||
|
code.parentElement.before(message);
|
||||||
|
}
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 0));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return rendering;
|
||||||
|
}
|
||||||
|
window.addEventListener('message', event => {
|
||||||
|
const message = event.data;
|
||||||
|
const target = pending.get(message.request);
|
||||||
|
if (!target) return;
|
||||||
|
if (message.type === 'expanded') {
|
||||||
|
target.innerHTML = message.html;
|
||||||
|
pending.delete(message.request);
|
||||||
|
render(target);
|
||||||
|
} else if (message.type === 'expandError') {
|
||||||
|
target.textContent = message.message;
|
||||||
|
pending.delete(message.request);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
document.addEventListener('click', event => {
|
||||||
|
const link = event.target.closest('a');
|
||||||
|
if (!link) return;
|
||||||
|
const href = link.getAttribute('href') || link.getAttribute('xlink:href');
|
||||||
|
if (!href) return;
|
||||||
|
event.preventDefault();
|
||||||
|
if (href.startsWith('#')) document.getElementById(decodeURIComponent(href.slice(1)))?.scrollIntoView();
|
||||||
|
else if (href.startsWith('command:dever.expandFlow?')) {
|
||||||
|
const details = document.createElement('details');
|
||||||
|
details.open = true;
|
||||||
|
const summary = document.createElement('summary');
|
||||||
|
summary.textContent = link.textContent;
|
||||||
|
const body = document.createElement('div');
|
||||||
|
body.textContent = '正在读取已检查的子流程…';
|
||||||
|
details.append(summary, body);
|
||||||
|
link.replaceWith(details);
|
||||||
|
pending.set(++request, body);
|
||||||
|
vscode.postMessage({ type: 'expand', href, request });
|
||||||
|
} else vscode.postMessage({ type: 'open', href });
|
||||||
|
});
|
||||||
|
render(document).then(() => {
|
||||||
|
document.getElementById(document.body.dataset.anchor)?.scrollIntoView();
|
||||||
|
document.body.dataset.rendered = 'true';
|
||||||
|
});
|
||||||
|
})();
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
const vscode = require('vscode');
|
||||||
|
const fs = require('node:fs/promises');
|
||||||
|
const path = require('node:path');
|
||||||
|
const { randomBytes } = require('node:crypto');
|
||||||
|
const { pathToFileURL, fileURLToPath } = require('node:url');
|
||||||
|
const markdown = require('markdown-it')({ html: true });
|
||||||
|
// 只渲染预览使用的锚点和折叠标签;业务文档里的其他 HTML 按文本显示。
|
||||||
|
markdown.renderer.rules.html_inline = (tokens, i) => /^(?:<a id="flow-[a-zA-Z0-9_-]+">|<\/a>)$/.test(tokens[i].content) ? tokens[i].content : markdown.utils.escapeHtml(tokens[i].content);
|
||||||
|
markdown.renderer.rules.html_block = (tokens, i) => /^(?:<a id="flow-[a-zA-Z0-9_-]+"><\/a>|<details><summary>实现细节<\/summary>|<\/details>)\s*$/.test(tokens[i].content) ? tokens[i].content : tokens[i].content.startsWith('<!--') ? '' : markdown.utils.escapeHtml(tokens[i].content);
|
||||||
|
const validateLink = markdown.validateLink;
|
||||||
|
markdown.validateLink = href => href.startsWith('file:') || validateLink(href);
|
||||||
|
|
||||||
|
// 流程图与调用表共用阅读面板;链接打开真实源码或当前索引。
|
||||||
|
async function openFlowPreview(context, target, root, calls, verifyTarget = calls?.verify) {
|
||||||
|
const panel = vscode.window.createWebviewPanel('dever.links', 'Dever 调用流程', vscode.ViewColumn.Beside, {
|
||||||
|
enableScripts: true,
|
||||||
|
localResourceRoots: [vscode.Uri.joinPath(context.extensionUri, 'dist')]
|
||||||
|
});
|
||||||
|
let current = target.fsPath;
|
||||||
|
let revision = 0;
|
||||||
|
async function render(filename, anchor = '') {
|
||||||
|
const generation = ++revision;
|
||||||
|
let text;
|
||||||
|
try {
|
||||||
|
text = calls ? await calls.read(filename) : await fs.readFile(filename, 'utf8');
|
||||||
|
} catch (error) {
|
||||||
|
// 保存触发的新一轮读取已经接管面板,旧读取失效时让新一轮继续。
|
||||||
|
if (generation !== revision) return;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
if (!calls && !text.startsWith('<!-- Generated by dever inspect --links. Do not edit. -->')) {
|
||||||
|
throw new Error('此文件不是生成的领域索引,请运行 dever inspect . --links。');
|
||||||
|
}
|
||||||
|
if (generation !== revision) return;
|
||||||
|
current = filename;
|
||||||
|
panel.title = calls ? `Dever · ${filename}` : `Dever · ${path.basename(path.dirname(filename))}`;
|
||||||
|
const script = panel.webview.asWebviewUri(vscode.Uri.joinPath(context.extensionUri, 'dist', 'flow-browser.js'));
|
||||||
|
const mermaid = panel.webview.asWebviewUri(vscode.Uri.joinPath(context.extensionUri, 'dist', 'mermaid.js'));
|
||||||
|
const nonce = randomBytes(16).toString('hex');
|
||||||
|
panel.webview.html = `<!DOCTYPE html><html><head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-${nonce}'; style-src ${panel.webview.cspSource} 'unsafe-inline'; img-src ${panel.webview.cspSource} data:; font-src ${panel.webview.cspSource} data:;">
|
||||||
|
<style>body{max-width:1100px;margin:24px auto;padding:0 24px;font:var(--vscode-font-size) var(--vscode-font-family);color:var(--vscode-editor-foreground);background:var(--vscode-editor-background)}a{color:var(--vscode-textLink-foreground)}table{border-collapse:collapse}td,th{padding:6px 12px;border:1px solid var(--vscode-panel-border)}pre{overflow:auto}details{margin:16px 0}.dever-flow{overflow:auto;margin:20px 0}.dever-flow svg{max-width:none!important}.dever-flow-error{color:var(--vscode-errorForeground)}</style>
|
||||||
|
</head><body data-anchor="${markdown.utils.escapeHtml(anchor)}">${markdown.render(text)}
|
||||||
|
<script nonce="${nonce}" src="${mermaid}"></script><script nonce="${nonce}" src="${script}"></script></body></html>`;
|
||||||
|
}
|
||||||
|
const messages = panel.webview.onDidReceiveMessage(async message => {
|
||||||
|
if (typeof message.href !== 'string') return;
|
||||||
|
if (message.type === 'expand' && calls) {
|
||||||
|
const generation = revision;
|
||||||
|
try {
|
||||||
|
if (!message.href.startsWith('command:dever.expandFlow?')) throw new Error('无效的子流程链接。');
|
||||||
|
const [requestedRoot, name] = JSON.parse(decodeURIComponent(message.href.split('?')[1]));
|
||||||
|
if (requestedRoot !== root) throw new Error('链接超出当前项目。');
|
||||||
|
const text = await calls.read(name);
|
||||||
|
if (generation === revision) await panel.webview.postMessage({ type: 'expanded', request: message.request, html: markdown.render(text) });
|
||||||
|
} catch (error) {
|
||||||
|
await panel.webview.postMessage({ type: 'expandError', request: message.request, message: error.message });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (message.type !== 'open') return;
|
||||||
|
try {
|
||||||
|
if (calls && message.href.startsWith('command:dever.showCalls?')) {
|
||||||
|
const [requestedRoot, name] = JSON.parse(decodeURIComponent(message.href.split('?')[1]));
|
||||||
|
if (requestedRoot !== root) throw new Error('链接超出当前项目。');
|
||||||
|
await render(name);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const destination = new URL(message.href, pathToFileURL(calls ? root + path.sep : current));
|
||||||
|
if (destination.protocol !== 'file:') throw new Error('流程阅读页只打开项目源码、说明和领域索引。');
|
||||||
|
const filename = fileURLToPath(destination);
|
||||||
|
const relative = path.relative(root, filename);
|
||||||
|
const outside = relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative);
|
||||||
|
if (outside && !verifyTarget) throw new Error('链接超出当前项目。');
|
||||||
|
if (!outside && !calls && path.basename(filename) === 'link.md') {
|
||||||
|
await render(filename, decodeURIComponent(destination.hash.slice(1)));
|
||||||
|
} else {
|
||||||
|
const location = /^#L(\d+)(?:,(\d+))?$/.exec(destination.hash);
|
||||||
|
const line = location ? Number(location[1]) - 1 : 0;
|
||||||
|
const column = location?.[2] ? Number(location[2]) - 1 : 0;
|
||||||
|
const document = verifyTarget
|
||||||
|
? await verifyTarget(filename)
|
||||||
|
: await vscode.workspace.openTextDocument(vscode.Uri.file(filename));
|
||||||
|
await vscode.window.showTextDocument(document, { viewColumn: vscode.ViewColumn.One, selection: new vscode.Range(line, column, line, column) });
|
||||||
|
}
|
||||||
|
} catch (error) { vscode.window.showErrorMessage(error.message); }
|
||||||
|
});
|
||||||
|
panel.onDidDispose(() => { revision++; messages.dispose(); });
|
||||||
|
if (calls) {
|
||||||
|
const changed = calls.changed.event(() => render(current).catch(error => {
|
||||||
|
panel.dispose();
|
||||||
|
vscode.window.showErrorMessage(error.message);
|
||||||
|
}));
|
||||||
|
panel.onDidDispose(() => changed.dispose());
|
||||||
|
}
|
||||||
|
context.subscriptions.push(panel);
|
||||||
|
try { await render(calls ? calls.name : current); } catch (error) { panel.dispose(); throw error; }
|
||||||
|
return panel;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { openFlowPreview };
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
// 编译器结果按身份建立邻接索引;每个 CodeLens 不再扫描整张调用图。
|
||||||
|
const indices = new WeakMap();
|
||||||
|
function graph(index) {
|
||||||
|
if (indices.has(index)) return indices.get(index);
|
||||||
|
const symbols = new Map(index.symbols.map(symbol => [symbol.id, symbol]));
|
||||||
|
const names = new Map(index.symbols.map(symbol => [symbol.name, symbol]));
|
||||||
|
const incoming = new Map(), outgoing = new Map(), sites = new Map(), declarations = new Map();
|
||||||
|
for (const call of index.calls) {
|
||||||
|
for (const [map, key] of [[incoming, call.callee], [outgoing, call.caller], [sites, call.site.file]]) {
|
||||||
|
if (!map.has(key)) map.set(key, []);
|
||||||
|
map.get(key).push(call);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const symbol of index.symbols) for (const site of symbol.declarations) {
|
||||||
|
if (!declarations.has(site.file)) declarations.set(site.file, []);
|
||||||
|
declarations.get(site.file).push(symbol);
|
||||||
|
}
|
||||||
|
const result = { symbols, names, incoming, outgoing, sites, declarations };
|
||||||
|
indices.set(index, result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
function compare(left, right) { return left.line - right.line || left.character - right.character; }
|
||||||
|
function contains(range, position) { return compare(range.start, position) <= 0 && compare(position, range.end) < 0; }
|
||||||
|
function at(index, file, position) {
|
||||||
|
const edges = graph(index).sites.get(file) || [];
|
||||||
|
const calls = edges.filter(call => contains(call.site, position));
|
||||||
|
// 嵌套调用点击优先采用最小范围,不把外层调用也当成定义目标。
|
||||||
|
calls.sort((a, b) => compare(b.site.start, a.site.start) || compare(a.site.end, b.site.end));
|
||||||
|
if (calls.length) {
|
||||||
|
const first = calls[0].site;
|
||||||
|
return [...new Set(calls.filter(call => compare(call.site.start, first.start) === 0
|
||||||
|
&& compare(call.site.end, first.end) === 0).map(call => call.callee))].map(id => graph(index).symbols.get(id));
|
||||||
|
}
|
||||||
|
return (graph(index).declarations.get(file) || []).filter(symbol => symbol.declarations.some(site => contains(site, position)));
|
||||||
|
}
|
||||||
|
function relations(index, id, incoming) {
|
||||||
|
const adjacency = incoming ? graph(index).incoming : graph(index).outgoing;
|
||||||
|
const grouped = new Map();
|
||||||
|
for (const call of adjacency.get(id) || []) {
|
||||||
|
const target = incoming ? call.caller : call.callee;
|
||||||
|
if (!grouped.has(target)) grouped.set(target, []);
|
||||||
|
grouped.get(target).push(call);
|
||||||
|
}
|
||||||
|
return [...grouped].map(([id, calls]) => ({ symbol: graph(index).symbols.get(id), calls }));
|
||||||
|
}
|
||||||
|
module.exports = { graph, at, relations, contains };
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
const vscode = require('vscode');
|
||||||
|
const { relations } = require('./graph.cjs');
|
||||||
|
const { uri } = require('./inspection.cjs');
|
||||||
|
|
||||||
|
function command(name, args) {
|
||||||
|
return `command:${name}?${encodeURIComponent(JSON.stringify(args))}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function description(inspection, index, symbol, root) {
|
||||||
|
const find = target => index.documentation.find(item => item.symbol === target.source_name);
|
||||||
|
let value = find(symbol);
|
||||||
|
if (!value) {
|
||||||
|
const binding = relations(index, symbol.id, false).find(item => item.calls.some(call => call.kind === 'entry'));
|
||||||
|
if (binding) value = find(binding.symbol);
|
||||||
|
}
|
||||||
|
if (!value) return undefined;
|
||||||
|
const documentIndex = { files: [index.documentation_files[value.file]] };
|
||||||
|
await inspection.verify(documentIndex, 0, root);
|
||||||
|
return { ...value, uri: uri(documentIndex, 0, root) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function registerHover(context, selector, inspection, lookup) {
|
||||||
|
context.subscriptions.push(vscode.languages.registerHoverProvider(selector, {
|
||||||
|
async provideHover(document, position) {
|
||||||
|
const state = await lookup(document, position);
|
||||||
|
if (!state?.symbols.length) return undefined;
|
||||||
|
const contents = [];
|
||||||
|
for (const symbol of state.symbols) {
|
||||||
|
const page = new vscode.MarkdownString();
|
||||||
|
page.isTrusted = { enabledCommands: ['dever.showCalls', 'dever.openDomainLinks', 'dever.previewDocumentation'] };
|
||||||
|
page.appendMarkdown(`**${symbol.name}**\n\n`);
|
||||||
|
if (state.index.documentation_errors.length) {
|
||||||
|
page.appendMarkdown('**说明校验未通过。** 失效或重复的标题详见“Dever”输出;签名和调用关系仍来自源码。\n\n');
|
||||||
|
}
|
||||||
|
for (const signature of symbol.signatures) page.appendCodeblock(signature, 'dever');
|
||||||
|
const detail = await description(inspection, state.index, symbol, state.root);
|
||||||
|
if (detail) {
|
||||||
|
page.baseUri = detail.uri;
|
||||||
|
page.appendMarkdown(`${detail.markdown}\n\n`);
|
||||||
|
} else {
|
||||||
|
page.appendMarkdown('尚未提供领域说明;签名和关系来自已保存源码。\n\n');
|
||||||
|
}
|
||||||
|
for (const incoming of [true, false]) {
|
||||||
|
const related = relations(state.index, symbol.id, incoming);
|
||||||
|
const label = incoming ? '调用方' : '调用目标';
|
||||||
|
const names = related.slice(0, 4).map(item => `\`${item.symbol.name}\``).join('、');
|
||||||
|
page.appendMarkdown(`${label}:${names || '当前静态索引中无记录'}${related.length > 4 ? `,共 ${related.length} 个` : ''}。\n\n`);
|
||||||
|
}
|
||||||
|
const links = [];
|
||||||
|
for (const site of symbol.declarations.slice(0, 1)) {
|
||||||
|
const target = uri(state.index, site.file, state.root).with({ fragment: `L${site.start.line + 1},${site.start.character + 1}` });
|
||||||
|
links.push(`[源码](${target.toString()})`);
|
||||||
|
}
|
||||||
|
if (detail) links.push(`[说明](${command('dever.previewDocumentation', [state.root, symbol.name])})`);
|
||||||
|
links.push(`[调用详情](${command('dever.showCalls', [state.root, symbol.name])})`);
|
||||||
|
links.push(`[领域流程](${command('dever.openDomainLinks', [state.root, symbol.name])})`);
|
||||||
|
page.appendMarkdown(links.join(' · '));
|
||||||
|
contents.push(page);
|
||||||
|
}
|
||||||
|
return new vscode.Hover(contents);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { registerHover, description, command };
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
const vscode = require('vscode');
|
||||||
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs/promises');
|
||||||
|
const { createHash } = require('node:crypto');
|
||||||
|
const { execFile } = require('node:child_process');
|
||||||
|
const { promisify } = require('node:util');
|
||||||
|
const execute = promisify(execFile);
|
||||||
|
|
||||||
|
function isSource(document) {
|
||||||
|
return document.languageId === 'dever';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function projectRoot(document) {
|
||||||
|
const folder = vscode.workspace.getWorkspaceFolder(document.uri)?.uri.fsPath;
|
||||||
|
for (let directory = path.dirname(document.uri.fsPath); ; directory = path.dirname(directory)) {
|
||||||
|
try {
|
||||||
|
await fs.stat(path.join(directory, 'module'));
|
||||||
|
return directory;
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== 'ENOENT') throw error;
|
||||||
|
}
|
||||||
|
if (directory === folder || directory === path.dirname(directory)) break;
|
||||||
|
}
|
||||||
|
return folder || document.uri.fsPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
function uri(index, file) { return vscode.Uri.file(index.files[file].path); }
|
||||||
|
|
||||||
|
function range(location) {
|
||||||
|
return new vscode.Range(location.start.line, location.start.character, location.end.line, location.end.character);
|
||||||
|
}
|
||||||
|
|
||||||
|
function expandIndex(index) {
|
||||||
|
const location = ([file, line, character, endLine, endCharacter]) => ({
|
||||||
|
file, start: { line, character }, end: { line: endLine, character: endCharacter }
|
||||||
|
});
|
||||||
|
const symbols = new Map(index.symbols.map(symbol => [symbol.id, symbol]));
|
||||||
|
for (const symbol of index.symbols) {
|
||||||
|
if (symbol.template === undefined) {
|
||||||
|
symbol.source_name ??= symbol.name;
|
||||||
|
symbol.declarations = symbol.declarations.map(location);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const symbol of index.symbols) {
|
||||||
|
if (symbol.template !== undefined) {
|
||||||
|
const template = symbols.get(symbol.template);
|
||||||
|
symbol.source_name = template.name;
|
||||||
|
symbol.declarations = template.declarations;
|
||||||
|
symbol.signatures = template.signatures.map(signature => signature.replace(template.name, () => symbol.name));
|
||||||
|
delete symbol.template;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const call of index.calls) call.site = location(call.site);
|
||||||
|
for (const issue of index.diagnostics) {
|
||||||
|
issue.location = location(issue.location);
|
||||||
|
issue.related = issue.related.map(([site, reason]) => [location(site), reason]);
|
||||||
|
}
|
||||||
|
for (const flow of index.flows || []) {
|
||||||
|
for (const node of flow.nodes) if (node.site) node.site = location(node.site);
|
||||||
|
}
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createInspection(context) {
|
||||||
|
const cache = new Map();
|
||||||
|
// 随包源码沿用最近一次实际索引它的项目,打开库文件后仍能继续读调用链。
|
||||||
|
const sourceOwners = new Map();
|
||||||
|
const changed = new vscode.EventEmitter();
|
||||||
|
const output = vscode.window.createOutputChannel('Dever');
|
||||||
|
const diagnostics = vscode.languages.createDiagnosticCollection('dever');
|
||||||
|
const status = vscode.window.createStatusBarItem();
|
||||||
|
status.text = 'Dever:有未保存修改,导航和流程暂不可用';
|
||||||
|
const savedState = () => {
|
||||||
|
if (vscode.workspace.textDocuments.some(document => document.isDirty && isSource(document))) status.show();
|
||||||
|
else status.hide();
|
||||||
|
};
|
||||||
|
context.subscriptions.push(changed, output, diagnostics, status);
|
||||||
|
const invalidate = () => { cache.clear(); diagnostics.clear(); savedState(); changed.fire(); };
|
||||||
|
context.subscriptions.push(vscode.workspace.onDidChangeTextDocument(event => {
|
||||||
|
if (isSource(event.document)) { diagnostics.clear(); savedState(); changed.fire(); }
|
||||||
|
}));
|
||||||
|
context.subscriptions.push(vscode.workspace.onDidCloseTextDocument(savedState));
|
||||||
|
const watcher = vscode.workspace.createFileSystemWatcher('**/{*.dv,*.dever,README.md,doc/*.md,dever.lock,dever.api,setting.json}');
|
||||||
|
context.subscriptions.push(watcher, watcher.onDidChange(invalidate), watcher.onDidCreate(invalidate), watcher.onDidDelete(invalidate));
|
||||||
|
context.subscriptions.push(vscode.workspace.onDidSaveTextDocument(document => {
|
||||||
|
if (isSource(document) || /[/\\]doc[/\\][^/\\]+\.md$/.test(document.uri.fsPath)) invalidate();
|
||||||
|
}));
|
||||||
|
context.subscriptions.push(vscode.workspace.onDidChangeConfiguration(event => {
|
||||||
|
if (event.affectsConfiguration('dever.command')) invalidate();
|
||||||
|
}));
|
||||||
|
|
||||||
|
async function load(root, symbol) {
|
||||||
|
const key = JSON.stringify([root, symbol]);
|
||||||
|
if (!vscode.workspace.isTrusted) throw new Error('请信任工作区后再运行 Dever 源码检查。');
|
||||||
|
if (!cache.has(key)) {
|
||||||
|
const command = vscode.workspace.getConfiguration('dever', vscode.Uri.file(root)).get('command');
|
||||||
|
const arguments_ = [...command.slice(1), 'inspect', root, '--json'];
|
||||||
|
if (symbol) arguments_.push('--symbol', symbol, '--depth', '0');
|
||||||
|
const promise = execute(command[0], arguments_, {
|
||||||
|
maxBuffer: 32 * 1024 * 1024, windowsHide: true
|
||||||
|
}).then(({ stdout }) => {
|
||||||
|
if (cache.get(key) !== promise) throw new Error('检查期间源码已变化,请重新查询调用关系。');
|
||||||
|
const index = expandIndex(JSON.parse(stdout));
|
||||||
|
for (const file of index.files) sourceOwners.set(file.path, root);
|
||||||
|
for (const error of index.documentation_errors) output.appendLine(error);
|
||||||
|
if (!symbol) {
|
||||||
|
const byFile = new Map(index.files.map((file, id) => [id, []]));
|
||||||
|
for (const issue of index.diagnostics) {
|
||||||
|
const diagnostic = new vscode.Diagnostic(range(issue.location), issue.message, vscode.DiagnosticSeverity.Error);
|
||||||
|
diagnostic.code = issue.code;
|
||||||
|
diagnostic.relatedInformation = issue.related.map(([site, reason]) => new vscode.DiagnosticRelatedInformation(
|
||||||
|
new vscode.Location(uri(index, site.file, root), range(site)), reason));
|
||||||
|
byFile.get(issue.location.file).push(diagnostic);
|
||||||
|
}
|
||||||
|
for (const [file, issues] of byFile) diagnostics.set(uri(index, file, root), issues);
|
||||||
|
}
|
||||||
|
return index;
|
||||||
|
}).catch(error => {
|
||||||
|
if (cache.get(key) === promise) cache.delete(key);
|
||||||
|
const message = error.stderr?.trim() || error.message;
|
||||||
|
output.appendLine(message);
|
||||||
|
throw new Error(message);
|
||||||
|
});
|
||||||
|
cache.set(key, promise);
|
||||||
|
}
|
||||||
|
const pending = cache.get(key);
|
||||||
|
const index = await pending;
|
||||||
|
if (cache.get(key) !== pending) throw new Error('检查期间源码已变化,请重新查询调用关系。');
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verify(index, file, root) {
|
||||||
|
const document = await vscode.workspace.openTextDocument(uri(index, file, root));
|
||||||
|
if (document.isDirty) throw new Error('调用关系基于已保存源码,请先保存文件。');
|
||||||
|
const digest = createHash('sha256').update(document.getText()).digest('hex');
|
||||||
|
if (digest !== index.files[file].sha256) {
|
||||||
|
invalidate();
|
||||||
|
throw new Error('源码已变化,请刷新调用关系。');
|
||||||
|
}
|
||||||
|
return document;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function current(document) {
|
||||||
|
if (document.isDirty) return undefined;
|
||||||
|
const root = sourceOwners.get(document.uri.fsPath) || await projectRoot(document);
|
||||||
|
if (vscode.workspace.textDocuments.some(value => value.isDirty && isSource(value)
|
||||||
|
&& (value.uri.fsPath === root || value.uri.fsPath.startsWith(`${root}${path.sep}`)))) return undefined;
|
||||||
|
const index = await load(root);
|
||||||
|
const sourcePath = document.uri.fsPath;
|
||||||
|
const file = index.files.findIndex(source => source.path === sourcePath);
|
||||||
|
if (file < 0) return undefined;
|
||||||
|
await verify(index, file, root);
|
||||||
|
return { root, index, file };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function location(index, site, root) {
|
||||||
|
await verify(index, site.file, root);
|
||||||
|
return new vscode.Location(uri(index, site.file, root), range(site));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkLinks(root) {
|
||||||
|
if (!vscode.workspace.isTrusted) throw new Error('请信任工作区后再检查领域流程。');
|
||||||
|
if (vscode.workspace.textDocuments.some(document => document.isDirty && isSource(document)
|
||||||
|
&& document.uri.fsPath.startsWith(`${root}${path.sep}`))) throw new Error('请先保存源码,再查看领域流程。');
|
||||||
|
const command = vscode.workspace.getConfiguration('dever', vscode.Uri.file(root)).get('command');
|
||||||
|
try {
|
||||||
|
await execute(command[0], [...command.slice(1), 'inspect', root, '--links', '--check'], { windowsHide: true });
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(error.stderr?.trim() || error.stdout?.trim() || error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { load, current, verify, location, checkLinks, invalidate, changed };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createInspection, expandIndex, range, uri, isSource, projectRoot };
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
{
|
||||||
|
"comments": {
|
||||||
|
"lineComment": "#",
|
||||||
|
"blockComment": ["/*", "*/"]
|
||||||
|
},
|
||||||
|
"brackets": [
|
||||||
|
[
|
||||||
|
"{",
|
||||||
|
"}"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"[",
|
||||||
|
"]"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"(",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"autoClosingPairs": [
|
||||||
|
{
|
||||||
|
"open": "{",
|
||||||
|
"close": "}",
|
||||||
|
"notIn": [
|
||||||
|
"string", "comment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"open": "[",
|
||||||
|
"close": "]",
|
||||||
|
"notIn": [
|
||||||
|
"string", "comment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"open": "(",
|
||||||
|
"close": ")",
|
||||||
|
"notIn": [
|
||||||
|
"string", "comment"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"open": "\"",
|
||||||
|
"close": "\"",
|
||||||
|
"notIn": [
|
||||||
|
"string", "comment"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"surroundingPairs": [
|
||||||
|
[
|
||||||
|
"{",
|
||||||
|
"}"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"[",
|
||||||
|
"]"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"(",
|
||||||
|
")"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"\"",
|
||||||
|
"\""
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"wordPattern": "[A-Za-z_][A-Za-z0-9_]*",
|
||||||
|
"indentationRules": {
|
||||||
|
"increaseIndentPattern": "^\\s*(?:[^\"]|\"(?:\\\\.|[^\"\\\\])*\")*[({\\[]\\s*$",
|
||||||
|
"decreaseIndentPattern": "^\\s*[})\\]]"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
const vscode = require('vscode');
|
||||||
|
const { createInspection, range, uri } = require('./inspection.cjs');
|
||||||
|
const { at, relations } = require('./graph.cjs');
|
||||||
|
const { registerReading } = require('./reading.cjs');
|
||||||
|
const { registerHover } = require('./hover.cjs');
|
||||||
|
|
||||||
|
function registerNavigation(context) {
|
||||||
|
const inspection = createInspection(context);
|
||||||
|
const selector = { language: 'dever', scheme: 'file' };
|
||||||
|
|
||||||
|
async function item(index, symbol, root) {
|
||||||
|
const first = symbol.declarations[0];
|
||||||
|
await inspection.verify(index, first.file, root);
|
||||||
|
const end = symbol.declarations.at(-1).end;
|
||||||
|
const span = range({ start: first.start, end });
|
||||||
|
const selected = new vscode.Range(span.start, span.start);
|
||||||
|
const value = new vscode.CallHierarchyItem(vscode.SymbolKind.Function, symbol.name, symbol.kind,
|
||||||
|
uri(index, first.file, root), span, selected);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function lookup(document, position) {
|
||||||
|
const state = await inspection.current(document);
|
||||||
|
return state ? { ...state, symbols: at(state.index, state.file, position) } : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
context.subscriptions.push(vscode.languages.registerDefinitionProvider(selector, {
|
||||||
|
async provideDefinition(document, position) {
|
||||||
|
const state = await lookup(document, position);
|
||||||
|
if (!state) return [];
|
||||||
|
return Promise.all(state.symbols.flatMap(symbol => symbol.declarations)
|
||||||
|
.map(site => inspection.location(state.index, site, state.root)));
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
context.subscriptions.push(vscode.languages.registerReferenceProvider(selector, {
|
||||||
|
async provideReferences(document, position, options) {
|
||||||
|
const state = await lookup(document, position);
|
||||||
|
if (!state) return [];
|
||||||
|
const ids = new Set(state.symbols.map(symbol => symbol.id));
|
||||||
|
const sites = state.index.calls.filter(call => ids.has(call.callee)).map(call => call.site);
|
||||||
|
if (options.includeDeclaration) sites.push(...state.symbols.flatMap(symbol => symbol.declarations));
|
||||||
|
const unique = [...new Map(sites.map(site => [JSON.stringify(site), site])).values()]
|
||||||
|
.sort((a, b) => a.file - b.file || a.start.line - b.start.line || a.start.character - b.start.character);
|
||||||
|
return Promise.all(unique.map(site => inspection.location(state.index, site, state.root)));
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
async function hierarchy(value, incoming) {
|
||||||
|
const document = await vscode.workspace.openTextDocument(value.uri);
|
||||||
|
const state = await inspection.current(document);
|
||||||
|
if (!state) throw new Error('请保存源码后重新打开调用层级。');
|
||||||
|
const { root, index, file } = state;
|
||||||
|
const start = value.selectionRange.start;
|
||||||
|
const symbol = index.symbols.find(symbol => symbol.name === value.name && symbol.declarations.some(site =>
|
||||||
|
site.file === file && site.start.line === start.line && site.start.character === start.character));
|
||||||
|
if (!symbol) throw new Error('函数位置已变化,请重新打开调用层级。');
|
||||||
|
await inspection.verify(index, symbol.declarations[0].file, root);
|
||||||
|
const result = [];
|
||||||
|
for (const relation of relations(index, symbol.id, incoming)) {
|
||||||
|
const target = await item(index, relation.symbol, root);
|
||||||
|
for (const call of relation.calls) await inspection.verify(index, call.site.file, root);
|
||||||
|
const ranges = relation.calls.map(call => range(call.site));
|
||||||
|
result.push(incoming ? new vscode.CallHierarchyIncomingCall(target, ranges)
|
||||||
|
: new vscode.CallHierarchyOutgoingCall(target, ranges));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
context.subscriptions.push(vscode.languages.registerCallHierarchyProvider(selector, {
|
||||||
|
async prepareCallHierarchy(document, position) {
|
||||||
|
const state = await lookup(document, position);
|
||||||
|
if (!state) return [];
|
||||||
|
return (await Promise.all(state.symbols.map(symbol => item(state.index, symbol, state.root)))).filter(Boolean);
|
||||||
|
},
|
||||||
|
provideCallHierarchyIncomingCalls(value) { return hierarchy(value, true); },
|
||||||
|
provideCallHierarchyOutgoingCalls(value) { return hierarchy(value, false); }
|
||||||
|
}));
|
||||||
|
context.subscriptions.push(vscode.languages.registerCodeLensProvider(selector, {
|
||||||
|
onDidChangeCodeLenses: inspection.changed.event,
|
||||||
|
async provideCodeLenses(document) {
|
||||||
|
const state = await inspection.current(document);
|
||||||
|
if (!state) return [];
|
||||||
|
return state.index.symbols.filter(symbol => symbol.declarations[0].file === state.file).map(symbol => {
|
||||||
|
const incoming = relations(state.index, symbol.id, true);
|
||||||
|
const count = incoming.reduce((total, relation) => total + relation.calls.length, 0);
|
||||||
|
const start = range(symbol.declarations[0]).start;
|
||||||
|
return new vscode.CodeLens(new vscode.Range(start, start), {
|
||||||
|
title: `${incoming.length} 个调用方 · ${count} 处调用 · 查看调用关系`,
|
||||||
|
command: 'dever.showCalls', arguments: [state.root, symbol.name]
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
registerReading(context, inspection, lookup);
|
||||||
|
registerHover(context, selector, inspection, lookup);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { registerNavigation };
|
||||||
Generated
+2458
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,111 @@
|
|||||||
|
{
|
||||||
|
"name": "dever-language",
|
||||||
|
"displayName": "Dever Language",
|
||||||
|
"description": "Dever source navigation, domain documentation, hover and call flows.",
|
||||||
|
"version": "0.0.2",
|
||||||
|
"main": "./extension.cjs",
|
||||||
|
"activationEvents": [
|
||||||
|
"onLanguage:dever"
|
||||||
|
],
|
||||||
|
"publisher": "shemic",
|
||||||
|
"private": true,
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"engines": {
|
||||||
|
"vscode": "^1.85.0"
|
||||||
|
},
|
||||||
|
"categories": [
|
||||||
|
"Programming Languages"
|
||||||
|
],
|
||||||
|
"keywords": [
|
||||||
|
"dever",
|
||||||
|
"markdown",
|
||||||
|
"syntax highlighting"
|
||||||
|
],
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "ssh://git@git.dever.cc:2222/dever/core.git",
|
||||||
|
"directory": "editor/vscode"
|
||||||
|
},
|
||||||
|
"contributes": {
|
||||||
|
"commands": [
|
||||||
|
{
|
||||||
|
"command": "dever.previewDocumentation",
|
||||||
|
"title": "Dever: Preview Documentation"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "dever.showCalls",
|
||||||
|
"title": "Dever: Show Calls"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "dever.openDomainLinks",
|
||||||
|
"title": "Dever: Open Domain Links"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"configuration": {
|
||||||
|
"title": "Dever",
|
||||||
|
"properties": {
|
||||||
|
"dever.command": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"minItems": 1,
|
||||||
|
"default": [
|
||||||
|
"dever"
|
||||||
|
],
|
||||||
|
"description": "Compiler executable followed by fixed arguments; inspect is appended without a shell."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"languages": [
|
||||||
|
{
|
||||||
|
"id": "dever",
|
||||||
|
"aliases": [
|
||||||
|
"Dever",
|
||||||
|
"dever"
|
||||||
|
],
|
||||||
|
"extensions": [
|
||||||
|
".dv",
|
||||||
|
".dever"
|
||||||
|
],
|
||||||
|
"configuration": "./language-configuration.json"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"grammars": [
|
||||||
|
{
|
||||||
|
"language": "dever",
|
||||||
|
"scopeName": "source.dever",
|
||||||
|
"path": "./syntaxes/dever.tmLanguage.json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"scopeName": "markdown.dever.codeblock",
|
||||||
|
"path": "./syntaxes/dever-markdown.tmLanguage.json",
|
||||||
|
"injectTo": [
|
||||||
|
"text.html.markdown"
|
||||||
|
],
|
||||||
|
"embeddedLanguages": {
|
||||||
|
"meta.embedded.block.dever": "dever"
|
||||||
|
},
|
||||||
|
"tokenTypes": {
|
||||||
|
"meta.embedded.block.dever": "other"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"build": "node build.cjs",
|
||||||
|
"vscode:prepublish": "npm run build",
|
||||||
|
"test": "node ../../test/editor-vscode/highlight.test.cjs",
|
||||||
|
"test:navigation": "node --test ../../test/editor-vscode/navigation.test.cjs",
|
||||||
|
"test:flows": "node --test ../../test/editor-vscode/flows.test.cjs",
|
||||||
|
"package": "vsce package --no-dependencies --skip-license"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@mermaid-js/tiny": "12.2.0",
|
||||||
|
"@vscode/vsce": "4.0.0",
|
||||||
|
"esbuild": "0.28.2",
|
||||||
|
"markdown-it": "15.0.3",
|
||||||
|
"vscode-oniguruma": "2.0.1",
|
||||||
|
"vscode-textmate": "9.2.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
const vscode = require('vscode');
|
||||||
|
const path = require('node:path');
|
||||||
|
const { relations } = require('./graph.cjs');
|
||||||
|
const { uri, projectRoot } = require('./inspection.cjs');
|
||||||
|
const { openFlowPreview } = require('./dist/flow-preview.cjs');
|
||||||
|
const { description, command } = require('./hover.cjs');
|
||||||
|
const { workflow } = require('./workflow.cjs');
|
||||||
|
|
||||||
|
function registerReading(context, inspection, lookup) {
|
||||||
|
const changed = new vscode.EventEmitter();
|
||||||
|
const previews = new Map();
|
||||||
|
async function verifyTarget(root, filename) {
|
||||||
|
const index = await inspection.load(root);
|
||||||
|
const file = index.files.find(file => file.path === filename)
|
||||||
|
?? index.documentation_files.find(file => file.path === filename);
|
||||||
|
if (!file) throw new Error('目标不在当前源码或说明索引中。');
|
||||||
|
return inspection.verify({ files: [file] }, 0, root);
|
||||||
|
}
|
||||||
|
context.subscriptions.push(changed, inspection.changed.event(() => {
|
||||||
|
for (const uri of previews.values()) changed.fire(uri);
|
||||||
|
}));
|
||||||
|
context.subscriptions.push(vscode.workspace.onDidCloseTextDocument(document => {
|
||||||
|
previews.delete(document.uri.toString());
|
||||||
|
}));
|
||||||
|
const provider = {
|
||||||
|
onDidChange: changed.event,
|
||||||
|
async provideTextDocumentContent(documentUri) {
|
||||||
|
previews.set(documentUri.toString(), documentUri);
|
||||||
|
const { root, name } = JSON.parse(documentUri.query);
|
||||||
|
const index = await inspection.load(root);
|
||||||
|
const symbols = index.symbols.filter(symbol => symbol.name === name || symbol.source_name === name);
|
||||||
|
if (!symbols.length) throw new Error(`函数已不存在:${name}`);
|
||||||
|
const lines = [`# ${name}`, ''];
|
||||||
|
const details = [index.coverage, ''];
|
||||||
|
const described = new Set();
|
||||||
|
if (index.documentation_errors.length) lines.push('**说明校验未通过。** 详见“Dever”输出。', '');
|
||||||
|
function link(site) {
|
||||||
|
const file = index.files[site.file];
|
||||||
|
const target = uri(index, site.file, root).with({ fragment: `L${site.start.line + 1},${site.start.character + 1}` });
|
||||||
|
return `[${file.path}:${site.start.line + 1}](${target.toString()})`;
|
||||||
|
}
|
||||||
|
for (const symbol of symbols) {
|
||||||
|
const detail = await description(inspection, index, symbol, root);
|
||||||
|
if (detail && !described.has(detail.symbol)) {
|
||||||
|
described.add(detail.symbol);
|
||||||
|
const topic = detail.uri.with({ fragment: `L${detail.line + 1}` });
|
||||||
|
lines.push(detail.markdown, '', `[主题说明](${topic.toString()})`, '');
|
||||||
|
}
|
||||||
|
for (const signature of symbol.signatures) details.push('```dever', signature, '```', '');
|
||||||
|
for (const site of symbol.declarations) {
|
||||||
|
await inspection.verify(index, site.file, root);
|
||||||
|
details.push('## 定义', '', link(site), '');
|
||||||
|
}
|
||||||
|
for (const incoming of [true, false]) {
|
||||||
|
details.push(incoming ? '## 谁调用它' : '## 它调用谁', '');
|
||||||
|
const related = relations(index, symbol.id, incoming);
|
||||||
|
if (!related.length) details.push('当前已检查源码中没有此类关系。', '');
|
||||||
|
else details.push('| 函数 | 领域 | 关系 | 调用位置 | 定义 / 上下游 |', '| --- | --- | --- | --- | --- |');
|
||||||
|
for (const relation of related) {
|
||||||
|
for (const call of relation.calls) {
|
||||||
|
await inspection.verify(index, call.site.file, root);
|
||||||
|
const definitions = relation.symbol.declarations.map(link).join('、') || '内建操作';
|
||||||
|
const chain = command('dever.showCalls', [root, relation.symbol.name]);
|
||||||
|
details.push(`| ${relation.symbol.name} | ${relation.symbol.name.split('.').slice(0, 2).join('.')} | ${call.kind} | ${link(call.site)} | ${definitions} · [上下游](${chain}) |`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
details.push('');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!described.size) lines.push('尚未提供业务说明。', '');
|
||||||
|
const selected = await inspection.load(root, name);
|
||||||
|
for (const symbol of selected.symbols) for (const site of symbol.declarations) await inspection.verify(selected, site.file, root);
|
||||||
|
const { diagram, labels } = workflow(selected, root);
|
||||||
|
lines.push(diagram, '', '<details><summary>实现细节</summary>', '');
|
||||||
|
if (labels.length) lines.push('## 节点原文', '', ...labels);
|
||||||
|
lines.push(...details, '</details>', '');
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
context.subscriptions.push(vscode.workspace.registerTextDocumentContentProvider('dever-calls', provider));
|
||||||
|
context.subscriptions.push(vscode.commands.registerCommand('dever.showCalls', async (root, name) => {
|
||||||
|
try {
|
||||||
|
if (!root || !name) {
|
||||||
|
const editor = vscode.window.activeTextEditor;
|
||||||
|
if (!editor) return;
|
||||||
|
const state = await lookup(editor.document, editor.selection.active);
|
||||||
|
if (!state) throw new Error('请先保存源码,再查看调用关系。');
|
||||||
|
if (!state.symbols.length) throw new Error('请把光标放在函数或调用位置。');
|
||||||
|
root = state.root;
|
||||||
|
name = state.symbols[0].name;
|
||||||
|
}
|
||||||
|
const target = vscode.Uri.from({ scheme: 'dever-calls', path: '/calls.md', query: JSON.stringify({ root, name }) });
|
||||||
|
await openFlowPreview(context, target, root, {
|
||||||
|
name,
|
||||||
|
changed: inspection.changed,
|
||||||
|
verify: filename => verifyTarget(root, filename),
|
||||||
|
read: name => provider.provideTextDocumentContent(target.with({ query: JSON.stringify({ root, name }) }))
|
||||||
|
});
|
||||||
|
} catch (error) { vscode.window.showErrorMessage(error.message); }
|
||||||
|
}));
|
||||||
|
context.subscriptions.push(vscode.commands.registerCommand('dever.previewDocumentation', async (root, name) => {
|
||||||
|
try {
|
||||||
|
const document = vscode.window.activeTextEditor?.document;
|
||||||
|
if (!root || !name) {
|
||||||
|
if (!document) return;
|
||||||
|
const state = await lookup(document, vscode.window.activeTextEditor.selection.active);
|
||||||
|
root = state?.root || await projectRoot(document);
|
||||||
|
name = state?.symbols[0]?.name;
|
||||||
|
}
|
||||||
|
const index = await inspection.load(root);
|
||||||
|
const symbol = index.symbols.find(value => value.name === name);
|
||||||
|
const detail = symbol && await description(inspection, index, symbol, root);
|
||||||
|
if (!detail) throw new Error('该符号尚未提供 doc/ 说明。');
|
||||||
|
await vscode.commands.executeCommand('markdown.showPreviewToSide', detail.uri.with({ fragment: `L${detail.line + 1}` }));
|
||||||
|
} catch (error) { vscode.window.showErrorMessage(error.message); }
|
||||||
|
}));
|
||||||
|
context.subscriptions.push(vscode.commands.registerCommand('dever.openDomainLinks', async (root, name) => {
|
||||||
|
try {
|
||||||
|
const document = vscode.window.activeTextEditor?.document;
|
||||||
|
if (!root && !document) return;
|
||||||
|
root ||= await projectRoot(document);
|
||||||
|
const index = await inspection.load(root);
|
||||||
|
const symbol = index.symbols.find(value => value.name === name);
|
||||||
|
const source = symbol?.declarations[0];
|
||||||
|
const filename = source ? index.files[source.file].path : document.uri.fsPath;
|
||||||
|
const relative = path.relative(path.join(root, 'module'), filename).split(path.sep);
|
||||||
|
if (relative.length < 3 || relative[0] === '..') {
|
||||||
|
throw new Error('请在 module/<组件>/<领域>/ 内的源码中执行此命令。');
|
||||||
|
}
|
||||||
|
const target = vscode.Uri.file(path.join(root, 'module', ...relative.slice(0, 2), 'link.md'));
|
||||||
|
await inspection.checkLinks(root);
|
||||||
|
const panel = await openFlowPreview(context, target, root, undefined, filename => verifyTarget(root, filename));
|
||||||
|
const changed = inspection.changed.event(() => panel.dispose());
|
||||||
|
panel.onDidDispose(() => changed.dispose());
|
||||||
|
} catch (error) {
|
||||||
|
vscode.window.showErrorMessage(`${error.message} 可在项目根运行 dever inspect . --links 生成索引。`);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { registerReading };
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"name": "Dever Markdown blocks",
|
||||||
|
"scopeName": "markdown.dever.codeblock",
|
||||||
|
"injectionSelector": "L:text.html.markdown -markup.fenced_code.block -markup.raw.block -markup.quote -markup.list -meta.embedded.block -comment",
|
||||||
|
"patterns": [
|
||||||
|
{
|
||||||
|
"name": "markup.fenced_code.block.markdown",
|
||||||
|
"contentName": "meta.embedded.block.dever source.dever",
|
||||||
|
"begin": "^ {0,3}(`{3,})[ \\t]*(dever)[ \\t]*$",
|
||||||
|
"end": "^ {0,3}\\1`* *$",
|
||||||
|
"beginCaptures": {
|
||||||
|
"1": { "name": "punctuation.definition.markdown.dever" },
|
||||||
|
"2": { "name": "fenced_code.block.language.markdown" }
|
||||||
|
},
|
||||||
|
"endCaptures": { "0": { "name": "punctuation.definition.markdown.dever" } },
|
||||||
|
"patterns": [{ "include": "source.dever" }]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "markup.fenced_code.block.markdown",
|
||||||
|
"contentName": "meta.embedded.block.dever source.dever",
|
||||||
|
"begin": "^ {0,3}(~{3,})[ \\t]*(dever)[ \\t]*$",
|
||||||
|
"end": "^ {0,3}\\1~* *$",
|
||||||
|
"beginCaptures": {
|
||||||
|
"1": { "name": "punctuation.definition.markdown.dever" },
|
||||||
|
"2": { "name": "fenced_code.block.language.markdown" }
|
||||||
|
},
|
||||||
|
"endCaptures": { "0": { "name": "punctuation.definition.markdown.dever" } },
|
||||||
|
"patterns": [{ "include": "source.dever" }]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
{
|
||||||
|
"name": "Dever",
|
||||||
|
"scopeName": "source.dever",
|
||||||
|
"patterns": [
|
||||||
|
{
|
||||||
|
"include": "#strings"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"include": "#comments"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"include": "#unsupported"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"include": "#declarations"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"include": "#constants"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"include": "#numbers"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"include": "#names"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"include": "#keywords"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"include": "#operators"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"repository": {
|
||||||
|
"comments": {
|
||||||
|
"patterns": [
|
||||||
|
{
|
||||||
|
"name": "comment.line.number-sign.dever",
|
||||||
|
"match": "(#).*$",
|
||||||
|
"captures": { "1": { "name": "punctuation.definition.comment.dever" } }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "comment.block.dever",
|
||||||
|
"begin": "/\\*",
|
||||||
|
"end": "\\*/",
|
||||||
|
"beginCaptures": { "0": { "name": "punctuation.definition.comment.begin.dever" } },
|
||||||
|
"endCaptures": { "0": { "name": "punctuation.definition.comment.end.dever" } }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"strings": {
|
||||||
|
"name": "string.quoted.double.dever",
|
||||||
|
"begin": "\"",
|
||||||
|
"end": "\"|$",
|
||||||
|
"beginCaptures": {
|
||||||
|
"0": {
|
||||||
|
"name": "punctuation.definition.string.begin.dever"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"endCaptures": {
|
||||||
|
"0": {
|
||||||
|
"name": "punctuation.definition.string.end.dever"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"patterns": [
|
||||||
|
{
|
||||||
|
"name": "constant.character.escape.dever",
|
||||||
|
"match": "\\\\(?:[\"\\\\nrt]|u\\{[0-9A-Fa-f]{1,6}\\})"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "invalid.illegal.escape.dever",
|
||||||
|
"match": "\\\\."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"declarations": {
|
||||||
|
"patterns": [
|
||||||
|
{
|
||||||
|
"match": "\\b(type)\\s+([A-Z][A-Za-z0-9_]*)",
|
||||||
|
"captures": {
|
||||||
|
"1": {
|
||||||
|
"name": "storage.type.dever"
|
||||||
|
},
|
||||||
|
"2": {
|
||||||
|
"name": "entity.name.type.dever"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": "^\\s*(?:(public)\\s+)?(get|post|put|delete|cmd|rest)\\b",
|
||||||
|
"captures": {
|
||||||
|
"1": {
|
||||||
|
"name": "storage.modifier.dever"
|
||||||
|
},
|
||||||
|
"2": {
|
||||||
|
"name": "keyword.control.api.dever"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": "^\\s*(external)\\s+(command|exec|pip|npm|go)\\b",
|
||||||
|
"captures": {
|
||||||
|
"1": {
|
||||||
|
"name": "storage.modifier.external.dever"
|
||||||
|
},
|
||||||
|
"2": {
|
||||||
|
"name": "keyword.other.external.dever"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "keyword.other.declaration.dever",
|
||||||
|
"match": "^\\s*(database|relation|seed|migrate|sql|index|unique|schedule)\\b"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"constants": {
|
||||||
|
"name": "constant.language.dever",
|
||||||
|
"match": "\\b(true|false|null|other)\\b"
|
||||||
|
},
|
||||||
|
"unsupported": {
|
||||||
|
"name": "invalid.illegal.keyword.dever",
|
||||||
|
"match": "\\b(package|exposes|pure|if|switch|match|when|by|for|while|break|continue|iterate|recur|repeat|return|function|throw|catch|try|import|use|class|interface|unsafe|macro)\\b"
|
||||||
|
},
|
||||||
|
"numbers": {
|
||||||
|
"name": "constant.numeric.dever",
|
||||||
|
"match": "(?<![A-Za-z0-9_])[0-9](?:_?[0-9])*(?:\\.[0-9](?:_?[0-9])*)?(?:[eE][+-]?[0-9](?:_?[0-9])*)?(?![A-Za-z0-9_])"
|
||||||
|
},
|
||||||
|
"names": {
|
||||||
|
"patterns": [
|
||||||
|
{
|
||||||
|
"name": "variable.other.member.dever",
|
||||||
|
"match": "\\b[a-z_][A-Za-z0-9_]*(?=\\s*:)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "entity.name.function.dever",
|
||||||
|
"match": "\\b[a-z_][A-Za-z0-9_]*(?=\\s*\\()"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "support.type.dever",
|
||||||
|
"match": "\\b(Int|Float|Decimal|Bool|Text|Bytes|Secret|List|Map|Stream|AsyncStream|Channel|Task|Group|Json|Date|Time|DateTime|Duration|Id|Uuid|Upload)\\b"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "entity.name.type.dever",
|
||||||
|
"match": "\\b[A-Z][A-Za-z0-9_]*\\b"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "entity.name.namespace.dever",
|
||||||
|
"match": "\\b(dever|app|domain|data|port|adapter)(?=\\.)"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"keywords": {
|
||||||
|
"patterns": [
|
||||||
|
{
|
||||||
|
"name": "keyword.operator.logical.dever",
|
||||||
|
"match": "\\b(and|or|not)\\b"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "storage.modifier.dever",
|
||||||
|
"match": "\\b(public|authenticated|long|global|transaction|job|recover|fails|private|owner)\\b"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "keyword.other.data.dever",
|
||||||
|
"match": "\\b(default|unique|index|raw|lower|upper|before|after|drop)\\b"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "keyword.other.adapter.dever",
|
||||||
|
"match": "\\b(setting|lib|file|allow)\\b"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "keyword.control.dever",
|
||||||
|
"match": "\\b(rule|flow|loop|each|in|skip|check|else|parallel|const)\\b"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"operators": {
|
||||||
|
"patterns": [
|
||||||
|
{
|
||||||
|
"name": "punctuation.separator.table.dever",
|
||||||
|
"match": "\\|"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "keyword.operator.dever",
|
||||||
|
"match": "//|=>|==|!=|<=|>=|[=+*/%<>?-]"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "punctuation.section.dever",
|
||||||
|
"match": "[{}()\\[\\]]"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "punctuation.separator.dever",
|
||||||
|
"match": "[,:.]"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
// 只呈现编译器已经确定的控制边、失败出口与调用位置,不按名字猜业务流程。
|
||||||
|
const { pathToFileURL } = require('node:url');
|
||||||
|
function escape(value) {
|
||||||
|
return value.replaceAll('&', '#38;').replaceAll('"', '#34;').replaceAll('<', '#60;')
|
||||||
|
.replaceAll('>', '#62;').replaceAll('|', '#124;').replaceAll('\n', ' ').replaceAll(String.fromCharCode(96), '#96;');
|
||||||
|
}
|
||||||
|
function workflow(index, root) {
|
||||||
|
const labels = [];
|
||||||
|
const diagram = (index.flows || []).map(flow => render(flow, index, root, labels)).join('\n');
|
||||||
|
return { diagram, labels };
|
||||||
|
}
|
||||||
|
function render(flow, index, root, labels) {
|
||||||
|
const fence = String.fromCharCode(96).repeat(3);
|
||||||
|
const lines = ['## 执行流程', '', '图显示可能的执行路径。点击节点打开源码,展开调用查看子流程。', '', fence + 'mermaid', 'flowchart TD'];
|
||||||
|
const full = [];
|
||||||
|
for (const [id, node] of flow.nodes.entries()) {
|
||||||
|
const [left, right] = node.kind === 'branch' ? ['{', '}'] : node.kind === 'end' ? ['([', '])'] : ['[', ']'];
|
||||||
|
const characters = [...node.label];
|
||||||
|
let label = node.label;
|
||||||
|
if (characters.length > 48) {
|
||||||
|
const prefix = characters.slice(0, 42).join('');
|
||||||
|
const args = node.kind === 'branch' ? -1 : prefix.indexOf('(');
|
||||||
|
label = (args > 0 ? prefix.slice(0, args) + '(…)' : prefix + '…') + ' [' + (id + 1) + ']';
|
||||||
|
full.push(`节点 ${id + 1}`, '', ...node.label.split('\n').map(line => ' ' + line), '');
|
||||||
|
}
|
||||||
|
lines.push(' n' + id + left + '"' + escape(label) + '"' + right);
|
||||||
|
if (node.site) {
|
||||||
|
const target = pathToFileURL(index.files[node.site.file].path);
|
||||||
|
target.hash = 'L' + (node.site.start.line + 1) + ',' + (node.site.start.character + 1);
|
||||||
|
lines.push(' click n' + id + ' href "' + target.href + '" "打开源码"');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const edge of flow.edges) lines.push(' n' + edge.from + ' -->' + (edge.label ? '|"' + escape(edge.label) + '"|' : '') + ' n' + edge.to);
|
||||||
|
lines.push(fence, '');
|
||||||
|
if (full.length) {
|
||||||
|
lines.push('带编号节点的原文见「实现细节」。', '');
|
||||||
|
labels.push('### ' + index.symbols.find(symbol => symbol.id === flow.symbol).name, '', ...full);
|
||||||
|
}
|
||||||
|
for (const node of flow.nodes) if (node.target) {
|
||||||
|
const target = 'command:dever.expandFlow?' + encodeURIComponent(JSON.stringify([root, node.target]));
|
||||||
|
lines.push('[展开 ' + node.target + '](' + target + ')', '');
|
||||||
|
}
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
|
module.exports = { workflow };
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Dever 示例项目
|
||||||
|
|
||||||
|
| 示例 | 阅读入口 | 运行条件 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| [文字游戏](text_game/README.md) | `game.escape.play`:规则表、状态推进和提前结束 | 可以直接运行,使用公开 HTTP,不需要数据库。 |
|
||||||
|
| [小 CMS](cms/README.md) | `content.article.publish`:数据模型、事务、分类与评论 | Test 使用隔离 SQLite;后台 HTTP 需要真实身份 Provider。 |
|
||||||
|
| [Agent](agent/README.md) | `assistant.agent.ask`:模型 Port、工具调用与轮数限制 | Test 使用模型替身;真实调用需要支持工具调用的模型和身份 Provider。 |
|
||||||
|
|
||||||
|
在示例目录执行 `dever check .` 和 `dever test .`。真实 HTTP 的启动方式、请求和预期结果见各示例说明。`link.md` 由 `dever inspect . --links` 从源码生成。
|
||||||
|
|
||||||
|
[业务合同夹具](workflows/README.md)用于展示订单与支付、审批、组织树、租户导入及筛选写法。它们没有组合成可运行的应用。
|
||||||
|
|
||||||
|
从空目录开发,请阅读[快速上手](../../GETTING_STARTED.md)。
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
开始任务前先读取 `/dm/AGENTS.md`,再读取目标路径适用的子级规则。
|
||||||
|
|
||||||
|
本项目使用 `core/skills/dever/SKILL.md` 的目录和边界合同,语法以 LANGUAGE 为准。Agent 状态和工具计算留在 Dever,JavaScript 只适配模型协议。Test 的 Port fake 只用于隔离模型边界,不把 fake 结果写成真实模型调用或受保护 HTTP 验收通过。
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# 小型 ReAct Agent
|
||||||
|
|
||||||
|
本例演示 ReAct 工具调用:模型选择工具,Dever 执行计算并将结果交给模型,直到得到回答或耗尽轮次。模型通过 Ollama 的 [Chat API](https://docs.ollama.com/api/chat) 调用。[工具往返测试](test/assistant/agent/tool_roundtrip.dv)仅替换模型 Port,实际执行工具、消息追加和轮次推进。
|
||||||
|
|
||||||
|
## 从这里读
|
||||||
|
|
||||||
|
1. [chat.dv](module/assistant/agent/api/web/chat.dv):一行受保护的 `long post ask`,外部模型调用不放进数据库事务。
|
||||||
|
2. [flow/agent.dv](module/assistant/agent/flow/agent.dv):先看 `ask → think → step → respond`。
|
||||||
|
3. 同文件 `executeTools → executeTool → calculate`:真正执行加法、乘法,把结果追加为 tool 消息。
|
||||||
|
4. [port/agent.dv](module/assistant/agent/port/agent.dv) 和 [适配器](module/assistant/agent/javascript/chat.mjs):一次模型调用的类型边界与 Ollama 协议转换。
|
||||||
|
|
||||||
|
```text
|
||||||
|
ask
|
||||||
|
think:最多调用模型 max_rounds 次
|
||||||
|
step:携带完整消息历史调用模型
|
||||||
|
respond
|
||||||
|
有工具调用 → 顺序执行 → 追加工具结果 → 下一轮
|
||||||
|
无工具调用 → 保存最终回答 → 结束循环
|
||||||
|
check:有回答则返回;预算耗尽仍未回答则明确失败
|
||||||
|
```
|
||||||
|
|
||||||
|
工具是普通的 Dever 计算,没有动态执行代码、工具注册表或通用 Agent 框架。`calculate` 的两行就是允许执行的全部工具。这里的工具无副作用;以后添加发邮件、支付等工具,须另行定义权限、确认和失败合同,不能照搬纯计算工具的处理。
|
||||||
|
|
||||||
|
## 怎么用
|
||||||
|
|
||||||
|
先在 [setting.json](config/setting.json) 填入实际 Ollama `/api/chat` 地址、支持 function tools 的模型名和每次请求的超时。示例地址故意使用 `.invalid`,不会指向某个已有服务。不自动启动、下载模型或调用收费服务。
|
||||||
|
|
||||||
|
HTTP 入口默认要求身份与对应权限,不公开模型调用能力。当前配置只列出站点路径、监听地址和模型设置,**真实登录 Provider 尚未接入,不能直接启动为完整服务**。运行前须接入 Provider、verify、登录和授权;缺失时明确报错,不增加假身份或降为匿名。
|
||||||
|
|
||||||
|
在项目目录执行 `dever test .` 验证业务;用 `dever lib install .` 准备受管 Node Worker 及原生依赖锁。真实认证和模型配置准备好之后,网页发送下列请求,携带已有登录凭据:
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /assistant/agent/web/chat/ask
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"question": "先算 12 加 30,再把结果乘以 2。请使用工具。",
|
||||||
|
"max_rounds": 5
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
一种可能的调用过程如下;这不是实测记录,也不保证模型每次选择完全相同的路径:
|
||||||
|
|
||||||
|
| 轮次 | 模型请求 | Dever 执行 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 1 | `Add(a=12, b=30)` | 得到 42,写入消息历史 |
|
||||||
|
| 2 | `Multiply(a=42, b=2)` | 得到 84,写入消息历史 |
|
||||||
|
| 3 | 最终回答 | 返回 `answer` 和 `rounds=3` |
|
||||||
|
|
||||||
|
同一轮多个工具按模型返回顺序执行,所有结果都带工具名称回传。模型最后一轮仍要求工具时,循环消耗完预算,主流程的 check 报 `BudgetExceeded`。`max_rounds` 统计模型调用次数,不是工具数。
|
||||||
|
|
||||||
|
消息追加直接写在 step 中,最终回答直接放入 State。工具循环只接收消息列表,不搬运整个 Agent 状态;不另设 remember、complete、finish 转发函数。
|
||||||
|
|
||||||
|
## 哪些检查只做一次
|
||||||
|
|
||||||
|
`Arguments` 声明参数类型与范围,受管 Worker 返回到 Dever 时按生成的合同校验,内部 `calculate` 不再检查。ToolName 使用普通枚举;未知工具名、错误参数和超范围值在 Port 边界拒绝。Ollama 的工具描述提供协议所需的名称与 JSON 形状,不在 JavaScript 重写参数范围或业务计算。
|
||||||
|
|
||||||
|
网络、超时、取消、JSON 和 Worker 合同错误直接传播,不自动重试,不补空答案。Ollama 普通回答可省略 `tool_calls`,适配器按协议转成空列表;明确的 null 或损坏结构不作“没有工具”处理。适配器接收并传播 Worker 的取消信号。
|
||||||
|
|
||||||
|
本例尚未完成真实 Ollama 模型调用与真实登录 Provider 接入。Worker 范围/枚举、受管资源和取消收尾由核心专项测试覆盖,不能据此声称已完成该项目的外部环境验收。JavaScript 单测只核对协议转换与错误传播。工作流由 [link.md](module/assistant/agent/link.md) 从真实源码生成。
|
||||||
|
|
||||||
|
## 新编译器的验收输入
|
||||||
|
|
||||||
|
| 场景 | 应有结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 未登录或没有入口权限 | 在 HTTP 边界拒绝,不调用模型 |
|
||||||
|
| 第一轮直接回答 | 返回答案,rounds=1 |
|
||||||
|
| 加法后乘法,再回答 | 工具结果进入下一轮消息,最终为 84 |
|
||||||
|
| 同轮多个工具 | 按顺序各执行一次,保留全部结果 |
|
||||||
|
| 每轮都要求工具 | 达到预算报 BudgetExceeded |
|
||||||
|
| 未知工具、缺参数、超范围 | Port 边界拒绝,不执行工具 |
|
||||||
|
| 网络失败、模型超时 | 保留失败,不返回空字符串成功 |
|
||||||
|
| 调用取消 | 停止网络与后续轮次,等待 Worker 收尾 |
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"adapter": {
|
||||||
|
"assistant.agent": {
|
||||||
|
"setting": {
|
||||||
|
"endpoint": "http://ollama.example.invalid:11434/api/chat",
|
||||||
|
"model": "replace-with-your-tool-capable-model",
|
||||||
|
"timeout_ms": 30000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"sites": { "web": { "path": "web" } },
|
||||||
|
"http": { "host": "127.0.0.1", "port": 18091 },
|
||||||
|
"log": { "level": "info" }
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
负责一次有预算的工具型 Agent 调用。主流程和工具规则见 [flow/agent.dv](flow/agent.dv),使用例子见 [项目说明](../../../README.md),符号说明见 [Agent 主题](doc/agent.md)。
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
setting {
|
||||||
|
endpoint: Text
|
||||||
|
model: Text
|
||||||
|
timeout_ms: Int >= 1 and <= 3600000
|
||||||
|
}
|
||||||
|
|
||||||
|
external npm "javascript/chat.mjs" {
|
||||||
|
allow network
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
long post ask = app.ask
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Agent
|
||||||
|
|
||||||
|
## assistant.agent.app.ask
|
||||||
|
|
||||||
|
模型可以直接回答,也可以请求使用计算工具。函数返回模型的最终回答和调用次数。如果用完允许的轮次仍没有回答,函数会报错。
|
||||||
|
|
||||||
|
## assistant.agent.app.think
|
||||||
|
|
||||||
|
每次消费一个轮次,得到最终回答便停止。全部轮次共享消息历史,工具结果进入下一次模型请求。
|
||||||
|
|
||||||
|
## assistant.agent.app.calculate
|
||||||
|
|
||||||
|
根据工具名选择加法或乘法。参数类型和范围由 Port 返回边界保证,这里只做计算。
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
type ToolName {
|
||||||
|
Add
|
||||||
|
Multiply
|
||||||
|
}
|
||||||
|
|
||||||
|
type Arguments {
|
||||||
|
a: Int >= -1000000 and <= 1000000
|
||||||
|
b: Int >= -1000000 and <= 1000000
|
||||||
|
}
|
||||||
|
|
||||||
|
type ToolCall {
|
||||||
|
name: ToolName
|
||||||
|
arguments: Arguments
|
||||||
|
}
|
||||||
|
|
||||||
|
type Message {
|
||||||
|
role: Text
|
||||||
|
content: Text
|
||||||
|
calls: List<ToolCall>
|
||||||
|
tool_name: ToolName?
|
||||||
|
}
|
||||||
|
|
||||||
|
type Turn {
|
||||||
|
content: Text
|
||||||
|
calls: List<ToolCall>
|
||||||
|
}
|
||||||
|
|
||||||
|
type State {
|
||||||
|
messages: List<Message>
|
||||||
|
answer: Text?
|
||||||
|
rounds: Int
|
||||||
|
}
|
||||||
|
|
||||||
|
type Reply {
|
||||||
|
answer: Text
|
||||||
|
rounds: Int
|
||||||
|
}
|
||||||
|
|
||||||
|
type Problem {
|
||||||
|
error BudgetExceeded
|
||||||
|
}
|
||||||
|
|
||||||
|
flow ask(question: Text, max_rounds: Int >= 1 and <= 10) (reply: Reply) {
|
||||||
|
state = app.think(question, max_rounds)
|
||||||
|
answer = state.answer
|
||||||
|
check answer != null else Problem.BudgetExceeded
|
||||||
|
reply = Reply { answer = answer, rounds = state.rounds }
|
||||||
|
}
|
||||||
|
|
||||||
|
flow step(index: Int, current: State) (acc: State, stop: Bool) {
|
||||||
|
turn = port.chat(current.messages)
|
||||||
|
messages = append(current.messages, Message { role = "assistant", content = turn.content, calls = turn.calls, tool_name = null })
|
||||||
|
stop = length(turn.calls) == 0
|
||||||
|
acc = app.respond(stop, turn, messages, index + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
start(question: Text) (state: State) {
|
||||||
|
state = State {
|
||||||
|
messages = [Message {
|
||||||
|
role = "system"
|
||||||
|
content = "你是计算助手。加法和乘法必须调用工具,用工具结果继续任务,完成后给出简短中文答案。"
|
||||||
|
calls = []
|
||||||
|
tool_name = null
|
||||||
|
}, Message { role = "user", content = question, calls = [], tool_name = null }]
|
||||||
|
answer = null
|
||||||
|
rounds = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
executeTool(call: ToolCall, messages: List<Message>) (next: List<Message>) {
|
||||||
|
value = app.calculate(call.name, call.arguments)
|
||||||
|
next = append(messages, Message { role = "tool", content = int.toText(value), calls = [], tool_name = call.name })
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
// 只转换 Ollama 协议;选工具、执行工具和推进轮次都在 Dever 中。
|
||||||
|
const tools = ['Add', 'Multiply'].map(name => ({
|
||||||
|
type: 'function',
|
||||||
|
function: {
|
||||||
|
name,
|
||||||
|
description: name === 'Add' ? '计算两个整数的和' : '计算两个整数的乘积',
|
||||||
|
parameters: {
|
||||||
|
type: 'object',
|
||||||
|
properties: {
|
||||||
|
a: { type: 'integer' },
|
||||||
|
b: { type: 'integer' }
|
||||||
|
},
|
||||||
|
required: ['a', 'b'],
|
||||||
|
additionalProperties: false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
function toMessage(message) {
|
||||||
|
const output = { role: message.role, content: message.content };
|
||||||
|
if (message.calls.length > 0) {
|
||||||
|
output.tool_calls = message.calls.map(call => ({ function: call }));
|
||||||
|
}
|
||||||
|
if (message.tool_name !== null) output.tool_name = message.tool_name;
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function chat(payload, setting, signal) {
|
||||||
|
const response = await fetch(setting.endpoint, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
model: setting.model,
|
||||||
|
messages: payload.messages.map(toMessage),
|
||||||
|
tools,
|
||||||
|
stream: false
|
||||||
|
}),
|
||||||
|
signal: AbortSignal.any([signal, AbortSignal.timeout(setting.timeout_ms)])
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error(`Ollama HTTP ${response.status}`);
|
||||||
|
const { message } = await response.json();
|
||||||
|
// tool_calls 在普通回答中可省略,这是协议定义的缺省,不是失败兜底。
|
||||||
|
const calls = message.tool_calls === undefined ? [] : message.tool_calls;
|
||||||
|
return {
|
||||||
|
turn: {
|
||||||
|
content: message.content,
|
||||||
|
calls: calls.map(({ function: call }) => ({
|
||||||
|
name: call.name,
|
||||||
|
arguments: call.arguments
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,513 @@
|
|||||||
|
<!-- Generated by dever inspect --links. Do not edit. -->
|
||||||
|
<!-- source-sha256: d0add6b9bc387eed7ab8561bafa659d8df2e8cc009d1c4523f11ee31aa171138 -->
|
||||||
|
|
||||||
|
# assistant/agent
|
||||||
|
|
||||||
|
按源码顺序阅读。图显示静态路径;运行故障结束当前调用,不是某次执行记录。
|
||||||
|
|
||||||
|
<a id="flow-274afd57a15a6a9cbfc1daeda85f059f1fb494e6285b6adb1e242d7f6213d70d"></a>
|
||||||
|
|
||||||
|
## assistant.agent.adapter.Setting
|
||||||
|
|
||||||
|
```dever
|
||||||
|
type assistant.agent.adapter.Setting
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<adapter/agent.dv#L1,1>)
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-3ac77485267f2f31580e6e2c6bf87b474f7b128ff06c29d914adeaea6bfc9aa8"></a>
|
||||||
|
|
||||||
|
## assistant.agent.adapter.setting
|
||||||
|
|
||||||
|
```dever
|
||||||
|
setting assistant.agent.adapter.setting: Setting
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<adapter/agent.dv#L1,1>)
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-a3aa464e21a51002ef06804f11ad182c00fc1f83b63e3179ab06309fa705feef"></a>
|
||||||
|
|
||||||
|
## assistant.agent.adapter.port.chat
|
||||||
|
|
||||||
|
```dever
|
||||||
|
assistant.agent.adapter.port.chat(messages: List<app.Message>) (turn: app.Turn)
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<adapter/agent.dv#L7,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0(["assistant.agent.adapter.port.chat"])
|
||||||
|
click n0 href "adapter/agent.dv#L7,1" "打开源码"
|
||||||
|
n1(["返回结果"])
|
||||||
|
n2["调用外部 Worker:握手后复用会话;响应按 Port 解码"]
|
||||||
|
click n2 href "adapter/agent.dv#L7,1" "打开源码"
|
||||||
|
n3["交付结果;取消时排空响应,协议故障回收进程组"]
|
||||||
|
click n3 href "adapter/agent.dv#L7,1" "打开源码"
|
||||||
|
n4(["传播原错误"])
|
||||||
|
n5["port · turn = external npm #34;javascript/chat.mjs#34; { allow network }"]
|
||||||
|
click n5 href "adapter/agent.dv#L7,1" "打开源码"
|
||||||
|
n0 --> n2
|
||||||
|
n2 --> n3
|
||||||
|
n2 -->|"失败"| n4
|
||||||
|
n3 --> n5
|
||||||
|
n5 --> n1
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-6f694083978d64cd744cea63939dfc841312dd01f6b300998d70d89f4b150d2d"></a>
|
||||||
|
|
||||||
|
## POST /assistant/agent/web/chat/ask
|
||||||
|
|
||||||
|
```dever
|
||||||
|
long post ask = app.ask
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<api/web/chat.dv#L1,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0["POST /assistant/agent/web/chat/ask"]
|
||||||
|
click n0 href "api/web/chat.dv#L1,1" "打开源码"
|
||||||
|
n1["站点 Host 校验"]
|
||||||
|
click n1 href "api/web/chat.dv#L1,1" "打开源码"
|
||||||
|
n2["签名、站点与有效期 → 项目 verify"]
|
||||||
|
click n2 href "api/web/chat.dv#L1,1" "打开源码"
|
||||||
|
n3["按可信身份选择物理租户库;global 保留控制库"]
|
||||||
|
click n3 href "api/web/chat.dv#L1,1" "打开源码"
|
||||||
|
n4["查询当前角色与精确入口权限"]
|
||||||
|
click n4 href "api/web/chat.dv#L1,1" "打开源码"
|
||||||
|
n5["按参数类型解码;拒绝未知、重复及缺失字段"]
|
||||||
|
click n5 href "api/web/chat.dv#L1,1" "打开源码"
|
||||||
|
n6[["assistant.agent.app.ask"]]
|
||||||
|
click n6 href "api/web/chat.dv#L1,1" "打开源码"
|
||||||
|
n7["返回 code / message / data"]
|
||||||
|
click n7 href "api/web/chat.dv#L1,1" "打开源码"
|
||||||
|
n8["错误响应;内部原因仅记服务日志"]
|
||||||
|
click n8 href "api/web/chat.dv#L1,1" "打开源码"
|
||||||
|
n0 -->|"成功"| n1
|
||||||
|
n1 -->|"通过"| n2
|
||||||
|
n2 -->|"通过"| n3
|
||||||
|
n3 -->|"通过"| n4
|
||||||
|
n4 -->|"通过"| n5
|
||||||
|
n5 -->|"通过"| n6
|
||||||
|
n6 -->|"成功"| n7
|
||||||
|
n1 -->|"失败"| n8
|
||||||
|
n2 -->|"失败"| n8
|
||||||
|
n3 -->|"失败"| n8
|
||||||
|
n4 -->|"失败"| n8
|
||||||
|
n5 -->|"失败"| n8
|
||||||
|
n6 -->|"失败"| n8
|
||||||
|
```
|
||||||
|
|
||||||
|
- 子流程 [assistant.agent.app.ask](<link.md#flow-cced3f5750acdabc70274dd6b50b2dc66bec2ec9c2de329a6093013752606e98>)
|
||||||
|
|
||||||
|
<a id="flow-b68502d89d9c9df86b85908291f30d10ac90137ac0e8ea41d23939a2288732cf"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.ToolName
|
||||||
|
|
||||||
|
```dever
|
||||||
|
type assistant.agent.app.ToolName
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/agent.dv#L1,1>)
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-d72936d1428133b976d5b5104cfc0d1f0cc182d548509e85c5dab7fe9c143477"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.Arguments
|
||||||
|
|
||||||
|
```dever
|
||||||
|
type assistant.agent.app.Arguments
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/agent.dv#L6,1>)
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-fcf7fc516bc34e2836302ca8e958b950c39e2c411043d64fb20be89a1ded1f72"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.ToolCall
|
||||||
|
|
||||||
|
```dever
|
||||||
|
type assistant.agent.app.ToolCall
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/agent.dv#L11,1>)
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-b4c0c8f75b2439058680a70a363bea8d8f5817fe4225f7d96fafdbefa7bfcedb"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.Message
|
||||||
|
|
||||||
|
```dever
|
||||||
|
type assistant.agent.app.Message
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/agent.dv#L16,1>)
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-9e0ee8ce21af8a55fb93fdca007630e49409e90d8d53dd700ed2330b1103a5bd"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.Turn
|
||||||
|
|
||||||
|
```dever
|
||||||
|
type assistant.agent.app.Turn
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/agent.dv#L23,1>)
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-50bf94a1a786c8d6f4030a6cedafc280ae843a47713d1083cbc617e3a6e41189"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.State
|
||||||
|
|
||||||
|
```dever
|
||||||
|
type assistant.agent.app.State
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/agent.dv#L28,1>)
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-7d5425798884f00a8899d9c6a872c9a22623235aa35c4be73f8c002697d3825e"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.Reply
|
||||||
|
|
||||||
|
```dever
|
||||||
|
type assistant.agent.app.Reply
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/agent.dv#L34,1>)
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-8c6491db0aa0a3624df68fb73f2c346be0e683c268a00b39852478598b342da2"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.Problem
|
||||||
|
|
||||||
|
```dever
|
||||||
|
type assistant.agent.app.Problem
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/agent.dv#L39,1>)
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-cced3f5750acdabc70274dd6b50b2dc66bec2ec9c2de329a6093013752606e98"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.ask
|
||||||
|
|
||||||
|
```dever
|
||||||
|
flow assistant.agent.app.ask(question: Text, max_rounds: Int >= 1 and <= 10) (reply: Reply)
|
||||||
|
```
|
||||||
|
|
||||||
|
模型可以直接回答,也可以请求使用计算工具。函数返回模型的最终回答和调用次数。如果用完允许的轮次仍没有回答,函数会报错。
|
||||||
|
|
||||||
|
[打开源码](<flow/agent.dv#L43,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0(["assistant.agent.app.ask"])
|
||||||
|
click n0 href "flow/agent.dv#L43,1" "打开源码"
|
||||||
|
n1(["返回结果"])
|
||||||
|
n2[["挂起 · app.think(question, max_rounds)"]]
|
||||||
|
click n2 href "flow/agent.dv#L44,11" "打开源码"
|
||||||
|
n3(["传播原错误"])
|
||||||
|
n4["loop · state = app.think(question, max_rounds)"]
|
||||||
|
click n4 href "flow/agent.dv#L44,3" "打开源码"
|
||||||
|
n5["calc · answer = state.answer"]
|
||||||
|
click n5 href "flow/agent.dv#L45,3" "打开源码"
|
||||||
|
n6{"check · answer != null"}
|
||||||
|
click n6 href "flow/agent.dv#L46,3" "打开源码"
|
||||||
|
n7["校验通过"]
|
||||||
|
n8["Problem.BudgetExceeded"]
|
||||||
|
click n8 href "flow/agent.dv#L46,29" "打开源码"
|
||||||
|
n9["calc · reply = Reply { answer = answer, rounds = state.rounds }"]
|
||||||
|
click n9 href "flow/agent.dv#L47,3" "打开源码"
|
||||||
|
n0 --> n2
|
||||||
|
n2 -->|"失败"| n3
|
||||||
|
n2 --> n4
|
||||||
|
n4 --> n5
|
||||||
|
n5 --> n6
|
||||||
|
n6 -->|"成立"| n7
|
||||||
|
n6 -->|"不成立"| n8
|
||||||
|
n8 -->|"失败"| n3
|
||||||
|
n7 --> n9
|
||||||
|
n9 --> n1
|
||||||
|
```
|
||||||
|
|
||||||
|
- 子流程 [assistant.agent.app.think](<link.md#flow-601fc7d46004bfb0408dc6f04811585a7dae0be561564f706068c01eed7ce47c>)
|
||||||
|
|
||||||
|
<a id="flow-57d7e01fc5b7bc1793b5e455a88448f5e7a9a5c465491f982ea948c1863158b7"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.step
|
||||||
|
|
||||||
|
```dever
|
||||||
|
flow assistant.agent.app.step(index: Int, current: State) (acc: State, stop: Bool)
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/agent.dv#L50,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0(["assistant.agent.app.step"])
|
||||||
|
click n0 href "flow/agent.dv#L50,1" "打开源码"
|
||||||
|
n1(["返回结果"])
|
||||||
|
n2[["挂起 · port.chat(current.messages)"]]
|
||||||
|
click n2 href "flow/agent.dv#L51,10" "打开源码"
|
||||||
|
n3(["传播原错误"])
|
||||||
|
n4["port · turn = port.chat(current.messages)"]
|
||||||
|
click n4 href "flow/agent.dv#L51,3" "打开源码"
|
||||||
|
n5["calc · messages = append(current.messages, Message { role = #34;assistant#34;, content = turn.content, calls = turn.calls, tool_name = null })"]
|
||||||
|
click n5 href "flow/agent.dv#L52,3" "打开源码"
|
||||||
|
n6["calc · stop = length(turn.calls) == 0"]
|
||||||
|
click n6 href "flow/agent.dv#L53,3" "打开源码"
|
||||||
|
n7[["app.respond(stop, turn, messages, index + 1)"]]
|
||||||
|
click n7 href "flow/agent.dv#L54,9" "打开源码"
|
||||||
|
n8["rule · acc = app.respond(stop, turn, messages, index + 1)"]
|
||||||
|
click n8 href "flow/agent.dv#L54,3" "打开源码"
|
||||||
|
n0 --> n2
|
||||||
|
n2 -->|"失败"| n3
|
||||||
|
n2 --> n4
|
||||||
|
n4 --> n5
|
||||||
|
n5 --> n6
|
||||||
|
n6 --> n7
|
||||||
|
n7 --> n8
|
||||||
|
n8 --> n1
|
||||||
|
```
|
||||||
|
|
||||||
|
- 子流程 [assistant.agent.adapter.port.chat](<link.md#flow-a3aa464e21a51002ef06804f11ad182c00fc1f83b63e3179ab06309fa705feef>)
|
||||||
|
- 子流程 [assistant.agent.app.respond](<link.md#flow-4b72c07e9544551c93a81251675b198b906f26b506d3cbf90920855875ed4aef>)
|
||||||
|
|
||||||
|
<a id="flow-9de7b5ba6751c54e8b3198b49ddb4a8f9630f5b568b3ea8e67da38dee25d449f"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.start
|
||||||
|
|
||||||
|
```dever
|
||||||
|
assistant.agent.app.start(question: Text) (state: State)
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/agent.dv#L57,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0(["assistant.agent.app.start"])
|
||||||
|
click n0 href "flow/agent.dv#L57,1" "打开源码"
|
||||||
|
n1(["返回结果"])
|
||||||
|
n2["state = State { messages = [Message { role = #34;system#34; content = #34;你是计算助手。加法和乘法必须调用工具,用工具结果继续任务,完成后给出简短中文答案。#34; calls = [] tool_name = null }, Message { role = #34;user#34;, content = question, calls = [], tool_name = null }] answer = null rounds = 0 }"]
|
||||||
|
click n2 href "flow/agent.dv#L58,11" "打开源码"
|
||||||
|
n0 --> n2
|
||||||
|
n2 --> n1
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-b10562e5aa621d3f01b7629c0aa8aa651fd3f6ccd8f71e199e76a3c425203014"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.executeTool
|
||||||
|
|
||||||
|
```dever
|
||||||
|
assistant.agent.app.executeTool(call: ToolCall, messages: List<Message>) (next: List<Message>)
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/agent.dv#L70,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0(["assistant.agent.app.executeTool"])
|
||||||
|
click n0 href "flow/agent.dv#L70,1" "打开源码"
|
||||||
|
n1(["返回结果"])
|
||||||
|
n2[["app.calculate(call.name, call.arguments)"]]
|
||||||
|
click n2 href "flow/agent.dv#L71,11" "打开源码"
|
||||||
|
n3["value = app.calculate(call.name, call.arguments)"]
|
||||||
|
click n3 href "flow/agent.dv#L71,11" "打开源码"
|
||||||
|
n4[["int.toText(value)"]]
|
||||||
|
click n4 href "flow/agent.dv#L72,62" "打开源码"
|
||||||
|
n5["next = append(messages, Message { role = #34;tool#34;, content = int.toText(value), calls = [], tool_name = call.name })"]
|
||||||
|
click n5 href "flow/agent.dv#L72,10" "打开源码"
|
||||||
|
n0 --> n2
|
||||||
|
n2 --> n3
|
||||||
|
n3 --> n4
|
||||||
|
n4 --> n5
|
||||||
|
n5 --> n1
|
||||||
|
```
|
||||||
|
|
||||||
|
- 子流程 [assistant.agent.app.calculate](<link.md#flow-fc4b94463ebbc65f8e5e9bc05b18295ec6aa43e7fa8ebec24a4becba0f05955a>)
|
||||||
|
- 子流程 [dever.int.app.toText](<../../dever/int/link.md#flow-6ee889c4b5160675479210a68a4370d8ec43f5806985e52d961dc433a86fc8d1>)
|
||||||
|
|
||||||
|
<a id="flow-601fc7d46004bfb0408dc6f04811585a7dae0be561564f706068c01eed7ce47c"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.think
|
||||||
|
|
||||||
|
```dever
|
||||||
|
loop assistant.agent.app.think(question: Text, max_rounds: Int >= 1 and <= 10) (state: State)
|
||||||
|
```
|
||||||
|
|
||||||
|
每次消费一个轮次,得到最终回答便停止。全部轮次共享消息历史,工具结果进入下一次模型请求。
|
||||||
|
|
||||||
|
[打开源码](<loop/agent.dv#L1,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0(["assistant.agent.app.think"])
|
||||||
|
click n0 href "loop/agent.dv#L1,1" "打开源码"
|
||||||
|
n1(["返回结果"])
|
||||||
|
n2[["app.start(question)"]]
|
||||||
|
click n2 href "loop/agent.dv#L3,23" "打开源码"
|
||||||
|
n3["初始化 current: app.start(question)"]
|
||||||
|
click n3 href "loop/agent.dv#L3,23" "打开源码"
|
||||||
|
n4{"全部行完成则停止,否则拉取下一元素"}
|
||||||
|
click n4 href "loop/agent.dv#L2,1" "打开源码"
|
||||||
|
n5["foldUntil(current = app.start(question), app.step(index, current))"]
|
||||||
|
click n5 href "loop/agent.dv#L3,3" "打开源码"
|
||||||
|
n6["下一输出行"]
|
||||||
|
n7{"本行是否已完成"}
|
||||||
|
click n7 href "loop/agent.dv#L3,3" "打开源码"
|
||||||
|
n8[["挂起 · app.step(index, current)"]]
|
||||||
|
click n8 href "loop/agent.dv#L3,44" "打开源码"
|
||||||
|
n9(["传播原错误"])
|
||||||
|
n10["采用新的累积状态"]
|
||||||
|
click n10 href "loop/agent.dv#L3,3" "打开源码"
|
||||||
|
n11{"stop 是否为 true"}
|
||||||
|
click n11 href "loop/agent.dv#L3,3" "打开源码"
|
||||||
|
n0 --> n2
|
||||||
|
n2 -->|"只求值一次"| n3
|
||||||
|
n3 -->|"来源只求值一次"| n4
|
||||||
|
n4 -->|"来源耗尽或全部完成"| n1
|
||||||
|
n4 --> n7
|
||||||
|
n7 -->|"已完成,跳过"| n6
|
||||||
|
n7 -->|"未完成"| n5
|
||||||
|
n5 --> n8
|
||||||
|
n8 -->|"失败"| n9
|
||||||
|
n8 -->|"更新成功"| n10
|
||||||
|
n10 -->|"随后判断停止"| n11
|
||||||
|
n11 -->|"是,标记本行完成"| n6
|
||||||
|
n11 -->|"否,本行继续累积"| n6
|
||||||
|
n6 -->|"继续"| n4
|
||||||
|
```
|
||||||
|
|
||||||
|
- 子流程 [assistant.agent.app.start](<link.md#flow-9de7b5ba6751c54e8b3198b49ddb4a8f9630f5b568b3ea8e67da38dee25d449f>)
|
||||||
|
- 子流程 [assistant.agent.app.step](<link.md#flow-57d7e01fc5b7bc1793b5e455a88448f5e7a9a5c465491f982ea948c1863158b7>)
|
||||||
|
|
||||||
|
<a id="flow-7812dd91228edaecfeb6fa6d35bf912008c8dadfed8d620ae1d188a1ca37f240"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.executeTools
|
||||||
|
|
||||||
|
```dever
|
||||||
|
loop assistant.agent.app.executeTools(calls: List<ToolCall>, messages: List<Message>) (next: List<Message>)
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<loop/agent.dv#L6,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0(["assistant.agent.app.executeTools"])
|
||||||
|
click n0 href "loop/agent.dv#L6,1" "打开源码"
|
||||||
|
n1(["返回结果"])
|
||||||
|
n2["初始化 current: messages"]
|
||||||
|
click n2 href "loop/agent.dv#L8,18" "打开源码"
|
||||||
|
n3{"全部行完成则停止,否则拉取下一元素"}
|
||||||
|
click n3 href "loop/agent.dv#L7,1" "打开源码"
|
||||||
|
n4["fold(current = messages, app.executeTool(call, current))"]
|
||||||
|
click n4 href "loop/agent.dv#L8,3" "打开源码"
|
||||||
|
n5["下一输出行"]
|
||||||
|
n6[["app.executeTool(call, current)"]]
|
||||||
|
click n6 href "loop/agent.dv#L8,28" "打开源码"
|
||||||
|
n0 -->|"只求值一次"| n2
|
||||||
|
n2 -->|"来源只求值一次"| n3
|
||||||
|
n3 -->|"来源耗尽或全部完成"| n1
|
||||||
|
n3 --> n4
|
||||||
|
n4 --> n6
|
||||||
|
n6 -->|"更新本行结果"| n5
|
||||||
|
n5 -->|"继续"| n3
|
||||||
|
```
|
||||||
|
|
||||||
|
- 子流程 [assistant.agent.app.executeTool](<link.md#flow-b10562e5aa621d3f01b7629c0aa8aa651fd3f6ccd8f71e199e76a3c425203014>)
|
||||||
|
|
||||||
|
<a id="flow-31a99349d15c55180048fb9e394ae9b6238e21625731653fa2f8389bcf34e184"></a>
|
||||||
|
|
||||||
|
## assistant.agent.port.chat
|
||||||
|
|
||||||
|
```dever
|
||||||
|
assistant.agent.port.chat(messages: List<app.Message>) (turn: app.Turn) fails dever.process.Error
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<port/agent.dv#L1,1>)
|
||||||
|
|
||||||
|
- 入口绑定 [assistant.agent.adapter.port.chat](<link.md#flow-a3aa464e21a51002ef06804f11ad182c00fc1f83b63e3179ab06309fa705feef>)
|
||||||
|
|
||||||
|
<a id="flow-4b72c07e9544551c93a81251675b198b906f26b506d3cbf90920855875ed4aef"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.respond
|
||||||
|
|
||||||
|
```dever
|
||||||
|
rule assistant.agent.app.respond(finished: Bool, turn: Turn, messages: List<Message>, rounds: Int) (state: State)
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<rule/agent.dv#L1,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0(["assistant.agent.app.respond"])
|
||||||
|
click n0 href "rule/agent.dv#L1,1" "打开源码"
|
||||||
|
n1(["返回结果"])
|
||||||
|
n2{"按输入选择唯一规则行"}
|
||||||
|
click n2 href "rule/agent.dv#L1,1" "打开源码"
|
||||||
|
n3["finished: true"]
|
||||||
|
click n3 href "rule/agent.dv#L3,3" "打开源码"
|
||||||
|
n4["state = State { messages = messages, answer = turn.content, rounds = rounds }"]
|
||||||
|
click n4 href "rule/agent.dv#L3,11" "打开源码"
|
||||||
|
n5["finished: false"]
|
||||||
|
click n5 href "rule/agent.dv#L4,3" "打开源码"
|
||||||
|
n6[["app.executeTools(turn.calls, messages)"]]
|
||||||
|
click n6 href "rule/agent.dv#L4,31" "打开源码"
|
||||||
|
n7["state = State { messages = app.executeTools(turn.calls, messages), answer = null, rounds = rounds }"]
|
||||||
|
click n7 href "rule/agent.dv#L4,12" "打开源码"
|
||||||
|
n0 --> n2
|
||||||
|
n2 -->|"匹配"| n3
|
||||||
|
n3 --> n4
|
||||||
|
n4 --> n1
|
||||||
|
n2 -->|"匹配"| n5
|
||||||
|
n5 --> n6
|
||||||
|
n6 --> n7
|
||||||
|
n7 --> n1
|
||||||
|
```
|
||||||
|
|
||||||
|
- 子流程 [assistant.agent.app.executeTools](<link.md#flow-7812dd91228edaecfeb6fa6d35bf912008c8dadfed8d620ae1d188a1ca37f240>)
|
||||||
|
|
||||||
|
<a id="flow-fc4b94463ebbc65f8e5e9bc05b18295ec6aa43e7fa8ebec24a4becba0f05955a"></a>
|
||||||
|
|
||||||
|
## assistant.agent.app.calculate
|
||||||
|
|
||||||
|
```dever
|
||||||
|
rule assistant.agent.app.calculate(name: ToolName, args: Arguments) (value: Int)
|
||||||
|
```
|
||||||
|
|
||||||
|
根据工具名选择加法或乘法。参数类型和范围由 Port 返回边界保证,这里只做计算。
|
||||||
|
|
||||||
|
[打开源码](<rule/agent.dv#L7,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0(["assistant.agent.app.calculate"])
|
||||||
|
click n0 href "rule/agent.dv#L7,1" "打开源码"
|
||||||
|
n1(["返回结果"])
|
||||||
|
n2{"按输入选择唯一规则行"}
|
||||||
|
click n2 href "rule/agent.dv#L7,1" "打开源码"
|
||||||
|
n3["name: Add"]
|
||||||
|
click n3 href "rule/agent.dv#L9,3" "打开源码"
|
||||||
|
n4["value = args.a + args.b"]
|
||||||
|
click n4 href "rule/agent.dv#L9,10" "打开源码"
|
||||||
|
n5["name: Multiply"]
|
||||||
|
click n5 href "rule/agent.dv#L10,3" "打开源码"
|
||||||
|
n6["value = args.a * args.b"]
|
||||||
|
click n6 href "rule/agent.dv#L10,15" "打开源码"
|
||||||
|
n0 --> n2
|
||||||
|
n2 -->|"匹配"| n3
|
||||||
|
n3 --> n4
|
||||||
|
n4 --> n1
|
||||||
|
n2 -->|"匹配"| n5
|
||||||
|
n5 --> n6
|
||||||
|
n6 --> n1
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
loop think(question: Text, max_rounds: Int >= 1 and <= 10) (state: State)
|
||||||
|
index in range(0, max_rounds) {
|
||||||
|
foldUntil(current = app.start(question), app.step(index, current))
|
||||||
|
}
|
||||||
|
|
||||||
|
loop executeTools(calls: List<ToolCall>, messages: List<Message>) (next: List<Message>)
|
||||||
|
call in calls {
|
||||||
|
fold(current = messages, app.executeTool(call, current))
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
chat(messages: List<app.Message>) (turn: app.Turn) fails dever.process.Error
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
rule respond(finished: Bool, turn: Turn, messages: List<Message>, rounds: Int) (state: State)
|
||||||
|
finished {
|
||||||
|
true => State { messages = messages, answer = turn.content, rounds = rounds }
|
||||||
|
false => State { messages = app.executeTools(turn.calls, messages), answer = null, rounds = rounds }
|
||||||
|
}
|
||||||
|
|
||||||
|
rule calculate(name: ToolName, args: Arguments) (value: Int)
|
||||||
|
name {
|
||||||
|
Add => args.a + args.b
|
||||||
|
Multiply => args.a * args.b
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
flow toolRoundtrip() ()
|
||||||
|
| step | kind | do |
|
||||||
|
| reply | flow | app.ask("计算 12 + 30", 4) |
|
||||||
|
| - | calc | assertEq(reply.answer, "42") |
|
||||||
|
| - | calc | assertEq(reply.rounds, 2) |
|
||||||
|
|
||||||
|
port.chat(messages: List<app.Message>) (turn: app.Turn) {
|
||||||
|
turn = next(length(messages), messages)
|
||||||
|
}
|
||||||
|
|
||||||
|
rule next(count: Int, messages: List<app.Message>) (turn: app.Turn)
|
||||||
|
| count | messages | turn |
|
||||||
|
| <= 2 | - | app.Turn {
|
||||||
|
content = ""
|
||||||
|
calls = [app.ToolCall { name = app.ToolName.Add, arguments = app.Arguments { a = 12, b = 30 } }]
|
||||||
|
} |
|
||||||
|
| > 2 | - | finished(messages) |
|
||||||
|
|
||||||
|
finished(messages: List<app.Message>) (turn: app.Turn) {
|
||||||
|
last = get(messages, length(messages) - 1)
|
||||||
|
check last != null else dever.process.Error.Failed("missing tool message")
|
||||||
|
assertEq(last.role, "tool")
|
||||||
|
assertEq(last.tool_name, app.ToolName.Add)
|
||||||
|
turn = app.Turn { content = last.content, calls = [] }
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { chat } from '../../module/assistant/agent/javascript/chat.mjs';
|
||||||
|
|
||||||
|
const setting = { endpoint: 'https://example.invalid/api/chat', model: 'test-model', timeout_ms: 1000 };
|
||||||
|
const call = { name: 'Add', arguments: { a: 12, b: 30 } };
|
||||||
|
|
||||||
|
test('发送工具历史并转换模型调用,不把供应商 index 传入 Dever', async t => {
|
||||||
|
let sent;
|
||||||
|
t.mock.method(globalThis, 'fetch', async (url, request) => {
|
||||||
|
assert.equal(url, setting.endpoint);
|
||||||
|
sent = JSON.parse(request.body);
|
||||||
|
return Response.json({ message: { content: '', tool_calls: [{ function: { index: 0, ...call } }] } });
|
||||||
|
});
|
||||||
|
const messages = [
|
||||||
|
{ role: 'user', content: '计算', calls: [], tool_name: null },
|
||||||
|
{ role: 'assistant', content: '', calls: [call], tool_name: null },
|
||||||
|
{ role: 'tool', content: '42', calls: [], tool_name: 'Add' }
|
||||||
|
];
|
||||||
|
const output = await chat({ messages }, setting, new AbortController().signal);
|
||||||
|
assert.deepEqual(output, { turn: { content: '', calls: [call] } });
|
||||||
|
assert.deepEqual(sent.messages, [
|
||||||
|
{ role: 'user', content: '计算' },
|
||||||
|
{ role: 'assistant', content: '', tool_calls: [{ function: call }] },
|
||||||
|
{ role: 'tool', content: '42', tool_name: 'Add' }
|
||||||
|
]);
|
||||||
|
assert.deepEqual(sent.tools.map(tool => tool.function.name), ['Add', 'Multiply']);
|
||||||
|
assert.equal(sent.stream, false);
|
||||||
|
assert.equal(sent.model, setting.model);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('普通回答允许省略 tool_calls', async t => {
|
||||||
|
t.mock.method(globalThis, 'fetch', async () => Response.json({ message: { content: '答案是 84。' } }));
|
||||||
|
assert.deepEqual(await chat({ messages: [] }, setting, new AbortController().signal), {
|
||||||
|
turn: { content: '答案是 84。', calls: [] }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('HTTP 失败向上传播', async t => {
|
||||||
|
t.mock.method(globalThis, 'fetch', async () => new Response('', { status: 503 }));
|
||||||
|
await assert.rejects(chat({ messages: [] }, setting, new AbortController().signal), /Ollama HTTP 503/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('取消信号到达 fetch,不产生成功结果', async t => {
|
||||||
|
t.mock.method(globalThis, 'fetch', async (_url, request) => {
|
||||||
|
request.signal.throwIfAborted();
|
||||||
|
assert.fail('已取消的请求不应继续');
|
||||||
|
});
|
||||||
|
const controller = new AbortController();
|
||||||
|
controller.abort(new Error('test cancellation'));
|
||||||
|
await assert.rejects(chat({ messages: [] }, setting, controller.signal), /test cancellation/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('损坏的 tool_calls 不当成没有工具', async t => {
|
||||||
|
t.mock.method(globalThis, 'fetch', async () => Response.json({ message: { content: '', tool_calls: null } }));
|
||||||
|
await assert.rejects(chat({ messages: [] }, setting, new AbortController().signal), TypeError);
|
||||||
|
});
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
开始任务前先读取 `/dm/AGENTS.md`,再读取目标路径适用的子级规则。
|
||||||
|
|
||||||
|
本项目以 CMS 为例演示 Dever 的数据模型与 HTTP 绑定,后台使用受保护入口,前台只公开已发布文章。普通 CRUD 优先 REST;有状态约束才写业务 flow。不默认加入版本控制和无用途的写后回查。真实登录 Provider 尚未接入,不将本例声称为完整可运行后台,不添加假 verify 或匿名管理入口。
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# 小 CMS:文章、分类与评论
|
||||||
|
|
||||||
|
本例使用数据模型和事务管理文章、分类与评论。前台可匿名阅读已发布的文章;后台 HTTP 入口需要配置身份 Provider。示例不提供管理网页或登录服务。[发布流程测试](test/content/article/publishing.dv)和[分类与评论测试](test/content/article/discussion.dv)使用临时 SQLite 数据库。
|
||||||
|
|
||||||
|
在项目目录执行 `dever check .` 和 `dever test .`;测试会隔离数据库,不读写示例 data。源码工作流见自动生成的 [link.md](module/content/article/link.md)。
|
||||||
|
|
||||||
|
## 基础 CRUD
|
||||||
|
|
||||||
|
普通文章数据模型配上 REST 入口,核心就是:
|
||||||
|
|
||||||
|
~~~dever
|
||||||
|
type Article {
|
||||||
|
title: Text(1, 200)
|
||||||
|
body: Text raw
|
||||||
|
}
|
||||||
|
~~~
|
||||||
|
|
||||||
|
~~~dever
|
||||||
|
rest data
|
||||||
|
~~~
|
||||||
|
|
||||||
|
常规 CRUD 直接使用 REST 绑定,无需编写转发流程。REST 的入口解码、字段约束、数据库操作和权限由既有能力承担;它仍需要真实身份配置,不是匿名接口。
|
||||||
|
|
||||||
|
## 有发布规则时才写 App
|
||||||
|
|
||||||
|
本例额外要求:只编辑和删除草稿,发布后可公开阅读,撤回后不再公开。因此文章使用明确业务入口,不能用无限制 replace 绕过这些规则。
|
||||||
|
|
||||||
|
- [data/cms.dv](module/content/article/data/article.dv):文章类型、字段约束与默认值;分类和评论分别在 [category.dv](module/content/article/data/category.dv)、[comment.dv](module/content/article/data/comment.dv)。
|
||||||
|
- [manage.dv](module/content/article/api/admin/manage.dv):后台 HTTP 绑定。
|
||||||
|
- [flow/cms.dv](module/content/article/flow/article.dv):真正需要的文章业务。
|
||||||
|
- [browse.dv](module/content/article/api/front/browse.dv):公开阅读和评论绑定。
|
||||||
|
|
||||||
|
后台入口绑定到本领域 App:
|
||||||
|
|
||||||
|
~~~dever
|
||||||
|
post create = app.create
|
||||||
|
put edit = app.edit
|
||||||
|
post publish = app.publish
|
||||||
|
post unpublish = app.unpublish
|
||||||
|
delete remove = app.remove
|
||||||
|
get list = app.list
|
||||||
|
~~~
|
||||||
|
|
||||||
|
## 请求怎么写
|
||||||
|
|
||||||
|
以下是接好真实认证后的请求合同。后台请求必须携带有效身份,并具有对应入口权限;本例业务 Test 不代替 HTTP 权限验收。
|
||||||
|
|
||||||
|
| 操作 | HTTP 路径 | 输入 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 创建 | POST /content/article/admin/manage/create | JSON:title、body |
|
||||||
|
| 编辑 | PUT /content/article/admin/manage/edit | JSON:article_id、title、body |
|
||||||
|
| 发布 | POST /content/article/admin/manage/publish | JSON:article_id |
|
||||||
|
| 撤回 | POST /content/article/admin/manage/unpublish | JSON:article_id |
|
||||||
|
| 删除 | DELETE /content/article/admin/manage/remove | query:article_id |
|
||||||
|
| 后台列表 | GET /content/article/admin/manage/list | query:page |
|
||||||
|
| 公开列表 | GET /content/article/front/browse/list | query:page |
|
||||||
|
| 公开详情 | GET /content/article/front/browse/detail | query:article_id |
|
||||||
|
| 创建分类 | POST /content/article/admin/manage/createCategory | JSON:name |
|
||||||
|
| 设置分类 | PUT /content/article/admin/manage/assignCategory | JSON:article_id、category_id |
|
||||||
|
| 提交评论 | POST /content/article/front/browse/comment | JSON:article_id、author、body |
|
||||||
|
| 审核评论 | POST /content/article/admin/manage/moderate | JSON:comment_id、approve |
|
||||||
|
| 公开评论 | GET /content/article/front/browse/comments | query:target_id、page |
|
||||||
|
|
||||||
|
创建正文例如 {"title":"第一篇文章","body":"你好,Dever。"}。创建返回 Article,后续使用实际返回的 id;编辑、发布、撤回和删除成功时 data 为 null,不为返回整条记录额外查询。
|
||||||
|
|
||||||
|
## 保留什么,省掉什么
|
||||||
|
|
||||||
|
字段长度、标题规范化和默认值只在数据模型声明。状态条件与修改在同一条 SQL 中执行,未更新到记录则报 Conflict;公开详情未找到则报 NotFound。不先查询再重复检查,不吞错或自动重试。
|
||||||
|
|
||||||
|
两个合法编辑按最后一次成功写入生效,本例不提供协同编辑冲突检测。发布/撤回保留状态约束,失败回滚。
|
||||||
|
|
||||||
|
评论默认待审核,只能提交给已发布文章;审核通过后才公开。提交与撤回通过同一文章行的条件更新串行,撤回后不再公开评论。审核使用 rule 表,取批准或拒绝的状态;没有另建审核服务或转换层。
|
||||||
|
|
||||||
|
## 认证接入与验收边界
|
||||||
|
|
||||||
|
认证按 [当前身份与权限合同](../../../LANGUAGE.md) 接入真实账号、会话及 Provider。本例没有假 verify。运行前必须完成 admin 站点的 Provider、verify、登录和授权配置;缺失时明确拒绝启动,不能将受保护接口降为匿名。
|
||||||
|
|
||||||
|
当前 Test 已验证真实创建、字段规范化、草稿隐藏、编辑、发布、公开查询、撤回隐藏和删除,以及分类外键、评论默认状态、审核和撤回后的评论隐藏。仍需随真实认证环境验收后台匿名/越权拒绝、状态冲突和 HTTP 错误响应;数据库并发错误照常传播。
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"database": {
|
||||||
|
"default": {
|
||||||
|
"type": "sqlite",
|
||||||
|
"path": "data/cms.db"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"sites": {
|
||||||
|
"admin": { "path": "admin" },
|
||||||
|
"front": { "path": "front" }
|
||||||
|
},
|
||||||
|
"http": { "host": "127.0.0.1", "port": 18090 },
|
||||||
|
"log": { "level": "info" }
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
负责文章草稿、发布和公开阅读。字段见 [data/article.dv](data/article.dv),主流程见 [flow/article.dv](flow/article.dv),完整用法见 [项目说明](../../../README.md),符号说明见 [文章主题](doc/article.md)。
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
post create = app.create
|
||||||
|
|
||||||
|
put edit = app.edit
|
||||||
|
|
||||||
|
post publish = app.publish
|
||||||
|
|
||||||
|
post unpublish = app.unpublish
|
||||||
|
|
||||||
|
delete remove = app.remove
|
||||||
|
|
||||||
|
get list = app.list
|
||||||
|
|
||||||
|
post createCategory = app.createCategory
|
||||||
|
|
||||||
|
put assignCategory = app.assignCategory
|
||||||
|
|
||||||
|
post moderate = app.moderate
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
public get list = app.browse
|
||||||
|
|
||||||
|
public get detail = app.detail
|
||||||
|
|
||||||
|
public post comment = app.comment
|
||||||
|
|
||||||
|
public get comments = app.comments
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
type Status {
|
||||||
|
Draft
|
||||||
|
Published
|
||||||
|
}
|
||||||
|
|
||||||
|
type Article {
|
||||||
|
title: Text(1, 120)
|
||||||
|
body: Text(1, 20000) raw
|
||||||
|
status: Status default Draft index
|
||||||
|
published_at: DateTime?
|
||||||
|
category_id: data.category.id?
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
type Category {
|
||||||
|
name: Text(1, 80) unique
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
type Status {
|
||||||
|
Pending
|
||||||
|
Approved
|
||||||
|
Rejected
|
||||||
|
}
|
||||||
|
|
||||||
|
type Comment {
|
||||||
|
article_id: data.id
|
||||||
|
author: Text(1, 40)
|
||||||
|
body: Text(1, 2000)
|
||||||
|
status: Status default Pending index
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# 文章
|
||||||
|
|
||||||
|
## content.article.app.publish
|
||||||
|
|
||||||
|
只有草稿可以发布。条件更新与结果检查在同一个事务内完成;成功无业务输出,不为回传整条文章再查询一次。
|
||||||
|
|
||||||
|
## content.article.app.edit
|
||||||
|
|
||||||
|
仅编辑草稿。数据模型处理字段规范化和长度约束,业务不重复检查。本例采用最后一次成功写入生效,不提供多人编辑的版本冲突检测。
|
||||||
|
|
||||||
|
## content.article.app.browse
|
||||||
|
|
||||||
|
公开返回已发布文章,每页十条。后台完整列表绑定需要身份与角色权限的 HTTP GET。
|
||||||
|
|
||||||
|
## content.article.app.comment
|
||||||
|
|
||||||
|
只有已发布的文章可以评论,其他情况按不存在处理。在事务中以条件更新锁定文章,再写评论,避免检查发布状态后被并发撤回。评论默认待审核,不在公开列表中出现。`article_id` 是普通外键;自动关系不参与默认接口输出。
|
||||||
|
|
||||||
|
## content.article.app.moderate
|
||||||
|
|
||||||
|
审核只处理待审核的评论,决定由 `app.verdict` 的规则表选择,条件更新与结果检查在同一个事务内完成;已审核的评论再次审核按冲突处理。
|
||||||
|
|
||||||
|
## content.article.app.comments
|
||||||
|
|
||||||
|
公开返回已发布文章通过审核的评论,每页二十条,按创建时间升序。撤回后不再公开评论。
|
||||||
|
|
||||||
|
## content.article.app.createCategory
|
||||||
|
|
||||||
|
分类名称在数据模型中唯一,重复创建由数据库约束拒绝。
|
||||||
|
|
||||||
|
## content.article.app.assignCategory
|
||||||
|
|
||||||
|
把文章归入分类;文章不存在时按不存在处理。`category_id` 是普通外键,文章直接输出存储字段。
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
transaction flow create(title: Text, body: Text) (article: data.Article) {
|
||||||
|
article = data.create({ title = title, body = body })
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction flow edit(article_id: data.id, title: Text, body: Text) () {
|
||||||
|
changed = data.update({ where = id == article_id and status == Draft }, { title = title, body = body })
|
||||||
|
check changed == 1 else Conflict
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction flow publish(article_id: data.id) () {
|
||||||
|
now = dever.time.now()
|
||||||
|
changed = data.update({ where = id == article_id and status == Draft }, { status = Published, published_at = now })
|
||||||
|
check changed == 1 else Conflict
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction flow unpublish(article_id: data.id) () {
|
||||||
|
changed = data.update({ where = id == article_id and status == Published }, { status = Draft, published_at = null })
|
||||||
|
check changed == 1 else Conflict
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction flow remove(article_id: data.id) () {
|
||||||
|
changed = data.delete({ where = id == article_id and status == Draft })
|
||||||
|
check changed == 1 else Conflict
|
||||||
|
}
|
||||||
|
|
||||||
|
flow list(page: Int >= 1) (articles: data.Page) {
|
||||||
|
articles = data.page(order = [created_at.desc, id.desc], page = page, size = 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
flow browse(page: Int >= 1) (articles: data.Page) {
|
||||||
|
articles = data.page(status == Published, order = [published_at.desc, id.desc], page = page, size = 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
flow detail(article_id: data.id) (article: data.Article) {
|
||||||
|
found = data.first(id == article_id and status == Published)
|
||||||
|
check found != null else NotFound
|
||||||
|
article = found
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction flow createCategory(name: Text) (category: data.category.Category) {
|
||||||
|
category = data.category.create({ name = name })
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction flow assignCategory(article_id: data.id, category_id: data.category.id) () {
|
||||||
|
changed = data.update({ where = id == article_id }, { category_id = category_id })
|
||||||
|
check changed == 1 else NotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction flow comment(article_id: data.id, author: Text, body: Text) (comment: data.comment.Comment) {
|
||||||
|
accepted = data.update({ where = id == article_id and status == Published }, { status = Published })
|
||||||
|
check accepted == 1 else NotFound
|
||||||
|
comment = data.comment.create({ article_id = article_id, author = author, body = body })
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction flow moderate(comment_id: data.comment.id, approve: Bool) () {
|
||||||
|
chosen = app.verdict(approve)
|
||||||
|
changed = data.comment.update({ where = id == comment_id and status == Pending }, { status = chosen })
|
||||||
|
check changed == 1 else Conflict
|
||||||
|
}
|
||||||
|
|
||||||
|
flow comments(target_id: data.id, page: Int >= 1) (comments: data.comment.Page) {
|
||||||
|
article = data.first(id == target_id and status == Published)
|
||||||
|
check article != null else NotFound
|
||||||
|
comments = data.comment.page(article_id == target_id and status == Approved, order = [created_at.asc, id.asc], page = page, size = 20)
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,5 @@
|
|||||||
|
rule verdict(approve: Bool) (status: data.comment.Status)
|
||||||
|
approve {
|
||||||
|
true => Approved
|
||||||
|
false => Rejected
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
flow discussion() ()
|
||||||
|
| step | kind | do |
|
||||||
|
| article | flow | app.create("讨论文章", "正文") |
|
||||||
|
| - | flow | app.publish(article.id) |
|
||||||
|
| first | flow | app.comment(article.id, "小明", "写得好") |
|
||||||
|
| second | flow | app.comment(article.id, "小红", "广告内容") |
|
||||||
|
| - | calc | assertEq(first.status, data.comment.Status.Pending) |
|
||||||
|
| pending | flow | app.comments(article.id, 1) |
|
||||||
|
| - | calc | assertEq(pending.total, 0) |
|
||||||
|
| - | flow | app.moderate(first.id, true) |
|
||||||
|
| - | flow | app.moderate(second.id, false) |
|
||||||
|
| visible | flow | app.comments(article.id, 1) |
|
||||||
|
| - | calc | assertEq(visible.total, 1) |
|
||||||
|
| category | flow | app.createCategory("新闻") |
|
||||||
|
| - | flow | app.assignCategory(article.id, category.id) |
|
||||||
|
| assigned | flow | app.detail(article.id) |
|
||||||
|
| - | calc | assertEq(assigned.category_id, category.id) |
|
||||||
|
| - | flow | app.unpublish(article.id) |
|
||||||
|
| hidden | flow | app.browse(1) |
|
||||||
|
| - | calc | assertEq(hidden.total, 0) |
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
flow publishing() ()
|
||||||
|
| step | kind | do |
|
||||||
|
| created | flow | app.create(" 第一篇 ", "原始正文") |
|
||||||
|
| - | calc | assertEq(created.title, "第一篇") |
|
||||||
|
| - | calc | assertEq(created.status, data.Status.Draft) |
|
||||||
|
| drafts | flow | app.browse(1) |
|
||||||
|
| - | calc | assertEq(drafts.total, 0) |
|
||||||
|
| - | flow | app.edit(created.id, "修改后的标题", "修改后的正文") |
|
||||||
|
| - | flow | app.publish(created.id) |
|
||||||
|
| published | flow | app.detail(created.id) |
|
||||||
|
| - | calc | assertEq(published.status, data.Status.Published) |
|
||||||
|
| - | calc | assertEq(published.title, "修改后的标题") |
|
||||||
|
| - | calc | assert(published.published_at != null) |
|
||||||
|
| visible | flow | app.browse(1) |
|
||||||
|
| - | calc | assertEq(visible.total, 1) |
|
||||||
|
| - | flow | app.unpublish(created.id) |
|
||||||
|
| hidden | flow | app.browse(1) |
|
||||||
|
| - | calc | assertEq(hidden.total, 0) |
|
||||||
|
| - | flow | app.remove(created.id) |
|
||||||
|
| remaining | flow | app.list(1) |
|
||||||
|
| - | calc | assertEq(remaining.total, 0) |
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
开始任务前先读取 `/dm/AGENTS.md`,再读取目标路径适用的子级规则。
|
||||||
|
|
||||||
|
本项目是Dever 文字游戏示例,使用随包 `core/skills/dever/SKILL.md`。游戏规则集中在 app 的规则表,保持纯计算,不增加数据库或通用游戏引擎。
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
# 文字游戏:逃出房间
|
||||||
|
|
||||||
|
玩家查看房间、寻找钥匙、打开门,也可以退出。业务入口 [flow/escape.dv](module/game/escape/flow/escape.dv) 和 [game.dv](module/game/escape/api/web/game.dv) 分别组织游戏流程和 HTTP 路由;状态分支定义在 [rule/escape.dv](module/game/escape/rule/escape.dv)。游戏不需要数据库或登录。两个入口都是公开 POST,直接绑定现有业务定义。
|
||||||
|
|
||||||
|
在项目目录执行 `dever check .`、`dever test .`,然后用 `dever run . -- api` 启动服务。监听配置见 setting.json;需要改地址时修改配置,不改业务源码。
|
||||||
|
|
||||||
|
启动后打开配置中的站点地址,首页是 [游戏页面](module/game/front/src/index.html)。`dever run` 读取组件的 `front/src`;`dever build` 生成并内嵌 `front/dist`。页面使用同源 API,游戏规则由 Dever 的 step 表处理,无需单独启动前端服务。
|
||||||
|
|
||||||
|
阅读顺序是 `play → advance → step`。所有状态分支集中在 `step` 规则表,`play` 负责消费行动列表;`foldUntil` 遇到胜利或退出就停止,不执行后面的行动。`start` 只是初始状态构造,不另建 Service。
|
||||||
|
|
||||||
|
## 一次玩完
|
||||||
|
|
||||||
|
以下请求使用 [setting.json](config/setting.json) 中配置的监听地址:
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /game/escape/web/game/play
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{"actions":["Look","Search","Open"]}
|
||||||
|
```
|
||||||
|
|
||||||
|
成功响应的 data 预期为:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"stage": "Won",
|
||||||
|
"message": "门开了,你逃出了房间!"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`play` 返回最后一回合的结果。空列表返回开场状态;`["Open"]` 提示需要钥匙;`["Search","Open","Quit"]` 在 Open 时获胜,后面的 Quit 不执行。
|
||||||
|
|
||||||
|
## 一步一步玩
|
||||||
|
|
||||||
|
界面逐回合向下面的路径发送 JSON,下一回合使用上次返回的 stage:
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /game/escape/web/game/step
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{"stage":"Locked","action":"Look"}
|
||||||
|
```
|
||||||
|
|
||||||
|
| 输入状态 | 行动 | 下一状态 | 屏幕内容 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Locked | Look | Locked | 门锁着,桌上有一个盒子 |
|
||||||
|
| Locked | Search | KeyFound | 找到钥匙 |
|
||||||
|
| KeyFound | Open | Won | 逃出房间 |
|
||||||
|
|
||||||
|
这是无存档、无奖励的 HTTP 规则演示,状态由调用者保存。客户端传入的 stage 不是可信的联网游戏存档;若做排行榜、奖励或多人游戏,状态应放数据模型并由服务端推进。
|
||||||
|
|
||||||
|
## 改规则时改哪里
|
||||||
|
|
||||||
|
新增动作时修改 Action 和 `step` 表;新增房间状态时修改 Stage 和对应行。编译器必须检查组合是否互斥穷尽,不靠补一个万能 else。Won/GaveUp 的整行是“游戏已经结束”的明确业务行为。
|
||||||
|
|
||||||
|
入口收到无法识别的动作会报错。每次行动返回 `stage` 和 `message`;`stage` 为 `Won` 或 `GaveUp` 时,游戏结束。
|
||||||
|
|
||||||
|
业务测试见 [scenarios.dv](test/game/escape/scenarios.dv)。HTTP 集成测试另外验证真实入口解码与未知动作拒绝;生成的 [link.md](module/game/escape/link.md) 展示源码工作流。
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"sites": { "web": { "path": "web", "hosts": ["localhost", "127.0.0.1"], "front": { "component": "game", "path": "/" } } },
|
||||||
|
"http": { "host": "127.0.0.1", "port": 18092 }
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
负责房间探索的状态变化。状态与动作的判断见 [rule/escape.dv](rule/escape.dv),操作例子见 [项目说明](../../../README.md),符号说明见 [游戏主题](doc/game.md)。
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
public post play = app.play
|
||||||
|
|
||||||
|
public post step = app.step
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# 逃出房间
|
||||||
|
|
||||||
|
## game.escape.app.play
|
||||||
|
|
||||||
|
按顺序执行行动,胜利或退出后停止。没有行动时返回开场状态。
|
||||||
|
|
||||||
|
## game.escape.app.step
|
||||||
|
|
||||||
|
根据当前状态和一个行动返回新状态与提示。Won/GaveUp 表示结束,不额外维护结束标志。查看、搜索、开门及退出的所有组合集中在规则表。
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
type Stage {
|
||||||
|
Locked
|
||||||
|
KeyFound
|
||||||
|
Won
|
||||||
|
GaveUp
|
||||||
|
}
|
||||||
|
|
||||||
|
type Action {
|
||||||
|
Look
|
||||||
|
Search
|
||||||
|
Open
|
||||||
|
Quit
|
||||||
|
}
|
||||||
|
|
||||||
|
type Turn {
|
||||||
|
stage: Stage
|
||||||
|
message: Text
|
||||||
|
}
|
||||||
|
|
||||||
|
start() (turn: Turn) {
|
||||||
|
turn = Turn { stage = Locked, message = "你醒来时,发现自己在一间上锁的房间里。" }
|
||||||
|
}
|
||||||
|
|
||||||
|
advance(action: Action, current: Turn) (acc: Turn, stop: Bool) {
|
||||||
|
acc = app.step(current.stage, action)
|
||||||
|
stop = acc.stage == Won or acc.stage == GaveUp
|
||||||
|
}
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
<!-- Generated by dever inspect --links. Do not edit. -->
|
||||||
|
<!-- source-sha256: 4fad8ed735126db92201e426929c78f8bf48d84df8564a20c9abc936f0fe3d3a -->
|
||||||
|
|
||||||
|
# game/escape
|
||||||
|
|
||||||
|
按源码顺序阅读。图显示静态路径;运行故障结束当前调用,不是某次执行记录。
|
||||||
|
|
||||||
|
<a id="flow-fd525ca826bf86c7ff043119fac95758e4b746975a5092aee80a5fdcd7e4aade"></a>
|
||||||
|
|
||||||
|
## POST /game/escape/web/game/play
|
||||||
|
|
||||||
|
```dever
|
||||||
|
public post play = app.play
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<api/web/game.dv#L1,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0["POST /game/escape/web/game/play"]
|
||||||
|
click n0 href "api/web/game.dv#L1,1" "打开源码"
|
||||||
|
n1["站点 Host 校验"]
|
||||||
|
click n1 href "api/web/game.dv#L1,1" "打开源码"
|
||||||
|
n2["按参数类型解码;拒绝未知、重复及缺失字段"]
|
||||||
|
click n2 href "api/web/game.dv#L1,1" "打开源码"
|
||||||
|
n3[["game.escape.app.play"]]
|
||||||
|
click n3 href "api/web/game.dv#L1,1" "打开源码"
|
||||||
|
n4["返回 code / message / data"]
|
||||||
|
click n4 href "api/web/game.dv#L1,1" "打开源码"
|
||||||
|
n5["错误响应;内部原因仅记服务日志"]
|
||||||
|
click n5 href "api/web/game.dv#L1,1" "打开源码"
|
||||||
|
n0 -->|"成功"| n1
|
||||||
|
n1 -->|"通过"| n2
|
||||||
|
n2 -->|"通过"| n3
|
||||||
|
n3 -->|"成功"| n4
|
||||||
|
n1 -->|"失败"| n5
|
||||||
|
n2 -->|"失败"| n5
|
||||||
|
n3 -->|"失败"| n5
|
||||||
|
```
|
||||||
|
|
||||||
|
- 子流程 [game.escape.app.play](<link.md#flow-9dfc359f6c8ebdac6103848e001a4dc947aed529a98b275a5f9dfa777a3a01bc>)
|
||||||
|
|
||||||
|
<a id="flow-b6a9b27b972bfe9b38dcbad1133a6131bf68c40687de7580fc8c47026d022093"></a>
|
||||||
|
|
||||||
|
## POST /game/escape/web/game/step
|
||||||
|
|
||||||
|
```dever
|
||||||
|
public post step = app.step
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<api/web/game.dv#L3,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0["POST /game/escape/web/game/step"]
|
||||||
|
click n0 href "api/web/game.dv#L3,1" "打开源码"
|
||||||
|
n1["站点 Host 校验"]
|
||||||
|
click n1 href "api/web/game.dv#L3,1" "打开源码"
|
||||||
|
n2["按参数类型解码;拒绝未知、重复及缺失字段"]
|
||||||
|
click n2 href "api/web/game.dv#L3,1" "打开源码"
|
||||||
|
n3[["game.escape.app.step"]]
|
||||||
|
click n3 href "api/web/game.dv#L3,1" "打开源码"
|
||||||
|
n4["返回 code / message / data"]
|
||||||
|
click n4 href "api/web/game.dv#L3,1" "打开源码"
|
||||||
|
n5["错误响应;内部原因仅记服务日志"]
|
||||||
|
click n5 href "api/web/game.dv#L3,1" "打开源码"
|
||||||
|
n0 -->|"成功"| n1
|
||||||
|
n1 -->|"通过"| n2
|
||||||
|
n2 -->|"通过"| n3
|
||||||
|
n3 -->|"成功"| n4
|
||||||
|
n1 -->|"失败"| n5
|
||||||
|
n2 -->|"失败"| n5
|
||||||
|
n3 -->|"失败"| n5
|
||||||
|
```
|
||||||
|
|
||||||
|
- 子流程 [game.escape.app.step](<link.md#flow-ccc70f2ace361a370d7852e76d42bae9b531f95552ecbc55fb22282d9d15444d>)
|
||||||
|
|
||||||
|
<a id="flow-65bdcbe09a4a25a28fb2c9ed48b5c8c5b9b51aa0c0d524588252aa575b3da17a"></a>
|
||||||
|
|
||||||
|
## game.escape.app.Stage
|
||||||
|
|
||||||
|
```dever
|
||||||
|
type game.escape.app.Stage
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/escape.dv#L1,1>)
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-ee0c1ed77e17cae1c1ae3068f3f680f3721f3ea457dd893aac8cca0e681d7f23"></a>
|
||||||
|
|
||||||
|
## game.escape.app.Action
|
||||||
|
|
||||||
|
```dever
|
||||||
|
type game.escape.app.Action
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/escape.dv#L8,1>)
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-377bd39fe59dd1973226cab9b4113f80934a5d264923a909a2c303e765e807c5"></a>
|
||||||
|
|
||||||
|
## game.escape.app.Turn
|
||||||
|
|
||||||
|
```dever
|
||||||
|
type game.escape.app.Turn
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/escape.dv#L15,1>)
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-ceaf1f1b0cd7c5d3df26b5920c4686c85d1f7827a411762e7e7ccc23b1737f52"></a>
|
||||||
|
|
||||||
|
## game.escape.app.start
|
||||||
|
|
||||||
|
```dever
|
||||||
|
game.escape.app.start() (turn: Turn)
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/escape.dv#L20,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0(["game.escape.app.start"])
|
||||||
|
click n0 href "flow/escape.dv#L20,1" "打开源码"
|
||||||
|
n1(["返回结果"])
|
||||||
|
n2["turn = Turn { stage = Locked, message = #34;你醒来时,发现自己在一间上锁的房间里。#34; }"]
|
||||||
|
click n2 href "flow/escape.dv#L21,10" "打开源码"
|
||||||
|
n0 --> n2
|
||||||
|
n2 --> n1
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
<a id="flow-8466c88245f19d3143112a145a76aa1cf0f8cc8565edd8dd976ae9f184ddaf4b"></a>
|
||||||
|
|
||||||
|
## game.escape.app.advance
|
||||||
|
|
||||||
|
```dever
|
||||||
|
game.escape.app.advance(action: Action, current: Turn) (acc: Turn, stop: Bool)
|
||||||
|
```
|
||||||
|
|
||||||
|
[打开源码](<flow/escape.dv#L24,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0(["game.escape.app.advance"])
|
||||||
|
click n0 href "flow/escape.dv#L24,1" "打开源码"
|
||||||
|
n1(["返回结果"])
|
||||||
|
n2[["app.step(current.stage, action)"]]
|
||||||
|
click n2 href "flow/escape.dv#L25,9" "打开源码"
|
||||||
|
n3["acc = app.step(current.stage, action)"]
|
||||||
|
click n3 href "flow/escape.dv#L25,9" "打开源码"
|
||||||
|
n4{"acc.stage == Won"}
|
||||||
|
click n4 href "flow/escape.dv#L26,10" "打开源码"
|
||||||
|
n5["计算右侧"]
|
||||||
|
click n5 href "flow/escape.dv#L26,30" "打开源码"
|
||||||
|
n6["布尔结果"]
|
||||||
|
click n6 href "flow/escape.dv#L26,10" "打开源码"
|
||||||
|
n7["stop = acc.stage == Won or acc.stage == GaveUp"]
|
||||||
|
click n7 href "flow/escape.dv#L26,10" "打开源码"
|
||||||
|
n0 --> n2
|
||||||
|
n2 --> n3
|
||||||
|
n3 --> n4
|
||||||
|
n4 -->|"不成立"| n5
|
||||||
|
n4 -->|"成立,短路"| n6
|
||||||
|
n5 --> n6
|
||||||
|
n6 --> n7
|
||||||
|
n7 --> n1
|
||||||
|
```
|
||||||
|
|
||||||
|
- 子流程 [game.escape.app.step](<link.md#flow-ccc70f2ace361a370d7852e76d42bae9b531f95552ecbc55fb22282d9d15444d>)
|
||||||
|
|
||||||
|
<a id="flow-9dfc359f6c8ebdac6103848e001a4dc947aed529a98b275a5f9dfa777a3a01bc"></a>
|
||||||
|
|
||||||
|
## game.escape.app.play
|
||||||
|
|
||||||
|
```dever
|
||||||
|
loop game.escape.app.play(actions: List<Action>) (turn: Turn)
|
||||||
|
```
|
||||||
|
|
||||||
|
按顺序执行行动,胜利或退出后停止。没有行动时返回开场状态。
|
||||||
|
|
||||||
|
[打开源码](<loop/escape.dv#L1,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0(["game.escape.app.play"])
|
||||||
|
click n0 href "loop/escape.dv#L1,1" "打开源码"
|
||||||
|
n1(["返回结果"])
|
||||||
|
n2[["app.start()"]]
|
||||||
|
click n2 href "loop/escape.dv#L3,23" "打开源码"
|
||||||
|
n3["初始化 current: app.start()"]
|
||||||
|
click n3 href "loop/escape.dv#L3,23" "打开源码"
|
||||||
|
n4{"全部行完成则停止,否则拉取下一元素"}
|
||||||
|
click n4 href "loop/escape.dv#L2,1" "打开源码"
|
||||||
|
n5["foldUntil(current = app.start(), app.advance(action, current))"]
|
||||||
|
click n5 href "loop/escape.dv#L3,3" "打开源码"
|
||||||
|
n6["下一输出行"]
|
||||||
|
n7{"本行是否已完成"}
|
||||||
|
click n7 href "loop/escape.dv#L3,3" "打开源码"
|
||||||
|
n8[["app.advance(action, current)"]]
|
||||||
|
click n8 href "loop/escape.dv#L3,36" "打开源码"
|
||||||
|
n9["采用新的累积状态"]
|
||||||
|
click n9 href "loop/escape.dv#L3,3" "打开源码"
|
||||||
|
n10{"stop 是否为 true"}
|
||||||
|
click n10 href "loop/escape.dv#L3,3" "打开源码"
|
||||||
|
n0 --> n2
|
||||||
|
n2 -->|"只求值一次"| n3
|
||||||
|
n3 -->|"来源只求值一次"| n4
|
||||||
|
n4 -->|"来源耗尽或全部完成"| n1
|
||||||
|
n4 --> n7
|
||||||
|
n7 -->|"已完成,跳过"| n6
|
||||||
|
n7 -->|"未完成"| n5
|
||||||
|
n5 --> n8
|
||||||
|
n8 -->|"更新成功"| n9
|
||||||
|
n9 -->|"随后判断停止"| n10
|
||||||
|
n10 -->|"是,标记本行完成"| n6
|
||||||
|
n10 -->|"否,本行继续累积"| n6
|
||||||
|
n6 -->|"继续"| n4
|
||||||
|
```
|
||||||
|
|
||||||
|
- 子流程 [game.escape.app.start](<link.md#flow-ceaf1f1b0cd7c5d3df26b5920c4686c85d1f7827a411762e7e7ccc23b1737f52>)
|
||||||
|
- 子流程 [game.escape.app.advance](<link.md#flow-8466c88245f19d3143112a145a76aa1cf0f8cc8565edd8dd976ae9f184ddaf4b>)
|
||||||
|
|
||||||
|
<a id="flow-ccc70f2ace361a370d7852e76d42bae9b531f95552ecbc55fb22282d9d15444d"></a>
|
||||||
|
|
||||||
|
## game.escape.app.step
|
||||||
|
|
||||||
|
```dever
|
||||||
|
rule game.escape.app.step(stage: Stage, action: Action) (turn: Turn)
|
||||||
|
```
|
||||||
|
|
||||||
|
根据当前状态和一个行动返回新状态与提示。Won/GaveUp 表示结束,不额外维护结束标志。查看、搜索、开门及退出的所有组合集中在规则表。
|
||||||
|
|
||||||
|
[打开源码](<rule/escape.dv#L1,1>)
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
n0(["game.escape.app.step"])
|
||||||
|
click n0 href "rule/escape.dv#L1,1" "打开源码"
|
||||||
|
n1(["返回结果"])
|
||||||
|
n2{"按输入选择唯一规则行"}
|
||||||
|
click n2 href "rule/escape.dv#L1,1" "打开源码"
|
||||||
|
n3["stage: Locked 且 action: Look"]
|
||||||
|
click n3 href "rule/escape.dv#L3,3" "打开源码"
|
||||||
|
n4["turn = Turn { stage = Locked, message = #34;门锁着,桌上有一个盒子。#34; }"]
|
||||||
|
click n4 href "rule/escape.dv#L3,21" "打开源码"
|
||||||
|
n5["stage: Locked 且 action: Search"]
|
||||||
|
click n5 href "rule/escape.dv#L4,3" "打开源码"
|
||||||
|
n6["turn = Turn { stage = KeyFound, message = #34;你在盒子里找到了钥匙。#34; }"]
|
||||||
|
click n6 href "rule/escape.dv#L4,23" "打开源码"
|
||||||
|
n7["stage: Locked 且 action: Open"]
|
||||||
|
click n7 href "rule/escape.dv#L5,3" "打开源码"
|
||||||
|
n8["turn = Turn { stage = Locked, message = #34;门打不开,需要钥匙。#34; }"]
|
||||||
|
click n8 href "rule/escape.dv#L5,21" "打开源码"
|
||||||
|
n9["stage: KeyFound 且 action: Look"]
|
||||||
|
click n9 href "rule/escape.dv#L6,3" "打开源码"
|
||||||
|
n10["turn = Turn { stage = KeyFound, message = #34;你拿着钥匙,出口就在前面。#34; }"]
|
||||||
|
click n10 href "rule/escape.dv#L6,23" "打开源码"
|
||||||
|
n11["stage: KeyFound 且 action: Search"]
|
||||||
|
click n11 href "rule/escape.dv#L7,3" "打开源码"
|
||||||
|
n12["turn = Turn { stage = KeyFound, message = #34;盒子空了,钥匙在你手里。#34; }"]
|
||||||
|
click n12 href "rule/escape.dv#L7,25" "打开源码"
|
||||||
|
n13["stage: KeyFound 且 action: Open"]
|
||||||
|
click n13 href "rule/escape.dv#L8,3" "打开源码"
|
||||||
|
n14["turn = Turn { stage = Won, message = #34;门开了,你逃出了房间!#34; }"]
|
||||||
|
click n14 href "rule/escape.dv#L8,23" "打开源码"
|
||||||
|
n15["stage: Locked 且 action: Quit"]
|
||||||
|
click n15 href "rule/escape.dv#L9,3" "打开源码"
|
||||||
|
n16["turn = Turn { stage = GaveUp, message = #34;你结束了这次探索。#34; }"]
|
||||||
|
click n16 href "rule/escape.dv#L9,21" "打开源码"
|
||||||
|
n17["stage: KeyFound 且 action: Quit"]
|
||||||
|
click n17 href "rule/escape.dv#L10,3" "打开源码"
|
||||||
|
n18["turn = Turn { stage = GaveUp, message = #34;你结束了这次探索。#34; }"]
|
||||||
|
click n18 href "rule/escape.dv#L10,23" "打开源码"
|
||||||
|
n19["stage: Won"]
|
||||||
|
click n19 href "rule/escape.dv#L11,3" "打开源码"
|
||||||
|
n20["turn = Turn { stage = Won, message = #34;你已经逃出房间了。#34; }"]
|
||||||
|
click n20 href "rule/escape.dv#L11,15" "打开源码"
|
||||||
|
n21["stage: GaveUp"]
|
||||||
|
click n21 href "rule/escape.dv#L12,3" "打开源码"
|
||||||
|
n22["turn = Turn { stage = GaveUp, message = #34;这次探索已经结束。#34; }"]
|
||||||
|
click n22 href "rule/escape.dv#L12,18" "打开源码"
|
||||||
|
n0 --> n2
|
||||||
|
n2 -->|"匹配"| n3
|
||||||
|
n3 --> n4
|
||||||
|
n4 --> n1
|
||||||
|
n2 -->|"匹配"| n5
|
||||||
|
n5 --> n6
|
||||||
|
n6 --> n1
|
||||||
|
n2 -->|"匹配"| n7
|
||||||
|
n7 --> n8
|
||||||
|
n8 --> n1
|
||||||
|
n2 -->|"匹配"| n9
|
||||||
|
n9 --> n10
|
||||||
|
n10 --> n1
|
||||||
|
n2 -->|"匹配"| n11
|
||||||
|
n11 --> n12
|
||||||
|
n12 --> n1
|
||||||
|
n2 -->|"匹配"| n13
|
||||||
|
n13 --> n14
|
||||||
|
n14 --> n1
|
||||||
|
n2 -->|"匹配"| n15
|
||||||
|
n15 --> n16
|
||||||
|
n16 --> n1
|
||||||
|
n2 -->|"匹配"| n17
|
||||||
|
n17 --> n18
|
||||||
|
n18 --> n1
|
||||||
|
n2 -->|"匹配"| n19
|
||||||
|
n19 --> n20
|
||||||
|
n20 --> n1
|
||||||
|
n2 -->|"匹配"| n21
|
||||||
|
n21 --> n22
|
||||||
|
n22 --> n1
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
loop play(actions: List<Action>) (turn: Turn)
|
||||||
|
action in actions {
|
||||||
|
foldUntil(current = app.start(), app.advance(action, current))
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
rule step(stage: Stage, action: Action) (turn: Turn)
|
||||||
|
(stage, action) {
|
||||||
|
(Locked, Look) => Turn { stage = Locked, message = "门锁着,桌上有一个盒子。" }
|
||||||
|
(Locked, Search) => Turn { stage = KeyFound, message = "你在盒子里找到了钥匙。" }
|
||||||
|
(Locked, Open) => Turn { stage = Locked, message = "门打不开,需要钥匙。" }
|
||||||
|
(KeyFound, Look) => Turn { stage = KeyFound, message = "你拿着钥匙,出口就在前面。" }
|
||||||
|
(KeyFound, Search) => Turn { stage = KeyFound, message = "盒子空了,钥匙在你手里。" }
|
||||||
|
(KeyFound, Open) => Turn { stage = Won, message = "门开了,你逃出了房间!" }
|
||||||
|
(Locked, Quit) => Turn { stage = GaveUp, message = "你结束了这次探索。" }
|
||||||
|
(KeyFound, Quit) => Turn { stage = GaveUp, message = "你结束了这次探索。" }
|
||||||
|
(Won, -) => Turn { stage = Won, message = "你已经逃出房间了。" }
|
||||||
|
(GaveUp, -) => Turn { stage = GaveUp, message = "这次探索已经结束。" }
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>逃出房间 · Dever</title>
|
||||||
|
<style>
|
||||||
|
:root { color-scheme: light dark; font-family: system-ui, sans-serif; }
|
||||||
|
body { max-width: 38rem; margin: 4rem auto; padding: 0 1.25rem; line-height: 1.7; }
|
||||||
|
h1 { font-size: 2rem; margin-bottom: .5rem; }
|
||||||
|
#story { min-height: 6rem; font-size: 1.15rem; }
|
||||||
|
fieldset { border: 0; padding: 0; display: flex; flex-wrap: wrap; gap: .7rem; }
|
||||||
|
button { padding: .7rem 1.1rem; font: inherit; cursor: pointer; }
|
||||||
|
#status { min-height: 2rem; }
|
||||||
|
</style>
|
||||||
|
<main>
|
||||||
|
<p>DEVER · 文字游戏</p>
|
||||||
|
<h1>逃出房间</h1>
|
||||||
|
<p>看看周围,找到钥匙,再打开那扇门。</p>
|
||||||
|
<p id="story" aria-live="polite"></p>
|
||||||
|
<fieldset id="actions" disabled>
|
||||||
|
<button data-action="Look">查看房间</button>
|
||||||
|
<button data-action="Search">寻找钥匙</button>
|
||||||
|
<button data-action="Open">打开门</button>
|
||||||
|
<button data-action="Quit">结束探索</button>
|
||||||
|
</fieldset>
|
||||||
|
<p id="status" role="status"></p>
|
||||||
|
<button id="restart">重新开始</button>
|
||||||
|
</main>
|
||||||
|
<script type="module">
|
||||||
|
const story = document.querySelector('#story');
|
||||||
|
const actions = document.querySelector('#actions');
|
||||||
|
const status = document.querySelector('#status');
|
||||||
|
const restart = document.querySelector('#restart');
|
||||||
|
let stage;
|
||||||
|
|
||||||
|
async function play(operation, input) {
|
||||||
|
actions.disabled = true;
|
||||||
|
restart.disabled = true;
|
||||||
|
status.textContent = '正在进行…';
|
||||||
|
try {
|
||||||
|
const response = await fetch('/game/escape/web/game/' + operation, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(input),
|
||||||
|
});
|
||||||
|
const result = await response.json();
|
||||||
|
if (!response.ok) throw new Error(result.message);
|
||||||
|
stage = result.data.stage;
|
||||||
|
story.textContent = result.data.message;
|
||||||
|
const finished = stage === 'Won' || stage === 'GaveUp';
|
||||||
|
actions.disabled = finished;
|
||||||
|
status.textContent = finished ? '本次探索结束,可以重新开始。' : '选择下一步行动。';
|
||||||
|
} catch (error) {
|
||||||
|
status.textContent = '请求失败:' + error.message + '。请点击重新开始。';
|
||||||
|
} finally {
|
||||||
|
restart.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const button of actions.querySelectorAll('button')) {
|
||||||
|
button.addEventListener('click', () => play('step', { stage, action: button.dataset.action }));
|
||||||
|
}
|
||||||
|
restart.addEventListener('click', () => play('play', { actions: [] }));
|
||||||
|
await play('play', { actions: [] });
|
||||||
|
</script>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
scenarios() () {
|
||||||
|
empty = app.play([])
|
||||||
|
assertEq(empty.stage, app.Stage.Locked)
|
||||||
|
locked = app.play([app.Action.Open])
|
||||||
|
assertEq(locked.stage, app.Stage.Locked)
|
||||||
|
searched = app.play([app.Action.Search, app.Action.Search])
|
||||||
|
assertEq(searched.stage, app.Stage.KeyFound)
|
||||||
|
won = app.play([app.Action.Look, app.Action.Search, app.Action.Open, app.Action.Quit])
|
||||||
|
assertEq(won.stage, app.Stage.Won)
|
||||||
|
quit = app.play([app.Action.Quit, app.Action.Search, app.Action.Open])
|
||||||
|
assertEq(quit.stage, app.Stage.GaveUp)
|
||||||
|
ended = app.step(app.Stage.Won, app.Action.Quit)
|
||||||
|
assertEq(ended.stage, app.Stage.Won)
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
开始任务前先读取 /dm/AGENTS.md,再读取目标路径适用的子级规则。
|
||||||
|
|
||||||
|
本目录是业务合同夹具。语言语法以[语言参考](../../../LANGUAGE.md)为准,运行条件和测试入口见 [README](README.md)。编写 Dever 应用时遵循[随包开发说明](../../../skills/dever/SKILL.md)。
|
||||||
|
|
||||||
|
明确外部输入、可信身份、事务和外部调用边界。生产支付、通知和筛选由实际 Adapter 接入;测试中的 Port fake 不用于生产,也不作为外部服务的验收依据。
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
# 业务工作流示例
|
||||||
|
|
||||||
|
这些示例演示如何用 Dever 处理支付、审批、导入和登录。支付、通知和外部筛选只声明了 Port,没有绑定 Adapter,因此整个示例目录不能直接构建。要运行这些功能,需为相应的 Port 配置服务实现。
|
||||||
|
|
||||||
|
| 业务 | 源码 | 看点 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 订单支付 | module/demo/order/flow/order.dv | long HTTP 读所属订单、调用支付、显式事务确认状态并入队通知;支付不放在数据库事务里 |
|
||||||
|
| 审批 | module/demo/approval/flow/approval.dv | 创建时默认 Pending,rule 选择决定,一次条件写转换状态;没有可绕过审批状态的通用 REST replace |
|
||||||
|
| 组织树/关系图 | module/demo/tree/flow/tree.dv | walk 广度优先遍历;业务明确去重,遇重复边/环只访问一次;无效节点引用报错,不自动补节点 |
|
||||||
|
| 租户批量导入 | module/demo/importer/flow/importer.dv | 受保护入口事务入队,Job 在执行租户中逐项写入;唯一性和字段规范化由数据模型完成 |
|
||||||
|
| 会话与成员验证 | module/demo/account/flow/account.dv | Provider 读取控制库,校验会话、用户、租户和成员状态,返回可信身份;不返回权限列表 |
|
||||||
|
| 分页、关系与私有字段 | module/demo/catalog/flow/catalog.dv | Category 直接 REST;Item 列表显式加载分类,仅公开需要的字段;SQL 使用具体结果 type 和参数绑定 |
|
||||||
|
| 调用外部服务筛选 | module/demo/selection/flow/selection.dv | 每个元素调用一次 Port;`find` 命中后停止,调用失败则返回错误 |
|
||||||
|
|
||||||
|
## 身份和数据库前提
|
||||||
|
|
||||||
|
真实集成时按[语言参考的 HTTP 与租户配置](../../../LANGUAGE.md#http-入口)设置控制连接、租户数据库、认证和站点。Provider 的 `verify` 绑定 `demo.account.verify`,`admin` 站点选择该 Provider。密钥和地址由实际环境提供,租户数据库通过显式命令准备。
|
||||||
|
|
||||||
|
`account` 在控制库保存用户、凭据、会话、租户和成员关系。`login` 先在事务外验证密码。验证期间用户可能改密或被停用,因此建立会话前,要在事务内核对密码哈希、凭据状态和成员资格。事务提交后才签发 Cookie。后续请求由核心先验签,再调用 `verify`。
|
||||||
|
|
||||||
|
示例只处理登录和会话,不提供注册入口。Cookie 登录须在 `sites` 中配置可信来源。会话有效期为一小时,Provider 的签名有效期应与之对应。登录成功只返回账号 ID。
|
||||||
|
|
||||||
|
业务函数从请求上下文获取用户和租户。订单的查询和更新都检查订单归属;审批入口则按审批权限授权,不限制管理员只能处理自己发起的申请。
|
||||||
|
|
||||||
|
## 支付与事务
|
||||||
|
|
||||||
|
`pay` 只允许用户支付自己的待付款订单。金额取自数据库。调用支付服务时,使用订单 UUID 作为幂等键:同一个键和金额必须返回同一收据;同一个键配不同金额必须报错。只有支付服务提供这项保证,才可以安全重试。
|
||||||
|
|
||||||
|
支付成功后,`markPaid` 在同一个事务中将订单改为已支付,并把通知加入队列。更新时再次核对订单归属、金额和待付款状态。如果条件不再满足,事务回滚并返回错误。此时外部扣款已经发生,数据库回滚不会退款。
|
||||||
|
|
||||||
|
`notifyPaid` 在数据库事务外发送通知。执行前,Worker 重新检查用户、成员资格、权限和队列所属租户。通知使用订单 UUID 去重;如果通知服务不支持幂等键,收件人可能收到重复通知。
|
||||||
|
|
||||||
|
测试用 Port 的替代实现检查调用顺序和错误处理。要验证实际扣款和通知送达,需接入对应服务。
|
||||||
|
|
||||||
|
## 遍历与导入
|
||||||
|
|
||||||
|
组织树按广度优先遍历。开始时按节点 ID 建立索引,重复 ID 或引用不存在的节点都会报错。节点第一次入队时就记为已访问,因此环和共享子节点都不会让同一节点被处理两次。
|
||||||
|
|
||||||
|
遍历时复用节点索引和队列。示例返回所有节点的名称,节点越多,结果列表占用的内存越大。只需逐项处理时,可使用 `Stream` 或无输出的 `loop`。
|
||||||
|
|
||||||
|
导入 Job 在一个事务中写入整批数据。编号重复或格式错误时整批回滚。相同的入队键只会复用活跃任务;已完成的批次再次提交,仍可能因编号重复而失败。
|
||||||
|
|
||||||
|
导入不使用 `create` 返回的记录,通知入队也不使用任务 ID。订单更新则要检查受影响的行数:只有一条记录从待付款改为已支付,才能继续入队。
|
||||||
|
|
||||||
|
有 I/O 或失败的筛选条件放在 flow 中,交给 fold/foldUntil 推进,不放进要求纯且不失败的过滤列。`find` 找到匹配项就返回该项,遍历结束仍未找到才返回 `null`。读取失败会中断查找并返回错误。
|
||||||
|
|
||||||
|
## 分页、关系与公开结果
|
||||||
|
|
||||||
|
分类使用 `rest data.category` 提供增删改查。商品含有私有成本字段 `supplier_cost`,因此列表只返回公开字段和总数。查询显式加载分类:`Loaded(null)` 表示商品未分组,`Unloaded` 表示尚未加载,示例会返回 `CategoryNotLoaded`。具名 SQL 直接返回 `List<app.Title>`。
|
||||||
|
|
||||||
|
示例覆盖空页、总数、分类加载状态,以及 SQLite 和 PostgreSQL 两种 SQL 方言的参数绑定。若直接返回含私有字段的数据模型分页结果,编译器会拒绝公开编码。使用游标分页时,也要为公开响应选择字段。
|
||||||
|
|
||||||
|
## 测试入口
|
||||||
|
|
||||||
|
- [业务合同测试](../../../test/rust/build/project/testing.rs)使用实际的审批、目录和筛选源码。审批状态、SQLite 分页、关系和具名 SQL 走真实实现;外部筛选调用使用显式 Port fake。
|
||||||
|
- [导入测试](../../../test/rust/build/project/testing_jobs.rs)使用实际的导入源码,在隔离数据库中验证队列、活跃任务去重、空批次、重复编号触发的整批回滚,以及失败后继续处理。
|
||||||
|
- [组织树用例](test/demo/tree/traversal.dv)覆盖广度优先、有环和共享子节点时的去重。单独使用树领域及其测试时,无需接入支付、通知或筛选服务。
|
||||||
|
|
||||||
|
在核心仓库根目录可运行两个集成测试:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo test --manifest-path rust/Cargo.toml --test build workflow_examples_use_real_models_and_explicit_external_fakes
|
||||||
|
cargo test --manifest-path rust/Cargo.toml --test build importer_example_runs_real_jobs_and_rolls_back_partial_batches
|
||||||
|
```
|
||||||
|
|
||||||
|
## 集成验收场景
|
||||||
|
|
||||||
|
| 场景 | 必须观察 |
|
||||||
|
| --- | --- |
|
||||||
|
| 重复支付、金额在支付间隙变化、通知入队失败 | 相同提供方键;状态写条件生效;数据库回滚;不重复扣款、不伪造退款 |
|
||||||
|
| Pending 审批成功,两次同时审批、修改已审批记录 | 恰好一次状态转换,其余 Conflict;不存在 REST 绕过路径 |
|
||||||
|
| 重复节点 ID、缺失子节点、重复边、环、深/宽图 | 重复键/缺失引用失败,其他按每节点一次结束;无递归和无全图逐轮复制 |
|
||||||
|
| 导入空批、重复 code、中途失败、取消、事务回滚 | 空批零次写入,失败不部分提交,真实连接可复用 |
|
||||||
|
| 两租户同号记录、入队后撤销会话/成员/权限、伪造租户 | 运行库拒绝越权/错配,不能回退控制库;不是只测编译和签名 |
|
||||||
|
| select/find 的成功、未命中、第三项失败、第二项命中 | 逐项一次,无提前全量求值;find 命中后不调用第三项;失败不返回默认结果 |
|
||||||
|
| 遍历一半取消、AsyncStream 短路 | 停止拉取,关闭来源,等待已启动工作结束;不把发出取消信号当完成 |
|
||||||
|
| inspect 与编辑器 | HTTP/Job、认证/租户/事务、Port、rule 分支与 loop 停止关系均来自实际语义模型 |
|
||||||
|
|
||||||
|
两租户队列和实时撤权已有独立的 SQLite、PostgreSQL 入口测试。接入实际 Provider 和外部服务后,仍需验证相关场景。分页、关系及私有字段以[语言参考](../../../LANGUAGE.md)为准。
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
public long post login = app.login
|
||||||
|
|
||||||
|
authenticated get current = app.userId
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
global type Credential {
|
||||||
|
username: Text(1, 80) lower unique
|
||||||
|
user_id: data.user.id
|
||||||
|
private password_hash: Text
|
||||||
|
active: Bool default true
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
global type Membership {
|
||||||
|
user_id: data.user.id
|
||||||
|
tenant_id: data.tenant.id
|
||||||
|
active: Bool default true
|
||||||
|
}
|
||||||
|
|
||||||
|
unique(user_id, tenant_id)
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
global type Session {
|
||||||
|
uuid: Uuid generated unique
|
||||||
|
subject: Text
|
||||||
|
user_id: data.user.id
|
||||||
|
tenant_id: data.tenant.id
|
||||||
|
tenant_key: Text
|
||||||
|
site: Text
|
||||||
|
expires_at: DateTime
|
||||||
|
revoked: Bool default false
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
global type Tenant {
|
||||||
|
key: Text unique
|
||||||
|
active: Bool default true
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
global type User {
|
||||||
|
uuid: Uuid generated unique
|
||||||
|
active: Bool default true
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
type Identity {
|
||||||
|
id: Text
|
||||||
|
user_id: data.user.id?
|
||||||
|
tenant_id: data.tenant.id?
|
||||||
|
}
|
||||||
|
|
||||||
|
flow verify(claims: dever.auth.Claims) (identity: Identity) {
|
||||||
|
session_id = uuid.parse(claims.session)
|
||||||
|
check session_id != null else Unauthorized
|
||||||
|
selected_key = claims.tenant
|
||||||
|
check selected_key != null else Unauthorized
|
||||||
|
now = dever.time.now()
|
||||||
|
session = data.session.first(uuid == session_id and subject == claims.subject and site == claims.site and tenant_key == selected_key and revoked == false and expires_at > now)
|
||||||
|
check session != null else Unauthorized
|
||||||
|
user_active = data.user.exists(id == session.user_id and active == true)
|
||||||
|
check user_active else Unauthorized
|
||||||
|
tenant_active = data.tenant.exists(id == session.tenant_id and key == session.tenant_key and active == true)
|
||||||
|
check tenant_active else Unauthorized
|
||||||
|
member_active = data.membership.exists(user_id == session.user_id and tenant_id == session.tenant_id and active == true)
|
||||||
|
check member_active else Unauthorized
|
||||||
|
identity = Identity { id = session.subject, user_id = session.user_id, tenant_id = session.tenant_id }
|
||||||
|
}
|
||||||
|
|
||||||
|
flow userId() (user_id: data.user.id) {
|
||||||
|
current: data.user.id? = dever.auth.userId()
|
||||||
|
check current != null else Unauthorized
|
||||||
|
user_id = current
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
flow login(username: Text, password: Secret, tenant: Text) (user_id: data.user.id) {
|
||||||
|
normalized = text.lower(text.trim(username))
|
||||||
|
credential = data.credential.first(username == normalized and active == true)
|
||||||
|
check credential != null else Unauthorized
|
||||||
|
valid = blocking(dever.crypto.passwordVerify(password, credential.password_hash))
|
||||||
|
check valid else Unauthorized
|
||||||
|
site = dever.site.key()
|
||||||
|
session = app.establishLogin(credential.id, credential.password_hash, tenant, site)
|
||||||
|
dever.auth.issueCookie(session.subject, uuid.toText(session.uuid), session.tenant_key)
|
||||||
|
user_id = session.user_id
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction flow establishLogin(credential_id: data.credential.id, verified_hash: Text, selected_key: Text, site_key: Text) (session: data.session.Session) {
|
||||||
|
credential = data.credential.first(id == credential_id and password_hash == verified_hash and active == true)
|
||||||
|
check credential != null else Unauthorized
|
||||||
|
user = data.user.first(id == credential.user_id and active == true)
|
||||||
|
check user != null else Unauthorized
|
||||||
|
tenant = data.tenant.first(key == selected_key and active == true)
|
||||||
|
check tenant != null else Unauthorized
|
||||||
|
member_active = data.membership.exists(user_id == user.id and tenant_id == tenant.id and active == true)
|
||||||
|
check member_active else Unauthorized
|
||||||
|
now = dever.time.now()
|
||||||
|
session = data.session.create({
|
||||||
|
subject = uuid.toText(user.uuid)
|
||||||
|
user_id = user.id
|
||||||
|
tenant_id = tenant.id
|
||||||
|
tenant_key = tenant.key
|
||||||
|
site = site_key
|
||||||
|
expires_at = dever.time.add(now, dever.time.duration(3600000))
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
post create = app.create
|
||||||
|
|
||||||
|
post review = app.review
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
type Status {
|
||||||
|
Pending
|
||||||
|
Approved
|
||||||
|
Rejected
|
||||||
|
}
|
||||||
|
|
||||||
|
type Request {
|
||||||
|
title: Text(1, 120)
|
||||||
|
status: Status default Pending
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
flow create(title: Text) (request: data.request.Request) {
|
||||||
|
request = data.request.create({ title = title })
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction flow review(request_id: data.request.id, approve: Bool) () {
|
||||||
|
chosen = app.decision(approve)
|
||||||
|
changed = data.request.update({ where = id == request_id and status == Pending }, { status = chosen })
|
||||||
|
check changed == 1 else Conflict
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
rule decision(approve: Bool) (status: data.request.Status)
|
||||||
|
approve {
|
||||||
|
true => Approved
|
||||||
|
false => Rejected
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
rest data.category
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
get list = app.list
|
||||||
|
|
||||||
|
get titles = app.titles
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
type Category {
|
||||||
|
name: Text(1, 80) unique
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
type Item {
|
||||||
|
title: Text(1, 120)
|
||||||
|
category_id: data.category.id?
|
||||||
|
private supplier_cost: Decimal(12, 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
sql titles(limit: Int >= 1 and <= 100) (rows: List<app.Title>) {
|
||||||
|
sqlite = "SELECT title FROM demo_catalog_item ORDER BY id LIMIT ?1"
|
||||||
|
postgres = "SELECT title FROM demo_catalog_item ORDER BY id LIMIT $1"
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
type Title {
|
||||||
|
title: Text
|
||||||
|
}
|
||||||
|
|
||||||
|
type Item {
|
||||||
|
id: data.item.id
|
||||||
|
title: Text
|
||||||
|
category: Text?
|
||||||
|
}
|
||||||
|
|
||||||
|
type Page {
|
||||||
|
items: List<Item>
|
||||||
|
total: Int
|
||||||
|
}
|
||||||
|
|
||||||
|
type Error {
|
||||||
|
error CategoryNotLoaded
|
||||||
|
}
|
||||||
|
|
||||||
|
flow list(page: Int >= 1) (result: Page) {
|
||||||
|
found = data.item.page(order = id.asc, with = [category], page = page, size = 20)
|
||||||
|
items = app.summaries(found.items)
|
||||||
|
result = Page { items = items, total = found.total }
|
||||||
|
}
|
||||||
|
|
||||||
|
flow titles(limit: Int >= 1 and <= 100) (rows: List<Title>) {
|
||||||
|
rows = data.item.titles(limit)
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
loop summaries(rows: List<data.item.Item>) (items: List<Item>)
|
||||||
|
row in rows {
|
||||||
|
list Item { id = row.id, title = row.title, category = app.loadedName(row.category) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
rule loadedName(value: Related<data.category.Category?>) (name: Text?)
|
||||||
|
value {
|
||||||
|
Loaded(category) => app.categoryName(category)
|
||||||
|
Unloaded => fail(Error.CategoryNotLoaded)
|
||||||
|
}
|
||||||
|
|
||||||
|
rule categoryName(value: data.category.Category?) (name: Text?)
|
||||||
|
value {
|
||||||
|
null => null
|
||||||
|
other => value.name
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
post submit = app.submit
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
database default
|
||||||
|
|
||||||
|
job importRows(input: app.Request) retry(1) timeout(30000) = app.importRows
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
type Item {
|
||||||
|
code: Text(1, 40) unique
|
||||||
|
title: Text(1, 120)
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
type Row {
|
||||||
|
code: Text
|
||||||
|
title: Text
|
||||||
|
}
|
||||||
|
|
||||||
|
type Request {
|
||||||
|
key: Text
|
||||||
|
rows: List<Row>
|
||||||
|
}
|
||||||
|
|
||||||
|
transaction flow submit(input: Request) (task_id: Id) {
|
||||||
|
task_id = enqueue(job.importRows, input, input.key)
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
loop importRows(input: Request) ()
|
||||||
|
row in input.rows {
|
||||||
|
do data.item.create({ code = row.code, title = row.title })
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
long post pay = app.pay
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
database default
|
||||||
|
|
||||||
|
long job notifyPaid(input: app.Notice) retry(3) timeout(30000) = app.notifyPaid
|
||||||
Loaded 100 of 816 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user