M1: 底座 —— @contracts 首版 + event / ledger / org / llm

@contracts 首版(§8.1 九个文件):
- id 品牌 ID / terminal 终态五名与归侧四标签 / envelope 信封六字段与四类事件
- card 工单两模式 + 对话卡族(形状对齐 2026-07-26 原型定稿)
- contract7 契约七件 / ledger 三级寻址与写三分 / process-package 流程包 DSL 与触发器三类
- manifest 活动包清单六区(含 CMMN·DMN·步序声明的资产形状)/ org / api 路由契约

模块(L1):
- event   信封存储、归属解析三级短路、投递五诺、监听注册表、三级消费裁定
- ledger  schema 自生长(最大化合并/最宽类型/只增不破坏)、任务视图叠加、写三分、冲突检查
- org     岗位授权(客体三类×动作三种)、停用前置检查、会话、种子播种
- llm     四元绑定、ModelGateway 三模式(live/record/replay)—— 两缝之一

app 装配:Hono 服务 + 鉴权中间件 + 治理台/工作台路由;drizzle 迁移;AES-256-GCM 凭证密封

ADR-007 工具链与门禁 · ADR-008 投递队列 · ADR-009 凭证加密
(ADR 编号自 007 续:编码规范 §14 已用到 006,README 写「从 005 续」是笔误)

门禁五道全绿;96 个测试通过,含对真实 PG 的 ledger 集成测试

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KeDBx2PHLavbURXB8LJJ7m
This commit is contained in:
JCAI Main Agent
2026-07-27 00:59:14 +08:00
co-authored by Claude Opus 5
parent 7cd664af3a
commit 14d4fa046a
120 changed files with 15236 additions and 78 deletions
+6 -1
View File
@@ -3,5 +3,10 @@
"version": "0.0.0",
"private": true,
"type": "module",
"exports": { ".": "./src/index.ts" }
"exports": {
".": "./src/index.ts"
},
"dependencies": {
"zod": "^4.4.3"
}
}
+111
View File
@@ -0,0 +1,111 @@
/**
* 治理台路由契约(编码规范 §8.1 / §9.1)。
* 治理台九功能不设后端 governance 模块:每个功能是对应模块的管理用例 + 本文件的路由组装(§3)。
*/
import { z } from 'zod';
import type { RouteContract } from './http.ts';
import { disableCheckSchema, grantSchema, positionSchema, staffSchema } from '../org.ts';
import { positionIdSchema, staffIdSchema } from '../id.ts';
/* ── 员工管理 ─────────────────────────────────────────────────────────── */
export const listStaffRoute = {
method: 'GET',
path: '/api/gov/staff',
output: z.object({
staff: z.array(staffSchema.extend({ position: positionSchema })),
positions: z.array(positionSchema),
}),
} as const satisfies RouteContract;
export const createStaffRoute = {
method: 'POST',
path: '/api/gov/staff',
body: z.object({
account: z.string().min(1),
name: z.string().min(1),
positionId: positionIdSchema,
}),
output: staffSchema,
} as const satisfies RouteContract;
export const disableStaffCheckRoute = {
method: 'GET',
path: '/api/gov/staff/:staffId/disable-check',
params: z.object({ staffId: staffIdSchema }),
output: disableCheckSchema,
} as const satisfies RouteContract;
export const disableStaffRoute = {
method: 'POST',
path: '/api/gov/staff/:staffId/disable',
params: z.object({ staffId: staffIdSchema }),
output: z.object({ ok: z.boolean(), check: disableCheckSchema }),
} as const satisfies RouteContract;
export const listGrantsRoute = {
method: 'GET',
path: '/api/gov/positions/:positionId/grants',
params: z.object({ positionId: positionIdSchema }),
output: z.object({ grants: z.array(grantSchema) }),
} as const satisfies RouteContract;
export const setGrantsRoute = {
method: 'POST',
path: '/api/gov/positions/:positionId/grants',
params: z.object({ positionId: positionIdSchema }),
body: z.object({ grants: z.array(grantSchema) }),
output: z.object({ grants: z.array(grantSchema) }),
} as const satisfies RouteContract;
/* ── 系统管理 · LLM 实例(四元绑定) ────────────────────────────────── */
export const LLM_PROVIDERS = ['openai-compatible', 'openai', 'deepseek', 'anthropic', 'qwen'] as const;
export const llmProviderSchema = z.enum(LLM_PROVIDERS);
export type LlmProvider = z.infer<typeof llmProviderSchema>;
/** 活动只见自定义模型名;Provider / URL / API-Key / Model 四元在系统侧绑定,活动不触厂商与密钥 */
export const llmInstanceViewSchema = z.object({
id: z.string(),
/** 自定义模型名(逻辑名)—— 活动以此声明引用 */
name: z.string().min(1),
provider: llmProviderSchema,
baseUrl: z.string().min(1),
model: z.string().min(1),
/** 密钥不出治理台:只回是否已绑定,永不回明文(OS 7.3 凭证隔离) */
apiKeyBound: z.boolean(),
/** 系统用途绑定:叙述性小结 / 汇报生成 / 蒸馏钩子,计量入系统账 */
systemUse: z.boolean().default(false),
enabled: z.boolean().default(true),
});
export type LlmInstanceView = z.infer<typeof llmInstanceViewSchema>;
export const listLlmInstancesRoute = {
method: 'GET',
path: '/api/gov/llm',
output: z.object({ instances: z.array(llmInstanceViewSchema) }),
} as const satisfies RouteContract;
export const upsertLlmInstanceRoute = {
method: 'POST',
path: '/api/gov/llm',
body: z.object({
id: z.string().optional(),
name: z.string().min(1),
provider: llmProviderSchema,
baseUrl: z.string().min(1),
model: z.string().min(1),
/** 只写不读:留空表示保持原值 */
apiKey: z.string().optional(),
systemUse: z.boolean().default(false),
enabled: z.boolean().default(true),
}),
output: llmInstanceViewSchema,
} as const satisfies RouteContract;
export const probeLlmInstanceRoute = {
method: 'POST',
path: '/api/gov/llm/:id/probe',
params: z.object({ id: z.string() }),
output: z.object({ ok: z.boolean(), latencyMs: z.number().int().optional(), error: z.string().optional() }),
} as const satisfies RouteContract;
+51
View File
@@ -0,0 +1,51 @@
/**
* 路由契约的形状(编码规范 §8.1 / §9.2)。
*
* 前端只经 `shared/typed-fetch` + 本目录的路由契约与服务端交互;组件内禁止裸 fetch。
* **禁止 Hono RPC 客户端** —— 它要求前端 import 后端类型,违反 §5.1。
*/
import type { z } from 'zod';
export const HTTP_METHODS = ['GET', 'POST', 'PATCH', 'DELETE'] as const;
export type HttpMethod = (typeof HTTP_METHODS)[number];
/**
* 一条路由契约。`path` 用 `:name` 表示路径参数,与 `params` 的键一一对应。
* body 只在 POST/PATCH 上有意义;GET 用 query。
*/
export type RouteContract<
TParams extends z.ZodTypeAny = z.ZodTypeAny,
TQuery extends z.ZodTypeAny = z.ZodTypeAny,
TBody extends z.ZodTypeAny = z.ZodTypeAny,
TOutput extends z.ZodTypeAny = z.ZodTypeAny,
> = {
readonly method: HttpMethod;
readonly path: string;
readonly params?: TParams;
readonly query?: TQuery;
readonly body?: TBody;
readonly output: TOutput;
};
export type RouteOutput<R extends RouteContract> = z.infer<R['output']>;
export type RouteBody<R extends RouteContract> = R['body'] extends z.ZodTypeAny
? z.infer<R['body']>
: never;
/** 结构化错误:前端按 code 分辨,不解析文案 */
export const API_ERROR_CODES = [
'unauthenticated',
'forbidden',
'not-found',
'validation-failed',
'conflict',
'precondition-failed',
'internal',
] as const;
export type ApiErrorCode = (typeof API_ERROR_CODES)[number];
export type ApiError = {
readonly code: ApiErrorCode;
readonly message: string;
readonly detail?: unknown;
};
+4
View File
@@ -0,0 +1,4 @@
export * from './http.ts';
export * from './workbench.ts';
export * from './governance.ts';
export * from './ingest.ts';
+41
View File
@@ -0,0 +1,41 @@
/**
* 入站路由契约(编码规范 §8.1)。
*
* 通道入站 → 归属解析 → 统一事件流(OS 06)。MVP 的邮件通道以**模拟通道**接入:
* mock 只允许出现在**外界**(邮件通道与外部系统),系统内部机制不得 mock(README MVP 完成判据)。
*/
import { z } from 'zod';
import type { RouteContract } from './http.ts';
import { channelIdSchema, eventIdSchema } from '../id.ts';
import { ownershipResolutionSchema } from '../envelope.ts';
/** 一封入站邮件的归一形状 —— 真实邮件通道与模拟通道共用 */
export const inboundMailSchema = z.object({
messageId: z.string().min(1),
threadId: z.string().optional(),
from: z.string().min(1),
to: z.array(z.string().min(1)).min(1),
cc: z.array(z.string()).default([]),
subject: z.string(),
body: z.string(),
receivedAt: z.iso.datetime(),
attachments: z
.array(z.object({ name: z.string(), contentType: z.string(), size: z.number().int().min(0), ref: z.string() }))
.default([]),
});
export type InboundMail = z.infer<typeof inboundMailSchema>;
export const ingestMailRoute = {
method: 'POST',
path: '/api/ingest/channel/:channelId/mail',
params: z.object({ channelId: channelIdSchema }),
body: inboundMailSchema,
output: z.object({
eventId: eventIdSchema,
resolution: ownershipResolutionSchema,
/** 三级消费的判定结果:命中的任务监听数 / 命中的触发器数;皆零则入消息兜底 */
listenersHit: z.number().int().min(0),
triggersHit: z.number().int().min(0),
fellBackToMessage: z.boolean(),
}),
} as const satisfies RouteContract;
+23
View File
@@ -0,0 +1,23 @@
/**
* 工作台路由契约(编码规范 §8.1 / §9.1)。
* 工作台五要素:任务 / 审批 / 消息 / 纪要 / 汇报 —— 同一份过程事实的五种投影。
*/
import { z } from 'zod';
import type { RouteContract } from './http.ts';
import { sessionSchema } from '../org.ts';
export const sessionRoute = {
method: 'GET',
path: '/api/session',
output: sessionSchema,
} as const satisfies RouteContract;
export const healthRoute = {
method: 'GET',
path: '/api/health',
output: z.object({
ok: z.boolean(),
version: z.string(),
db: z.enum(['up', 'down']),
}),
} as const satisfies RouteContract;
+492
View File
@@ -0,0 +1,492 @@
/**
* 人类工具的卡协议(编码规范 §8.1 / §9;语义出处 OS 05,AM 06/07)。
*
* **双层边界**:范式(loop / flow / skill)是后端实现逻辑的模型,只存在于引擎层;
* 本文件是**前端呈现协议**,前端永远感知不到范式。旧文「四卡」的映射:
* 执行卡 → 执行工单(work order · execution)
* 放行卡 → 验收(工作区可修订报告 + 对话区验收单)(work order · acceptance)
* 决策 / 补全 → 对话卡(decision / elicitation)
* 落地失败卡 = 执行工单的系统预置形态,不构成第五种卡(OS 7.3)。
*
* 形状以 2026-07-26 原型定稿为准(`~/coding/JCAI_PRD/workbench/_data/model.ts`);
* 枚举值改用英文标识符 + 本文件的 *_LABEL 字典,界面文案由字典给出、与原型逐字一致。
*/
import { z } from 'zod';
import {
cardIdSchema,
deliverableIdSchema,
stageIdSchema,
staffIdSchema,
workOrderIdSchema,
} from './id.ts';
import { acceptanceLevelSchema, rejectionKindSchema } from './terminal.ts';
/* ── 基础原语 ─────────────────────────────────────────────────────────── */
export const TONES = ['ok', 'warn', 'danger', 'brand', 'muted'] as const;
export const toneSchema = z.enum(TONES);
export type Tone = z.infer<typeof toneSchema>;
/** 依据快照:调用必附上下文(OS 05)—— 裸调用基座必须拒发 */
export const basisSchema = z.array(z.object({ k: z.string(), v: z.string() }));
export type Basis = z.infer<typeof basisSchema>;
export const formOptionSchema = z.object({
value: z.string(),
label: z.string(),
negative: z.boolean().optional(),
});
export type FormOption = z.infer<typeof formOptionSchema>;
export const FORM_FIELD_KINDS = [
'text',
'textarea',
'radio',
'number',
'select',
'check',
'date',
'money',
'file',
] as const;
export const formFieldKindSchema = z.enum(FORM_FIELD_KINDS);
export type FormFieldKind = z.infer<typeof formFieldKindSchema>;
/** 表单字段:结构化交互的原子。卡片表单由本 schema 驱动渲染与校验,后端回传校验同 schema(§9.2) */
export const formFieldSchema = z.object({
key: z.string().min(1),
label: z.string(),
kind: formFieldKindSchema,
placeholder: z.string().optional(),
options: z.array(formOptionSchema).optional(),
/** 字段分组(渲染为表单小节) */
group: z.string().optional(),
hint: z.string().optional(),
/** AI 拟值 —— 验收工单落地时已填好,人可改全部字段 */
ai: z.string().optional(),
unit: z.string().optional(),
required: z.boolean().optional(),
cols: z.union([z.literal(1), z.literal(2)]).optional(),
});
export type FormField = z.infer<typeof formFieldSchema>;
/* ── 视图块:视图区的结构化呈现(活动推送,只读) ────────────────────── */
const fileDocSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('markdown'), name: z.string(), md: z.string() }),
z.object({
kind: z.literal('excel'),
name: z.string(),
sheet: z.string(),
rows: z.array(z.array(z.string())),
}),
z.object({
kind: z.literal('word'),
name: z.string(),
blocks: z.array(
z.union([
z.object({ t: z.enum(['h1', 'h2', 'p']), text: z.string() }),
z.object({ t: z.literal('ul'), items: z.array(z.string()) }),
]),
),
}),
z.object({ kind: z.literal('pdf'), name: z.string(), src: z.string() }),
]);
export type FileDoc = z.infer<typeof fileDocSchema>;
export { fileDocSchema };
export const viewBlockSchema = z.discriminatedUnion('t', [
z.object({ t: z.literal('callout'), tone: toneSchema, text: z.string() }),
z.object({
t: z.literal('kv'),
title: z.string().optional(),
items: z.array(
z.object({
k: z.string(),
v: z.string(),
/** 绑定某工作事项的回填字段:未答显示占位,作答后实时落定 */
fromItem: z.object({ item: z.string(), field: z.string() }).optional(),
}),
),
}),
z.object({
t: z.literal('badges'),
title: z.string().optional(),
items: z.array(z.object({ label: z.string(), on: z.boolean() })),
}),
z.object({
t: z.literal('table'),
title: z.string().optional(),
cols: z.array(z.string()),
rows: z.array(z.array(z.string())),
editable: z.boolean().optional(),
editableCols: z.array(z.number().int()).optional(),
linkDonut: z
.object({
col: z.number().int(),
title: z.string().optional(),
unit: z.string().optional(),
map: z.array(z.object({ match: z.string(), label: z.string(), tone: toneSchema })),
})
.optional(),
}),
z.object({
t: z.literal('bars'),
title: z.string().optional(),
max: z.number().optional(),
redline: z.number().optional(),
items: z.array(
z.object({
label: z.string(),
value: z.number(),
text: z.string().optional(),
tone: toneSchema.optional(),
}),
),
}),
z.object({
t: z.literal('donut'),
title: z.string().optional(),
unit: z.string().optional(),
items: z.array(z.object({ label: z.string(), value: z.number(), tone: toneSchema })),
}),
z.object({
t: z.literal('mail'),
dir: z.enum(['in', 'out']),
statusLabel: z.string().optional(),
editable: z.boolean().optional(),
from: z.string(),
fromAddr: z.string().optional(),
to: z.string(),
cc: z.string().optional(),
subject: z.string(),
time: z.string(),
body: z.string(),
attachments: z
.array(z.object({ name: z.string(), meta: z.string().optional(), file: fileDocSchema.optional() }))
.optional(),
}),
z.object({
t: z.literal('cards'),
title: z.string().optional(),
items: z.array(
z.object({
tag: z.string(),
icon: z.string().optional(),
tone: toneSchema.optional(),
title: z.string(),
code: z.string().optional(),
swap: z.object({ from: z.string(), to: z.string(), hint: z.string().optional() }).optional(),
big: z.string(),
bigLabel: z.string().optional(),
meta: z.array(z.object({ k: z.string(), v: z.string() })).optional(),
note: z.string().optional(),
from: z.string().optional(),
time: z.string().optional(),
}),
),
}),
z.object({ t: z.literal('waiting'), label: z.string(), hint: z.string().optional() }),
z.object({
t: z.literal('files'),
title: z.string().optional(),
items: z.array(z.object({ label: z.string(), desc: z.string(), file: fileDocSchema })),
}),
]);
export type ViewBlock = z.infer<typeof viewBlockSchema>;
/* ── 阶段与过程成果 ───────────────────────────────────────────────────── */
/**
* 阶段:交互层的统一进展刻度。
* 引擎层的来源随范式而异(loop = CMMN Stage / 里程碑,flow = 步序位置),前端不感知。
*/
export const stageSchema = z.object({
id: stageIdSchema,
label: z.string(),
round: z.number().int().min(1).optional(),
});
export type Stage = z.infer<typeof stageSchema>;
export const DELIVERABLE_STATES = ['draft', 'pending-acceptance', 'released', 'rejected'] as const;
export const deliverableStateSchema = z.enum(DELIVERABLE_STATES);
export type DeliverableState = z.infer<typeof deliverableStateSchema>;
export const DELIVERABLE_STATE_LABEL: Readonly<Record<DeliverableState, string>> = {
draft: '草稿',
'pending-acceptance': '待验收',
released: '已放行',
rejected: '已驳回',
};
/** 过程成果:每个成果都要经验收放行才落地(放行门,OS 09) */
export const deliverableSchema = z.object({
id: deliverableIdSchema,
stage: stageIdSchema,
round: z.number().int().min(1).optional(),
title: z.string(),
desc: z.string().optional(),
blocks: z.array(viewBlockSchema),
state: deliverableStateSchema,
at: z.string().optional(),
});
export type Deliverable = z.infer<typeof deliverableSchema>;
/* ── 工单两模式(执行 / 验收) ────────────────────────────────────────── */
export const WORK_ORDER_MODES = ['execution', 'acceptance'] as const;
export const workOrderModeSchema = z.enum(WORK_ORDER_MODES);
export type WorkOrderMode = z.infer<typeof workOrderModeSchema>;
export const WORK_ORDER_MODE_LABEL: Readonly<Record<WorkOrderMode, string>> = {
execution: '执行',
acceptance: '验收',
};
/** 完成回传:谁、何时、答了什么(回传即留痕) */
export const workDoneSchema = z.object({
at: z.iso.datetime(),
by: staffIdSchema,
result: z.string(),
values: z.record(z.string(), z.string()).optional(),
});
export type WorkDone = z.infer<typeof workDoneSchema>;
const workOrderBase = {
id: workOrderIdSchema,
at: z.iso.datetime(),
title: z.string(),
/** 调用必附上下文 —— basis 为空的工单基座必须拒发 */
basis: basisSchema,
stage: stageIdSchema.optional(),
done: workDoneSchema.optional(),
};
/** 执行工单:作业指导书 + 空表单(补全并入此类);落地失败卡是它的系统预置形态 */
export const executionWorkOrderSchema = z.object({
...workOrderBase,
mode: z.literal('execution'),
/** 系统预置形态标记:landing-failure = 落地失败卡(OS 7.3) */
preset: z.enum(['landing-failure']).optional(),
ask: z.string(),
standard: z.string().optional(),
steps: z.array(z.string()).optional(),
/** 报告正文取自哪份过程成果 —— 人要在数据上作判断,数据就得摆在表单旁边 */
basedOn: deliverableIdSchema.optional(),
blocks: z.array(viewBlockSchema).optional(),
fields: z.array(formFieldSchema),
submitLabel: z.string().optional(),
});
export type ExecutionWorkOrder = z.infer<typeof executionWorkOrderSchema>;
export const acceptanceCriterionCheckSchema = z.object({
label: z.string(),
level: acceptanceLevelSchema,
pass: z.boolean(),
});
export type AcceptanceCriterionCheck = z.infer<typeof acceptanceCriterionCheckSchema>;
/** 待落地动作意向:预检全过才上卡,卡面呈现的即已验证的动作清单(OS 7.3) */
export const actionIntentViewSchema = z.object({
label: z.string(),
effect: z.enum(['read', 'write']),
detail: z.string(),
});
export type ActionIntentView = z.infer<typeof actionIntentViewSchema>;
export const ACTION_EFFECT_LABEL: Readonly<Record<'read' | 'write', string>> = {
read: '读',
write: '写',
};
/** 验收工单:AI 拟好的可修订报告 + 判据逐条核对 + 放行三选一 */
export const acceptanceWorkOrderSchema = z.object({
...workOrderBase,
mode: z.literal('acceptance'),
deliverable: deliverableIdSchema,
criteria: z.array(acceptanceCriterionCheckSchema),
actions: z.array(actionIntentViewSchema).optional(),
/** 报告可修订:字段随成果 schema 渲染,AI 拟值已填 */
fields: z.array(formFieldSchema).default([]),
passLabel: z.string().optional(),
});
export type AcceptanceWorkOrder = z.infer<typeof acceptanceWorkOrderSchema>;
export const workOrderSchema = z.discriminatedUnion('mode', [
executionWorkOrderSchema,
acceptanceWorkOrderSchema,
]);
export type WorkOrder = z.infer<typeof workOrderSchema>;
/* ── 对话卡族(决策 / 补全 / 评价) ──────────────────────────────────── */
/** AI 发言的类型标记 —— 对话区可分辨:结论 / 指导 / 判据 */
export const AI_TAGS = ['conclusion', 'guidance', 'criterion'] as const;
export const aiTagSchema = z.enum(AI_TAGS);
export type AiTag = z.infer<typeof aiTagSchema>;
export const AI_TAG_LABEL: Readonly<Record<AiTag, string>> = {
conclusion: '结论',
guidance: '指导',
criterion: '判据',
};
const chatBase = { id: cardIdSchema, at: z.iso.datetime() };
/** 决策卡:分支条件选择表;含自定义收尾项 */
export const decisionCardSchema = z.object({
...chatBase,
k: z.literal('decision'),
ask: z.string(),
basis: basisSchema,
recommend: z.string().optional(),
options: z.array(
z.object({
value: z.string(),
label: z.string(),
detail: z.string().optional(),
consequence: z.string().optional(),
recommended: z.boolean().optional(),
}),
),
/** 自定义收尾项:人可给出选项之外的处置(附理由) */
allowCustom: z.boolean().default(false),
chosen: z
.object({
value: z.string(),
at: z.iso.datetime(),
by: staffIdSchema,
note: z.string().optional(),
})
.optional(),
});
export type DecisionCard = z.infer<typeof decisionCardSchema>;
/** 补全卡:就地要几个小信息;含「没法填」旁路 —— 两条路必走其一 */
export const elicitationCardSchema = z.object({
...chatBase,
k: z.literal('elicitation'),
ask: z.string(),
basis: basisSchema.optional(),
fields: z.array(
z.object({ key: z.string(), label: z.string(), placeholder: z.string().optional() }),
),
done: z
.object({
at: z.iso.datetime(),
by: staffIdSchema,
values: z.record(z.string(), z.string()),
/** 没法填的理由 —— 人让 AI 迭代一轮需求 */
reason: z.string().optional(),
})
.optional(),
});
export type ElicitationCard = z.infer<typeof elicitationCardSchema>;
/** 评价卡:任务评价(评分 1–5 + 改进建议) */
export const ratingCardSchema = z.object({
...chatBase,
k: z.literal('rating'),
ask: z.string(),
basis: basisSchema.optional(),
done: z
.object({
at: z.iso.datetime(),
by: staffIdSchema,
score: z.number().int().min(1).max(5),
note: z.string().optional(),
})
.optional(),
});
export type RatingCard = z.infer<typeof ratingCardSchema>;
export const chatCardSchema = z.discriminatedUnion('k', [
decisionCardSchema,
elicitationCardSchema,
ratingCardSchema,
]);
export type ChatCard = z.infer<typeof chatCardSchema>;
/* ── 对话流消息 ───────────────────────────────────────────────────────── */
export const chatMessageSchema = z.discriminatedUnion('k', [
z.object({
...chatBase,
k: z.literal('ai'),
text: z.string(),
tag: aiTagSchema.optional(),
/** 指涉的工单 id —— 对话区点击即让视图区定位到那张工单 */
ref: workOrderIdSchema.optional(),
}),
z.object({ ...chatBase, k: z.literal('human'), text: z.string(), by: staffIdSchema }),
z.object({
...chatBase,
k: z.literal('system'),
type: z.enum(['data', 'time', 'human', 'control']),
text: z.string(),
}),
decisionCardSchema,
elicitationCardSchema,
ratingCardSchema,
]);
export type ChatMessage = z.infer<typeof chatMessageSchema>;
/* ── 回传协议(前端 → 后端;后端以同一 schema 校验,§9.2) ───────────── */
export const workOrderReplySchema = z.discriminatedUnion('mode', [
z.object({
mode: z.literal('execution'),
workOrderId: workOrderIdSchema,
values: z.record(z.string(), z.string()),
}),
z.object({
mode: z.literal('acceptance'),
workOrderId: workOrderIdSchema,
/** 三选一:放行通过 / 驳回重做 / 驳回迭代 —— 驳回必附意见 */
verdict: z.union([z.literal('pass'), rejectionKindSchema]),
/** 报告的人工修订(可空 = 全盘采信 AI 拟值) */
values: z.record(z.string(), z.string()).default({}),
comment: z.string().optional(),
/** 选择组的出口选择:恰发一口,随放行一并确认(AM 1.2) */
selectedPorts: z.record(z.string(), z.string()).default({}),
}),
]);
export type WorkOrderReply = z.infer<typeof workOrderReplySchema>;
export const chatCardReplySchema = z.discriminatedUnion('k', [
z.object({
k: z.literal('decision'),
cardId: cardIdSchema,
value: z.string(),
note: z.string().optional(),
}),
z.object({
k: z.literal('elicitation'),
cardId: cardIdSchema,
values: z.record(z.string(), z.string()).default({}),
/** 「没法填」旁路 */
reason: z.string().optional(),
}),
z.object({
k: z.literal('rating'),
cardId: cardIdSchema,
score: z.number().int().min(1).max(5),
note: z.string().optional(),
}),
]);
export type ChatCardReply = z.infer<typeof chatCardReplySchema>;
/**
* 驳回必附意见 —— 三规矩之一的机检形态(OS 05)。
* 后端回传校验与前端提交校验共用本函数。
*/
export function rejectionNeedsComment(reply: WorkOrderReply): boolean {
return reply.mode === 'acceptance' && reply.verdict !== 'pass' && !reply.comment?.trim();
}
/** 补全卡两条路必走其一:要么填值,要么给「没法填」的理由 */
export function elicitationReplyIsEmpty(reply: ChatCardReply): boolean {
if (reply.k !== 'elicitation') return false;
const hasValue = Object.values(reply.values).some((v) => v.trim() !== '');
return !hasValue && !reply.reason?.trim();
}
+180
View File
@@ -0,0 +1,180 @@
/**
* 契约七件(编码规范 §8.1;语义出处 OS 4.1,AM 01)。
*
* 契约是活动对调用方暴露的全部真相,也是对 Agent 机制的全部授权;
* 两种范式同一契约格式 —— 这是「统一套执行契约」的锚点。
* 契约必须在活动启动前冻结;运行中不得变更 —— 变更即新版本。
*
* ADR-003:**声明层 = JSON Schema 2020-12 子集**(活动声明是运行时数据,可 diff 可版本),
* 代码层 = zod。本文件用 zod 描述「声明的形状」,声明里的 schema 字段本身是 JSON Schema。
*/
import { z } from 'zod';
import { acceptanceLevelSchema } from './terminal.ts';
import { activityIdSchema, skillIdSchema } from './id.ts';
/** JSON Schema 2020-12 子集的运行时形态 —— 由 ajv 校验,不在编译期展开 */
export const jsonSchemaSchema = z.record(z.string(), z.unknown());
export type JsonSchema = z.infer<typeof jsonSchemaSchema>;
/* ── ① 输入口:单一入口,data + message ──────────────────────────────── */
export const contractInputSchema = z.object({
/** data:结构化载荷,按 schema 校验,缺项不得启动 */
data: jsonSchemaSchema,
/** message:委托消息(自然语言),可为空;**不得携带扩大授权的效力** */
messageAllowed: z.boolean().default(true),
messageHint: z.string().optional(),
});
export type ContractInput = z.infer<typeof contractInputSchema>;
/* ── ② 输出口:必发(AND)与选择组(XOR) ──────────────────────────── */
export const outputPortSchema = z.object({
name: z.string().min(1),
/** 交付物 schema —— 调用方仅凭口名与 schema 即可衔接下游 */
payload: jsonSchemaSchema,
description: z.string().optional(),
});
export type OutputPort = z.infer<typeof outputPortSchema>;
export const outputPortsSchema = z.object({
/** 必发口:每次「放行完成」必发;可多口,同时发射 */
mandatory: z.array(outputPortSchema).default([]),
/** 选择组:组内恰发一口;选择由环内决断,在放行(验收工单)上一并确认 */
selective: z
.array(
z.object({
group: z.string().min(1),
ports: z.array(outputPortSchema).min(2),
}),
)
.default([]),
});
export type OutputPorts = z.infer<typeof outputPortsSchema>;
/* ── ③ 必交付物 ─────────────────────────────────────────────────────── */
export const requiredDeliverableSchema = z.object({
key: z.string().min(1),
label: z.string(),
/** 缺一不得提交放行 —— 验收工单「成果清单」的来源 */
schema: jsonSchemaSchema.optional(),
});
export type RequiredDeliverable = z.infer<typeof requiredDeliverableSchema>;
/* ── ④ 验收判据:逐条标注真实等级 L1–L5 ───────────────────────────── */
export const acceptanceCriterionSchema = z.object({
key: z.string().min(1),
label: z.string(),
level: acceptanceLevelSchema,
/** L1/L2 的机检表达式(S-FEEL);L3–L5 由环内实证 / 独立评审 / 人放行承担 */
predicate: z.string().optional(),
/** loop 可引用业务模型的完成判据或 DMN 决策 */
modelRef: z.string().optional(),
});
export type AcceptanceCriterion = z.infer<typeof acceptanceCriterionSchema>;
/* ── ⑤ 禁区 ─────────────────────────────────────────────────────────── */
export const prohibitionSchema = z.object({
key: z.string().min(1),
/** 应短而硬;负面清单优于正面枚举 */
statement: z.string().min(1),
});
export type Prohibition = z.infer<typeof prohibitionSchema>;
/* ── ⑥ 授权边界 ─────────────────────────────────────────────────────── */
export const authorizationBoundarySchema = z.object({
/** AI 可自决的范围:金额 / 折扣 / 措辞等,以 S-FEEL 谓词或叙述给出 */
discretion: z.array(z.object({ key: z.string(), statement: z.string() })).default([]),
/** 预授权动作清单 —— 必须逐项列举,方可在过程中即时执行写类动作(OS 7.3) */
preauthorizedActions: z
.array(z.object({ tool: z.string(), operation: z.string(), limit: z.string().optional() }))
.default([]),
/** 调人预算(打扰上限) */
humanCallBudget: z.number().int().min(0),
});
export type AuthorizationBoundary = z.infer<typeof authorizationBoundarySchema>;
/* ── ⑦ 资源声明 ─────────────────────────────────────────────────────── */
/** 预算四类上限 —— 由基座在环外强制,不得由活动代码自查自守(AM 10.1) */
export const budgetCapsSchema = z.object({
steps: z.number().int().min(1),
tokens: z.number().int().min(1),
/** 活跃时长(分钟);挂起、监听等待、待卡回传不计入 */
activeMinutes: z.number().int().min(1),
humanCalls: z.number().int().min(0),
});
export type BudgetCaps = z.infer<typeof budgetCapsSchema>;
export const resourceDeclarationSchema = z.object({
/** 工具调用契约引用 + 版本约束 */
tools: z
.array(z.object({ name: z.string().min(1), version: z.string().optional() }))
.default([]),
skills: z.array(skillIdSchema).default([]),
/** 活动使用的 LLM,以自定义模型名(逻辑名)声明;活动不触厂商与密钥 */
models: z.array(z.string().min(1)).default([]),
/** 岗位:调人时卡投递到哪个工位 */
roles: z.array(z.string().min(1)).default([]),
budget: budgetCapsSchema,
});
export type ResourceDeclaration = z.infer<typeof resourceDeclarationSchema>;
/* ── 七件合体 ───────────────────────────────────────────────────────── */
export const sevenPartContractSchema = z.object({
activityId: activityIdSchema,
version: z.string().min(1),
input: contractInputSchema,
output: outputPortsSchema,
requiredDeliverables: z.array(requiredDeliverableSchema).default([]),
acceptanceCriteria: z.array(acceptanceCriterionSchema).default([]),
prohibitions: z.array(prohibitionSchema).default([]),
authorization: authorizationBoundarySchema,
resources: resourceDeclarationSchema,
});
export type SevenPartContract = z.infer<typeof sevenPartContractSchema>;
/**
* 完成时的发射集合 = 全部必发口 + 每个选择组各一口(AM 1.2)。
* 纯函数,前后端同源:前端预演、后端裁决。
*/
export function emissionPortNames(
ports: OutputPorts,
selected: Readonly<Record<string, string>>,
): string[] {
const out = ports.mandatory.map((p) => p.name);
for (const group of ports.selective) {
const choice = selected[group.group];
if (choice !== undefined) out.push(choice);
}
return out;
}
/** 选择组必须恰选一口 —— 未选或选了组外的口即非法 */
export function validateSelection(
ports: OutputPorts,
selected: Readonly<Record<string, string>>,
): string[] {
const errors: string[] = [];
for (const group of ports.selective) {
const choice = selected[group.group];
if (choice === undefined) {
errors.push(`选择组「${group.group}」未选出口`);
continue;
}
if (!group.ports.some((p) => p.name === choice)) {
errors.push(`选择组「${group.group}」的出口「${choice}」不在组内`);
}
}
return errors;
}
/** 验收等级不得谎报:L4 不得标注为 L1–L3;生成者不得自评(AM 12.1) */
export function machineCheckable(criterion: AcceptanceCriterion): boolean {
return criterion.level === 'L1' || criterion.level === 'L2';
}
+222
View File
@@ -0,0 +1,222 @@
/**
* 统一事件标准(编码规范 §8.1;语义出处 OS 06)。
*
* 系统向活动只以统一信封抛四类事件;一条事件流,三级消费(任务监听 / 触发器 / 消息)。
* 投递五诺(先持久后投递 / 同任务按序 / 至少一次 + 幂等 / 处理有回执 / 扇出与幂等)
* 是 `event` 模块的实现承诺,不在本文件表达 —— 本文件只定信封的形状。
*/
import { z } from 'zod';
import {
channelIdSchema,
deliveryIdSchema,
eventIdSchema,
listenerIdSchema,
positionIdSchema,
taskIdSchema,
triggerIdSchema,
workflowIdSchema,
} from './id.ts';
import { controlSemanticSchema } from './terminal.ts';
/* ── 四类事件 ─────────────────────────────────────────────────────────── */
export const EVENT_TYPES = ['data', 'time', 'human', 'control'] as const;
export const eventTypeSchema = z.enum(EVENT_TYPES);
export type EventType = z.infer<typeof eventTypeSchema>;
export const EVENT_TYPE_LABEL: Readonly<Record<EventType, string>> = {
data: '数据',
time: '时间',
human: '人',
control: '控制',
};
/* ── 关联:消费目标 + 起因 ────────────────────────────────────────────── */
/** 消费目标四类(OS 6.1):任务 / 触发器 / 工作流 / 消息收件岗位 */
export const eventTargetSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('task'), id: taskIdSchema }),
z.object({ kind: z.literal('trigger'), id: triggerIdSchema }),
z.object({ kind: z.literal('workflow'), id: workflowIdSchema }),
z.object({ kind: z.literal('message-position'), id: positionIdSchema }),
]);
export type EventTarget = z.infer<typeof eventTargetSchema>;
/** 起因:数据对象 / 卡 ID / 定时器 ID —— 「这条事件是被什么激起的」 */
export const eventCauseSchema = z.object({
kind: z.enum(['ledger-write', 'card-reply', 'timer', 'inbound', 'governance', 'engine']),
ref: z.string().min(1),
});
export type EventCause = z.infer<typeof eventCauseSchema>;
/* ── 来源 ─────────────────────────────────────────────────────────────── */
export const EVENT_SOURCES = ['channel', 'engine', 'desk', 'governance'] as const;
export const eventSourceKindSchema = z.enum(EVENT_SOURCES);
export type EventSourceKind = z.infer<typeof eventSourceKindSchema>;
export const eventSourceSchema = z.object({
kind: eventSourceKindSchema,
/** 通道来源必带通道实例 ID */
channelId: channelIdSchema.optional(),
detail: z.string().optional(),
});
export type EventSource = z.infer<typeof eventSourceSchema>;
/* ── 载荷 ─────────────────────────────────────────────────────────────── */
/** 载荷:schema 化内容 + 原件指针(如邮件原文的存档地址) */
export const eventPayloadSchema = z.object({
data: z.record(z.string(), z.unknown()),
/** 原件指针 —— 存档地址,不是内容本身 */
originRef: z.string().optional(),
});
export type EventPayload = z.infer<typeof eventPayloadSchema>;
/* ── 信封六字段 ───────────────────────────────────────────────────────── */
export const envelopeSchema = z.object({
/** ① 事件 ID —— 全局唯一,幂等键 */
id: eventIdSchema,
/** ② 类型 —— 四类之一 */
type: eventTypeSchema,
/**
* ③ 关联 —— 消费目标 + 起因。
*
* `target` 可空:存储态的事件未必知道自己该被谁消费(归属解析与三级消费判定在后)。
* **投递态**的单目标由 `Delivery.target` 承载 —— 「信封关联 = 单目标」的承诺(OS 6.3 扇出)
* 在投递记录上成立,存储的原始事件只有一份。
*/
correlation: z.object({
target: eventTargetSchema.optional(),
cause: eventCauseSchema,
/** 关联键:归属解析与监听过滤的匹配面(单号、线程 ID、域.对象 主键…) */
keys: z.record(z.string(), z.string()).default({}),
}),
/** ④ 载荷 */
payload: eventPayloadSchema,
/** ⑤ 时间与来源 */
occurredAt: z.iso.datetime(),
source: eventSourceSchema,
/** ⑥ 留痕指针 —— 事件存储位置;投递入任务后另记任务记忆指针 */
trace: z.object({
storeRef: z.string().min(1),
taskMemoryRef: z.string().optional(),
}),
});
export type Envelope = z.infer<typeof envelopeSchema>;
/**
* 尚未落存储的信封草稿 —— `publish` 的入参。
*
* `target` 在此**可空**:原始事件未必知道自己该被谁消费。归属解析(6.2)与三级消费判定
* (任务监听 / 触发器 / 消息兜底,6.3)由 `event` 模块完成,并为每个命中目标生成一份
* 独立投递 —— 投递出去的信封「关联 = 单目标」,这正是扇出与幂等承诺的形态。
* `storeRef` 由 event adapter 落库时补。
*/
export const envelopeDraftSchema = envelopeSchema
.omit({ id: true, trace: true })
.extend({ id: eventIdSchema.optional() });
export type EnvelopeDraft = z.infer<typeof envelopeDraftSchema>;
/* ── 四类事件的载荷细化 ──────────────────────────────────────────────── */
/** 控制事件载荷:三语义 + 发起人 */
export const controlPayloadSchema = z.object({
semantic: controlSemanticSchema,
reason: z.string().optional(),
issuedBy: z.string().min(1),
});
export type ControlPayload = z.infer<typeof controlPayloadSchema>;
/** 时间事件载荷:哪个监听 / 定时器到点 */
export const timePayloadSchema = z.object({
listenerId: listenerIdSchema.optional(),
timerRef: z.string().min(1),
/** 时限阶梯:提醒 → 升级(OS 03 催办阶梯) */
escalation: z.enum(['nudge', 'reroute', 'escalate']).optional(),
});
export type TimePayload = z.infer<typeof timePayloadSchema>;
/** 数据事件载荷:域.对象.主键 的正式版写入 —— 草稿写不抛事件(OS 09) */
export const dataPayloadSchema = z.object({
domain: z.string().min(1),
object: z.string().min(1),
primaryKey: z.record(z.string(), z.union([z.string(), z.number()])),
changed: z.array(z.string()).default([]),
operation: z.enum(['insert', 'update', 'delete']),
});
export type DataPayload = z.infer<typeof dataPayloadSchema>;
/* ── 监听声明(OS 6.3 / AM 4.4) ─────────────────────────────────────── */
/**
* 处理语义:loop 事件即观察 / flow 事件即步的完成条件。
* 这是**引擎层**的区分,交互层不可见(编码规范 §9 双层边界)。
*/
export const LISTENER_SEMANTICS = ['observe', 'complete-step'] as const;
export const listenerSemanticSchema = z.enum(LISTENER_SEMANTICS);
export type ListenerSemantic = z.infer<typeof listenerSemanticSchema>;
export const listenerSpecSchema = z.object({
/** 静态(随业务模型)/ 动态(运行中由 Agent 机制临场登记) */
origin: z.enum(['static', 'dynamic']),
eventType: eventTypeSchema,
/** 关联键过滤 —— 「凭什么认出就是它」 */
keyFilter: z.record(z.string(), z.string()).default({}),
/** 内容条件:S-FEEL 表达式,对信封与载荷字段求值 */
condition: z.string().optional(),
semantic: listenerSemanticSchema,
/**
* 时限必配 —— 无来源又无时限的监听是「幽灵等待」,安装静态审必须拒绝(AM 4.4)。
* ISO-8601 duration,如 P3D。
*/
deadline: z.string().min(2),
/** 到期动作阶梯:提醒 → 换道 → 升级 */
escalation: z.array(z.enum(['nudge', 'reroute', 'escalate'])).default(['nudge', 'escalate']),
});
export type ListenerSpec = z.infer<typeof listenerSpecSchema>;
export const registeredListenerSchema = listenerSpecSchema.extend({
id: listenerIdSchema,
taskId: taskIdSchema,
registeredAt: z.iso.datetime(),
expiresAt: z.iso.datetime(),
state: z.enum(['armed', 'fired', 'expired', 'cancelled']),
});
export type RegisteredListener = z.infer<typeof registeredListenerSchema>;
/* ── 投递记录 ─────────────────────────────────────────────────────────── */
export const deliverySchema = z.object({
id: deliveryIdSchema,
eventId: eventIdSchema,
target: eventTargetSchema,
attempt: z.number().int().min(1),
state: z.enum(['pending', 'delivered', 'failed', 'dead-letter']),
lastError: z.string().optional(),
});
export type Delivery = z.infer<typeof deliverySchema>;
/* ── 归属解析(OS 6.2) ──────────────────────────────────────────────── */
/** 匹配次序确定、逐级短路:① 线程精确 ② 关联键命中监听 ③ 地址 + 时间窗 */
export const OWNERSHIP_RULES = ['thread', 'listener-key', 'address-window'] as const;
export const ownershipRuleSchema = z.enum(OWNERSHIP_RULES);
export type OwnershipRule = z.infer<typeof ownershipRuleSchema>;
export const ownershipResolutionSchema = z.discriminatedUnion('outcome', [
z.object({
outcome: z.literal('owned'),
rule: ownershipRuleSchema,
taskId: taskIdSchema,
}),
z.object({
outcome: z.literal('unowned'),
/** 宁交人,不错投 —— 歧义与提取失败一律降级为无主 */
reason: z.enum(['no-match', 'ambiguous', 'extract-failed']),
/** 无主入站的相关人 = 通道实例配置的默认认领岗位 */
fallbackPosition: positionIdSchema.optional(),
}),
]);
export type OwnershipResolution = z.infer<typeof ownershipResolutionSchema>;
+93
View File
@@ -0,0 +1,93 @@
/**
* 品牌 ID(编码规范 §8.1)。
*
* 每一类 ID 有自己的名义类型 —— TaskId 传不进要 WorkflowId 的位置,编译期就拦下。
* 运行时形态一律是非空字符串;生成归 adapter(clock / uuid 走 port,domain 零随机)。
*/
import { z } from 'zod';
function brandedId<B extends string>(_brand: B, label: string) {
return z
.string()
.min(1, `${label}不得为空`)
.max(128, `${label}过长`)
.brand<B>();
}
/* ── 组织 ─────────────────────────────────────────────────────────────── */
export const staffIdSchema = brandedId('StaffId', '员工 ID');
export type StaffId = z.infer<typeof staffIdSchema>;
export const positionIdSchema = brandedId('PositionId', '岗位 ID');
export type PositionId = z.infer<typeof positionIdSchema>;
/* ── 流程层 ───────────────────────────────────────────────────────────── */
export const processPackageIdSchema = brandedId('ProcessPackageId', '流程包 ID');
export type ProcessPackageId = z.infer<typeof processPackageIdSchema>;
export const workflowIdSchema = brandedId('WorkflowId', '工作流 ID');
export type WorkflowId = z.infer<typeof workflowIdSchema>;
export const nodeIdSchema = brandedId('NodeId', '节点 ID');
export type NodeId = z.infer<typeof nodeIdSchema>;
export const triggerIdSchema = brandedId('TriggerId', '触发器 ID');
export type TriggerId = z.infer<typeof triggerIdSchema>;
export const approvalIdSchema = brandedId('ApprovalId', '审批单 ID');
export type ApprovalId = z.infer<typeof approvalIdSchema>;
/* ── 活动与任务 ───────────────────────────────────────────────────────── */
export const activityIdSchema = brandedId('ActivityId', '活动 ID');
export type ActivityId = z.infer<typeof activityIdSchema>;
export const taskIdSchema = brandedId('TaskId', '任务 ID');
export type TaskId = z.infer<typeof taskIdSchema>;
export const deliverableIdSchema = brandedId('DeliverableId', '过程成果 ID');
export type DeliverableId = z.infer<typeof deliverableIdSchema>;
export const stageIdSchema = brandedId('StageId', '阶段 ID');
export type StageId = z.infer<typeof stageIdSchema>;
/* ── 人类工具 ─────────────────────────────────────────────────────────── */
export const cardIdSchema = brandedId('CardId', '卡 ID');
export type CardId = z.infer<typeof cardIdSchema>;
export const workOrderIdSchema = brandedId('WorkOrderId', '工单 ID');
export type WorkOrderId = z.infer<typeof workOrderIdSchema>;
/* ── 事件 ─────────────────────────────────────────────────────────────── */
export const eventIdSchema = brandedId('EventId', '事件 ID');
export type EventId = z.infer<typeof eventIdSchema>;
export const deliveryIdSchema = brandedId('DeliveryId', '投递 ID');
export type DeliveryId = z.infer<typeof deliveryIdSchema>;
export const listenerIdSchema = brandedId('ListenerId', '监听 ID');
export type ListenerId = z.infer<typeof listenerIdSchema>;
export const messageIdSchema = brandedId('MessageId', '消息 ID');
export type MessageId = z.infer<typeof messageIdSchema>;
/* ── 调用层与基座 ─────────────────────────────────────────────────────── */
export const toolIdSchema = brandedId('ToolId', '工具 ID');
export type ToolId = z.infer<typeof toolIdSchema>;
export const llmInstanceIdSchema = brandedId('LlmInstanceId', 'LLM 实例 ID');
export type LlmInstanceId = z.infer<typeof llmInstanceIdSchema>;
export const channelIdSchema = brandedId('ChannelId', '通道实例 ID');
export type ChannelId = z.infer<typeof channelIdSchema>;
export const skillIdSchema = brandedId('SkillId', '技能 ID');
export type SkillId = z.infer<typeof skillIdSchema>;
export const memoryEntryIdSchema = brandedId('MemoryEntryId', '记忆条目 ID');
export type MemoryEntryId = z.infer<typeof memoryEntryIdSchema>;
export const actionIntentIdSchema = brandedId('ActionIntentId', '动作意向 ID');
export type ActionIntentId = z.infer<typeof actionIntentIdSchema>;
export const minuteIdSchema = brandedId('MinuteId', '纪要 ID');
export type MinuteId = z.infer<typeof minuteIdSchema>;
+12 -1
View File
@@ -3,4 +3,15 @@
* 只有 zod schema、常量、品牌类型与推导类型,零实现。
* 修改本包任何导出 = 契约变更(§12.4)。
*/
export const CONTRACTS_VERSION = '0.0.0-m0';
export const CONTRACTS_VERSION = '0.1.0-m1';
export * from './id.ts';
export * from './terminal.ts';
export * from './envelope.ts';
export * from './card.ts';
export * from './contract7.ts';
export * from './ledger.ts';
export * from './process-package.ts';
export * from './manifest.ts';
export * from './org.ts';
export * from './api/index.ts';
+192
View File
@@ -0,0 +1,192 @@
/**
* 数据与台账(编码规范 §8.1 / §7.2;语义出处 OS 04 / 09,AM 10.3 / 11.1)。
*
* 三级寻址「数据域.数据对象.字段」+ 通用事务性接口 + 写三分(系统写 / 草稿写 / 放行写)。
* 写三分是 `ledger` 出口上的**三个不同方法**,不是一个带 flag 的方法 —— 调用方拿不到「绕门」的形态。
*/
import { z } from 'zod';
import { taskIdSchema } from './id.ts';
/* ── 三级寻址 ─────────────────────────────────────────────────────────── */
const identifier = z
.string()
.min(1)
.max(63)
.regex(/^[a-z][a-z0-9_]*$/, '标识符只准小写字母开头、字母数字下划线');
/**
* 数据域:活动自持域用活动名,共享域固定为 `shared`(AM 11.3 暗耦合禁令)。
* 活动间不得共享自持域的数据表;跨活动的事实只有两条路 —— 输出口载荷,或共享域。
*/
export const SHARED_DOMAIN = 'shared';
export const ledgerAddressSchema = z.object({
domain: identifier,
object: identifier,
field: identifier.optional(),
});
export type LedgerAddress = z.infer<typeof ledgerAddressSchema>;
export function formatAddress(address: LedgerAddress): string {
return address.field === undefined
? `${address.domain}.${address.object}`
: `${address.domain}.${address.object}.${address.field}`;
}
export function parseAddress(text: string): LedgerAddress {
const parts = text.split('.');
if (parts.length < 2 || parts.length > 3) throw new Error(`非法台账地址:${text}`);
const [domain, object, field] = parts;
return ledgerAddressSchema.parse(field === undefined ? { domain, object } : { domain, object, field });
}
export function isSharedDomain(address: LedgerAddress): boolean {
return address.domain === SHARED_DOMAIN;
}
/* ── 字段声明与自生长 ────────────────────────────────────────────────── */
/**
* 字段类型 —— 台账自生长的类型格。
* 「同名异型取能兼容双方的最宽类型」(放宽即增,不破坏);语义互斥才拦下(OS 04)。
*/
export const LEDGER_FIELD_TYPES = ['text', 'number', 'integer', 'boolean', 'date', 'timestamp', 'json'] as const;
export const ledgerFieldTypeSchema = z.enum(LEDGER_FIELD_TYPES);
export type LedgerFieldType = z.infer<typeof ledgerFieldTypeSchema>;
/** 字段使用声明 —— 声明的是**活动要用什么字段**,不是对象该定义什么字段 */
export const fieldDeclarationSchema = z.object({
name: identifier,
type: ledgerFieldTypeSchema,
label: z.string().optional(),
/** 主键参与:对象的主键由声明的最大化合并决定 */
primaryKey: z.boolean().default(false),
/** 治理:脱敏 / 保留期 / 可学习标记(OS 8.1 治理先行) */
masked: z.boolean().default(false),
});
export type FieldDeclaration = z.infer<typeof fieldDeclarationSchema>;
export const objectDeclarationSchema = z.object({
domain: identifier,
object: identifier,
label: z.string().optional(),
fields: z.array(fieldDeclarationSchema).min(1),
});
export type ObjectDeclaration = z.infer<typeof objectDeclarationSchema>;
/* ── 通用事务接口 DTO ────────────────────────────────────────────────── */
export const ledgerRowSchema = z.record(z.string(), z.unknown());
export type LedgerRow = z.infer<typeof ledgerRowSchema>;
export const ledgerKeySchema = z.record(z.string(), z.union([z.string(), z.number()]));
export type LedgerKey = z.infer<typeof ledgerKeySchema>;
export const LEDGER_OPERATIONS = ['insert', 'update', 'upsert', 'delete'] as const;
export const ledgerOperationSchema = z.enum(LEDGER_OPERATIONS);
export type LedgerOperation = z.infer<typeof ledgerOperationSchema>;
export const ledgerMutationSchema = z.object({
address: ledgerAddressSchema.omit({ field: true }),
operation: ledgerOperationSchema,
key: ledgerKeySchema,
values: ledgerRowSchema.default({}),
});
export type LedgerMutation = z.infer<typeof ledgerMutationSchema>;
/** 查询:简单等值过滤 + 排序 + 分页(治理台数据管理的记录浏览也走这里) */
export const ledgerQuerySchema = z.object({
address: ledgerAddressSchema.omit({ field: true }),
where: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()])).default({}),
orderBy: z.array(z.object({ field: identifier, dir: z.enum(['asc', 'desc']) })).default([]),
limit: z.number().int().min(1).max(500).default(50),
offset: z.number().int().min(0).default(0),
});
export type LedgerQuery = z.infer<typeof ledgerQuerySchema>;
export const ledgerPageSchema = z.object({
rows: z.array(ledgerRowSchema),
total: z.number().int().min(0),
});
export type LedgerPage = z.infer<typeof ledgerPageSchema>;
/* ── 写三分(OS 09) ────────────────────────────────────────────────── */
/**
* ① system —— 系统写:入站归一、流转记录、留痕。登记世界已发生的事实,不过放行门,
* 写入正式版并**即时产生数据事件**。
* ② draft —— 草稿写:任务级草稿层(读己之写:本任务可见、正式版不可见、**不产生数据事件**)。
* ③ release —— 放行写:草稿层合并入正式版,**此刻才产生数据事件**。
*/
export const WRITE_KINDS = ['system', 'draft', 'release'] as const;
export const writeKindSchema = z.enum(WRITE_KINDS);
export type WriteKind = z.infer<typeof writeKindSchema>;
export const WRITE_KIND_LABEL: Readonly<Record<WriteKind, string>> = {
system: '系统写',
draft: '草稿写',
release: '放行写',
};
/** 三分的不变量,机检用:只有 draft 不抛数据事件 */
export function emitsDataEvent(kind: WriteKind): boolean {
return kind !== 'draft';
}
/* ── 任务视图与草稿层 ────────────────────────────────────────────────── */
/** 任务视图 = 正式版 + 本任务草稿层;环内推进读它,不依赖事件(OS 09) */
export const taskViewRequestSchema = z.object({
taskId: taskIdSchema,
query: ledgerQuerySchema,
});
export type TaskViewRequest = z.infer<typeof taskViewRequestSchema>;
export const draftPatchSchema = z.object({
taskId: taskIdSchema,
address: ledgerAddressSchema.omit({ field: true }),
key: ledgerKeySchema,
patch: ledgerRowSchema,
/** 草稿删除:合并时物理删除正式版行 */
tombstone: z.boolean().default(false),
});
export type DraftPatch = z.infer<typeof draftPatchSchema>;
/** 数据冲突检查(落地预检第五项):他单已改同一字段即预检不过(OS 7.3) */
export const draftConflictSchema = z.object({
address: ledgerAddressSchema,
key: ledgerKeySchema,
field: z.string(),
draftValue: z.unknown(),
officialValue: z.unknown(),
/** 草稿建立时读到的基线值 —— 与当前正式版不同即冲突 */
baselineValue: z.unknown(),
});
export type DraftConflict = z.infer<typeof draftConflictSchema>;
/* ── 动作意向(写类工具调用,登记后集中在放行时落地,OS 7.3) ───────── */
export const ACTION_INTENT_STATES = [
'drafted',
'prechecked',
'landed',
'failed',
'abandoned',
] as const;
export const actionIntentStateSchema = z.enum(ACTION_INTENT_STATES);
export type ActionIntentState = z.infer<typeof actionIntentStateSchema>;
export const actionIntentSchema = z.object({
id: z.string().min(1),
taskId: taskIdSchema,
tool: z.string().min(1),
/** 入参冻结 —— 登记时即定,放行时按幂等键执行 */
input: z.record(z.string(), z.unknown()),
idempotencyKey: z.string().min(1),
state: actionIntentStateSchema,
label: z.string(),
detail: z.string().optional(),
error: z.string().optional(),
});
export type ActionIntent = z.infer<typeof actionIntentSchema>;
+280
View File
@@ -0,0 +1,280 @@
/**
* 活动包清单六区与资产形状(编码规范 §8.1;语义出处 OS 11.1,AM 11)。
*
* 清单机器可读,系统**不执行代码即知包为何物** —— 导入登记、安装静态审、编排装配读的都是清单。
* 资产与包分离版本化(OS 11.3):包版本管代码 / 契约 / 交互模版 / Harness;
* 资产版本管业务模型 / DMN / 技能 —— 包只携初始版,此后由进化管线在系统内产生。
*/
import { z } from 'zod';
import { activityIdSchema, skillIdSchema } from './id.ts';
import { jsonSchemaSchema, sevenPartContractSchema } from './contract7.ts';
import { listenerSpecSchema } from './envelope.ts';
import { objectDeclarationSchema } from './ledger.ts';
/* ── 范式 ─────────────────────────────────────────────────────────────── */
/** 范式只存在于**引擎层**;交互层不可区分(编码规范 §9 双层边界) */
export const PARADIGMS = ['loop', 'flow'] as const;
export const paradigmSchema = z.enum(PARADIGMS);
export type Paradigm = z.infer<typeof paradigmSchema>;
/** 活动类型两维分类之一(治理台活动库):标准活动 = flow,案例活动 = loop */
export const ACTIVITY_TYPE_LABEL: Readonly<Record<Paradigm, string>> = {
loop: '案例活动',
flow: '标准活动',
};
/* ── ① 身份 ─────────────────────────────────────────────────────────── */
export const manifestIdentitySchema = z.object({
activityId: activityIdSchema,
name: z.string().min(1),
packageVersion: z.string().min(1),
/** 业务分类(一级,组织自定)—— 与活动类型两维平级、相互独立 */
category: z.string().min(1),
paradigm: paradigmSchema,
sdkVersion: z.string().min(1),
checksum: z.string().min(1),
signature: z.string().optional(),
});
export type ManifestIdentity = z.infer<typeof manifestIdentitySchema>;
/* ── ③ 声明 ─────────────────────────────────────────────────────────── */
export const harnessConfigSchema = z.object({
/** 记忆窗口:每次 LLM 调用加载多少轮会话历史 —— 活动侧唯一记忆接口(AM 09) */
memoryWindow: z.number().int().min(1).max(200).default(20),
/** 停滞检测:多久无推进算空转(ISO-8601 duration) */
stallAfter: z.string().min(2).default('PT30M'),
/** 时限阶梯 */
nudge: z.array(z.object({ after: z.string().min(2), action: z.enum(['nudge', 'escalate']) })).default([]),
/** 步失败的默认重试(flow 每步可覆盖) */
retry: z.object({ times: z.number().int().min(0).max(10).default(2), backoff: z.string().default('PT30S') }).default({
times: 2,
backoff: 'PT30S',
}),
});
export type HarnessConfig = z.infer<typeof harnessConfigSchema>;
export const manifestDeclarationsSchema = z.object({
/** 模型声明:自定义模型名(逻辑名);安装静态审核对名称已绑定 */
models: z.array(z.string().min(1)).default([]),
/** 工具声明:调用契约引用 + 版本约束 */
tools: z.array(z.object({ name: z.string().min(1), version: z.string().optional() })).default([]),
/** 台账与共享域使用声明(域.对象.字段) */
ledger: z.array(objectDeclarationSchema).default([]),
/** 静态监听声明 —— 时限必配,悬空监听安装时拒绝 */
listeners: z.array(listenerSpecSchema).default([]),
harness: harnessConfigSchema,
});
export type ManifestDeclarations = z.infer<typeof manifestDeclarationsSchema>;
/* ── ④ 资产初始版 ───────────────────────────────────────────────────── */
/* flow 的业务模型:步序声明(AM 05) */
export const STEP_KINDS = ['tool', 'llm', 'human', 'pure-tool'] as const;
export const stepKindSchema = z.enum(STEP_KINDS);
export type StepKind = z.infer<typeof stepKindSchema>;
/** 失败策略:声明给定,不临场(AM 5.3) */
export const stepFailurePolicySchema = z.object({
retry: z.object({ times: z.number().int().min(0).max(10), backoff: z.string().min(2) }),
/** 重试仍败 —— 转人兜底(改发人类工具卡)或受阻待人 */
fallback: z.discriminatedUnion('kind', [
z.object({ kind: z.literal('human'), workOrder: z.enum(['execution', 'acceptance']) }),
z.object({ kind: z.literal('blocked') }),
]),
});
export type StepFailurePolicy = z.infer<typeof stepFailurePolicySchema>;
const stepBase = {
name: z.string().min(1),
label: z.string().min(1),
/** 入参映射:取自任务数据 / 上步出参 */
input: z.record(z.string(), z.string()).default({}),
/** 出参写入:落任务数据(草稿态) */
output: z.object({ domain: z.string(), object: z.string(), fields: z.record(z.string(), z.string()) }).optional(),
/** 条件跳步:任务数据上的确定性谓词(S-FEEL),零 LLM */
when: z.string().optional(),
failure: stepFailurePolicySchema,
};
export const flowStepSchema = z.discriminatedUnion('kind', [
z.object({ ...stepBase, kind: z.literal('tool'), tool: z.string().min(1) }),
z.object({
...stepBase,
kind: z.literal('llm'),
/** 模板与出参 schema 随声明版本冻结;出参必过 schema 校验(AM 12.3) */
model: z.string().min(1),
template: z.string().min(1),
outputSchema: jsonSchemaSchema,
}),
z.object({
...stepBase,
kind: z.literal('human'),
/** 工单两模式;末步通常是验收工单 */
workOrder: z.enum(['execution', 'acceptance']),
/** 卡内容 —— 由 card schema 渲染 */
card: z.record(z.string(), z.unknown()),
/** 异步步的完成条件 = 人事件;时限必配 */
deadline: z.string().min(2),
}),
z.object({ ...stepBase, kind: z.literal('pure-tool'), tool: z.string().min(1) }),
]);
export type FlowStep = z.infer<typeof flowStepSchema>;
export const flowModelSchema = z.object({
paradigm: z.literal('flow'),
steps: z.array(flowStepSchema).min(1),
/** 确定的并行组:组内步无依赖、全完成再继续 */
parallelGroups: z.array(z.object({ name: z.string(), steps: z.array(z.string()).min(2) })).default([]),
});
export type FlowModel = z.infer<typeof flowModelSchema>;
/* loop 的业务模型:CMMN XML + 案例说明书 + DMN(AM 03) */
export const dmnDecisionTableSchema = z.object({
id: z.string().min(1),
label: z.string(),
hitPolicy: z.enum(['UNIQUE', 'FIRST', 'PRIORITY', 'COLLECT']).default('FIRST'),
inputs: z.array(z.object({ name: z.string().min(1), expression: z.string().min(1) })).min(1),
outputs: z.array(z.object({ name: z.string().min(1) })).min(1),
rules: z
.array(
z.object({
id: z.string().min(1),
/** 单元格谓词:S-FEEL(空串 = 「-」任意匹配) */
when: z.array(z.string()),
then: z.array(z.unknown()),
annotation: z.string().optional(),
}),
)
.min(1),
});
export type DmnDecisionTable = z.infer<typeof dmnDecisionTableSchema>;
export const dmnModelSchema = z.object({
/** DRD:声明「定什么需要知道什么」—— 决策 → 依赖的决策 / 输入项 */
drd: z.array(
z.object({
decision: z.string().min(1),
requires: z.array(z.string()).default([]),
inputs: z.array(z.string()).default([]),
}),
),
tables: z.array(dmnDecisionTableSchema),
});
export type DmnModel = z.infer<typeof dmnModelSchema>;
export const loopModelSchema = z.object({
paradigm: z.literal('loop'),
/** 案例模型 · 机器面:CMMN XML,语义引擎以它为运行结构 */
cmmnXml: z.string().min(1),
/** 案例模型 · 叙事面:说明书,与 XML **同版本发布,不允许分叉**(AM 12.2) */
narrative: z.string().min(1),
dmn: dmnModelSchema,
});
export type LoopModel = z.infer<typeof loopModelSchema>;
export const businessModelSchema = z.discriminatedUnion('paradigm', [loopModelSchema, flowModelSchema]);
export type BusinessModel = z.infer<typeof businessModelSchema>;
/* 技能(AM 08):载方法不载权力 */
export const skillSchema = z.object({
id: skillIdSchema,
label: z.string().min(1),
/** 何时适用 —— 常驻上下文只有目录,按事加载正文 */
applicability: z.string().min(1),
/** 怎么判断、怎么编排工具 */
method: z.string().min(1),
/** 结晶片段脚本:反复出现的确定性子序列;按纯工具规矩注册留痕 */
crystallized: z
.array(z.object({ tool: z.string().min(1), input: z.record(z.string(), z.string()) }))
.default([]),
knowledgeRefs: z.array(z.string()).default([]),
version: z.string().min(1),
});
export type Skill = z.infer<typeof skillSchema>;
export const manifestAssetsSchema = z.object({
businessModel: businessModelSchema,
skills: z.array(skillSchema).default([]),
/** 视图 HTML 模版 —— 模版是内容不是代码,容器净化渲染、无脚本执行权 */
viewTemplates: z.array(z.object({ name: z.string().min(1), html: z.string() })).default([]),
/** 卡内容 schema */
cardSchemas: z.record(z.string(), jsonSchemaSchema).default({}),
/** 蒸馏钩子:终态封卷 / 里程碑达成时从任务记忆归纳 */
distillHooks: z
.array(z.object({ on: z.enum(['terminal', 'milestone']), milestone: z.string().optional(), prompt: z.string() }))
.default([]),
});
export type ManifestAssets = z.infer<typeof manifestAssetsSchema>;
/* ── ⑤ 样例集 ───────────────────────────────────────────────────────── */
export const sampleCaseSchema = z.object({
name: z.string().min(1),
input: z.record(z.string(), z.unknown()),
message: z.string().optional(),
/** 期望输出口与载荷形状 —— 首装审与回归的依据 */
expect: z.object({
ports: z.array(z.string()).min(1),
payloadShape: jsonSchemaSchema.optional(),
}),
});
export type SampleCase = z.infer<typeof sampleCaseSchema>;
/* ── 清单六区合体 ───────────────────────────────────────────────────── */
export const activityManifestSchema = z.object({
identity: manifestIdentitySchema,
contract: sevenPartContractSchema,
declarations: manifestDeclarationsSchema,
assets: manifestAssetsSchema,
samples: z.array(sampleCaseSchema).min(1),
/** ⑥ 代码入口:.JS 产物的入口与校验和 */
entry: z.object({ file: z.string().min(1), checksum: z.string().min(1) }),
});
export type ActivityManifest = z.infer<typeof activityManifestSchema>;
/* ── 安装两审的报告形状(OS 11.2) ─────────────────────────────────── */
export const staticAuditFindingSchema = z.object({
code: z.enum([
'signature-invalid',
'sdk-incompatible',
'schema-invalid',
'tool-contract-missing',
'model-name-unbound',
'dangling-listener',
'template-has-script',
'environment-capability',
'dynamic-eval',
'ledger-type-conflict',
'acceptance-level-misreported',
]),
severity: z.enum(['error', 'warn']),
message: z.string(),
at: z.string().optional(),
});
export type StaticAuditFinding = z.infer<typeof staticAuditFindingSchema>;
export const replayAuditReportSchema = z.object({
/** 「旧成不坏」是生效硬门;「旧败能成」为报告参考项,不作门槛 */
oldPassStillPass: z.boolean(),
checked: z.number().int().min(0),
regressions: z.array(z.object({ taskId: z.string(), detail: z.string() })).default([]),
newlyBlocked: z.array(z.object({ taskId: z.string(), detail: z.string() })).default([]),
/** 首次安装无历史:免回放审,以静态审 + 样例集替代 */
skippedNoHistory: z.boolean().default(false),
});
export type ReplayAuditReport = z.infer<typeof replayAuditReportSchema>;
export const installVerdictSchema = z.object({
accepted: z.boolean(),
staticFindings: z.array(staticAuditFindingSchema),
replay: replayAuditReportSchema,
});
export type InstallVerdict = z.infer<typeof installVerdictSchema>;
+109
View File
@@ -0,0 +1,109 @@
/**
* 员工、岗位与权限(编码规范 §4 · `org`;语义出处 OS 02 员工管理)。
*
* 权限按岗位授予:客体三类(数据 域.对象[.字段] / 治理功能 / 任务)× 动作三种(读 / 写 / 治理)。
* 任务负责人与被征答人对所涉内容**天然可见**,不另行授权。
* 单组织、≤50 人:不做多租户,不引 OAuth/OIDC(编码规范 §4 鉴权定调)。
*/
import { z } from 'zod';
import { positionIdSchema, staffIdSchema } from './id.ts';
export const positionSchema = z.object({
id: positionIdSchema,
code: z.string().min(1),
name: z.string().min(1),
note: z.string().optional(),
});
export type Position = z.infer<typeof positionSchema>;
export const STAFF_STATES = ['active', 'disabled'] as const;
export const staffStateSchema = z.enum(STAFF_STATES);
export type StaffState = z.infer<typeof staffStateSchema>;
export const staffSchema = z.object({
id: staffIdSchema,
account: z.string().min(1),
name: z.string().min(1),
positionId: positionIdSchema,
state: staffStateSchema.default('active'),
});
export type Staff = z.infer<typeof staffSchema>;
/* ── 岗位授权:客体三类 × 动作三种 ─────────────────────────────────── */
export const GRANT_ACTIONS = ['read', 'write', 'govern'] as const;
export const grantActionSchema = z.enum(GRANT_ACTIONS);
export type GrantAction = z.infer<typeof grantActionSchema>;
export const GRANT_ACTION_LABEL: Readonly<Record<GrantAction, string>> = {
read: '读',
write: '写',
govern: '治理',
};
/** 治理台九功能 —— 授权客体之一 */
export const GOVERNANCE_FUNCTIONS = [
'task',
'staff',
'process',
'trigger',
'activity',
'tool',
'data',
'memory',
'system',
] as const;
export const governanceFunctionSchema = z.enum(GOVERNANCE_FUNCTIONS);
export type GovernanceFunction = z.infer<typeof governanceFunctionSchema>;
export const GOVERNANCE_FUNCTION_LABEL: Readonly<Record<GovernanceFunction, string>> = {
task: '任务管理',
staff: '员工管理',
process: '工作流管理',
trigger: '触发器配置',
activity: '活动库管理',
tool: '工具管理',
data: '数据管理',
memory: '记忆管理',
system: '系统管理',
};
export const grantObjectSchema = z.discriminatedUnion('kind', [
z.object({
kind: z.literal('data'),
domain: z.string().min(1),
object: z.string().min(1),
field: z.string().optional(),
}),
z.object({ kind: z.literal('governance'), function: governanceFunctionSchema }),
z.object({ kind: z.literal('task'), activityId: z.string().optional() }),
]);
export type GrantObject = z.infer<typeof grantObjectSchema>;
export const grantSchema = z.object({
positionId: positionIdSchema,
object: grantObjectSchema,
action: grantActionSchema,
});
export type Grant = z.infer<typeof grantSchema>;
/* ── 停用前置检查(OS 02) ─────────────────────────────────────────── */
/** 员工停用前,其在途任务与待答卡须先改派完毕 */
export const disableCheckSchema = z.object({
staffId: staffIdSchema,
blocked: z.boolean(),
openTasks: z.array(z.object({ taskId: z.string(), title: z.string() })).default([]),
openCards: z.array(z.object({ cardId: z.string(), title: z.string() })).default([]),
openApprovals: z.array(z.object({ approvalId: z.string(), title: z.string() })).default([]),
});
export type DisableCheck = z.infer<typeof disableCheckSchema>;
/* ── 会话 ─────────────────────────────────────────────────────────────── */
export const sessionSchema = z.object({
staff: staffSchema,
position: positionSchema,
grants: z.array(grantSchema),
});
export type Session = z.infer<typeof sessionSchema>;
+279
View File
@@ -0,0 +1,279 @@
/**
* 流程包 DSL 与触发器配置(编码规范 §8.1;语义出处 OS 03)。
*
* 流程包 = 调用接口 + 两种活动(声明)+ 审批点 + 两种网关;工作流 = 其运行时实例。
* 触发器与流程包**平级**:不入流程包结构、不随流程包版本,配置独立存放。
*
* 编排铁律:**连线即映射,画图即校验,不闭合不得发布** —— 存在未完成边、未满足必填
* 或类型冲突的流程包可存草稿、不得发布。校验算法在 `process` 的 domain,本文件只定形状。
*/
import { z } from 'zod';
import {
activityIdSchema,
nodeIdSchema,
processPackageIdSchema,
staffIdSchema,
triggerIdSchema,
} from './id.ts';
import { jsonSchemaSchema } from './contract7.ts';
/* ── 负责人四策略(OS 03) ──────────────────────────────────────────── */
export const OWNER_STRATEGIES = ['assigned', 'sole', 'rotation', 'follow-source'] as const;
export const ownerStrategySchema = z.enum(OWNER_STRATEGIES);
export type OwnerStrategy = z.infer<typeof ownerStrategySchema>;
export const OWNER_STRATEGY_LABEL: Readonly<Record<OwnerStrategy, string>> = {
assigned: '指定人',
sole: '岗位唯一人',
rotation: '轮值',
'follow-source': '来源跟随',
};
export const ownerSpecSchema = z.object({
/** 编排声明岗位,起单时确定性解析 */
position: z.string().min(1),
strategy: ownerStrategySchema.default('sole'),
/** strategy = assigned 时直接绑定员工(慎用) */
staffId: staffIdSchema.optional(),
});
export type OwnerSpec = z.infer<typeof ownerSpecSchema>;
/* ── 边与载荷映射 ────────────────────────────────────────────────────── */
/**
* 映射来源四类:上游输出口载荷字段 / 流程变量 / 起单载荷 / 常量;
* 允许 S-FEEL 表达式做转换(与触发器字段映射同一形式)。
*/
export const mappingSourceSchema = z.discriminatedUnion('from', [
z.object({ from: z.literal('output-port'), port: z.string().min(1), path: z.string().min(1) }),
z.object({ from: z.literal('workflow-var'), name: z.string().min(1) }),
z.object({ from: z.literal('initiation'), path: z.string().min(1) }),
z.object({ from: z.literal('constant'), value: z.unknown() }),
z.object({ from: z.literal('expression'), sfeel: z.string().min(1) }),
]);
export type MappingSource = z.infer<typeof mappingSourceSchema>;
export const fieldMappingSchema = z.object({
/** 下游活动契约 data 的字段路径 */
target: z.string().min(1),
source: mappingSourceSchema,
});
export type FieldMapping = z.infer<typeof fieldMappingSchema>;
export const edgeSchema = z.object({
id: z.string().min(1),
from: nodeIdSchema,
to: nodeIdSchema,
/** XOR 网关出边的条件(S-FEEL);AND 出边留空 */
condition: z.string().optional(),
/** 连一条边即须完成该边映射 —— 必填未映射 = 边未完成 */
mapping: z.array(fieldMappingSchema).default([]),
/** 边标签:画布上的出口名(如「TYPE-A」「通过」) */
label: z.string().optional(),
/** 回边标记:人裁决后重开新任务实例(同节点、新任务 ID、留痕关联) */
reopen: z.boolean().default(false),
});
export type Edge = z.infer<typeof edgeSchema>;
/* ── 失败走向四选一(OS 03) ────────────────────────────────────────── */
export const failureDispositionSchema = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('terminate') }),
z.object({ kind: z.literal('reroute'), edgeId: z.string().min(1) }),
z.object({ kind: z.literal('escalate'), approvalNodeId: nodeIdSchema }),
/** 仅限 AND 分支;静态校验其下游映射不得依赖该分支的必填字段 */
z.object({ kind: z.literal('tolerate') }),
]);
export type FailureDisposition = z.infer<typeof failureDispositionSchema>;
export const FAILURE_DISPOSITION_LABEL: Readonly<Record<FailureDisposition['kind'], string>> = {
terminate: '终止流',
reroute: '改道',
escalate: '升审批',
tolerate: '容忍',
};
/* ── 催办阶梯(时限机制复用) ────────────────────────────────────────── */
export const nudgeLadderSchema = z.object({
/** ISO-8601 duration */
deadline: z.string().min(2),
steps: z.array(z.object({ after: z.string().min(2), action: z.enum(['nudge', 'escalate']) })).default([]),
});
export type NudgeLadder = z.infer<typeof nudgeLadderSchema>;
/* ── 节点 ─────────────────────────────────────────────────────────────── */
export const GATEWAY_KINDS = ['parallel', 'exclusive'] as const;
export const gatewayKindSchema = z.enum(GATEWAY_KINDS);
export type GatewayKind = z.infer<typeof gatewayKindSchema>;
export const GATEWAY_KIND_LABEL: Readonly<Record<GatewayKind, string>> = {
parallel: '并行网关',
exclusive: '异或网关',
};
const nodeBase = {
id: nodeIdSchema,
label: z.string().min(1),
/** 画布坐标 —— 布局引擎的输入;不影响语义 */
layout: z.object({ row: z.number().int(), col: z.number().int() }).optional(),
};
export const processNodeSchema = z.discriminatedUnion('kind', [
z.object({ ...nodeBase, kind: z.literal('start') }),
z.object({
...nodeBase,
kind: z.literal('end'),
/** 流程包显式终点的输出声明 */
output: jsonSchemaSchema.optional(),
}),
z.object({
...nodeBase,
kind: z.literal('activity'),
/** 以声明入流:引用活动库中已安装的活动 */
activityId: activityIdSchema,
/** 版本约束:留空 = 装配时取最新生效版 */
activityVersion: z.string().optional(),
owner: ownerSpecSchema,
failure: failureDispositionSchema.default({ kind: 'terminate' }),
/** 委托消息模板,可插值载荷字段;缺省为空 */
message: z.string().optional(),
}),
z.object({
...nodeBase,
kind: z.literal('approval'),
/** 审批点功能属性四件:审批岗位 / 输入装配映射 / 驳回走向 / 催办阶梯 */
approver: ownerSpecSchema,
/** 驳回走向:声明式,不由临场决定 */
reject: z.discriminatedUnion('kind', [
z.object({ kind: z.literal('reopen'), nodeId: nodeIdSchema, mapping: z.array(fieldMappingSchema).default([]) }),
z.object({ kind: z.literal('terminate') }),
]),
nudge: nudgeLadderSchema.optional(),
message: z.string().optional(),
}),
z.object({
...nodeBase,
kind: z.literal('gateway'),
gateway: gatewayKindSchema,
/** 分叉 / 汇合 */
mode: z.enum(['fork', 'join']),
}),
]);
export type ProcessNode = z.infer<typeof processNodeSchema>;
/* ── 调用接口:流程包的唯一出入口 ───────────────────────────────────── */
export const callInterfaceSchema = z.object({
input: jsonSchemaSchema,
/** 显式终点的输出声明 —— 末端输出载荷按此交付、按来源回执 */
output: jsonSchemaSchema,
});
export type CallInterface = z.infer<typeof callInterfaceSchema>;
/* ── 流程包 ───────────────────────────────────────────────────────────── */
export const PROCESS_PACKAGE_STATES = ['draft', 'published', 'retired'] as const;
export const processPackageStateSchema = z.enum(PROCESS_PACKAGE_STATES);
export type ProcessPackageState = z.infer<typeof processPackageStateSchema>;
export const processPackageSchema = z.object({
id: processPackageIdSchema,
name: z.string().min(1),
version: z.number().int().min(1),
state: processPackageStateSchema,
callInterface: callInterfaceSchema,
nodes: z.array(processNodeSchema).min(2),
edges: z.array(edgeSchema),
/** 流程变量声明:边映射的 workflow-var 来源 */
variables: z.array(z.object({ name: z.string().min(1), schema: jsonSchemaSchema })).default([]),
description: z.string().optional(),
});
export type ProcessPackage = z.infer<typeof processPackageSchema>;
/* ── 编排校验的报告形状(前端画布即时预览与后端裁决同源) ───────────── */
export const CLOSURE_VIOLATION_KINDS = [
'edge-unmapped',
'required-unmapped',
'type-conflict',
'dangling-node',
'gateway-unbalanced',
'join-ambiguous-source',
'tolerate-required-dependency',
'unknown-activity',
'missing-owner-position',
] as const;
export const closureViolationKindSchema = z.enum(CLOSURE_VIOLATION_KINDS);
export type ClosureViolationKind = z.infer<typeof closureViolationKindSchema>;
export const closureViolationSchema = z.object({
kind: closureViolationKindSchema,
nodeId: nodeIdSchema.optional(),
edgeId: z.string().optional(),
field: z.string().optional(),
message: z.string(),
});
export type ClosureViolation = z.infer<typeof closureViolationSchema>;
export const closureReportSchema = z.object({
publishable: z.boolean(),
violations: z.array(closureViolationSchema),
});
export type ClosureReport = z.infer<typeof closureReportSchema>;
/* ── 触发器三类(OS 3.1) ──────────────────────────────────────────── */
export const TRIGGER_KINDS = ['periodic', 'event', 'registration'] as const;
export const triggerKindSchema = z.enum(TRIGGER_KINDS);
export type TriggerKind = z.infer<typeof triggerKindSchema>;
export const TRIGGER_KIND_LABEL: Readonly<Record<TriggerKind, string>> = {
periodic: '周期触发',
event: '事件触发',
registration: '登记触发',
};
export const triggerConfigSchema = z.object({
id: triggerIdSchema,
name: z.string().min(1),
enabled: z.boolean().default(true),
/** 触发器只知道调用接口,不知流程内部 */
processPackageId: processPackageIdSchema,
/** 起单载荷装配:事件信封与载荷字段 → 调用接口的 data 字段;缺必填即起单失败入死信 */
mapping: z.array(fieldMappingSchema).default([]),
spec: z.discriminatedUnion('kind', [
z.object({
kind: z.literal('periodic'),
/** 日历型:纯日历规则 */
mode: z.literal('calendar'),
/** cron 风格的日历表达式 */
calendar: z.string().min(1),
}),
z.object({
kind: z.literal('periodic'),
/** 数据日历型:按台账日期字段 + 偏移 + 过滤条件逐行起单 */
mode: z.literal('data-calendar'),
domain: z.string().min(1),
object: z.string().min(1),
dateField: z.string().min(1),
/** 偏移:如 -P3D 表示日期字段前 3 天 */
offset: z.string().min(2),
filter: z.string().optional(),
}),
z.object({
kind: z.literal('event'),
/** 命中规则:S-FEEL,对事件信封与载荷字段求值 */
rule: z.string().min(1),
eventType: z.enum(['data', 'time', 'human', 'control']).default('data'),
}),
z.object({
kind: z.literal('registration'),
/** 登记表单由调用接口 schema 自动渲染 */
formHint: z.string().optional(),
}),
]),
});
export type TriggerConfig = z.infer<typeof triggerConfigSchema>;
+125
View File
@@ -0,0 +1,125 @@
/**
* 终态五名与非终态注记(编码规范 §8.1;语义出处 OS 4.3 / AM 1.3)。
*
* 终态由**系统**裁定,封闭枚举,活动与模型不得增删。
*/
import { z } from 'zod';
/** 终态五名 —— 唯一成功终态是 released(放行通过且落地收敛,输出口已发射) */
export const TERMINAL_STATES = ['released', 'blocked', 'stalled', 'exhausted', 'terminated'] as const;
export const terminalStateSchema = z.enum(TERMINAL_STATES);
export type TerminalState = z.infer<typeof terminalStateSchema>;
export const TERMINAL_STATE_LABEL: Readonly<Record<TerminalState, string>> = {
released: '放行完成',
blocked: '受阻待人',
stalled: '停滞熔断',
exhausted: '预算耗尽',
terminated: '被终止',
};
/** 触发者 —— OS 4.3 的第三列 */
export const TERMINAL_STATE_TRIGGER: Readonly<Record<TerminalState, string>> = {
released: '放行卡 + 落地执行',
blocked: 'Agent 机制申报,或治理台判定',
stalled: '预算执行器 · 停滞检测',
exhausted: '预算执行器 · 预算越限',
terminated: '控制事件 · 终止(含工作流级联)',
};
export function isSuccessTerminal(state: TerminalState): boolean {
return state === 'released';
}
/* ── 非终态注记(OS 4.3「不是终态」) ─────────────────────────────────── */
/** 驳回:放行卡的环内回转,任务继续 —— redo 按原要求重做 / revise 带意见迭代 */
export const REJECTION_KINDS = ['redo', 'revise'] as const;
export const rejectionKindSchema = z.enum(REJECTION_KINDS);
export type RejectionKind = z.infer<typeof rejectionKindSchema>;
export const REJECTION_KIND_LABEL: Readonly<Record<RejectionKind, string>> = {
redo: '驳回重做',
revise: '驳回迭代',
};
/** 控制三语义(OS 06):暂停 = 可恢复冻结 · 叫停 = 负责人紧急中断 · 终止 = 不可恢复关闭 */
export const CONTROL_SEMANTICS = ['pause', 'halt', 'terminate'] as const;
export const controlSemanticSchema = z.enum(CONTROL_SEMANTICS);
export type ControlSemantic = z.infer<typeof controlSemanticSchema>;
export const CONTROL_SEMANTIC_LABEL: Readonly<Record<ControlSemantic, string>> = {
pause: '暂停',
halt: '叫停',
terminate: '终止',
};
/**
* 任务运行态 —— 与终态分层:终态是收场名,运行态是「此刻在干嘛」。
* landing-blocked(落地受阻)是运行态不是终态,处置后仍收敛于终态名录(OS 7.3)。
*/
export const TASK_RUNTIME_STATES = [
'running',
'awaiting-human',
'awaiting-event',
'suspended',
'landing-blocked',
'terminal',
] as const;
export const taskRuntimeStateSchema = z.enum(TASK_RUNTIME_STATES);
export type TaskRuntimeState = z.infer<typeof taskRuntimeStateSchema>;
export const TASK_RUNTIME_STATE_LABEL: Readonly<Record<TaskRuntimeState, string>> = {
running: '运行中',
'awaiting-human': '等人回传',
'awaiting-event': '监听中',
suspended: '已挂起',
'landing-blocked': '落地受阻',
terminal: '已终结',
};
/* ── 工作流状态:流内各任务状态的聚合投影(OS 3.2) ──────────────────── */
export const WORKFLOW_STATES = ['running', 'waiting', 'completed', 'terminated', 'abnormal'] as const;
export const workflowStateSchema = z.enum(WORKFLOW_STATES);
export type WorkflowState = z.infer<typeof workflowStateSchema>;
export const WORKFLOW_STATE_LABEL: Readonly<Record<WorkflowState, string>> = {
running: '运行中',
waiting: '等待中',
completed: '已完成',
terminated: '已终止',
abnormal: '异常',
};
/* ── 归侧四标签(OS 8.1):度量的口径来源,零埋点 ─────────────────────── */
export const ATTRIBUTION_SIDES = ['machine', 'human', 'human-verdict', 'world-wait'] as const;
export const attributionSideSchema = z.enum(ATTRIBUTION_SIDES);
export type AttributionSide = z.infer<typeof attributionSideSchema>;
export const ATTRIBUTION_SIDE_LABEL: Readonly<Record<AttributionSide, string>> = {
machine: '机器产出',
human: '人产出',
'human-verdict': '人裁决',
'world-wait': '世界等待',
};
/* ── 验收分级 L1–L5(AM 10.2) ──────────────────────────────────────── */
export const ACCEPTANCE_LEVELS = ['L1', 'L2', 'L3', 'L4', 'L5'] as const;
export const acceptanceLevelSchema = z.enum(ACCEPTANCE_LEVELS);
export type AcceptanceLevel = z.infer<typeof acceptanceLevelSchema>;
export const ACCEPTANCE_LEVEL_LABEL: Readonly<Record<AcceptanceLevel, string>> = {
L1: '形式校验 · 引擎自动',
L2: '机检 · 引擎自动',
L3: '抽验 · 环内实证',
L4: '独立评审 · LLM 评审者',
L5: '人放行 · 责任关',
};
/** L1–L4 是质量关,L5 是责任关 —— 判据全绿只是可提交,完成只出自放行通过 */
export function isResponsibilityGate(level: AcceptanceLevel): boolean {
return level === 'L5';
}