docs: unify compute return type to Maybe (T | null)
This commit is contained in:
@@ -59,21 +59,24 @@ Sense 是系统中唯一的一等公民。一个 Sense 定义一个 compute 函
|
||||
|
||||
Sense 是多态的——每种 Sense 有自己的 Payload 类型。
|
||||
|
||||
所有 Sense 的 compute 返回 `T | null`。返回值时发 signal,返回 `null` 时静默——不写存储、不发 signal、不触发下游 reflex。
|
||||
|
||||
```typescript
|
||||
// 原始采样:读物理世界
|
||||
// 原始采样:读物理世界,每次都有值
|
||||
// senses/cpu-usage.ts
|
||||
export async function compute(): Promise<number> {
|
||||
return os.loadavg()[0]
|
||||
export async function compute(): Promise<number | null> {
|
||||
return os.loadavg()[0] // 实际上总是有值
|
||||
}
|
||||
|
||||
// 派生计算(即"Projection"):读其他 Sense 的存储
|
||||
// senses/active-tasks.ts
|
||||
export async function compute(): Promise<Task[]> {
|
||||
export async function compute(): Promise<Task[] | null> {
|
||||
const prev = myDb.prepare('SELECT * FROM tasks').all()
|
||||
const newEvents = taskEventsDb.prepare(
|
||||
'SELECT * FROM events WHERE ts > ?'
|
||||
).all(lastSync)
|
||||
return applyChanges(prev, newEvents)
|
||||
const result = applyChanges(prev, newEvents)
|
||||
return hasChanges(result, prev) ? result : null // 无变化则静默
|
||||
}
|
||||
```
|
||||
|
||||
@@ -83,17 +86,18 @@ export async function compute(): Promise<Task[]> {
|
||||
|
||||
#### Sense → Workflow 的桥接
|
||||
|
||||
一个 Sense 的 compute 如果返回 `ThreadStart | null`,引擎看到非 null 就自动发起 Workflow Thread。不需要额外的"桥"概念。
|
||||
当 Payload 类型是 `ThreadStart` 时,引擎看到非 null 的返回值就自动发起 Workflow Thread。不需要额外的"桥"概念——这只是 `Maybe (Payload a)` 的一个特例。
|
||||
|
||||
```typescript
|
||||
// senses/should-cleanup.ts
|
||||
// Payload = ThreadStart,null 则不触发
|
||||
export async function compute(): Promise<ThreadStart | null> {
|
||||
const disk = diskDb.prepare(
|
||||
'SELECT value FROM samples ORDER BY ts DESC LIMIT 1'
|
||||
).get()
|
||||
return disk.value > 90
|
||||
? { workflowId: 'cleanup', context: { usage: disk.value } }
|
||||
: null
|
||||
: null // 磁盘正常,静默
|
||||
}
|
||||
```
|
||||
|
||||
@@ -425,10 +429,10 @@ systemd (最后防线,只管进程存活)
|
||||
用 Haskell 描述核心类型和函数:
|
||||
|
||||
```haskell
|
||||
-- Sense 是多态的
|
||||
-- Sense 是多态的,compute 返回 Maybe
|
||||
class Sense a where
|
||||
type Payload a
|
||||
compute :: IO (Payload a)
|
||||
compute :: IO (Maybe (Payload a)) -- Nothing → 静默,Just → 发 signal
|
||||
|
||||
-- Reflex 是纯数据
|
||||
data Reflex = Reflex
|
||||
@@ -451,7 +455,7 @@ execute :: Role -> Prompt -> IO CommandEvent -- 有副作用 ❌
|
||||
|
||||
| 函数 | 纯/IO |
|
||||
|------|-------|
|
||||
| `compute` (Sense) | IO — 读世界或读存储 |
|
||||
| `compute` (Sense) | IO — 读世界或读存储,返回 Maybe |
|
||||
| `moderate` (Workflow) | 纯 ✅ |
|
||||
| `execute` (Role) | IO — 调 API、改文件 |
|
||||
| Reflex 条件判断 | 纯数据,引擎硬编码 |
|
||||
|
||||
Reference in New Issue
Block a user