活动伪函数占位:机器步落台账 + 一张验收单 —— 顺手揪出三个引擎 bug

按你定的形态做:占位一律机器步,每个活动只留一张验收单要人签;
**不碰活动内部的业务判断** —— 打标、定价、比价那些一概不做。

## 占位怎么占

一枚纯工具 `slot.placeholder`:只穿透上游给的值、给显眼的默认(数值一律 0,
主键给「PN-占位」这类),行上写 `status: '占位'`。它不判断任何事。
骨架 = N 个机器步各落一行台账 + 末步一张验收单。
验收单的卡面要人填的正是**该活动该产出、而占位产不出的判断**(如两枚去向旗)——
人类步的回传值同样经 writeOutput 落台账、步序在后,所以人填的覆盖占位的默认。
占位期要走哪个分支,在验收时说,不必改代码。

六个槽位一律 flow 范式(A2/A3/A6 本该是 loop,但 loop 要 Agent 真调模型;
占位是固定序列,声明成 flow 才诚实),那份没人用的 loop 骨架顺手删了。
预算改成固定 humanCalls: 2(机器步不吃人工调用)。

## 三个引擎 bug,都是「无声卡住」

**① 异或汇合在等一条永远不来的分支。** `joinReady` 按并行汇合写(全部责任分支收敛才放行),
可 G2J 是异或 —— 两条分支互斥、结构上只来一条。于是「不需要寻源」这条路上永远在等 A3。
最坑的是**连死路事件都没有**:边是选中了的,只在汇合判定里被 continue 跳过,
从外面看就是 A1 办结后什么都不再发生。已改为异或汇合不等,加了三条测试。

**② 出口载荷取的是落地前的草稿值,不是落地事实。** `releaseWrite` 直接回 `draft.patch`。
人的回传值天生是字符串 `"true"`,列是 boolean,PG 存的时候转了,可发出去的口里还是字符串
—— 下游活动入参校验当场拒收「/needSourcing must be boolean」,节点报 blocked,
而台账里明明是对的。改为合并后**读回来**:出口载荷与台账逐字一致,类型由列定义说了算。

**③ 审批箱按岗位码筛,无视工作组绑定。** 引擎派审批时「绑定先于策略」(ADR-011),
装了组的单实际派给被绑定的人;而收件与裁决两处都只比 `me.position.code` ——
于是「审批派给了我、我的审批箱里没有」,单子谁也看不见,流永远卡在审批点(实测)。
`toChain` 早为同一件事修过一次,这是漏的两处,一并按派单口径改。

## 顺带

`cards.issue` 的验收分支写死 `fields: []`,而 `acceptanceWorkOrderSchema` 本来就有 `fields`
—— 是没填,不是设计上不要。执行与验收现在共用同一份字段解析。

我自己也踩了一个:验收步的出参映射键写成驼峰 `needSourcing`,但**键是台账列名**
(小写蛇形),draftWrite 抛「非法标识符」,而且是在放行之后抛 —— 任务卡在 running、
台账一行没有、推进器一秒一次无限重试。测试里加了「所有出参键必须匹配 ^[a-z][a-z0-9_]*$」。

## 实测走到哪

起单 → A1(两机器步落台账,一张验收单)→ 人填 needAlternative=false →
G1 判「不需要选型」→ G2 判「不需要寻源」→ **G2J 通过** → A4 成本定价办结 →
A5 审批点(审批箱可见)→ 裁决通过 → **G3 判到 A6**(链位 6/7)。
A6 的三个去向要选择组(T2),到那儿为止。

typecheck ✓ lint ✓ depcruise 374 模块 ✓ api:check ✓ 498 测试 ✓

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KeDBx2PHLavbURXB8LJJ7m
This commit is contained in:
2026-07-28 13:16:17 +08:00
co-authored by Claude Opus 5
parent b2f5f69d6a
commit 58d914b8a2
9 changed files with 487 additions and 114 deletions
@@ -7,16 +7,51 @@ import { describe, expect, it } from 'vitest';
import { MVP_SLOTS, SLOT_ARTIFACT } from '../seed-mvp-slots.ts';
describe('MVP_SLOTS', () => {
it('六槽位,id 与范式如 MVP(A5 审批点内置,不入库)', () => {
/*
* 占位期六个槽位**一律 flow**。A2/A3/A6 本该是案例活动(loop),
* 但 loop 由 Agent 每拍决策、要真调模型;占位本身是固定序列,声明成 flow 才诚实。
* 真开发它们为案例活动时,以新包版本装回 loop —— 那时这条断言要跟着改。
*/
it('六槽位,占位期一律 flow(A5 审批点内置,不入库)', () => {
const byId = new Map(MVP_SLOTS.map((m) => [m.identity.activityId as string, m.identity.paradigm]));
expect(MVP_SLOTS).toHaveLength(6);
expect(byId.get('rfq-intake')).toBe('flow');
expect(byId.get('alt-selection')).toBe('loop');
expect(byId.get('sourcing-inquiry')).toBe('loop');
expect(byId.get('cost-pricing')).toBe('flow');
for (const id of ['rfq-intake', 'alt-selection', 'sourcing-inquiry', 'cost-pricing', 'quote-negotiation', 'intel-archive']) {
expect(byId.get(id), id).toBe('flow');
}
expect(byId.has('pricing-approval')).toBe(false);
expect(byId.get('quote-negotiation')).toBe('loop');
expect(byId.get('intel-archive')).toBe('flow');
});
/*
* 占位骨架的形状:**机器步落台账 + 末步一张验收单**。三条都是踩过坑才立的:
* · 不写台账 → 发不出口 → 网关判不了 → 流停在第一个活动
* · 末步不是验收 → 活动永远不 release → 「等人却没东西给人答」
* · 出参映射的键必须是**台账列名**(小写蛇形)—— 写成驼峰会在放行后抛「非法标识符」
*/
it('占位骨架:机器步全是 pure-tool,末步是验收,出参键是台账列名', () => {
for (const m of MVP_SLOTS) {
const model = m.assets.businessModel as {
paradigm: string;
steps: ReadonlyArray<{ kind: string; workOrder?: string; output?: { fields: Record<string, string> } }>;
};
expect(model.paradigm, m.identity.activityId).toBe('flow');
const steps = model.steps;
expect(steps.length, m.identity.activityId).toBeGreaterThanOrEqual(2);
const last = steps[steps.length - 1]!;
expect(last.kind, `${m.identity.activityId} 末步该是人类步`).toBe('human');
expect(last.workOrder, `${m.identity.activityId} 末步该是验收单`).toBe('acceptance');
for (const s of steps.slice(0, -1)) {
expect(s.kind, `${m.identity.activityId} 机器步该是纯工具`).toBe('pure-tool');
expect(s.output, `${m.identity.activityId} 机器步该落一行台账`).toBeDefined();
}
// 所有出参映射的键都必须是小写蛇形(台账标识符闸:^[a-z][a-z0-9_]*$)
for (const s of steps) {
for (const col of Object.keys(s.output?.fields ?? {})) {
expect(col, `${m.identity.activityId} 的出参键 ${col} 不是台账列名`).toMatch(/^[a-z][a-z0-9_]*$/);
}
}
}
});
it('A1 出口带两枚去向旗;A2 透传 needSourcing —— 网关条件的数据来源', () => {
+26 -4
View File
@@ -37,8 +37,18 @@ export function registerDeskApprovalRoutes(app: Hono<AppEnv>, container: Contain
.flatMap<ApprovalItem>((i) => {
const node = pkg.nodes.find((n) => n.id === i.nodeId);
if (node?.kind !== 'approval') return [];
// 审批人卡到岗位 —— 不是我的岗位就不进我的审批要素
if (node.approver.position !== me.position.code) return [];
/*
* 谁的审批,要和**真正派单时的口径一致**(ADR-011:绑定先于策略)。
*
* 从前这里只比岗位码:`node.approver.position !== me.position.code` 就滤掉。
* 可引擎派审批时先看工作组绑定(`workGroup[岗位] → 员工`),装了组的单
* 实际派给的是被绑定的那个人 —— 于是出现「审批派给了我、我的审批箱里没有」:
* 单子谁也看不见,流永远卡在审批点(实测:工作组把 PM 绑到本人,审批箱空)。
* `toChain` 早为同一件事修过一次,这里是漏的那一处。
*/
const bound = w.workGroup?.[node.approver.position];
const mine = bound === undefined ? node.approver.position === me.position.code : bound === me.id;
if (!mine) return [];
return [
{
id: `${w.id}:${i.nodeId}#${i.instance}`,
@@ -92,8 +102,20 @@ export function registerDeskApprovalRoutes(app: Hono<AppEnv>, container: Contain
const body: ApiError = { code: 'not-found', message: `节点不是审批点:${nodeId}` };
return c.json(body, 404);
}
if (node.approver.position !== me.position.code) {
const body: ApiError = { code: 'forbidden', message: `审批点卡在 ${node.approver.position} 工位,岗位 ${me.position.code} 不得裁决` };
/*
* 裁决权也要按**派单口径**核,不是只比岗位码 —— 与上面的收件口径同一条规矩。
* 只比岗位的话:装了工作组的单看得见却裁不了(403),人干瞪眼、流卡死。
*/
const boundApprover = workflow.workGroup?.[node.approver.position];
const mayDecide = boundApprover === undefined ? node.approver.position === me.position.code : boundApprover === me.id;
if (!mayDecide) {
const body: ApiError = {
code: 'forbidden',
message:
boundApprover === undefined
? `审批点卡在 ${node.approver.position} 工位,岗位 ${me.position.code} 不得裁决`
: `本单的 ${node.approver.position} 由工作组绑定给了他人,你不得裁决`,
};
return c.json(body, 403);
}
+220 -82
View File
@@ -6,6 +6,11 @@
* A5 定价审批是**内置审批点**(审批不是任务,零开发、不入库),不在槽位之列。
*
* 实现待底座完备后逐个开发:届时以新包版本经安装通道换入,槽位契约不动。
*
* **占位期六个槽位一律 `flow` 范式**(2026-07-28):A2/A3/A6 本该是案例活动(loop),
* 但 loop 由 Agent 每拍决策、要真调模型;占位本身就是固定序列,声明成 flow 才诚实。
* 真开发它们为案例活动时,以新包版本装回 `paradigm: 'loop'`,那时按 CMMN + DMN 重写业务模型
* —— 所以这里不留一份没人用的 loop 骨架占地方。
*/
import { createHash } from 'node:crypto';
import { activityManifestSchema } from '@contracts';
@@ -24,49 +29,71 @@ export const SLOT_ARTIFACT = [
const checksum = createHash('sha256').update(SLOT_ARTIFACT).digest('hex');
/**
* flow 槽位的业务模型骨架:MVP 作业指导书的步骤标题 —— 未实现期一步一张执行工单,人工可兜。
*
* 卡面**必须自述**。空卡(`card: {}`)会让工单落回默认的「请处理」+ 一个「结果」框:
* 七个活动派出七张一模一样的卡,收卡的人不知道自己走到哪一步、这一步要干什么 ——
* 整条流就没法手工走通,而手工走通恰恰是逐个开发活动之前最该做的验证。
* 所以这里把步骤标签、第几步、以及「实现待开发、先人工兜」的实情都摆到卡面上。
* 认的键见 `wiring/engines.ts` 的 `cards.issue`:`title` / `ask` / `fields` / `basis`。
*
* **末步必须是验收工单**,否则活动永远收不了口。`flow-runner` 写死了这条:
* `released = lastStepIsAcceptance(steps) && lastVerdictPassed(position)` ——
* 六步全写成 execution 时,人把六张单都答完,任务却停在 `awaiting-human`:
* 没有待答工单、没有待答卡,**等人却没东西给人答**,必交出口也发不出去,
* 下游网关判不了、整条流走不出 A1(实测)。
*
* 声明的步骤来自 MVP 作业指导书,不篡改它的语义 —— 所以在其后**追加**一步收口验收:
* 放行即活动办结、按出口选择发射;驳回即退回重做。
*/
const flowSkeleton = (steps: readonly string[]) => {
const total = steps.length + 1;
const failure = { retry: { times: 0, backoff: 'PT30S' }, fallback: { kind: 'blocked' as const } };
const source = { k: '来源', v: '活动槽位的步序声明(实现待开发)' };
/** 一步机器落地:调占位工具,把它的出参按映射落成台账的一行 */
type Landing = {
/** 人读的步名 */
readonly label: string;
readonly domain: string;
readonly object: string;
/** 主键列 → 取值路径(占位工具出参的键,或作用域里的键) */
readonly key: Readonly<Record<string, string>>;
/** 业务列 → 取值路径 */
readonly fields: Readonly<Record<string, string>>;
};
const work = steps.map((label, i) => ({
/**
* 占位期的业务模型骨架 —— **机器步落地 + 一张验收单要人签**。
*
* 为什么是这个形状:
*
* ① **必须写台账**。出口载荷只从落地事实推导(数组字段 ← 这一单的落地行,
* 标量字段 ← 落地行铺平后的值)。不写台账就发不出口 → 下游网关没有判据 →
* 一条边都选不中 → 流无声停在第一个活动(实测过,并有 route-dead-end 事件写明缺哪个键)。
*
* ② **末步必须是验收工单**。`flow-runner` 写死了 `released = 末步是验收 && 裁决通过` ——
* 末步不是验收,活动永远不 release:人把前面的单都答完,任务却停在 `awaiting-human`,
* 没有待答工单也没有待答卡,**等人却没东西给人答**(实测)。
*
* ③ **占位不替活动做判断**。落的值来自占位工具,它只穿透上游给的值、给显眼的默认,
* 行上写 `status: '占位'`。打标、定价、比价那些是活动自己的内容,真实现时整段换掉。
*
* ④ **验收单可以改写落地值**。人类步的回传值同样经 `writeOutput` 落台账(flow-runner 的
* resume 路径),步序在后、后写赢 —— 占位期要走哪个分支,在验收时说,不必改代码。
*
* 一步只写**一行**(`writeOutput` 每步一次 draftWrite),所以要几行就给几个 landing。
*/
const placeholderSkeleton = (
sop: readonly string[],
landings: readonly Landing[],
/** 台账列名 → 回传字段名 */
ask: Readonly<Record<string, string>>,
) => {
const total = landings.length + 1;
const failure = { retry: { times: 0, backoff: 'PT30S' }, fallback: { kind: 'blocked' as const } };
const source = { k: '来源', v: '活动槽位占位产出(不做业务判断;真实现时整段换掉)' };
const machine = landings.map((l, i) => ({
name: `S${i + 1}`,
label,
input: {},
kind: 'human' as const,
workOrder: 'execution' as const,
card: {
title: label,
ask: `这一步的自动化还没开发,先由你来办:${label}。办完把结果填回来,流程照常往下走。`,
basis: [{ k: '步序', v: `第 ${i + 1} 步 / 共 ${total} 步` }, source],
label: l.label,
/* 入参映射:占位工具要的键从任务数据取 —— 上游给了就穿过去 */
input: {
rfqRef: 'rfqRef',
customerCode: 'customerCode',
pn: 'pn',
quotedAt: 'quotedAt',
needAlternative: 'needAlternative',
needSourcing: 'needSourcing',
},
deadline: 'P1D',
// 失败策略声明给定,不临场:人步失败即受阻待人 —— 槽位期没有可重试的机器步
kind: 'pure-tool' as const,
tool: 'slot.placeholder',
output: { domain: l.domain, object: l.object, key: l.key, fields: l.fields },
failure,
}));
return {
paradigm: 'flow' as const,
steps: [
...work,
...machine,
{
name: `S${total}`,
label: '收口验收',
@@ -75,12 +102,29 @@ const flowSkeleton = (steps: readonly string[]) => {
workOrder: 'acceptance' as const,
card: {
title: '收口验收',
/*
* 卡面要人填的正是**这个活动该产出、而占位产不出**的判断值(如两枚去向旗)。
* 填了就覆盖占位行的同一列 —— 于是下游网关判的是人的决定,不是占位的默认。
*/
...(Object.keys(ask).length === 0 ? {} : { fields: Object.values(ask) }),
basis: [
{ k: '步序', v: `第 ${total} 步 / 共 ${total} 步(收口)` },
{ k: '前置', v: `${steps.length} 步已由人工代办:${steps.join(' · ')}` },
{ k: '作业指导书', v: sop.join(' · ') },
{ k: '占位落地', v: landings.map((l) => `${l.domain}.${l.object}`).join('、') },
source,
],
},
/* 验收也要把值落回同一行:人填的覆盖占位的 */
...(landings[landings.length - 1] === undefined
? {}
: {
output: {
domain: landings[landings.length - 1]!.domain,
object: landings[landings.length - 1]!.object,
key: landings[landings.length - 1]!.key,
fields: ask,
},
}),
deadline: 'P1D',
failure,
},
@@ -89,13 +133,114 @@ const flowSkeleton = (steps: readonly string[]) => {
};
};
/** loop 槽位:CMMN 骨架(MVP 案例图的项)+ 叙事一句话;DMN 待实现期再挂 */
const loopSkeleton = (items: readonly string[], narrative: string) => ({
paradigm: 'loop' as const,
cmmnXml: `<case><casePlanModel autoComplete="true">${items.map((it) => `<task name="${it}"/>`).join('')}</casePlanModel></case>`,
narrative,
dmn: { drd: [], tables: [] },
});
/**
* 各活动占位期要落的台账行 —— 按各自契约出口的必填字段倒推。
*
* 数组字段(records / rows / floors)由「这一单的全部落地行」整体构成,所以只要有行就有值;
* 标量字段必须有**对应的列**才取得到 —— 这就是为什么 A1/A2 要落「受理结论」那一行。
* 一步一行,所以列在这里的条数就是机器步的步数。
*/
const LANDINGS: Readonly<Record<string, readonly Landing[]>> = {
'rfq-intake': [
{
label: '落统一受理记录',
domain: 'project',
object: 'intake_record',
key: { customer_code: 'customerCode', pn: 'pn' },
fields: { status: 'status' },
},
{
// 两枚去向旗落这一行:一单一行,G1/G2 读同一个值(挂按料号分的行会 last-write-wins)
label: '落受理结论(去向旗)',
domain: 'project',
object: 'intake_verdict',
key: { rfq_ref: 'rfqRef' },
fields: { need_alternative: 'needAlternative', need_sourcing: 'needSourcing', status: 'status' },
},
],
'alt-selection': [
{
label: '落替代对标表',
domain: 'project',
object: 'alt_benchmark',
key: { original_pn: 'pn', candidate_pn: 'pn' },
fields: { alt_grade: 'status' },
},
{
// A2 回写**同一行**的 needSourcing —— 去向只有一个出处,不复制
label: '回写受理结论(是否还要寻源)',
domain: 'project',
object: 'intake_verdict',
key: { rfq_ref: 'rfqRef' },
fields: { need_sourcing: 'needSourcing', status: 'status' },
},
],
'sourcing-inquiry': [
{
label: '落寻源比价表',
domain: 'project',
object: 'sourcing_compare',
key: { pn: 'pn', supplier: 'supplier' },
fields: { quote_price: 'quotePrice', verdict: 'status' },
},
{
label: '落供应商底价表',
domain: 'project',
object: 'supplier_floor',
key: { pn: 'pn', supplier: 'supplier' },
fields: { floor_price: 'floorPrice' },
},
],
'cost-pricing': [
{
label: '落报价草案',
domain: 'project',
object: 'quote_draft',
key: { pn: 'pn' },
fields: { proposed_price: 'proposedPrice' },
},
],
'quote-negotiation': [
{
label: '落正式报价单',
domain: 'project',
object: 'formal_quote',
key: { pn: 'pn' },
fields: { unit_price_cny: 'unitPrice' },
},
],
'intel-archive': [
{
label: '落报价落地率统计',
domain: 'project',
object: 'landing_stats',
key: { period: 'period' },
fields: { landing_rate: 'landingRate' },
},
],
};
/**
* 验收单要人填的值 —— **这个活动该产出、而占位产不出的判断**。
* 填了就覆盖占位行的同一列,下游网关判的是人的决定。
* A6 的三个去向不在这儿:那是选择组(恰发一口),由放行时选口给出。
*
* 形状是「**台账列名 → 回传字段名**」,两边不能混:
* 列名必须是小写蛇形(台账的标识符闸是 `^[a-z][a-z0-9_]*$`),
* 回传字段名是卡面表单的键、跟着活动契约的驼峰走。
* 我把这两个搞混过一次:`fields: { needSourcing: 'needSourcing' }` 直接把驼峰当列名,
* draftWrite 抛「非法标识符:needSourcing」,而且是在放行之后抛 —— 任务卡在 running、
* 台账一行没有,推进器还在一秒一次地重试。
*/
const ASK: Readonly<Record<string, Readonly<Record<string, string>>>> = {
'rfq-intake': { need_alternative: 'needAlternative', need_sourcing: 'needSourcing' },
'alt-selection': { need_sourcing: 'needSourcing' },
'sourcing-inquiry': {},
'cost-pricing': {},
'quote-negotiation': {},
'intel-archive': {},
};
const identity = (activityId: string, name: string, paradigm: 'flow' | 'loop') => ({
activityId,
@@ -113,10 +258,13 @@ const identity = (activityId: string, name: string, paradigm: 'flow' | 'loop') =
* 0.4.0:flow 骨架末步追加**收口验收**—— 没有它活动永远不 release,
* 六步答完就卡在「等人却没东西给人答」(实测)。
* 0.5.0:A1/A2 声明「受理结论」对象(两枚去向旗有处落地);A2 入参加 rfqRef。
* 0.6.0:占位期骨架改**机器步落台账 + 一张验收单**(用户定:只留验收要人签)。
* 六个槽位一律 flow 范式;预算固定 humanCalls: 2。
* 0.6.1:修验收步的出参映射 —— 键是**台账列名**(小写蛇形),不是回传字段名。
* 契约的入参出口一直没动,故 `contract.version` 始终 0.1.0。
* 在途任务按启动时版本跑完,不受影响。
*/
packageVersion: '0.5.0',
packageVersion: '0.6.1',
category: '统一报价',
paradigm,
sdkVersion: '0.1.0-m5',
@@ -143,19 +291,18 @@ const STEPS = {
} as const;
/**
* 预算 —— `humanCalls` 必须**够这个槽位自己的人类步数**,不能六个槽位共用一个数。
* 预算 —— `humanCalls` 必须**够这个槽位实际要问人的次数**。
*
* 曾经共用 `humanCalls: 3`,而 A1 声明了 6 个人类步:手工走到第 3 步就 `exhausted`
* 曾经六个槽位共用 `humanCalls: 3`,而那时 A1 有 6 个人类步:走到第 3 步就 `exhausted`
* 终态、工作流转 abnormal,活动**结构上永远走不完**(实测:used 3 / cap 3,停在 A1)。
* 槽位期是一步一张工单,所以按步数给:声明的 n 步 + 1 张收口验收 + 1 次余量。
* 实现期活动自己声明真实预算时,这条约束不变:实际要问人的次数 ≤ humanCalls。
* 现在占位期是**机器步 + 一张验收单**,只问人一次,所以固定给 2(1 张验收 + 1 次余量)。
* 这条约束本身不随形态变:实现期活动自己声明真实预算时,实际要问人的次数 ≤ humanCalls。
*/
const budgetFor = (declaredSteps: number) => ({
const budgetFor = () => ({
steps: 40,
tokens: 200_000,
activeMinutes: 60,
// n 张执行 + 1 张验收(flowSkeleton 追加的收口步)+ 1 次余量
humanCalls: declaredSteps + 2,
humanCalls: 2,
});
/**
@@ -163,10 +310,10 @@ const budgetFor = (declaredSteps: number) => ({
* 运行时只认 `resources.budget.humanCalls`(见 `wiring/engines.ts` 的 `caps`);
* `authorization.humanCallBudget` 只给治理台显示。两者不一致,治理台就会摆一个假数。
*/
const authorizationFor = (humanSteps: number) => ({
const authorizationFor = () => ({
discretion: [],
preauthorizedActions: [],
humanCallBudget: budgetFor(humanSteps).humanCalls,
humanCallBudget: budgetFor().humanCalls,
});
export const MVP_SLOTS: readonly ActivityManifest[] = [
@@ -211,8 +358,8 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
selective: [],
},
...contractRest,
authorization: authorizationFor(STEPS.rfqIntake.length),
resources: { tools: [{ name: 'crm.history-price-read' }], skills: [], models: [], roles: ['BD'], budget: budgetFor(STEPS.rfqIntake.length) },
authorization: authorizationFor(),
resources: { tools: [{ name: 'crm.history-price-read' }], skills: [], models: [], roles: ['BD'], budget: budgetFor() },
},
declarations: {
models: [],
@@ -232,7 +379,7 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
]),
},
assets: {
businessModel: flowSkeleton(STEPS.rfqIntake),
businessModel: placeholderSkeleton(STEPS.rfqIntake, LANDINGS['rfq-intake']!, ASK['rfq-intake']!),
skills: [],
viewTemplates: [],
cardSchemas: {},
@@ -250,7 +397,7 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
/* ── A2 替代选型(Case · FAE) ──────────────────────────────────── */
activityManifestSchema.parse({
identity: identity('alt-selection', '替代选型', 'loop'),
identity: identity('alt-selection', '替代选型', 'flow'),
contract: {
activityId: 'alt-selection',
// 0.2.0:入参加 rfqRef —— 办结时要回写「受理结论」那一行,主键就是它
@@ -290,8 +437,8 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
selective: [],
},
...contractRest,
authorization: authorizationFor(STEPS.altSelection.length),
resources: { tools: [{ name: 'crm.history-price-read' }], skills: [], models: [], roles: ['FAE'], budget: budgetFor(STEPS.altSelection.length) },
authorization: authorizationFor(),
resources: { tools: [{ name: 'crm.history-price-read' }], skills: [], models: [], roles: ['FAE'], budget: budgetFor() },
},
declarations: {
models: [],
@@ -307,10 +454,7 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
]),
},
assets: {
businessModel: loopSkeleton(
STEPS.altSelection,
'MVP §1.5:上接 G1 是否需要选型;齐了即收 —— 必做项完成且无进行中项即结案,办结经 G2 定去向。',
),
businessModel: placeholderSkeleton(STEPS.altSelection, LANDINGS['alt-selection']!, ASK['alt-selection']!),
skills: [],
viewTemplates: [],
cardSchemas: {},
@@ -328,7 +472,7 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
/* ── A3 寻源询价(Case · PRM) ──────────────────────────────────── */
activityManifestSchema.parse({
identity: identity('sourcing-inquiry', '寻源询价', 'loop'),
identity: identity('sourcing-inquiry', '寻源询价', 'flow'),
contract: {
activityId: 'sourcing-inquiry',
version: '0.1.0',
@@ -361,13 +505,13 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
selective: [],
},
...contractRest,
authorization: authorizationFor(STEPS.sourcingInquiry.length),
authorization: authorizationFor(),
resources: {
tools: [{ name: 'crm.history-price-read' }, { name: 'mail.send' }],
skills: [],
models: [],
roles: ['PRM'],
budget: budgetFor(STEPS.sourcingInquiry.length),
budget: budgetFor(),
},
},
declarations: {
@@ -383,10 +527,7 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
]),
},
assets: {
businessModel: loopSkeleton(
STEPS.sourcingInquiry,
'MVP §1.7:上接 G2 是否需要寻源;齐了即收 —— 必做项完成且无进行中项即结案,办结转 A4 成本定价。',
),
businessModel: placeholderSkeleton(STEPS.sourcingInquiry, LANDINGS['sourcing-inquiry']!, ASK['sourcing-inquiry']!),
skills: [],
viewTemplates: [],
cardSchemas: {},
@@ -436,8 +577,8 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
selective: [],
},
...contractRest,
authorization: authorizationFor(STEPS.costPricing.length),
resources: { tools: [{ name: 'crm.history-price-read' }], skills: [], models: [], roles: ['BD'], budget: budgetFor(STEPS.costPricing.length) },
authorization: authorizationFor(),
resources: { tools: [{ name: 'crm.history-price-read' }], skills: [], models: [], roles: ['BD'], budget: budgetFor() },
},
declarations: {
models: [],
@@ -447,7 +588,7 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
ledger: declarationsFor(['intel.history_price', 'customer.profile', 'project.quote_draft']),
},
assets: {
businessModel: flowSkeleton(STEPS.costPricing),
businessModel: placeholderSkeleton(STEPS.costPricing, LANDINGS['cost-pricing']!, ASK['cost-pricing']!),
skills: [],
viewTemplates: [],
cardSchemas: {},
@@ -465,7 +606,7 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
/* ── A6 报价议价(Case · BD) ───────────────────────────────────── */
activityManifestSchema.parse({
identity: identity('quote-negotiation', '报价议价', 'loop'),
identity: identity('quote-negotiation', '报价议价', 'flow'),
contract: {
activityId: 'quote-negotiation',
version: '0.1.0',
@@ -497,13 +638,13 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
selective: [],
},
...contractRest,
authorization: authorizationFor(STEPS.quoteNegotiation.length),
authorization: authorizationFor(),
resources: {
tools: [{ name: 'crm.history-price-read' }, { name: 'mail.send' }],
skills: [],
models: [],
roles: ['BD'],
budget: budgetFor(STEPS.quoteNegotiation.length),
budget: budgetFor(),
},
},
declarations: {
@@ -514,10 +655,7 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
ledger: declarationsFor(['project.formal_quote', 'project.followup']),
},
assets: {
businessModel: loopSkeleton(
STEPS.quoteNegotiation,
'MVP §1.4:上接审批通过进入;发出标准报价并跟谈,办结经 G4 议价结果定去向(成交 / 有异议 / 拒绝或超时)。',
),
businessModel: placeholderSkeleton(STEPS.quoteNegotiation, LANDINGS['quote-negotiation']!, ASK['quote-negotiation']!),
skills: [],
viewTemplates: [],
cardSchemas: {},
@@ -567,8 +705,8 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
selective: [],
},
...contractRest,
authorization: authorizationFor(STEPS.intelArchive.length),
resources: { tools: [], skills: [], models: [], roles: ['BD'], budget: budgetFor(STEPS.intelArchive.length) },
authorization: authorizationFor(),
resources: { tools: [], skills: [], models: [], roles: ['BD'], budget: budgetFor() },
},
declarations: {
models: [],
@@ -578,7 +716,7 @@ export const MVP_SLOTS: readonly ActivityManifest[] = [
ledger: declarationsFor(['intel.history_price', 'customer.profile', 'project.landing_stats']),
},
assets: {
businessModel: flowSkeleton(STEPS.intelArchive),
businessModel: placeholderSkeleton(STEPS.intelArchive, LANDINGS['intel-archive']!, ASK['intel-archive']!),
skills: [],
viewTemplates: [],
cardSchemas: {},
+63 -10
View File
@@ -51,14 +51,66 @@ const MAIL_TOOL = {
connectionKeys: ['endpoint'],
};
/**
* 活动槽位的占位产出 —— **编排层跑通期专用的纯工具**。
*
* 六个活动只有契约面。出口载荷只从落地事实推导,不写台账就发不出口、
* 网关判不了、流走不出第一个活动。这枚工具把契约要求的字段落成一行,只为让编排层能被走通。
* 它**不含任何业务判断**(实现见 `tools/first-party.ts` 的 `slotPlaceholder`);
* 真开发某个活动时,那个活动的步序整个换掉,这枚工具从它的白名单里摘掉。
*/
const PLACEHOLDER_TOOL = {
name: 'slot.placeholder',
version: '0.1.0',
description: '活动槽位占位产出:把契约要求的字段落成一行(不做业务判断;真实现后摘除)',
input: {
type: 'object',
properties: {
rfqRef: { type: 'string' },
customerCode: { type: 'string' },
pn: { type: 'string' },
supplier: { type: 'string' },
quotedAt: { type: 'string' },
needAlternative: { type: 'boolean' },
needSourcing: { type: 'boolean' },
},
},
output: {
type: 'object',
properties: {
placeholder: { type: 'boolean' },
status: { type: 'string' },
rfqRef: { type: 'string' },
customerCode: { type: 'string' },
pn: { type: 'string' },
supplier: { type: 'string' },
period: { type: 'string' },
needAlternative: { type: 'boolean' },
needSourcing: { type: 'boolean' },
floorPrice: { type: 'number' },
quotePrice: { type: 'number' },
proposedPrice: { type: 'number' },
unitPrice: { type: 'number' },
landingRate: { type: 'number' },
},
},
// 纯工具:无外效应、无连接配置 —— 同输入必同出参
effect: 'read' as const,
errors: [],
idempotent: true,
timeoutMs: 5_000,
retries: 0,
connectionKeys: [] as string[],
};
/** 白名单:逐槽位授权 —— 谁能调什么,治理台说了算,活动代码里看不到这张表 */
const ALLOWLIST: Readonly<Record<string, readonly string[]>> = {
'rfq-intake': [HISTORY_TOOL.name],
'alt-selection': [HISTORY_TOOL.name],
'sourcing-inquiry': [HISTORY_TOOL.name, MAIL_TOOL.name],
'cost-pricing': [HISTORY_TOOL.name],
'quote-negotiation': [HISTORY_TOOL.name, MAIL_TOOL.name],
'intel-archive': [],
'rfq-intake': [HISTORY_TOOL.name, PLACEHOLDER_TOOL.name],
'alt-selection': [HISTORY_TOOL.name, PLACEHOLDER_TOOL.name],
'sourcing-inquiry': [HISTORY_TOOL.name, MAIL_TOOL.name, PLACEHOLDER_TOOL.name],
'cost-pricing': [HISTORY_TOOL.name, PLACEHOLDER_TOOL.name],
'quote-negotiation': [HISTORY_TOOL.name, MAIL_TOOL.name, PLACEHOLDER_TOOL.name],
'intel-archive': [PLACEHOLDER_TOOL.name],
};
export async function seedMvp(container: Container): Promise<void> {
@@ -88,17 +140,18 @@ export async function seedMvp(container: Container): Promise<void> {
log('① LLM 实例已绑定:deepseek-v4-flash · deepseek-v4-pro · quote-extractor(→ flash,系统用途)');
/* ② 功能工具注册两审 + 逐槽位白名单 */
for (const contract of [HISTORY_TOOL, MAIL_TOOL]) {
for (const contract of [HISTORY_TOOL, MAIL_TOOL, PLACEHOLDER_TOOL]) {
const verdict = await container.toolbox.register({
contract,
samples: [
{
// 样例集一份喂两件工具:并集覆盖各家必填
// 样例集一份喂三件工具:并集覆盖各家必填
input: { pn: 'LM358DR', to: 'x@y.com', subject: '询价' },
expectShape: { type: 'object' },
},
],
connectionValues: { endpoint: 'replay://crm' },
// 占位工具是纯工具,没有连接目标 —— 与真工具同门过两审,但不给它端点
...(contract.connectionKeys.length === 0 ? {} : { connectionValues: { endpoint: 'replay://crm' } }),
});
if (!verdict.accepted) {
log(' 工具 ' + contract.name + ' 未过两审:' + verdict.staticFindings.map((f) => f.message).join('; '));
@@ -107,7 +160,7 @@ export async function seedMvp(container: Container): Promise<void> {
for (const [activityId, tools] of Object.entries(ALLOWLIST)) {
await container.toolbox.setAllowlist(activityId, tools);
}
log('② 功能工具已注册并入白名单(读类 1 · 写类 1,逐槽位授权)');
log('② 功能工具已注册并入白名单(读类 1 · 写类 1 · 占位纯工具 1,逐槽位授权)');
/* ③ 六个活动槽位经安装通道装入 —— 声明物化把四域十八对象建出来 */
await installSlots(container);
+47
View File
@@ -123,6 +123,52 @@ const mailSend: ToolHandler = async ({ input, connection }) => {
};
};
/* ── 活动槽位的占位产出(编排层跑通期专用) ─────────────────────────────
*
* 六个活动都只有契约面、没有实现。而出口载荷只从**落地事实**推导,
* 所以不写台账就发不出口、网关判不了、流走不出第一个活动。
* 这枚工具就是为此:把该活动契约要求的字段落成一行,让编排层能被整条走通。
*
* **它不做任何业务判断。** 不打标、不定价、不比价 —— 那些是活动自己的内容,
* 真实现时这一步整个换掉,不是在这儿慢慢长成活动。
* 拿得到的值原样穿过去(上游给了就用),拿不到就给一个**明确是占位**的默认,
* 并在行上写 `status: '占位'`,查台账的人一眼看得出这行不是真业务数据。
*
* 人在收口验收时填的值会覆盖同一行同一列(步序在后,后写赢)——
* 占位期要走某个分支,就在验收时说,不必改代码。
*/
const slotPlaceholder: ToolHandler = async ({ input }) => {
const text = (key: string, fallback: string) => {
const v = input[key];
return typeof v === 'string' && v !== '' ? v : fallback;
};
const flag = (key: string) => input[key] === true || input[key] === 'true';
return {
ok: true,
output: {
/** 占位标记 —— 落到行上,也留在出参里供留痕 */
placeholder: true,
status: '占位',
/* 主键类:上游给了就用,没给就用一个显眼的占位号 */
rfqRef: text('rfqRef', 'RFQ-占位'),
customerCode: text('customerCode', 'C-占位'),
pn: text('pn', 'PN-占位'),
supplier: text('supplier', '供应商-占位'),
period: text('quotedAt', '期-占位').slice(0, 7),
/* 去向类:原样穿过,默认 false —— 占位不替活动做判断,要分支就在验收时说 */
needAlternative: flag('needAlternative'),
needSourcing: flag('needSourcing'),
/* 数值类:一律 0,不编造像真的数字 */
floorPrice: 0,
quotePrice: 0,
proposedPrice: 0,
unitPrice: 0,
landingRate: 0,
},
};
};
export const FIRST_PARTY_TOOLS: ReadonlyArray<readonly [string, ToolHandler]> = [
['crm.history-price-read', historyPriceRead],
['quote-intake.classify', classify],
@@ -132,4 +178,5 @@ export const FIRST_PARTY_TOOLS: ReadonlyArray<readonly [string, ToolHandler]> =
['quote-archive.profile', profile],
['quote-archive.landing-rate', landingRate],
['mail.send', mailSend],
['slot.placeholder', slotPlaceholder],
];
+12 -4
View File
@@ -263,20 +263,28 @@ export function wireEngines(deps: EngineWiringDeps): EngineWiring {
: Object.entries(input.card)
.filter(([k, v]) => !['title', 'fields', 'ask', 'basis'].includes(k) && v !== null && v !== undefined && v !== '')
.map(([k, v]) => ({ k, v: typeof v === 'object' ? JSON.stringify(v) : String(v) }));
/*
* 卡面声明的字段 → 表单域。执行与验收共用这一份解析:
* 验收工单从前写死 `fields: []`,可 `acceptanceWorkOrderSchema` 本来就有 `fields` ——
* 是这里没填,不是设计上不要。放行时人要修订的值(如「这一单到底要不要选型」)
* 就靠它;答完经 `writeOutput` 落台账,覆盖上游步写的同一列。
*/
const declaredFields = Array.isArray(input.card['fields'])
? (input.card['fields'] as string[]).map((key) => ({ key, label: key, kind: 'text' as const, required: true }))
: undefined;
if (input.workOrder === 'acceptance') {
const issued = await deps.humanTool.issueAcceptance(context, {
title,
basis: basis.length > 0 ? basis : [{ k: '来源', v: '步序声明' }],
deliverable: String(input.card['deliverable'] ?? 'deliverable') as never,
criteria: [{ label: '成果齐备', level: 'L5', pass: false }],
fields: [],
fields: declaredFields ?? [],
});
await taskStore.addConsumption(input.taskId, { humanCalls: 1 });
return { id: issued.order.id };
}
const fields = Array.isArray(input.card['fields'])
? (input.card['fields'] as string[]).map((key) => ({ key, label: key, kind: 'text' as const, required: true }))
: [{ key: 'result', label: '结果', kind: 'textarea' as const, required: true }];
const fields = declaredFields ?? [{ key: 'result', label: '结果', kind: 'textarea' as const, required: true }];
const issued = await deps.humanTool.issueExecution(context, {
title,
basis: basis.length > 0 ? basis : [{ k: '来源', v: '步序声明' }],
@@ -157,6 +157,16 @@ export function createLedgerService(deps: LedgerServiceDeps): LedgerService {
if (drafts.length === 0) return { mergedRows: 0, emittedEvents: 0, merged: [] };
const pending: EnvelopeDraft[] = [];
/*
* 合并后**读回来**的行 —— 「落地即事实」,事实是表里那一份,不是写进去之前的草稿。
*
* 从前这里直接回 `draft.patch`,于是出口载荷可以跟台账不一致:草稿里是字符串
* `"true"`(人的回传值天生是字符串),列是 boolean,PG 存的时候转了,可发出去的口里
* 还是字符串 —— 下游活动的入参校验当场拒收「/needSourcing must be boolean」,
* 节点起不来、报 blocked,而台账里明明是对的(实测)。
* 读回来之后,出口载荷与台账逐字一致,类型也由列定义说了算。
*/
const landed: Array<{ domain: string; object: string; key: Record<string, unknown>; values: Record<string, unknown> }> = [];
await deps.store.transaction(async (store, draftStore) => {
for (const draft of drafts) {
@@ -170,6 +180,14 @@ export function createLedgerService(deps: LedgerServiceDeps): LedgerService {
}
const existing = await store.selectByKeys(ref, [draft.key]);
await store.upsert(ref, draft.key, draft.patch);
const stored = (await store.selectByKeys(ref, [draft.key]))[0];
landed.push({
domain: draft.domain,
object: draft.object,
key: draft.key,
// 读不回来只能退回草稿(理论上不该发生:刚 upsert 过);宁可退也不丢这一行
values: stored ?? draft.patch,
});
pending.push(
dataEvent(
ref,
@@ -185,13 +203,7 @@ export function createLedgerService(deps: LedgerServiceDeps): LedgerService {
});
for (const envelope of pending) await deps.events.publish(envelope);
return {
mergedRows: drafts.length,
emittedEvents: pending.length,
merged: drafts
.filter((d) => !d.tombstone)
.map((d) => ({ domain: d.domain, object: d.object, key: d.key, values: d.patch })),
};
return { mergedRows: drafts.length, emittedEvents: pending.length, merged: landed };
},
async query(query: LedgerQuery): Promise<LedgerPage> {
@@ -360,3 +360,47 @@ describe('joinReady —— 网关直通道不参与等待', () => {
expect(joinReady(pkg, 'J', new Set(['X', 'Y']), new Set())).not.toBe(false);
});
});
/*
* 异或汇合不等 —— 这条曾经让流无声停住。
*
* G2J(寻源汇合)是异或:「需要寻源」走 A3、「不需要」直通,两条互斥、只来一条。
* 而 `joinReady` 原本按并行汇合写(全部责任分支收敛才放行),于是在「不需要寻源」那条路上
* 永远在等 A3 —— 一个结构上不会激活的分支。症状最坑的地方是**连死路事件都没有**:
* 边是选中了的,只是在汇合判定里被 continue 跳过,从外面看就是 A1 办结后什么都不再发生。
*/
describe('joinReady —— 异或汇合只来一条,不等', () => {
const xor = processPackageSchema.parse({
id: 'p-xor-join',
name: '异或汇合测试',
version: 1,
state: 'active',
callInterface: { input: { type: 'object' }, output: { type: 'object' } },
nodes: [
{ kind: 'start', id: 'S', label: '开始' },
{ kind: 'gateway', id: 'G', label: '要不要绕', gateway: 'exclusive', mode: 'fork', basis: '判据' },
{ kind: 'activity', id: 'X', label: 'X', activityId: 'a-x', owner: { kind: 'position', position: 'BD' } },
{ kind: 'gateway', id: 'J', label: '汇合', gateway: 'exclusive', mode: 'join' },
{ kind: 'end', id: 'E', label: '结束' },
],
edges: [
{ id: 'e1', from: 'S', to: 'G', mapping: [], reopen: false },
{ id: 'e2', from: 'G', to: 'X', condition: 'go = true', mapping: [], reopen: false },
// 直通:不绕 X,从网关直接进汇合
{ id: 'e3', from: 'G', to: 'J', condition: 'go = false', mapping: [], reopen: false },
{ id: 'e4', from: 'X', to: 'J', mapping: [], reopen: false },
{ id: 'e5', from: 'J', to: 'E', mapping: [], reopen: false },
],
variables: [],
});
it('走直通那条:X 从未激活,汇合照样放行', () => {
expect(joinReady(xor, 'J', new Set(), new Set())).toBe(true);
});
it('走 X 那条:X 收敛后放行', () => {
expect(joinReady(xor, 'J', new Set(['X']), new Set())).toBe(true);
});
// 并行汇合「该等的还得等」由上一个 describe 的「还差一条 → 不回齐」守着,不在这儿重复
});
@@ -100,6 +100,20 @@ export function joinReady(
converged: ReadonlySet<string>,
tolerated: ReadonlySet<string>,
): boolean {
const node = pkg.nodes.find((n) => n.id === joinNodeId);
/*
* **异或汇合不等。**
*
* 上面那句「回齐」是按并行汇合写的:AND 分叉出去的每一支都要跑,所以汇合处要等齐。
* 异或汇合是另一回事 —— 两条分支互斥,**结构上只会来一条**,另一条永远不激活。
* 拿「全部入边都收敛」去要求它,就是在等一个不可能到来的分支:
* 实测 G2J(寻源汇合)在「不需要寻源」这条路上永远 false,流无声停在 G2J,
* 而且**连死路事件都没有** —— 边是选中了的,只是在汇合判定里被 continue 跳过,
* 从外面看就是 A1 办结后什么都不再发生。
*/
if (node?.kind === 'gateway' && node.gateway === 'exclusive') return true;
const isGateway = (nodeId: string): boolean =>
pkg.nodes.find((n) => n.id === nodeId)?.kind === 'gateway';
const inbound = pkg.edges.filter((e) => e.to === joinNodeId && !isGateway(e.from));