Archived
范式退役:活动只剩一种、只跑 Loop;审批活动可管;活动库重做
用户定的两件,一并落地。
**一、活动不再分 flow 和 loop —— 彻底退役 flow**
· `flow-engine` 模块整个删除(runner 379 行 + step-sequence 184 行 + 测试);
· `paradigm` 从清单身份、`activity_package`/`task` 两张表、任务卡与活动库一并退场;
`businessModel` 不再是判别联合 —— 只有案例模型(CMMN + 说明书 + DMN)一形;
· task 的引擎分派从「按 paradigm 取两个之一」收成**唯一的引擎**;
· `activities/` 四个 flow 活动(A1 受理 / A4 定价 / A6 议价 / A7 归档)各写了一份
案例模型:阶段照原来的步分,触达世界的项一律 manualActivationRule,
能算的交 DMN(A1 的三分类 P-03、A4 的 P-01/P-02)不交 Agent;
· 六个占位槽位的骨架从「机器步落台账 + 一张验收单」改成案例骨架,包版本 0.8.0 → 0.9.0。
**代价写在明处,不假装没有**:`turn-runner` 每一拍都要 `agent.decide` ——
环境里没有模型 key,案例活动一步也走不动。三套端到端(统一报价 / 新建流程包 / 测试台
Trace)整套跳过,文件头写明恢复条件:①有可用模型 ②走法改写成按 Enabled 集推进。
**不许把断言改松让它变绿** —— 绿得不诚实比红着更坏。debt.md 已记。
**二、审批活动可管**(新能力)
· `sys.approval_template`:审批点**可复用的那一半** —— 审批人看哪几项、按什么名字看、
怎么催、说什么话。谁来审不在里面(与活动点同口径,运营时轮值);驳回回哪个节点
也不在里面(那是每张图自己的事,留在节点上);
· 三条路由 + 引用反查:还被审批点引着就不许删(409),删了那些节点会**静默**退回旧行为;
· 运行时 `basisOf`:引了模板就按模板筛与改名,没引即旧行为(载荷全摊开)。
模板改了只影响新发出的审批单 —— 在途单的依据在发出那一刻已定形。
**三、活动库重做**:一区两格 —— 「活动(装进来的)」与「审批活动(配出来的)」,
都用流程卡那套两段式卡片(头 + 四格数据板),幽灵卡当入口(装入活动 / 新建审批活动);
「标准/案例」那一维随范式一起撤,业务分类成了唯一的一维,以行内小签呈现。
迁移 0020:两张表 drop paradigm、建 approval_template。已在开发库跑过并重播种。
实测(丁子乔账号):建「定价审批」模板 → 流程包 A5 属性里选得到 → 引用反查计数正确。
四闸绿(api:check 随本提交)。
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KeDBx2PHLavbURXB8LJJ7m
This commit is contained in:
@@ -14,7 +14,7 @@
|
||||
`TemplateGuard` `Clock` `IdGenerator`
|
||||
- 用例工厂:`createRegistryService(deps): ActivityRegistryService`
|
||||
- 纯函数:`staticAudit` `auditPassed` `danglingListeners` `acceptanceLevelFindings`
|
||||
`flowFindings` `loopFindings` `scanArtifact` `buildLoadEnvelope` `shouldSeedAsset`
|
||||
`loopFindings` `scanArtifact` `buildLoadEnvelope` `shouldSeedAsset`
|
||||
`canTransition` `assertTransition` `judgeReplay` `mayTakeEffect`
|
||||
- adapter:`createRegistryStore`
|
||||
- Drizzle 表:`activityPackageTable` `activityAssetTable` `assetIncrementTable`
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* 活动库:**独立的安装与卸载入口** —— 不在编排中发生。
|
||||
* 安装恒为新增、版本并存;在途任务按其启动时版本跑完,切换零丢单。
|
||||
*/
|
||||
import type { ActivityManifest, InstallVerdict, Paradigm, StaticAuditFinding } from '@contracts';
|
||||
import type { ActivityManifest, InstallVerdict, StaticAuditFinding } from '@contracts';
|
||||
import type {
|
||||
AssetKind,
|
||||
AssetVersion,
|
||||
@@ -25,7 +25,6 @@ export type {
|
||||
InstallVerdict,
|
||||
LoadEnvelope,
|
||||
PackageVersion,
|
||||
Paradigm,
|
||||
ReplayCase,
|
||||
ReplayVerdict,
|
||||
StaticAuditFinding,
|
||||
@@ -57,7 +56,6 @@ export type ActivityCard = {
|
||||
readonly activityId: string;
|
||||
readonly name: string;
|
||||
readonly category: string;
|
||||
readonly paradigm: Paradigm;
|
||||
readonly packageVersions: readonly PackageVersion[];
|
||||
readonly assetVersions: readonly AssetVersion[];
|
||||
readonly enabled: boolean;
|
||||
|
||||
@@ -36,7 +36,6 @@ export {
|
||||
acceptanceLevelFindings,
|
||||
auditPassed,
|
||||
danglingListeners,
|
||||
flowFindings,
|
||||
loopFindings,
|
||||
scanArtifact,
|
||||
staticAudit,
|
||||
|
||||
@@ -13,7 +13,6 @@ export const activityPackageTable = sys.table(
|
||||
version: text('version').notNull(),
|
||||
name: text('name').notNull(),
|
||||
category: text('category').notNull(),
|
||||
paradigm: text('paradigm').notNull(),
|
||||
manifest: jsonb('manifest').notNull(),
|
||||
/** .JS 产物 —— 装载时由 registry 交给范式运行器(ADR-004) */
|
||||
artifact: text('artifact').notNull(),
|
||||
@@ -23,7 +22,7 @@ export const activityPackageTable = sys.table(
|
||||
},
|
||||
(t) => [
|
||||
primaryKey({ columns: [t.activityId, t.version] }),
|
||||
index('activity_package_category_idx').on(t.category, t.paradigm),
|
||||
index('activity_package_category_idx').on(t.category),
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ export function createRegistryStore(db: Db): RegistryStore {
|
||||
version: manifest.identity.packageVersion,
|
||||
name: manifest.identity.name,
|
||||
category: manifest.identity.category,
|
||||
paradigm: manifest.identity.paradigm,
|
||||
manifest,
|
||||
artifact,
|
||||
state: 'active',
|
||||
|
||||
@@ -78,30 +78,9 @@ export function acceptanceLevelFindings(manifest: ActivityManifest): StaticAudit
|
||||
return out;
|
||||
}
|
||||
|
||||
/** flow 判据:每步的六件齐备;复杂路由不得入 flow(AM 12.3) */
|
||||
export function flowFindings(manifest: ActivityManifest): StaticAuditFinding[] {
|
||||
const model = manifest.assets.businessModel;
|
||||
if (model.paradigm !== 'flow') return [];
|
||||
const out: StaticAuditFinding[] = [];
|
||||
const names = new Set<string>();
|
||||
for (const [index, step] of model.steps.entries()) {
|
||||
const at = `assets.businessModel.steps[${index}]`;
|
||||
if (names.has(step.name)) out.push({ code: 'schema-invalid', severity: 'error', message: `步名重复:${step.name}`, at });
|
||||
names.add(step.name);
|
||||
if (step.kind === 'human' && (step.deadline.trim() === '' || !DURATION.test(step.deadline))) {
|
||||
out.push({ code: 'dangling-listener', severity: 'error', message: `人类工具步 ${step.name} 缺时限 —— 无死等`, at });
|
||||
}
|
||||
if (step.kind === 'llm' && Object.keys(step.outputSchema).length === 0) {
|
||||
out.push({ code: 'schema-invalid', severity: 'error', message: `LLM 步 ${step.name} 缺出参 schema —— 模板与出参随版本冻结`, at });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** loop 判据:双表示同版本,不允许分叉(AM 12.2) */
|
||||
export function loopFindings(manifest: ActivityManifest): StaticAuditFinding[] {
|
||||
const model = manifest.assets.businessModel;
|
||||
if (model.paradigm !== 'loop') return [];
|
||||
const out: StaticAuditFinding[] = [];
|
||||
if (model.cmmnXml.trim() === '') {
|
||||
out.push({ code: 'schema-invalid', severity: 'error', message: '案例模型缺 CMMN XML', at: 'assets.businessModel.cmmnXml' });
|
||||
@@ -152,7 +131,6 @@ export function staticAudit(manifest: ActivityManifest, external: ExternalChecks
|
||||
|
||||
out.push(...danglingListeners(manifest));
|
||||
out.push(...acceptanceLevelFindings(manifest));
|
||||
out.push(...flowFindings(manifest));
|
||||
out.push(...loopFindings(manifest));
|
||||
|
||||
return out;
|
||||
|
||||
@@ -138,7 +138,6 @@ export function createRegistryService(deps: RegistryServiceDeps): ActivityRegist
|
||||
activityId,
|
||||
name: manifest.identity.name,
|
||||
category: manifest.identity.category,
|
||||
paradigm: manifest.identity.paradigm,
|
||||
packageVersions: versions,
|
||||
assetVersions: await deps.store.listAssets(activityId),
|
||||
enabled: await deps.store.enabledOf(activityId),
|
||||
@@ -245,7 +244,7 @@ function serializeAsset(manifest: ActivityManifest, kind: AssetKind): string {
|
||||
return JSON.stringify(manifest.assets.businessModel);
|
||||
case 'dmn':
|
||||
return JSON.stringify(
|
||||
manifest.assets.businessModel.paradigm === 'loop' ? manifest.assets.businessModel.dmn : { drd: [], tables: [] },
|
||||
manifest.assets.businessModel.dmn,
|
||||
);
|
||||
case 'skill':
|
||||
return JSON.stringify(manifest.assets.skills);
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
# module: flow-engine
|
||||
|
||||
职责: flow 范式:步序声明的装载与静态检查、四种步型的执行、条件跳步、
|
||||
重试与声明给定的兜底、异步步的监听登记与事件续跑、步序位置的持久
|
||||
不负责: 任务生命周期与终态裁定(见 task)、放行与落地(见 release)、
|
||||
复杂路由(**不得在 flow 内表达** —— 上升为流程层网关或改用 loop)
|
||||
|
||||
公开出口: index.ts
|
||||
- 类型:`FlowEngineService` `FlowPosition` `StepRuntime` `AdvanceOutcome` `FailureAction` `NextAction`
|
||||
- 错误:`FlowDeclarationInvalidError`
|
||||
- 端口类型:`FlowStateStore` `PredicateEvaluator` `TaskDataGateway` `ToolStepInvoker`
|
||||
`LlmStepGateway` `CardGateway` `ListenerRegistrar` `MemoryRecorder` `TaskContext`
|
||||
- 用例工厂:`createFlowRunner(deps): FlowEngineService`
|
||||
- 纯函数:`nextAction` `markStep` `failureAction` `checkDeclaration` `initialPosition`
|
||||
`lastStepIsAcceptance` `parallelGroupComplete`
|
||||
- adapter:`createFlowStateStore`;Drizzle 表:`flowStateTable`
|
||||
|
||||
层级: L5(编码规范 §4)
|
||||
依赖: @contracts;@shared/db;skill-engine(L4,步引用结晶片段);
|
||||
port 注入:ledger / toolbox / llm / human-tool / event / memory
|
||||
被依赖: task
|
||||
|
||||
不变量(AM 05 / 12.3):
|
||||
- **零临场调度**:下一步由 `nextAction` 从声明算出,LLM 只以「被调用的工具」出现
|
||||
- **条件必谓词**:跳步条件经 `PredicateEvaluator`(@sfeel)确定性求值,零 LLM
|
||||
- **失败路径声明给定**:`failureAction` 只从声明读重试次数与兜底,不临场发明
|
||||
- **异步步 = 监听**:人类工具步登记人事件监听,**时限必配**,无死等
|
||||
- **出参落草稿层**:步的产出是草稿态,放行前不落事实
|
||||
- **写类工具登记为动作意向**:flow 里同样不即时触达世界(除契约显式预授权)
|
||||
- **谱全程可静态检查**:`checkDeclaration` 不过即 `FlowDeclarationInvalidError`,不得上架
|
||||
- 步序位置持久于 `flowStateTable` —— 断点续跑的三份持久状态之一
|
||||
@@ -1,155 +0,0 @@
|
||||
/** flow 步序:声明校验 / 失败走向 / 兜底出参 —— domain 测试零 mock(AM 12.3) */
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { flowStepSchema } from '@contracts';
|
||||
import type { FlowStep } from '@contracts';
|
||||
import {
|
||||
checkDeclaration,
|
||||
fallbackFields,
|
||||
failureAction,
|
||||
initialPosition,
|
||||
lastStepIsAcceptance,
|
||||
markStep,
|
||||
parallelGroupComplete,
|
||||
resolvePath,
|
||||
} from '../internal/domain/step-sequence.ts';
|
||||
|
||||
const llmStep = (over: Record<string, unknown> = {}): FlowStep =>
|
||||
flowStepSchema.parse({
|
||||
kind: 'llm',
|
||||
name: 'S3',
|
||||
label: 'S3 逐条解析归一',
|
||||
input: { rfqRef: 'rfqRef' },
|
||||
output: { domain: 'quote_intake', object: 'record', fields: { pn: 'pn', brand: 'brand', eau: 'eau' } },
|
||||
model: 'quote-extractor',
|
||||
template: '解析 {{rfqRef}}',
|
||||
outputSchema: { type: 'object' },
|
||||
failure: { retry: { times: 2, backoff: 'PT30S' }, fallback: { kind: 'human', workOrder: 'execution' } },
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('人兜底:出参契约属于步,不属于执行者', () => {
|
||||
it('兜底卡问的字段 = 这一步声明的出参 —— 人填完能落进作用域', () => {
|
||||
// 若只给一个笼统的「结果」框,下游按 output.fields 取值会取空,在下一步崩
|
||||
expect(fallbackFields(llmStep())).toEqual(['pn', 'brand', 'eau']);
|
||||
});
|
||||
|
||||
it('行标识也要问 —— 主键取不到就写不进台账', () => {
|
||||
const step = flowStepSchema.parse({
|
||||
kind: 'llm',
|
||||
name: 'S1',
|
||||
label: '生成正式报价单',
|
||||
input: {},
|
||||
model: 'm',
|
||||
template: 't',
|
||||
outputSchema: { type: 'object' },
|
||||
output: {
|
||||
domain: 'q',
|
||||
object: 'formal_quote',
|
||||
key: { quote_no: 'quoteNo', pn: 'pn' },
|
||||
fields: { unit_price: 'unitPrice' },
|
||||
},
|
||||
failure: { retry: { times: 0, backoff: 'PT1S' }, fallback: { kind: 'human', workOrder: 'execution' } },
|
||||
});
|
||||
// pn 上游已给,不必再问;quoteNo 没人给过,必须问
|
||||
expect(fallbackFields(step, { pn: 'LM358DR' })).toEqual(['quoteNo', 'unitPrice']);
|
||||
expect(fallbackFields(step, {})).toEqual(['quoteNo', 'pn', 'unitPrice']);
|
||||
});
|
||||
|
||||
it('无出参声明的步不凭空造字段', () => {
|
||||
const step = flowStepSchema.parse({
|
||||
kind: 'llm',
|
||||
name: 'S9',
|
||||
label: '只说不写的一步',
|
||||
input: {},
|
||||
model: 'm',
|
||||
template: 't',
|
||||
outputSchema: { type: 'object' },
|
||||
failure: { retry: { times: 0, backoff: 'PT1S' }, fallback: { kind: 'blocked' } },
|
||||
});
|
||||
expect(fallbackFields(step)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('失败走向声明给定,不临场发明', () => {
|
||||
it('重试次数未用尽 → retry', () => {
|
||||
expect(failureAction(llmStep(), 1).kind).toBe('retry');
|
||||
});
|
||||
|
||||
it('重试用尽 → 按声明的 fallback 转人', () => {
|
||||
const action = failureAction(llmStep(), 2);
|
||||
expect(action.kind).toBe('human');
|
||||
});
|
||||
|
||||
it('声明 blocked 的步不转人 —— 走向是声明的,不是猜的', () => {
|
||||
const step = llmStep({ failure: { retry: { times: 0, backoff: 'PT1S' }, fallback: { kind: 'blocked' } } });
|
||||
expect(failureAction(step, 0).kind).toBe('blocked');
|
||||
});
|
||||
});
|
||||
|
||||
describe('步序位置', () => {
|
||||
it('初始位置每步待跑', () => {
|
||||
const position = initialPosition([llmStep(), llmStep({ name: 'S4' })]);
|
||||
expect(position.index).toBe(0);
|
||||
expect(position.steps.map((s) => s.state)).toEqual(['pending', 'pending']);
|
||||
});
|
||||
|
||||
it('markStep 只改那一步,其余原样', () => {
|
||||
const position = initialPosition([llmStep(), llmStep({ name: 'S4' })]);
|
||||
const next = markStep(position, 1, { state: 'done' });
|
||||
expect(next.steps.map((s) => s.state)).toEqual(['pending', 'done']);
|
||||
});
|
||||
|
||||
it('并行组要全完成才算完成', () => {
|
||||
const position = markStep(initialPosition([llmStep(), llmStep({ name: 'S4' })]), 0, { state: 'done' });
|
||||
expect(parallelGroupComplete(position, ['S3', 'S4'])).toBe(false);
|
||||
expect(parallelGroupComplete(markStep(position, 1, { state: 'done' }), ['S3', 'S4'])).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('声明校验', () => {
|
||||
it('步名重复即拒', () => {
|
||||
expect(checkDeclaration([llmStep(), llmStep()]).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('末步是验收工单可辨', () => {
|
||||
const acceptance: FlowStep = flowStepSchema.parse({
|
||||
kind: 'human',
|
||||
name: 'S6',
|
||||
label: '验收',
|
||||
input: {},
|
||||
workOrder: 'acceptance',
|
||||
card: {},
|
||||
deadline: 'P1D',
|
||||
failure: { retry: { times: 0, backoff: 'PT1S' }, fallback: { kind: 'blocked' } },
|
||||
});
|
||||
expect(lastStepIsAcceptance([llmStep(), acceptance])).toBe(true);
|
||||
expect(lastStepIsAcceptance([llmStep()])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('取值路径 —— 入参出参共用一份', () => {
|
||||
const shaped = {
|
||||
records: [
|
||||
{ pn: 'LM358DR', brand: 'TI', eau: 12000 },
|
||||
{ pn: 'NE555P', brand: 'TI', eau: 3000 },
|
||||
],
|
||||
missingKeyFields: 0,
|
||||
flat: 'x',
|
||||
};
|
||||
|
||||
it('数组下标按数字段下行 —— 模型按 schema 回嵌套结构是最常见的情形', () => {
|
||||
expect(resolvePath(shaped, 'records.0.pn')).toBe('LM358DR');
|
||||
expect(resolvePath(shaped, 'records.1.brand')).toBe('TI');
|
||||
});
|
||||
|
||||
it('扁平键照旧', () => {
|
||||
expect(resolvePath(shaped, 'missingKeyFields')).toBe(0);
|
||||
expect(resolvePath(shaped, 'flat')).toBe('x');
|
||||
});
|
||||
|
||||
it('走不通的路径回 undefined,不抛 —— 缺字段由下游的契约校验如实报出来', () => {
|
||||
expect(resolvePath(shaped, 'records.9.pn')).toBeUndefined();
|
||||
expect(resolvePath(shaped, 'nope.deep.deeper')).toBeUndefined();
|
||||
expect(resolvePath(undefined, 'a.b')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
/**
|
||||
* module: flow-engine —— 对外类型(编码规范 §10.1;语义出处 AM 05)。
|
||||
*
|
||||
* flow 范式:步序声明运行器(四种步型、重试与兜底、事件即步条件)。
|
||||
* **零临场调度** —— 运行中不得由 LLM 决定步序、跳步或兜底。
|
||||
*/
|
||||
import type { FlowModel, FlowStep, TaskId } from '@contracts';
|
||||
import type { FailureAction, FlowIssue, FlowPosition, NextAction, StepRuntime, StepState } from './internal/domain/step-sequence.ts';
|
||||
|
||||
export type { FailureAction, FlowIssue, FlowModel, FlowPosition, FlowStep, NextAction, StepRuntime, StepState };
|
||||
|
||||
export class FlowDeclarationInvalidError extends Error {
|
||||
constructor(readonly issues: readonly FlowIssue[]) {
|
||||
super(`步序声明不完整,不得上架:${issues.map((i) => `${i.step}:${i.message}`).join('; ')}`);
|
||||
this.name = 'FlowDeclarationInvalidError';
|
||||
}
|
||||
}
|
||||
|
||||
/** 一次推进的结果 —— 由 task 驱动,不自转 */
|
||||
export type AdvanceOutcome = {
|
||||
readonly position: FlowPosition;
|
||||
readonly status: 'running' | 'awaiting' | 'finished' | 'blocked';
|
||||
/** awaiting 时:在等什么 */
|
||||
readonly waitingFor?: { readonly kind: 'human' | 'event' | 'time'; readonly ref: string; readonly deadline: string };
|
||||
/** finished 时:末步验收工单的裁决决定终态 */
|
||||
readonly released?: boolean;
|
||||
/** 选择组的出口选择:恰发一口,随放行一并确认 */
|
||||
readonly selectedPorts?: Record<string, string>;
|
||||
readonly blockedReason?: string;
|
||||
};
|
||||
|
||||
export type FlowEngineService = {
|
||||
/** 装载步序声明并校验 —— 谱必须全程可静态检查 */
|
||||
load(taskId: TaskId, model: FlowModel): Promise<FlowPosition>;
|
||||
position(taskId: TaskId): Promise<FlowPosition | undefined>;
|
||||
/** 推进一步(或若干确定步);异步步进入 awaiting 并登记监听 */
|
||||
advance(taskId: TaskId): Promise<AdvanceOutcome>;
|
||||
/** 事件即步的完成条件:人事件 / 数据事件 / 时间事件到达即续跑 */
|
||||
resume(taskId: TaskId, event: { kind: 'human' | 'data' | 'time'; ref: string; payload: Record<string, unknown> }): Promise<AdvanceOutcome>;
|
||||
};
|
||||
@@ -1,47 +0,0 @@
|
||||
/**
|
||||
* module: flow-engine —— 唯一出口。只做 re-export,不写逻辑(编码规范 §10.1)。
|
||||
*/
|
||||
export type {
|
||||
AdvanceOutcome,
|
||||
FailureAction,
|
||||
FlowEngineService,
|
||||
FlowIssue,
|
||||
FlowModel,
|
||||
FlowPosition,
|
||||
FlowStep,
|
||||
NextAction,
|
||||
StepRuntime,
|
||||
StepState,
|
||||
} from './contract.ts';
|
||||
export { FlowDeclarationInvalidError } from './contract.ts';
|
||||
|
||||
export type {
|
||||
CardGateway,
|
||||
Clock,
|
||||
FlowStateStore,
|
||||
IdGenerator,
|
||||
ListenerRegistrar,
|
||||
LlmStepGateway,
|
||||
MemoryRecorder,
|
||||
PredicateEvaluator,
|
||||
TaskContext,
|
||||
TaskDataGateway,
|
||||
ToolStepInvoker,
|
||||
} from './port.ts';
|
||||
|
||||
export type { FlowRunnerDeps } from './internal/usecase/flow-runner.ts';
|
||||
export { createFlowRunner } from './internal/usecase/flow-runner.ts';
|
||||
|
||||
export {
|
||||
checkDeclaration,
|
||||
failureAction,
|
||||
initialPosition,
|
||||
lastStepIsAcceptance,
|
||||
markStep,
|
||||
nextAction,
|
||||
parallelGroupComplete,
|
||||
STEP_STATES,
|
||||
} from './internal/domain/step-sequence.ts';
|
||||
|
||||
export { createFlowStateStore } from './internal/adapter/flow-state-store.ts';
|
||||
export { flowStateTable } from './internal/adapter/flow-state-schema.ts';
|
||||
@@ -1,14 +0,0 @@
|
||||
/**
|
||||
* flow-engine 的 sys schema 表(编码规范 §7 / ADR-002)。
|
||||
* 运行时实例状态 —— 断点续跑的三份持久状态之一(OS 09)。
|
||||
*/
|
||||
import { jsonb, text, timestamp } from 'drizzle-orm/pg-core';
|
||||
import { sys } from '@shared/db.ts';
|
||||
|
||||
export const flowStateTable = sys.table('flow_state', {
|
||||
taskId: text('task_id').primaryKey(),
|
||||
model: jsonb('model').notNull(),
|
||||
/** 步序位置 */
|
||||
position: jsonb('position').notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
@@ -1,30 +0,0 @@
|
||||
/**
|
||||
* flow-engine 存储 adapter —— Drizzle 只准出现在 adapter(编码规范 §5.3)。
|
||||
*/
|
||||
import { eq } from 'drizzle-orm';
|
||||
import type { FlowModel, TaskId } from '@contracts';
|
||||
import { flowModelSchema } from '@contracts';
|
||||
import type { Db } from '@shared/db.ts';
|
||||
import type { FlowStateStore } from '../../port.ts';
|
||||
import type { FlowPosition } from '../domain/step-sequence.ts';
|
||||
import { flowStateTable } from './flow-state-schema.ts';
|
||||
|
||||
export function createFlowStateStore(db: Db): FlowStateStore {
|
||||
return {
|
||||
async save(taskId: TaskId, model: FlowModel, position: FlowPosition) {
|
||||
await db
|
||||
.insert(flowStateTable)
|
||||
.values({ taskId, model, position, updatedAt: new Date() })
|
||||
.onConflictDoUpdate({
|
||||
target: flowStateTable.taskId,
|
||||
set: { model, position, updatedAt: new Date() },
|
||||
});
|
||||
},
|
||||
async load(taskId: TaskId) {
|
||||
const rows = await db.select().from(flowStateTable).where(eq(flowStateTable.taskId, taskId)).limit(1);
|
||||
const row = rows[0];
|
||||
if (row === undefined) return undefined;
|
||||
return { model: flowModelSchema.parse(row.model), position: row.position as FlowPosition };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
/**
|
||||
* flow 步序推进 —— 纯逻辑,零 IO(编码规范 §5.3;语义出处 AM 05)。
|
||||
*
|
||||
* 「flow 是活动内的**确定性范式**:业务模型 = 步序声明 —— 一条谱;
|
||||
* 引擎照谱执行,**零临场调度**,调度权归系统。
|
||||
* 差异只有一处:下一步由**声明给定**,不由 AI 决断。
|
||||
* LLM 在 flow 里可以出现,但只以『被调用的工具』出现,不是调度者。」
|
||||
*/
|
||||
import type { FlowStep } from '@contracts';
|
||||
|
||||
export const STEP_STATES = ['pending', 'running', 'awaiting', 'done', 'skipped', 'failed'] as const;
|
||||
export type StepState = (typeof STEP_STATES)[number];
|
||||
|
||||
export type StepRuntime = {
|
||||
readonly name: string;
|
||||
readonly state: StepState;
|
||||
readonly attempt: number;
|
||||
readonly output?: Record<string, unknown>;
|
||||
readonly error?: string;
|
||||
/** 验收工单的放行裁决:pass / 驳回类别 —— 末步据此定终局 */
|
||||
readonly verdict?: string;
|
||||
/** 选择组的出口选择:恰发一口,随放行一并确认(AM 1.2) */
|
||||
readonly selectedPorts?: Record<string, string>;
|
||||
};
|
||||
|
||||
export type FlowPosition = {
|
||||
/** 步序位置 —— 三份持久状态之一(OS 09 断点续跑) */
|
||||
readonly index: number;
|
||||
readonly steps: readonly StepRuntime[];
|
||||
};
|
||||
|
||||
export function initialPosition(steps: readonly FlowStep[]): FlowPosition {
|
||||
return { index: 0, steps: steps.map((s) => ({ name: s.name, state: 'pending', attempt: 0 })) };
|
||||
}
|
||||
|
||||
/** 条件跳步:条件必须是任务数据上的**确定性谓词**,由引擎求值,零 LLM(AM 5.2) */
|
||||
export type PredicateEvaluator = (expression: string, scope: Readonly<Record<string, unknown>>) => boolean;
|
||||
|
||||
export type NextAction =
|
||||
| { readonly kind: 'run'; readonly step: FlowStep; readonly index: number }
|
||||
| { readonly kind: 'skip'; readonly step: FlowStep; readonly index: number; readonly reason: string }
|
||||
| { readonly kind: 'await'; readonly step: FlowStep; readonly index: number }
|
||||
| { readonly kind: 'finished' };
|
||||
|
||||
/**
|
||||
* 下一步由声明给定。异步步(人类工具步 / 等事件的步)进入 `await` —— 完成条件 = 监听。
|
||||
*/
|
||||
export function nextAction(
|
||||
declaration: readonly FlowStep[],
|
||||
position: FlowPosition,
|
||||
scope: Readonly<Record<string, unknown>>,
|
||||
evaluate: PredicateEvaluator,
|
||||
): NextAction {
|
||||
for (let i = position.index; i < declaration.length; i += 1) {
|
||||
const step = declaration[i]!;
|
||||
const runtime = position.steps[i];
|
||||
if (runtime?.state === 'done' || runtime?.state === 'skipped') continue;
|
||||
if (runtime?.state === 'awaiting') return { kind: 'await', step, index: i };
|
||||
|
||||
if (step.when !== undefined && !evaluate(step.when, scope)) {
|
||||
return { kind: 'skip', step, index: i, reason: `条件不成立:${step.when}` };
|
||||
}
|
||||
return { kind: 'run', step, index: i };
|
||||
}
|
||||
return { kind: 'finished' };
|
||||
}
|
||||
|
||||
export function markStep(position: FlowPosition, index: number, patch: Partial<StepRuntime>): FlowPosition {
|
||||
const steps = position.steps.map((s, i) => (i === index ? { ...s, ...patch } : s));
|
||||
const advanced = patch.state === 'done' || patch.state === 'skipped';
|
||||
return { index: advanced ? index + 1 : index, steps };
|
||||
}
|
||||
|
||||
/* ── 失败与缺口:声明给定,不临场(AM 5.3) ────────────────────────── */
|
||||
|
||||
export type FailureAction =
|
||||
| { readonly kind: 'retry'; readonly attempt: number; readonly backoff: string }
|
||||
/** 转人兜底:改发人类工具卡,卡内容随声明 */
|
||||
| { readonly kind: 'human'; readonly workOrder: 'execution' | 'acceptance' }
|
||||
/** 受阻待人:挂起,携阻因 */
|
||||
| { readonly kind: 'blocked' };
|
||||
|
||||
/**
|
||||
* 「每步声明重试次数与间隔;重试仍败,按声明走下一步。
|
||||
* **flow 内不得出现『由 AI 决定怎么办』的失败处理** —— 需要临场,即说明该活动不该是 flow。」
|
||||
*/
|
||||
export function failureAction(step: FlowStep, attempt: number): FailureAction {
|
||||
if (attempt < step.failure.retry.times) {
|
||||
return { kind: 'retry', attempt: attempt + 1, backoff: step.failure.retry.backoff };
|
||||
}
|
||||
return step.failure.fallback.kind === 'human'
|
||||
? { kind: 'human', workOrder: step.failure.fallback.workOrder }
|
||||
: { kind: 'blocked' };
|
||||
}
|
||||
|
||||
/* ── 静态检查:谱必须全程可静态检查(AM 12.3) ────────────────────── */
|
||||
|
||||
export type FlowIssue = { readonly step: string; readonly message: string };
|
||||
|
||||
export function checkDeclaration(steps: readonly FlowStep[]): FlowIssue[] {
|
||||
const out: FlowIssue[] = [];
|
||||
const names = new Set<string>();
|
||||
for (const step of steps) {
|
||||
if (names.has(step.name)) out.push({ step: step.name, message: '步名重复' });
|
||||
names.add(step.name);
|
||||
// 步序声明完整:步型 / 入参映射 / 出参写入 / 完成条件 / 失败策略齐备
|
||||
if (step.failure.retry.times < 0) out.push({ step: step.name, message: '重试次数不得为负' });
|
||||
if (step.kind === 'human' && step.deadline.trim() === '') {
|
||||
out.push({ step: step.name, message: '人类工具步必配时限 —— 无死等' });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 终态映射(AM 5.3):放行完成 = 末步验收工单「放行通过」 */
|
||||
export function lastStepIsAcceptance(steps: readonly FlowStep[]): boolean {
|
||||
const last = steps.at(-1);
|
||||
return last !== undefined && last.kind === 'human' && last.workOrder === 'acceptance';
|
||||
}
|
||||
|
||||
/** 并行组:组内步无依赖、**全完成再继续** */
|
||||
export function parallelGroupComplete(position: FlowPosition, members: readonly string[]): boolean {
|
||||
return members.every((name) => {
|
||||
const runtime = position.steps.find((s) => s.name === name);
|
||||
return runtime?.state === 'done' || runtime?.state === 'skipped';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 人兜底时要回填的字段 —— 取自这一步**声明的出参**。
|
||||
*
|
||||
* 出参契约属于**步**,不属于执行者:同一步无论由 LLM、工具还是人做完,
|
||||
* 落进作用域的形状必须一致。若兜底卡只给一个笼统的「结果」文本框,
|
||||
* 人填了也落不进去 —— 下游按 `output.fields` 取值,取不到就在下一步崩。
|
||||
*
|
||||
* 返回键名数组,与 human 步的 `card.fields` 同形:卡的渲染只有一套。
|
||||
*/
|
||||
export function fallbackFields(step: FlowStep, scope: Readonly<Record<string, unknown>> = {}): readonly string[] {
|
||||
if (step.output === undefined) return [];
|
||||
// 出参的值要问,**行标识**也要问 —— 主键取不到就写不进台账(非空约束会在合并时挡下)。
|
||||
// 作用域里已经有的键不必再问一遍:上游给过就是给过了。
|
||||
const keys = Object.values(step.output.key).filter((path) => scope[path] === undefined);
|
||||
return [...new Set([...keys, ...Object.values(step.output.fields)])];
|
||||
}
|
||||
|
||||
/**
|
||||
* 末步的放行裁决是否「通过」—— **完成只出自放行通过**(OS 05)。
|
||||
* 驳回(重做 / 迭代)不是完成:谱虽走完,任务不得进 released。
|
||||
*/
|
||||
export function lastVerdictPassed(position: FlowPosition): boolean {
|
||||
const last = position.steps[position.steps.length - 1];
|
||||
return last?.verdict === 'pass';
|
||||
}
|
||||
|
||||
/** 末步随放行确认的出口选择 —— 落地收敛时按它发射 */
|
||||
export function lastSelectedPorts(position: FlowPosition): Record<string, string> {
|
||||
return position.steps[position.steps.length - 1]?.selectedPorts ?? {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 取值路径:点号分段下行,数组下标按数字段走(`records.0.pn`)。
|
||||
*
|
||||
* **入参与出参共用这一份**:声明里写的路径是同一种写法,不该一边能走点号、
|
||||
* 另一边只认扁平键 —— 那会让「模型按 schema 回了嵌套结构」这种最常见的情形
|
||||
* 悄悄写出一条空记录。
|
||||
*/
|
||||
export function resolvePath(source: unknown, path: string): unknown {
|
||||
/*
|
||||
* 整键优先:作用域里有些键**本身带点号**(台账地址 `域.对象`)。
|
||||
* 先按字面整键找,找不到再按点号下行 —— 反过来会把地址键拆成两级、永远找不到。
|
||||
*/
|
||||
if (typeof source === 'object' && source !== null && !Array.isArray(source)) {
|
||||
const direct = (source as Record<string, unknown>)[path];
|
||||
if (direct !== undefined) return direct;
|
||||
}
|
||||
return path.split('.').reduce<unknown>((acc, seg) => {
|
||||
if (acc === null || acc === undefined || typeof acc !== 'object') return undefined;
|
||||
if (Array.isArray(acc)) {
|
||||
const index = Number(seg);
|
||||
return Number.isInteger(index) ? acc[index] : undefined;
|
||||
}
|
||||
return (acc as Record<string, unknown>)[seg];
|
||||
}, source);
|
||||
}
|
||||
@@ -1,379 +0,0 @@
|
||||
/**
|
||||
* flow 运行器 —— 照谱执行,零临场调度(编码规范 §5.3;语义出处 AM 05)。
|
||||
*/
|
||||
import type { FlowStep, TaskId } from '@contracts';
|
||||
import type { AdvanceOutcome, FlowEngineService } from '../../contract.ts';
|
||||
import { FlowDeclarationInvalidError } from '../../contract.ts';
|
||||
import type {
|
||||
CardGateway,
|
||||
Clock,
|
||||
FlowStateStore,
|
||||
ListenerRegistrar,
|
||||
LlmStepGateway,
|
||||
SchemaValidator,
|
||||
ViewGateway,
|
||||
MemoryRecorder,
|
||||
PredicateEvaluator,
|
||||
TaskContext,
|
||||
TaskDataGateway,
|
||||
ToolStepInvoker,
|
||||
} from '../../port.ts';
|
||||
import type { FlowPosition } from '../domain/step-sequence.ts';
|
||||
import {
|
||||
checkDeclaration,
|
||||
fallbackFields,
|
||||
lastSelectedPorts,
|
||||
lastStepIsAcceptance,
|
||||
lastVerdictPassed,
|
||||
failureAction,
|
||||
initialPosition,
|
||||
markStep,
|
||||
nextAction,
|
||||
resolvePath,
|
||||
} from '../domain/step-sequence.ts';
|
||||
|
||||
export type FlowRunnerDeps = {
|
||||
readonly state: FlowStateStore;
|
||||
readonly evaluate: PredicateEvaluator;
|
||||
readonly data: TaskDataGateway;
|
||||
readonly tools: ToolStepInvoker;
|
||||
readonly llm: LlmStepGateway;
|
||||
readonly schemas: SchemaValidator;
|
||||
readonly views: ViewGateway;
|
||||
readonly cards: CardGateway;
|
||||
readonly listeners: ListenerRegistrar;
|
||||
readonly memory: MemoryRecorder;
|
||||
readonly tasks: TaskContext;
|
||||
readonly clock: Clock;
|
||||
};
|
||||
|
||||
export function createFlowRunner(deps: FlowRunnerDeps): FlowEngineService {
|
||||
async function loaded(taskId: TaskId) {
|
||||
const found = await deps.state.load(taskId);
|
||||
if (found === undefined) throw new Error(`flow 未装载:${taskId}`);
|
||||
return found;
|
||||
}
|
||||
|
||||
/** 出参写入落**草稿层**(草稿态);放行前不落事实 */
|
||||
async function writeOutput(taskId: TaskId, step: FlowStep, output: Record<string, unknown>): Promise<void> {
|
||||
if (step.output === undefined) return;
|
||||
const patch: Record<string, unknown> = {};
|
||||
for (const [field, path] of Object.entries(step.output.fields)) {
|
||||
// 路径优先(模型常按 schema 回嵌套结构),取不到再退回扁平键
|
||||
patch[field] = resolvePath(output, path) ?? output[path] ?? output[field];
|
||||
}
|
||||
// 写哪一行:主键取自出参,取不到再回作用域(起单入参往往就带着主键)
|
||||
const scope = await deps.data.view(taskId);
|
||||
const key: Record<string, string | number> = {};
|
||||
for (const [column, path] of Object.entries(step.output.key)) {
|
||||
const value = resolvePath(output, path) ?? output[path] ?? resolvePath(scope, path);
|
||||
// 主键值只能是标量;取不到就不填,让台账的非空约束在合并时如实报出来
|
||||
if (typeof value === 'string' || typeof value === 'number') key[column] = value;
|
||||
}
|
||||
await deps.data.draftWrite({
|
||||
taskId,
|
||||
domain: step.output.domain,
|
||||
object: step.output.object,
|
||||
key,
|
||||
patch,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按步序位置推视图 —— 声明了 `view` 才推,推的是这一步跑完后的**任务视图**。
|
||||
* 推送失败不该把步拖垮:呈现是投影,投影出问题不改变已经发生的事实。
|
||||
*/
|
||||
async function pushStepView(taskId: TaskId, step: FlowStep, activityId: string): Promise<void> {
|
||||
if (step.view === undefined) return;
|
||||
try {
|
||||
await deps.views.push({ taskId, activityId, template: step.view, scope: await deps.data.view(taskId) });
|
||||
} catch (error) {
|
||||
/*
|
||||
* 呈现失败只丢这一帧画面,不影响步序推进 —— 但**必须留痕**:
|
||||
* 静默吞掉会让「视图区一直空着」变成一桩查不出原因的怪事。
|
||||
*/
|
||||
await deps.memory.append({
|
||||
taskId,
|
||||
kind: 'engine-transition',
|
||||
title: `视图推送失败(不影响推进):${error instanceof Error ? error.message : String(error)}`,
|
||||
detail: { step: step.name, template: step.view },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** 回传协议 → 出参:取 `values`;非回传形状的人事件按原样当出参 */
|
||||
function replyValuesOf(payload: Record<string, unknown>): Record<string, unknown> {
|
||||
const values = payload['values'];
|
||||
return typeof values === 'object' && values !== null ? (values as Record<string, unknown>) : payload;
|
||||
}
|
||||
|
||||
function inputOf(step: FlowStep, scope: Record<string, unknown>): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [key, path] of Object.entries(step.input)) out[key] = resolvePath(scope, path);
|
||||
return out;
|
||||
}
|
||||
|
||||
async function runOne(
|
||||
taskId: TaskId,
|
||||
step: FlowStep,
|
||||
index: number,
|
||||
position: FlowPosition,
|
||||
): Promise<AdvanceOutcome> {
|
||||
const context = await deps.tasks.of(taskId);
|
||||
const scope = await deps.data.view(taskId);
|
||||
const payload = inputOf(step, scope);
|
||||
const attempt = (position.steps[index]?.attempt ?? 0) + 1;
|
||||
|
||||
await deps.memory.append({
|
||||
taskId,
|
||||
kind: 'action',
|
||||
title: `步 ${index + 1} · ${step.label}(${step.kind})`,
|
||||
// 步类型显式入留痕:度量的判据由引擎给出,不靠解析标题后缀
|
||||
detail: { step: step.name, stepKind: step.kind, attempt, input: payload },
|
||||
});
|
||||
|
||||
switch (step.kind) {
|
||||
case 'tool':
|
||||
case 'pure-tool': {
|
||||
// 写类工具在 flow 里同样登记为动作意向 —— 触达世界的动作集中在放行时落地
|
||||
if (step.kind === 'tool' && (await deps.tools.isWriteEffect(step.tool))) {
|
||||
await deps.tools.registerIntent({ taskId, tool: step.tool, input: payload, label: step.label });
|
||||
const next = markStep(position, index, { state: 'done', attempt });
|
||||
await deps.state.save(taskId, (await loaded(taskId)).model, next);
|
||||
return { position: next, status: 'running' };
|
||||
}
|
||||
const result = await deps.tools.invoke({
|
||||
tool: step.tool,
|
||||
input: payload,
|
||||
activityId: context.activityId,
|
||||
taskId,
|
||||
stepNo: index,
|
||||
});
|
||||
if (!result.ok) return handleFailure(taskId, step, index, position, attempt, result.error?.message ?? '工具失败');
|
||||
if (result.output !== undefined) await writeOutput(taskId, step, result.output);
|
||||
await pushStepView(taskId, step, context.activityId);
|
||||
const next = markStep(position, index, { state: 'done', attempt, ...(result.output === undefined ? {} : { output: result.output }) });
|
||||
await deps.state.save(taskId, (await loaded(taskId)).model, next);
|
||||
return { position: next, status: 'running' };
|
||||
}
|
||||
|
||||
case 'llm': {
|
||||
// LLM 只以「被调用的工具」出现,不是调度者;模板与出参 schema 随声明版本冻结
|
||||
const prompt = step.template.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, path: string) => String(payload[path] ?? ''));
|
||||
const result = await deps.llm.generate({
|
||||
model: step.model,
|
||||
prompt,
|
||||
outputSchema: step.outputSchema,
|
||||
taskId,
|
||||
stepNo: index,
|
||||
});
|
||||
if (!result.ok) return handleFailure(taskId, step, index, position, attempt, result.error ?? 'LLM 步失败');
|
||||
|
||||
/*
|
||||
* 「出参必过 schema 校验」(AM 12.3)。
|
||||
* 解析不出来或不合 schema = **这一步失败了**,走声明的失败走向;
|
||||
* 从前是静默当成 `{}` 写下去 —— 一条空记录、一行不报错,
|
||||
* 真正的毛病要到下游缺字段时才炸,而且炸在别处。
|
||||
*/
|
||||
const parsed = result.object;
|
||||
const check = deps.schemas.validate(step.outputSchema, parsed);
|
||||
if (parsed === undefined || !check.ok) {
|
||||
const detail = parsed === undefined ? '出参不是 JSON' : check.errors.join('; ');
|
||||
await deps.memory.append({
|
||||
taskId,
|
||||
kind: 'result',
|
||||
title: `步 ${index + 1} 出参不合 schema:${detail}`,
|
||||
detail: { step: step.name, text: (result.text ?? '').slice(0, 500) },
|
||||
});
|
||||
return handleFailure(taskId, step, index, position, attempt, `出参不合 schema:${detail}`);
|
||||
}
|
||||
|
||||
const output = parsed as Record<string, unknown>;
|
||||
await writeOutput(taskId, step, output);
|
||||
await pushStepView(taskId, step, context.activityId);
|
||||
const next = markStep(position, index, { state: 'done', attempt, output });
|
||||
await deps.state.save(taskId, (await loaded(taskId)).model, next);
|
||||
return { position: next, status: 'running' };
|
||||
}
|
||||
|
||||
case 'human': {
|
||||
// 异步步:完成条件 = 人事件;时限必配。
|
||||
// 发卡本身可能被 Harness 拦下(调人预算触顶等)—— 那是**这一步失败了**,
|
||||
// 走它声明的失败走向;不接住就会每一拍重发一次、永远发不出去也永远不报错。
|
||||
let card: { id: string };
|
||||
try {
|
||||
card = await deps.cards.issue({
|
||||
taskId,
|
||||
ownerId: context.ownerId,
|
||||
humanCallCap: context.humanCallCap,
|
||||
workOrder: step.workOrder,
|
||||
card: step.card,
|
||||
});
|
||||
} catch (error) {
|
||||
return handleFailure(
|
||||
taskId,
|
||||
step,
|
||||
index,
|
||||
position,
|
||||
attempt,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
await deps.listeners.register({
|
||||
taskId,
|
||||
eventType: 'human',
|
||||
keyFilter: { cardId: card.id },
|
||||
deadline: step.deadline,
|
||||
});
|
||||
// 发卡的同时把全景推上去:人要在数据上作判断,数据就得摆在卡旁边
|
||||
await pushStepView(taskId, step, context.activityId);
|
||||
const next = markStep(position, index, { state: 'awaiting', attempt });
|
||||
await deps.state.save(taskId, (await loaded(taskId)).model, next);
|
||||
return {
|
||||
position: next,
|
||||
status: 'awaiting',
|
||||
waitingFor: { kind: 'human', ref: card.id, deadline: step.deadline },
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 失败路径**声明给定**,不临场发明 */
|
||||
async function handleFailure(
|
||||
taskId: TaskId,
|
||||
step: FlowStep,
|
||||
index: number,
|
||||
position: FlowPosition,
|
||||
attempt: number,
|
||||
error: string,
|
||||
): Promise<AdvanceOutcome> {
|
||||
const action = failureAction(step, attempt);
|
||||
await deps.memory.append({
|
||||
taskId,
|
||||
kind: 'result',
|
||||
title: `步 ${index + 1} 失败:${error} → ${action.kind}`,
|
||||
detail: { step: step.name, attempt, action },
|
||||
});
|
||||
|
||||
if (action.kind === 'retry') {
|
||||
const next = markStep(position, index, { state: 'pending', attempt, error });
|
||||
await deps.state.save(taskId, (await loaded(taskId)).model, next);
|
||||
return { position: next, status: 'running' };
|
||||
}
|
||||
|
||||
if (action.kind === 'human') {
|
||||
const context = await deps.tasks.of(taskId);
|
||||
const card = await deps.cards.issue({
|
||||
taskId,
|
||||
ownerId: context.ownerId,
|
||||
humanCallCap: context.humanCallCap,
|
||||
workOrder: action.workOrder,
|
||||
card: {
|
||||
title: `步「${step.label}」重试仍败,转人兜底`,
|
||||
reason: error,
|
||||
// 兜底的人要交的东西,和这一步**本来该产出的东西**同形:
|
||||
// 出参契约是步的契约,不因换谁来做而变(统一执行契约)。
|
||||
fields: fallbackFields(step, await deps.data.view(taskId)),
|
||||
},
|
||||
});
|
||||
await deps.listeners.register({
|
||||
taskId,
|
||||
eventType: 'human',
|
||||
keyFilter: { cardId: card.id },
|
||||
deadline: 'P3D',
|
||||
});
|
||||
const next = markStep(position, index, { state: 'awaiting', attempt, error });
|
||||
await deps.state.save(taskId, (await loaded(taskId)).model, next);
|
||||
return { position: next, status: 'awaiting', waitingFor: { kind: 'human', ref: card.id, deadline: 'P3D' } };
|
||||
}
|
||||
|
||||
const next = markStep(position, index, { state: 'failed', attempt, error });
|
||||
await deps.state.save(taskId, (await loaded(taskId)).model, next);
|
||||
return { position: next, status: 'blocked', blockedReason: error };
|
||||
}
|
||||
|
||||
return {
|
||||
async load(taskId, model) {
|
||||
const issues = checkDeclaration(model.steps);
|
||||
if (issues.length > 0) throw new FlowDeclarationInvalidError(issues);
|
||||
const position = initialPosition(model.steps);
|
||||
await deps.state.save(taskId, model, position);
|
||||
await deps.memory.append({
|
||||
taskId,
|
||||
kind: 'engine-transition',
|
||||
title: `装载步序声明:${model.steps.length} 步`,
|
||||
});
|
||||
return position;
|
||||
},
|
||||
|
||||
async position(taskId) {
|
||||
return (await deps.state.load(taskId))?.position;
|
||||
},
|
||||
|
||||
async advance(taskId) {
|
||||
const { model, position } = await loaded(taskId);
|
||||
const scope = await deps.data.view(taskId);
|
||||
const action = nextAction(model.steps, position, scope, deps.evaluate);
|
||||
|
||||
switch (action.kind) {
|
||||
case 'finished': {
|
||||
// 末步是验收工单时,终态由其**裁决**给出 —— 完成只出自放行通过。
|
||||
// 裁决记在末步的 runtime 上(resume 时落笔),谱走完在这里读出来。
|
||||
const released = lastStepIsAcceptance(model.steps) && lastVerdictPassed(position);
|
||||
// 出口选择随放行一并确认,落地收敛时照它发射
|
||||
return { position, status: 'finished', released, selectedPorts: lastSelectedPorts(position) };
|
||||
}
|
||||
case 'skip': {
|
||||
await deps.memory.append({
|
||||
taskId,
|
||||
kind: 'engine-transition',
|
||||
title: `跳步:${action.step.label} —— ${action.reason}`,
|
||||
});
|
||||
const next = markStep(position, action.index, { state: 'skipped' });
|
||||
await deps.state.save(taskId, model, next);
|
||||
return { position: next, status: 'running' };
|
||||
}
|
||||
case 'await':
|
||||
return {
|
||||
position,
|
||||
status: 'awaiting',
|
||||
waitingFor: { kind: 'event', ref: action.step.name, deadline: 'P3D' },
|
||||
};
|
||||
case 'run':
|
||||
return runOne(taskId, action.step, action.index, position);
|
||||
}
|
||||
},
|
||||
|
||||
/** 事件即步的完成条件 —— 到达即续跑,挂起期间事件不丢 */
|
||||
async resume(taskId, event) {
|
||||
const { model, position } = await loaded(taskId);
|
||||
const index = position.steps.findIndex((s) => s.state === 'awaiting');
|
||||
if (index < 0) return { position, status: 'running' };
|
||||
|
||||
const step = model.steps[index];
|
||||
await deps.memory.append({
|
||||
taskId,
|
||||
kind: 'engine-transition',
|
||||
title: `事件到达,步 ${index + 1} 完成条件满足(${event.kind})`,
|
||||
detail: { ref: event.ref },
|
||||
});
|
||||
// 放行裁决落笔在这一步的运行时上:谱走完时据此定终局
|
||||
const verdict = event.kind === 'human' ? String(event.payload['verdict'] ?? '') : '';
|
||||
const chosen = event.payload['selectedPorts'];
|
||||
const selectedPorts =
|
||||
typeof chosen === 'object' && chosen !== null ? (chosen as Record<string, string>) : undefined;
|
||||
if (step !== undefined && event.kind === 'human') {
|
||||
// 人事件的载荷是**回传协议**的形状(`{mode, workOrderId, values}`),
|
||||
// 出参在 `values` 里;直接把整个载荷当出参写,落进去的会是协议壳而不是答案。
|
||||
await writeOutput(taskId, step, replyValuesOf(event.payload));
|
||||
}
|
||||
const next = markStep(
|
||||
position,
|
||||
index,
|
||||
verdict === '' ? { state: 'done' } : { state: 'done', verdict, ...(selectedPorts === undefined ? {} : { selectedPorts }) },
|
||||
);
|
||||
await deps.state.save(taskId, model, next);
|
||||
return { position: next, status: 'running' };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"name": "@modules/flow-engine",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": { ".": "./index.ts" }
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
/**
|
||||
* module: flow-engine —— 本模块要外界提供的能力(编码规范 §10.1 / §5.3)。
|
||||
*/
|
||||
import type { FlowModel, StaffId, TaskId } from '@contracts';
|
||||
import type { FlowPosition } from './internal/domain/step-sequence.ts';
|
||||
|
||||
export type Clock = { now(): Date };
|
||||
export type IdGenerator = { next(): string };
|
||||
|
||||
/** 运行时实例状态 —— 三份持久状态之一(OS 09) */
|
||||
export type FlowStateStore = {
|
||||
save(taskId: TaskId, model: FlowModel, position: FlowPosition): Promise<void>;
|
||||
load(taskId: TaskId): Promise<{ model: FlowModel; position: FlowPosition } | undefined>;
|
||||
};
|
||||
|
||||
/** 条件谓词求值 —— app 注入 `@sfeel`;零 LLM */
|
||||
export type PredicateEvaluator = (expression: string, scope: Readonly<Record<string, unknown>>) => boolean;
|
||||
|
||||
/** 任务数据 —— app 注入 `ledger`(L1):读任务视图 = 正式版 + 本任务草稿层 */
|
||||
export type TaskDataGateway = {
|
||||
view(taskId: TaskId): Promise<Record<string, unknown>>;
|
||||
draftWrite(input: {
|
||||
taskId: TaskId;
|
||||
domain: string;
|
||||
object: string;
|
||||
key: Record<string, string | number>;
|
||||
patch: Record<string, unknown>;
|
||||
}): Promise<void>;
|
||||
};
|
||||
|
||||
/** 工具步与纯工具步 —— app 注入 `toolbox`(L2) */
|
||||
export type ToolStepInvoker = {
|
||||
invoke(input: {
|
||||
tool: string;
|
||||
input: Record<string, unknown>;
|
||||
activityId: string;
|
||||
taskId: TaskId;
|
||||
stepNo: number;
|
||||
}): Promise<{ ok: boolean; output?: Record<string, unknown>; error?: { message: string; retryable: boolean } }>;
|
||||
/** 写类工具在 flow 里也走「登记动作意向」,除非契约显式预授权 */
|
||||
registerIntent(input: {
|
||||
taskId: TaskId;
|
||||
tool: string;
|
||||
input: Record<string, unknown>;
|
||||
label: string;
|
||||
}): Promise<void>;
|
||||
isWriteEffect(tool: string): Promise<boolean>;
|
||||
};
|
||||
|
||||
/** LLM 步 —— app 注入 `llm`(L1)的 ModelGateway;模板与出参 schema 随声明版本冻结 */
|
||||
export type LlmStepGateway = {
|
||||
generate(input: {
|
||||
model: string;
|
||||
prompt: string;
|
||||
outputSchema: Record<string, unknown>;
|
||||
taskId: TaskId;
|
||||
stepNo: number;
|
||||
/** 出参原文 —— 解析失败时要能说清「模型到底回了什么」 */
|
||||
}): Promise<{ ok: boolean; object?: unknown; text?: string; error?: string }>;
|
||||
};
|
||||
|
||||
/** 出参校验 —— app 注入 ajv:LLM 步的出参**必过声明的 schema**(AM 12.3) */
|
||||
export type SchemaValidator = {
|
||||
validate(schema: Record<string, unknown>, value: unknown): { ok: boolean; errors: string[] };
|
||||
};
|
||||
|
||||
/**
|
||||
* 视图流控 —— app 注入 `interaction`(L3)。
|
||||
* flow 按步序位置推声明的模版;推的是**填好数的 HTML**,容器只渲染不执行。
|
||||
*/
|
||||
export type ViewGateway = {
|
||||
/** 按模版名取模版、以任务视图填数、推给前端;模版不存在就什么都不做 */
|
||||
push(input: { taskId: TaskId; activityId: string; template: string; scope: Record<string, unknown> }): Promise<void>;
|
||||
};
|
||||
|
||||
/** 人类工具步 —— app 注入 `human-tool`(L3) */
|
||||
export type CardGateway = {
|
||||
issue(input: {
|
||||
taskId: TaskId;
|
||||
ownerId: StaffId;
|
||||
humanCallCap: number;
|
||||
workOrder: 'execution' | 'acceptance';
|
||||
card: Record<string, unknown>;
|
||||
}): Promise<{ id: string }>;
|
||||
};
|
||||
|
||||
/** 监听登记 —— app 注入 `event`(L1):异步步的完成条件 = 监听,时限必配 */
|
||||
export type ListenerRegistrar = {
|
||||
register(input: {
|
||||
taskId: TaskId;
|
||||
eventType: 'data' | 'time' | 'human';
|
||||
keyFilter: Record<string, string>;
|
||||
deadline: string;
|
||||
}): Promise<{ id: string }>;
|
||||
};
|
||||
|
||||
export type MemoryRecorder = {
|
||||
append(input: {
|
||||
taskId: TaskId;
|
||||
kind: 'action' | 'result' | 'engine-transition';
|
||||
title: string;
|
||||
detail?: Record<string, unknown>;
|
||||
}): Promise<void>;
|
||||
};
|
||||
|
||||
/** 任务上下文 —— 活动 ID、负责人、预算 */
|
||||
export type TaskContext = {
|
||||
of(taskId: TaskId): Promise<{ activityId: string; ownerId: StaffId; humanCallCap: number }>;
|
||||
};
|
||||
@@ -30,6 +30,10 @@
|
||||
与**活动装载**(unknown-activity);字段类的三条检查(边未映射 / 必填未映射 / 类型相抵)全退役。
|
||||
- **版本可删,两道闸**:生效版不可删(先停用,`ActiveVersionError`)、在途钉版不可删
|
||||
(那些单要按它跑完,`PinnedVersionError`)。
|
||||
- **审批模板**(`approvalTemplate`,2026-07-29 用户定「审批活动要能管」):把审批点
|
||||
**可复用的那一半**提出来 —— 审批人看哪几项、按什么名字看、怎么催、说什么话;
|
||||
不可复用的那半(驳回回哪个节点)仍在节点上。**谁来审不在模板里** ——
|
||||
与活动点同一口径,运营时按组轮值。删模板前反查引用,还被引着即 `TemplateInUseError`。
|
||||
- **整条流可删**(`deleteFlow`,2026-07-29):连同全部版本。生效版这道闸**不设** ——
|
||||
删整条流是明示动作,先停用再删只是多一步仪式;在途单那道闸照设。
|
||||
「还有调起规则指着它」由**路由层**反查(process 不依赖 trigger,L7 不知道它存在)。
|
||||
|
||||
@@ -61,6 +61,9 @@ function harness(seed: ProcessPackage[], pinned = 0) {
|
||||
deletePackage: async () => undefined,
|
||||
renameVersion: async () => undefined,
|
||||
renumberVersion: async () => undefined,
|
||||
listApprovalTemplates: async () => [],
|
||||
upsertApprovalTemplate: async () => undefined,
|
||||
deleteApprovalTemplate: async () => undefined,
|
||||
nodeOwners: async () => ({}),
|
||||
setNodeOwner: async () => undefined,
|
||||
},
|
||||
|
||||
@@ -71,6 +71,9 @@ function harness(validationErrors: readonly string[]): Harness {
|
||||
deletePackage: async () => undefined,
|
||||
renameVersion: async () => undefined,
|
||||
renumberVersion: async () => undefined,
|
||||
listApprovalTemplates: async () => [],
|
||||
upsertApprovalTemplate: async () => undefined,
|
||||
deleteApprovalTemplate: async () => undefined,
|
||||
nodeOwners: async () => ({}),
|
||||
setNodeOwner: async () => undefined,
|
||||
},
|
||||
|
||||
@@ -68,6 +68,9 @@ function harness(rows: ProcessPackage[], pinned = 0): Harness {
|
||||
updateInstance: async () => undefined,
|
||||
listInstances: async () => [],
|
||||
findInstanceByTask: async () => undefined,
|
||||
listApprovalTemplates: async () => [],
|
||||
upsertApprovalTemplate: async () => undefined,
|
||||
deleteApprovalTemplate: async () => undefined,
|
||||
nodeOwners: async () => ({}),
|
||||
setNodeOwner: async () => undefined,
|
||||
},
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* 用例与 Mastra 工作流编译随后(编码规范 §6.1)。
|
||||
*/
|
||||
import type {
|
||||
ApprovalTemplate,
|
||||
ClosureReport,
|
||||
ClosureViolation,
|
||||
OwnerSpec,
|
||||
@@ -93,6 +94,13 @@ export type ProcessService = {
|
||||
*/
|
||||
editVersion(id: string, version: number, patch: { version?: number; name?: string }): Promise<ProcessPackage[]>;
|
||||
|
||||
/* ── 审批模板(审批活动)—— 看什么 / 怎么催 / 说什么 ── */
|
||||
/** 列模板,连同「被哪些包的哪些审批点引着」 */
|
||||
approvalTemplates(): Promise<Array<ApprovalTemplate & { usedBy: Array<{ packageId: string; nodeId: string }> }>>;
|
||||
saveApprovalTemplate(template: ApprovalTemplate): Promise<ApprovalTemplate>;
|
||||
/** 还被审批点引着就不许删(`TemplateInUseError`)—— 删了那些节点会静默退回旧行为 */
|
||||
deleteApprovalTemplate(id: string): Promise<void>;
|
||||
|
||||
/* ── 节点负责人(运营配置):显式指派 > 这里 > 轮值 ── */
|
||||
nodeOwners(packageId: string): Promise<Record<string, string>>;
|
||||
setNodeOwner(packageId: string, nodeId: string, staffId: string | undefined): Promise<void>;
|
||||
@@ -183,6 +191,17 @@ export class VersionTakenError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** 模板还被审批点引着 —— 删了那些节点会静默退回「载荷全摊开」,不许悄悄改变行为 */
|
||||
export class TemplateInUseError extends Error {
|
||||
constructor(
|
||||
readonly templateId: string,
|
||||
readonly usedBy: ReadonlyArray<{ packageId: string; nodeId: string }>,
|
||||
) {
|
||||
super(`审批模板 ${templateId} 还被 ${usedBy.length} 个审批点引着 —— 先把那些节点改掉再删`);
|
||||
this.name = 'TemplateInUseError';
|
||||
}
|
||||
}
|
||||
|
||||
export class PositionVacantError extends Error {
|
||||
constructor(readonly position: string) {
|
||||
super(`岗位空缺,无法解析负责人:${position} —— 按节点失败走向处置,或转治理台待指派`);
|
||||
|
||||
@@ -19,7 +19,7 @@ export type {
|
||||
WorkflowState,
|
||||
} from './contract.ts';
|
||||
export { ActiveVersionError, CallInterfaceViolationError, NotClosedError, VersionTakenError,
|
||||
PinnedVersionError, PositionVacantError, StaleVersionError } from './contract.ts';
|
||||
PinnedVersionError, PositionVacantError, StaleVersionError, TemplateInUseError } from './contract.ts';
|
||||
|
||||
export type {
|
||||
FlowRuntime,
|
||||
|
||||
@@ -19,6 +19,21 @@ export const processPackageTable = sys.table(
|
||||
(t) => [primaryKey({ columns: [t.id, t.version] }), index('process_package_state_idx').on(t.state)],
|
||||
);
|
||||
|
||||
/**
|
||||
* 审批模板(2026-07-29)—— 审批活动的可复用那一半:看什么 / 怎么催 / 说什么。
|
||||
* 不长版本:模板是运营配置,改了即刻对**新起的审批单**生效,在途单不受影响
|
||||
* (在途单的依据在发出那一刻已经定形,存在审批单自己身上)。
|
||||
*/
|
||||
export const approvalTemplateTable = sys.table('approval_template', {
|
||||
id: text('id').primaryKey(),
|
||||
name: text('name').notNull(),
|
||||
/** [{ field, label }] —— 空数组即旧行为:载荷全摊开 */
|
||||
basis: jsonb('basis').notNull().default([]),
|
||||
nudge: jsonb('nudge'),
|
||||
message: text('message'),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const workflowTable = sys.table(
|
||||
'workflow',
|
||||
{
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
*/
|
||||
import { and, asc, desc, eq, isNull } from 'drizzle-orm';
|
||||
import type { ProcessPackage, TerminalState, WorkflowState } from '@contracts';
|
||||
import { processPackageSchema } from '@contracts';
|
||||
import { approvalTemplateSchema, processPackageSchema } from '@contracts';
|
||||
import type { Db } from '@shared/db.ts';
|
||||
import type { ProcessStore, WorkflowRecord } from '../../port.ts';
|
||||
import type { NodeInstance } from '../domain/owner-resolution.ts';
|
||||
import { nodeInstanceTable, processPackageTable, workflowTable, nodeOwnerTable } from './process-schema.ts';
|
||||
import { approvalTemplateTable, nodeInstanceTable, processPackageTable, workflowTable, nodeOwnerTable } from './process-schema.ts';
|
||||
|
||||
type WorkflowRow = typeof workflowTable.$inferSelect;
|
||||
|
||||
@@ -98,6 +98,36 @@ export function createProcessStore(db: Db): ProcessStore {
|
||||
.where(and(eq(workflowTable.packageId, id), eq(workflowTable.packageVersion, from)));
|
||||
},
|
||||
|
||||
async listApprovalTemplates() {
|
||||
const rows = await db.select().from(approvalTemplateTable).orderBy(asc(approvalTemplateTable.name));
|
||||
return rows.map((r) => approvalTemplateSchema.parse({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
basis: r.basis,
|
||||
...(r.nudge === null ? {} : { nudge: r.nudge }),
|
||||
...(r.message === null ? {} : { message: r.message }),
|
||||
}));
|
||||
},
|
||||
|
||||
async upsertApprovalTemplate(template) {
|
||||
const values = {
|
||||
id: template.id,
|
||||
name: template.name,
|
||||
basis: template.basis,
|
||||
nudge: template.nudge ?? null,
|
||||
message: template.message ?? null,
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
await db.insert(approvalTemplateTable).values(values).onConflictDoUpdate({
|
||||
target: approvalTemplateTable.id,
|
||||
set: { name: values.name, basis: values.basis, nudge: values.nudge, message: values.message, updatedAt: values.updatedAt },
|
||||
});
|
||||
},
|
||||
|
||||
async deleteApprovalTemplate(id) {
|
||||
await db.delete(approvalTemplateTable).where(eq(approvalTemplateTable.id, id));
|
||||
},
|
||||
|
||||
async getPackage(id, version) {
|
||||
const conditions = [eq(processPackageTable.id, id)];
|
||||
if (version !== undefined) conditions.push(eq(processPackageTable.version, version));
|
||||
|
||||
@@ -56,6 +56,22 @@ export function createSelfHostedRuntime(deps: SelfHostedRuntimeDeps): FlowRuntim
|
||||
}
|
||||
|
||||
/** 起一个节点:活动 → 起单;审批点 → 卡工位;终点 → 收束 */
|
||||
/**
|
||||
* 审批单上给人看什么 —— 引了模板就按模板筛与改名,没引就把载荷全摊开(旧行为)。
|
||||
* 模板里点名的字段载荷里没有,如实写「—」:漏一项比编一项好。
|
||||
*/
|
||||
async function basisOf(
|
||||
node: Extract<ProcessNode, { kind: 'approval' }> | undefined,
|
||||
payload: Record<string, unknown>,
|
||||
): Promise<Array<{ k: string; v: string }>> {
|
||||
if (node?.templateId === undefined) return Object.entries(payload).map(([k, v]) => ({ k, v: String(v) }));
|
||||
const template = (await deps.store.listApprovalTemplates()).find((t) => t.id === node.templateId);
|
||||
if (template === undefined || template.basis.length === 0) {
|
||||
return Object.entries(payload).map(([k, v]) => ({ k, v: String(v) }));
|
||||
}
|
||||
return template.basis.map((b) => ({ k: b.label, v: payload[b.field] === undefined ? '—' : String(payload[b.field]) }));
|
||||
}
|
||||
|
||||
async function enter(
|
||||
record: WorkflowRecord,
|
||||
pkg: ProcessPackage,
|
||||
@@ -163,7 +179,12 @@ export function createSelfHostedRuntime(deps: SelfHostedRuntimeDeps): FlowRuntim
|
||||
nodeId: node.id,
|
||||
approverId: resolution.staffId as StaffId,
|
||||
subject: dispatch.node.label,
|
||||
basis: Object.entries(payload).map(([k, v]) => ({ k, v: String(v) })),
|
||||
/*
|
||||
* 审批依据:引了模板就按模板筛与改名(审批人只看该看的、按人话看);
|
||||
* 没引模板即旧行为 —— 把载荷全摊开。模板改了只影响**新发出的**审批单,
|
||||
* 在途单的依据在发出那一刻已经定形,存在审批单自己身上。
|
||||
*/
|
||||
basis: await basisOf(node.kind === 'approval' ? node : undefined, payload),
|
||||
});
|
||||
await deps.store.insertInstance(record.id, {
|
||||
nodeId: node.id,
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
NotClosedError,
|
||||
PinnedVersionError,
|
||||
StaleVersionError,
|
||||
TemplateInUseError,
|
||||
VersionTakenError,
|
||||
} from '../../contract.ts';
|
||||
import type {
|
||||
@@ -193,6 +194,35 @@ export function createProcessService(deps: ProcessServiceDeps): ProcessService {
|
||||
return deps.store.listPackages();
|
||||
},
|
||||
|
||||
async approvalTemplates() {
|
||||
const [templates, packages] = await Promise.all([
|
||||
deps.store.listApprovalTemplates(),
|
||||
deps.store.listPackages(),
|
||||
]);
|
||||
// 引用反查:哪个包的哪个审批点引着它 —— 删之前要能看见,不能删完才发现
|
||||
return templates.map((t) => ({
|
||||
...t,
|
||||
usedBy: packages.flatMap((pkg) =>
|
||||
pkg.nodes
|
||||
.filter((n) => n.kind === 'approval' && n.templateId === t.id)
|
||||
.map((n) => ({ packageId: pkg.id, nodeId: n.id })),
|
||||
),
|
||||
}));
|
||||
},
|
||||
|
||||
async saveApprovalTemplate(template) {
|
||||
await deps.store.upsertApprovalTemplate(template);
|
||||
return template;
|
||||
},
|
||||
|
||||
async deleteApprovalTemplate(id) {
|
||||
const all = await this.approvalTemplates();
|
||||
const hit = all.find((t) => t.id === id);
|
||||
if (hit === undefined) throw new Error(`审批模板不存在:${id}`);
|
||||
if (hit.usedBy.length > 0) throw new TemplateInUseError(id, hit.usedBy);
|
||||
await deps.store.deleteApprovalTemplate(id);
|
||||
},
|
||||
|
||||
async editVersion(id, version, patch) {
|
||||
const one = await deps.store.getPackage(id, version);
|
||||
if (one === undefined) throw new StaleVersionError(id, version);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* module: process —— 本模块要外界提供的能力(编码规范 §10.1 / §5.3)。
|
||||
*/
|
||||
import type { ProcessNode, ProcessPackage, StaffId, TerminalState, WorkflowState } from '@contracts';
|
||||
import type { ApprovalTemplate, ProcessNode, ProcessPackage, StaffId, TerminalState, WorkflowState } from '@contracts';
|
||||
import type { NodeInstance } from './internal/domain/owner-resolution.ts';
|
||||
import type { ActivityContractFace } from './internal/domain/closure.ts';
|
||||
|
||||
@@ -86,6 +86,11 @@ export type ProcessStore = {
|
||||
*/
|
||||
renumberVersion(id: string, from: number, to: number): Promise<void>;
|
||||
getPackage(id: string, version?: number): Promise<ProcessPackage | undefined>;
|
||||
|
||||
/* ── 审批模板(审批活动的可复用那一半) ─────────────────────── */
|
||||
listApprovalTemplates(): Promise<ApprovalTemplate[]>;
|
||||
upsertApprovalTemplate(template: ApprovalTemplate): Promise<void>;
|
||||
deleteApprovalTemplate(id: string): Promise<void>;
|
||||
listPackages(): Promise<ProcessPackage[]>;
|
||||
|
||||
insertWorkflow(record: WorkflowRecord): Promise<void>;
|
||||
|
||||
@@ -53,7 +53,6 @@ function harness(): Harness {
|
||||
},
|
||||
activities: {
|
||||
load: async () => ({
|
||||
paradigm: 'flow' as const,
|
||||
caps: { steps: 40, tokens: 200000, humanCalls: 2, activeMinutes: 60 },
|
||||
envelope: {},
|
||||
inputSchema: INPUT_SCHEMA,
|
||||
@@ -62,10 +61,7 @@ function harness(): Harness {
|
||||
}),
|
||||
},
|
||||
schemas: { validate: () => ({ ok: true, errors: [] }) },
|
||||
engines: {
|
||||
flow: { load: async () => undefined, advance: async () => ({ status: 'running' }), onEvent: async () => ({ status: 'running' }) },
|
||||
loop: { load: async () => undefined, advance: async () => ({ status: 'running' }), onEvent: async () => ({ status: 'running' }) },
|
||||
},
|
||||
engine: { load: async () => undefined, advance: async () => ({ status: 'running' }), onEvent: async () => ({ status: 'running' }) },
|
||||
memory: { append: async () => undefined, hasHistory: async () => true, seal: async () => undefined, distill: async () => undefined },
|
||||
landing: {
|
||||
land: async () => ({ converged: true, emittedPorts: [] as string[], ledgerRowsMerged: 0, facts: {} as LandedFacts }),
|
||||
|
||||
@@ -33,7 +33,6 @@ function harness(land: () => Promise<never> | Promise<{ converged: boolean; emit
|
||||
h.task = {
|
||||
id: TASK,
|
||||
activityId: 'a-1',
|
||||
paradigm: 'flow',
|
||||
ownerId: 's-1' as Task['ownerId'],
|
||||
title: '占位活动',
|
||||
runtime: 'running',
|
||||
@@ -59,7 +58,6 @@ function harness(land: () => Promise<never> | Promise<{ converged: boolean; emit
|
||||
},
|
||||
activities: {
|
||||
load: async () => ({
|
||||
paradigm: 'flow' as const,
|
||||
caps: h.task.caps,
|
||||
envelope: {},
|
||||
inputSchema: {},
|
||||
@@ -68,10 +66,11 @@ function harness(land: () => Promise<never> | Promise<{ converged: boolean; emit
|
||||
}),
|
||||
},
|
||||
schemas: { validate: () => ({ ok: true, errors: [] }) },
|
||||
engines: {
|
||||
// 谱走完 + 放行通过 —— 接下来就该落地
|
||||
flow: { load: async () => undefined, advance: async () => ({ status: 'finished', released: true, selectedPorts: {} }), onEvent: async () => ({ status: 'running' }) },
|
||||
loop: { load: async () => undefined, advance: async () => ({ status: 'running' }), onEvent: async () => ({ status: 'running' }) },
|
||||
// 案子办完 + 放行通过 —— 接下来就该落地
|
||||
engine: {
|
||||
load: async () => undefined,
|
||||
advance: async () => ({ status: 'finished', released: true, selectedPorts: {} }),
|
||||
onEvent: async () => ({ status: 'running' }),
|
||||
},
|
||||
memory: {
|
||||
append: async (input) => {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* 任务运行时:生命周期与**终态五名裁定**、Harness 预算执行器 / 停滞熔断、
|
||||
* 控制三语义、改派、断点续跑。范式(loop / flow)在此汇流 —— 对流程层与交互层不可区分。
|
||||
*/
|
||||
import type { BudgetCaps, ControlSemantic, Paradigm, StaffId, TaskId, TaskRuntimeState, TerminalState } from '@contracts';
|
||||
import type { BudgetCaps, ControlSemantic, StaffId, TaskId, TaskRuntimeState, TerminalState } from '@contracts';
|
||||
import type { BudgetBreach, Consumption, HarnessVerdict } from './internal/domain/harness.ts';
|
||||
import type { ControlOutcome, ResumeReadiness, TaskSnapshot, TerminalCause } from './internal/domain/lifecycle.ts';
|
||||
|
||||
@@ -15,7 +15,6 @@ export type {
|
||||
ControlOutcome,
|
||||
ControlSemantic,
|
||||
HarnessVerdict,
|
||||
Paradigm,
|
||||
ResumeReadiness,
|
||||
TaskRuntimeState,
|
||||
TaskSnapshot,
|
||||
@@ -50,7 +49,6 @@ export type LandedFacts = {
|
||||
export type Task = {
|
||||
readonly id: TaskId;
|
||||
readonly activityId: string;
|
||||
readonly paradigm: Paradigm;
|
||||
/** 起单来源:工作流节点;登记触发的直起单为 undefined */
|
||||
readonly workflowId?: string;
|
||||
readonly nodeId?: string;
|
||||
|
||||
@@ -9,7 +9,6 @@ export type {
|
||||
ControlOutcome,
|
||||
ControlSemantic,
|
||||
HarnessVerdict,
|
||||
Paradigm,
|
||||
ResumeReadiness,
|
||||
StartTaskInput,
|
||||
Task,
|
||||
|
||||
@@ -9,7 +9,6 @@ export const taskTable = sys.table(
|
||||
{
|
||||
id: text('id').primaryKey(),
|
||||
activityId: text('activity_id').notNull(),
|
||||
paradigm: text('paradigm').notNull(),
|
||||
workflowId: text('workflow_id'),
|
||||
nodeId: text('node_id'),
|
||||
/** 恰有一名负责人 */
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* task 存储 adapter —— Drizzle 只准出现在 adapter(编码规范 §5.3)。
|
||||
*/
|
||||
import { and, asc, eq, isNull, sql } from 'drizzle-orm';
|
||||
import type { BudgetCaps, Paradigm, StaffId, TaskId, TaskRuntimeState, TerminalState } from '@contracts';
|
||||
import type { BudgetCaps, StaffId, TaskId, TaskRuntimeState, TerminalState } from '@contracts';
|
||||
import type { Db } from '@shared/db.ts';
|
||||
import type { TaskStore } from '../../port.ts';
|
||||
import type { Task } from '../../contract.ts';
|
||||
@@ -15,7 +15,6 @@ function toTask(row: Row): Task {
|
||||
return {
|
||||
id: row.id as TaskId,
|
||||
activityId: row.activityId,
|
||||
paradigm: row.paradigm as Paradigm,
|
||||
...(row.workflowId === null ? {} : { workflowId: row.workflowId }),
|
||||
...(row.nodeId === null ? {} : { nodeId: row.nodeId }),
|
||||
ownerId: row.ownerId as StaffId,
|
||||
@@ -43,7 +42,6 @@ export function createTaskStore(db: Db): TaskStore {
|
||||
await db.insert(taskTable).values({
|
||||
id: task.id,
|
||||
activityId: task.activityId,
|
||||
paradigm: task.paradigm,
|
||||
workflowId: task.workflowId ?? null,
|
||||
nodeId: task.nodeId ?? null,
|
||||
ownerId: task.ownerId,
|
||||
|
||||
@@ -30,8 +30,8 @@ export type TaskServiceDeps = {
|
||||
readonly store: TaskStore;
|
||||
readonly activities: ActivityLoader;
|
||||
readonly schemas: SchemaValidator;
|
||||
/** 范式引擎按 paradigm 分派 —— 对上层不可区分 */
|
||||
readonly engines: Readonly<Record<'loop' | 'flow', ParadigmEngine>>;
|
||||
/** 唯一的引擎(2026-07-29:活动不再分范式,内部实现都是 Loop) */
|
||||
readonly engine: ParadigmEngine;
|
||||
readonly memory: MemoryRecorder;
|
||||
/** 落地收敛 —— 放行通过的那一刻才碰事实 */
|
||||
readonly landing: LandingGateway;
|
||||
@@ -72,10 +72,6 @@ export function createTaskService(deps: TaskServiceDeps): TaskService {
|
||||
return task;
|
||||
}
|
||||
|
||||
function engineOf(task: Task): ParadigmEngine {
|
||||
return deps.engines[task.paradigm];
|
||||
}
|
||||
|
||||
/** Harness 在环外先判:越限即熔断并挂起,处置归治理台 */
|
||||
async function harnessCheck(task: Task, stallAfter: string) {
|
||||
const lastProgress = (await deps.store.lastProgressAt(task.id)) ?? new Date(task.startedAt);
|
||||
@@ -103,7 +99,6 @@ export function createTaskService(deps: TaskServiceDeps): TaskService {
|
||||
const task: Task = {
|
||||
id: taskIdSchema.parse(deps.ids.next()),
|
||||
activityId: input.activityId,
|
||||
paradigm: loaded.paradigm,
|
||||
...(input.workflowId === undefined ? {} : { workflowId: input.workflowId }),
|
||||
...(input.nodeId === undefined ? {} : { nodeId: input.nodeId }),
|
||||
ownerId: input.ownerId,
|
||||
@@ -123,7 +118,7 @@ export function createTaskService(deps: TaskServiceDeps): TaskService {
|
||||
// message 计入初始观察、全程留痕;**不得扩大授权边界**
|
||||
detail: { data: input.data, message: input.message, envelope: loaded.envelope },
|
||||
});
|
||||
await engineOf(task).load(task.id, loaded.businessModel);
|
||||
await deps.engine.load(task.id, loaded.businessModel);
|
||||
await deps.interaction.setPhase(task.id, 'active');
|
||||
if (missing.length > 0) {
|
||||
await deps.memory.append({
|
||||
@@ -169,7 +164,7 @@ export function createTaskService(deps: TaskServiceDeps): TaskService {
|
||||
}
|
||||
|
||||
const startedAt = deps.clock.now().getTime();
|
||||
const outcome = await engineOf(task).advance(taskId);
|
||||
const outcome = await deps.engine.advance(taskId);
|
||||
// 步计量:loop 的一次决策循环 / flow 的一个声明步。
|
||||
// 活跃时长按**这一拍真正花掉的时间**计 —— 挂起等人的时间不算活跃,那是世界等待。
|
||||
const used = await deps.store.addConsumption(taskId, {
|
||||
@@ -303,7 +298,7 @@ export function createTaskService(deps: TaskServiceDeps): TaskService {
|
||||
}
|
||||
}
|
||||
|
||||
await engineOf(task).onEvent(taskId, event);
|
||||
await deps.engine.onEvent(taskId, event);
|
||||
await deps.store.markProgress(taskId, deps.clock.now());
|
||||
return this.tick(taskId);
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* module: task —— 本模块要外界提供的能力(编码规范 §10.1 / §5.3)。
|
||||
*/
|
||||
import type { BudgetCaps, Paradigm, StaffId, TaskId, TerminalState } from '@contracts';
|
||||
import type { BudgetCaps, StaffId, TaskId, TerminalState } from '@contracts';
|
||||
import type { Consumption } from './internal/domain/harness.ts';
|
||||
import type { LandedFacts, Task } from './contract.ts';
|
||||
|
||||
@@ -21,7 +21,6 @@ export type TaskStore = {
|
||||
/** 活动装载 —— app 注入 `activity-registry`(L4) */
|
||||
export type ActivityLoader = {
|
||||
load(activityId: string): Promise<{
|
||||
paradigm: Paradigm;
|
||||
caps: BudgetCaps;
|
||||
envelope: Record<string, unknown>;
|
||||
/** 输入 data 的 JSON Schema —— 缺项不得启动 */
|
||||
|
||||
Reference in New Issue
Block a user