Dever v0.0.2

This commit is contained in:
Codex committed 2026-11-27 06:03:56 +00:00
commit e6e175ebcf
816 files changed
+120349

No files matched your search

+13
View File
@@ -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)。
+3
View File
@@ -0,0 +1,3 @@
开始任务前先读取 `/dm/AGENTS.md`,再读取目标路径适用的子级规则。
本项目使用 `core/skills/dever/SKILL.md` 的目录和边界合同,语法以 LANGUAGE 为准。Agent 状态和工具计算留在 Dever,JavaScript 只适配模型协议。Test 的 Port fake 只用于隔离模型边界,不把 fake 结果写成真实模型调用或受保护 HTTP 验收通过。
+73
View File
@@ -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 收尾 |
+14
View File
@@ -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);
});
+3
View File
@@ -0,0 +1,3 @@
开始任务前先读取 `/dm/AGENTS.md`,再读取目标路径适用的子级规则。
本项目以 CMS 为例演示 Dever 的数据模型与 HTTP 绑定,后台使用受保护入口,前台只公开已发布文章。普通 CRUD 优先 REST;有状态约束才写业务 flow。不默认加入版本控制和无用途的写后回查。真实登录 Provider 尚未接入,不将本例声称为完整可运行后台,不添加假 verify 或匿名管理入口。
+78
View File
@@ -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 错误响应;数据库并发错误照常传播。
+14
View File
@@ -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) |
+3
View File
@@ -0,0 +1,3 @@
开始任务前先读取 `/dm/AGENTS.md`,再读取目标路径适用的子级规则。
本项目是Dever 文字游戏示例,使用随包 `core/skills/dever/SKILL.md`。游戏规则集中在 app 的规则表,保持纯计算,不增加数据库或通用游戏引擎。
+58
View File
@@ -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)
}
+5
View File
@@ -0,0 +1,5 @@
开始任务前先读取 /dm/AGENTS.md,再读取目标路径适用的子级规则。
本目录是业务合同夹具。语言语法以[语言参考](../../../LANGUAGE.md)为准,运行条件和测试入口见 [README](README.md)。编写 Dever 应用时遵循[随包开发说明](../../../skills/dever/SKILL.md)。
明确外部输入、可信身份、事务和外部调用边界。生产支付、通知和筛选由实际 Adapter 接入;测试中的 Port fake 不用于生产,也不作为外部服务的验收依据。
+79
View File
@@ -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
@@ -0,0 +1,12 @@
type Status {
Pending
Paid
}
type Order {
uuid: Uuid generated unique
private owner owner_id: demo.account.data.user.id = dever.auth.userId()
amount: Decimal(12, 2)
status: Status default Pending
receipt: Text?
}
@@ -0,0 +1,23 @@
type Notice {
key: Uuid
receipt: Text
}
flow pay(order_id: data.id) () {
user_id = demo.account.userId()
order = data.first(id == order_id and owner_id == user_id and status == Pending)
check order != null else Conflict
receipt = port.pay(order.uuid, order.amount)
app.markPaid(order, receipt)
}
transaction flow markPaid(order: data.Order, receipt: Text) () {
user_id = demo.account.userId()
changed = data.update({ where = id == order.id and owner_id == user_id and status == Pending and amount == order.amount }, { status = Paid, receipt = receipt })
check changed == 1 else Conflict
enqueue(job.notifyPaid, Notice { key = order.uuid, receipt = receipt }, uuid.toText(order.uuid))
}
flow notifyPaid(input: Notice) () {
port.notify(input.key, input.receipt)
}
@@ -0,0 +1,3 @@
pay(key: Uuid, amount: Decimal) (receipt: Text) fails dever.process.Error
notify(key: Uuid, receipt: Text) () fails dever.process.Error
@@ -0,0 +1,9 @@
flow checkOne(value: Text, kept: List<Text>) (selected: List<Text>) {
accepted = port.accept(value)
selected = app.keep(accepted, value, kept)
}
flow findOne(value: Text) (acc: Text?, stop: Bool) {
stop = port.accept(value)
acc = app.foundValue(stop, value)
}
@@ -0,0 +1,9 @@
loop select(values: List<Text>) (selected: List<Text>)
value in values {
fold(kept = [], app.checkOne(value, kept))
}
loop find(values: List<Text>) (found: Text?)
value in values {
foldUntil(previous = null, app.findOne(value))
}
@@ -0,0 +1 @@
accept(value: Text) (accepted: Bool) fails dever.process.Error
@@ -0,0 +1,11 @@
rule keep(accepted: Bool, value: Text, kept: List<Text>) (selected: List<Text>)
accepted {
true => append(kept, value)
false => kept
}
rule foundValue(accepted: Bool, value: Text) (found: Text?)
accepted {
true => value
false => null
}
@@ -0,0 +1 @@
public post names = app.names
@@ -0,0 +1,33 @@
type Node {
id: Int
name: Text
children: List<Int>
}
type Cursor {
nodes: Map<Int, Node>
pending: List<Int>
position: Int
seen: Map<Int, Bool>
}
start(nodes: List<Node>, root: Int) (cursor: Cursor) {
cursor = Cursor { nodes = app.indexNodes(nodes), pending = [root], position = 0, seen = put({}, root, true) }
}
nextNode(cursor: Cursor) (step: Walk<Node, Cursor>) {
step = app.visit(get(cursor.pending, cursor.position), cursor)
}
expand(node_id: Int, cursor: Cursor) (step: Walk<Node, Cursor>) {
node = get(cursor.nodes, node_id)
check node != null else Invalid
next = cursor
next.position = next.position + 1
next = app.enqueueChildren(node.children, next)
step = Next(node, next)
}
enqueueChild(child: Int, cursor: Cursor) (next: Cursor) {
next = app.enqueue(get(cursor.seen, child) != null, child, cursor)
}
@@ -0,0 +1,14 @@
loop names(nodes: List<Node>, root: Int) (names: List<Text>)
node in walk(app.start(nodes, root), app.nextNode) {
list node.name
}
loop indexNodes(nodes: List<Node>) (indexed: Map<Int, Node>)
node in nodes {
index node.id
}
loop enqueueChildren(children: List<Int>, cursor: Cursor) (next: Cursor)
child in children {
fold(queue = cursor, app.enqueueChild(child, queue))
}
@@ -0,0 +1,16 @@
rule visit(node_id: Int?, cursor: Cursor) (step: Walk<Node, Cursor>)
node_id {
null => Done
other => app.expand(node_id, cursor)
}
rule enqueue(seen: Bool, child: Int, cursor: Cursor) (next: Cursor)
seen {
true => cursor
false => Cursor {
nodes = cursor.nodes
pending = append(cursor.pending, child)
position = cursor.position
seen = put(cursor.seen, child, true)
}
}
@@ -0,0 +1,12 @@
flow shortCircuit() ()
| step | kind | do |
| selected | loop | app.select(["no", "yes"]) |
| - | calc | assertEq(selected, ["yes"]) |
| found | loop | app.find(["no", "yes", "explode"]) |
| - | calc | assertEq(found, "yes") |
rule port.accept(value: Text) (accepted: Bool)
| value | accepted |
| "yes" | true |
| "explode" | fail(dever.process.Error.Failed("不应继续调用命中之后的元素")) |
| other | false |
@@ -0,0 +1,4 @@
traversal() () {
nodes = [app.Node { id = 1, name = "总部", children = [2, 3] }, app.Node { id = 2, name = "开发", children = [4] }, app.Node { id = 3, name = "测试", children = [4] }, app.Node { id = 4, name = "共享小组", children = [1] }]
assertEq(app.names(nodes, 1), ["总部", "开发", "测试", "共享小组"])
}