This repository has been archived on 2026-09-13. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
BPOS-TMP-REPO/packages/contracts/src/ledger.ts
T
JCAI Main AgentandClaude Opus 5 14d4fa046a 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
2026-07-27 00:59:14 +08:00

193 lines
8.0 KiB
TypeScript

/**
* 数据与台账(编码规范 §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>;