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:
co-authored by
Claude Opus 5
parent
7cd664af3a
commit
14d4fa046a
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* 台账 schema 自生长 —— 纯算法,零 IO(编码规范 §7.2:落此文件,零 mock 全覆盖测试)。
|
||||
*
|
||||
* 语义出处 OS 04 / AM 11.1:
|
||||
* 声明的是**活动要用什么字段**,不是对象该定义什么字段;
|
||||
* 对象的实际 schema = 全部使用声明的**最大化合并**(并集);
|
||||
* 定义**只增不破坏**:声明永不缩表、不删改已有字段;
|
||||
* 同名字段类型不一致时,以**能兼容双方的最宽类型**落地(放宽即增,不破坏),静态审提示、不阻塞;
|
||||
* **语义互斥**不可兼容的极端情形才拦下,交数据管理裁决。
|
||||
*/
|
||||
import type { FieldDeclaration, LedgerFieldType, ObjectDeclaration } from '@contracts';
|
||||
|
||||
/* ── 类型格:widen(a, b) = 能同时容纳 a 与 b 的最窄类型 ────────────────── */
|
||||
|
||||
/**
|
||||
* 标量的加宽链:
|
||||
* integer → number → text
|
||||
* date → timestamp → text
|
||||
* boolean → text
|
||||
* `json` 是容器类型,与任何标量**语义互斥** —— 不加宽,直接拦下。
|
||||
*/
|
||||
const SCALAR_CHAIN: Readonly<Record<LedgerFieldType, readonly LedgerFieldType[]>> = {
|
||||
integer: ['integer', 'number', 'text'],
|
||||
number: ['number', 'text'],
|
||||
date: ['date', 'timestamp', 'text'],
|
||||
timestamp: ['timestamp', 'text'],
|
||||
boolean: ['boolean', 'text'],
|
||||
text: ['text'],
|
||||
json: ['json'],
|
||||
};
|
||||
|
||||
export type WidenResult =
|
||||
| { readonly ok: true; readonly type: LedgerFieldType; readonly widened: boolean }
|
||||
| { readonly ok: false; readonly reason: string };
|
||||
|
||||
export function widen(a: LedgerFieldType, b: LedgerFieldType): WidenResult {
|
||||
if (a === b) return { ok: true, type: a, widened: false };
|
||||
if (a === 'json' || b === 'json') {
|
||||
return { ok: false, reason: `json 与 ${a === 'json' ? b : a} 语义互斥,不可兼容` };
|
||||
}
|
||||
// 取两条链的最靠前的公共上界
|
||||
for (const candidate of SCALAR_CHAIN[a]) {
|
||||
if (SCALAR_CHAIN[b].includes(candidate)) {
|
||||
return { ok: true, type: candidate, widened: true };
|
||||
}
|
||||
}
|
||||
/* istanbul ignore next —— text 是标量的公共顶,理论不可达 */
|
||||
return { ok: false, reason: `${a} 与 ${b} 无公共上界` };
|
||||
}
|
||||
|
||||
/* ── 合并结果 ───────────────────────────────────────────────────────── */
|
||||
|
||||
export type MergedField = {
|
||||
readonly name: string;
|
||||
readonly type: LedgerFieldType;
|
||||
readonly label: string | undefined;
|
||||
readonly primaryKey: boolean;
|
||||
readonly masked: boolean;
|
||||
};
|
||||
|
||||
export type MergeNotice = {
|
||||
readonly kind: 'type-widened' | 'masked-propagated' | 'label-kept-first';
|
||||
readonly field: string;
|
||||
readonly message: string;
|
||||
};
|
||||
|
||||
export type MergeConflict = {
|
||||
readonly kind: 'type-incompatible' | 'primary-key-divergent';
|
||||
readonly field: string;
|
||||
readonly message: string;
|
||||
};
|
||||
|
||||
export type MergedObject = {
|
||||
readonly domain: string;
|
||||
readonly object: string;
|
||||
readonly label: string | undefined;
|
||||
readonly fields: readonly MergedField[];
|
||||
readonly primaryKey: readonly string[];
|
||||
};
|
||||
|
||||
export type MergeResult = {
|
||||
readonly merged: MergedObject | undefined;
|
||||
/** 静态审提示,不阻塞 */
|
||||
readonly notices: readonly MergeNotice[];
|
||||
/** 语义互斥 —— 拦下,交数据管理裁决 */
|
||||
readonly conflicts: readonly MergeConflict[];
|
||||
};
|
||||
|
||||
function mergeField(
|
||||
acc: MergedField,
|
||||
next: FieldDeclaration,
|
||||
notices: MergeNotice[],
|
||||
conflicts: MergeConflict[],
|
||||
): MergedField {
|
||||
const w = widen(acc.type, next.type);
|
||||
if (!w.ok) {
|
||||
conflicts.push({ kind: 'type-incompatible', field: acc.name, message: w.reason });
|
||||
return acc;
|
||||
}
|
||||
if (w.widened) {
|
||||
notices.push({
|
||||
kind: 'type-widened',
|
||||
field: acc.name,
|
||||
message: `同名异型 ${acc.type} + ${next.type} → 取最宽类型 ${w.type}(放宽即增,不破坏)`,
|
||||
});
|
||||
}
|
||||
// 脱敏取或:任一声明要求脱敏即脱敏(安全方向单调)
|
||||
const masked = acc.masked || next.masked;
|
||||
if (masked && !acc.masked) {
|
||||
notices.push({ kind: 'masked-propagated', field: acc.name, message: '任一声明要求脱敏即脱敏' });
|
||||
}
|
||||
if (next.label !== undefined && acc.label !== undefined && next.label !== acc.label) {
|
||||
notices.push({
|
||||
kind: 'label-kept-first',
|
||||
field: acc.name,
|
||||
message: `字段名称冲突(${acc.label} / ${next.label}),保留首个声明`,
|
||||
});
|
||||
}
|
||||
return {
|
||||
name: acc.name,
|
||||
type: w.type,
|
||||
label: acc.label ?? next.label,
|
||||
// 主键参与取或:任一声明视其为主键即入主键集
|
||||
primaryKey: acc.primaryKey || next.primaryKey,
|
||||
masked,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 最大化合并:把同一个「域.对象」的**全部**使用声明合成一份对象 schema。
|
||||
* 声明顺序不影响结果(合并是可交换、可结合的)——除标签保留首个声明外。
|
||||
*/
|
||||
export function mergeDeclarations(declarations: readonly ObjectDeclaration[]): MergeResult {
|
||||
const notices: MergeNotice[] = [];
|
||||
const conflicts: MergeConflict[] = [];
|
||||
|
||||
const first = declarations[0];
|
||||
if (first === undefined) return { merged: undefined, notices, conflicts };
|
||||
|
||||
for (const d of declarations) {
|
||||
if (d.domain !== first.domain || d.object !== first.object) {
|
||||
throw new Error(`mergeDeclarations 只接受同一对象的声明:${d.domain}.${d.object} ≠ ${first.domain}.${first.object}`);
|
||||
}
|
||||
}
|
||||
|
||||
const byName = new Map<string, MergedField>();
|
||||
const order: string[] = [];
|
||||
|
||||
for (const declaration of declarations) {
|
||||
for (const field of declaration.fields) {
|
||||
const existing = byName.get(field.name);
|
||||
if (existing === undefined) {
|
||||
order.push(field.name);
|
||||
byName.set(field.name, {
|
||||
name: field.name,
|
||||
type: field.type,
|
||||
label: field.label,
|
||||
primaryKey: field.primaryKey,
|
||||
masked: field.masked,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
byName.set(field.name, mergeField(existing, field, notices, conflicts));
|
||||
}
|
||||
}
|
||||
|
||||
const fields = order.map((name) => byName.get(name)!);
|
||||
const primaryKey = fields.filter((f) => f.primaryKey).map((f) => f.name);
|
||||
|
||||
return {
|
||||
merged: {
|
||||
domain: first.domain,
|
||||
object: first.object,
|
||||
label: declarations.find((d) => d.label !== undefined)?.label,
|
||||
fields,
|
||||
primaryKey,
|
||||
},
|
||||
notices,
|
||||
conflicts,
|
||||
};
|
||||
}
|
||||
|
||||
/* ── 与已物化 schema 的差分:生成「只增不破坏」的变更计划 ─────────────── */
|
||||
|
||||
export type MaterializedColumn = {
|
||||
readonly name: string;
|
||||
readonly type: LedgerFieldType;
|
||||
};
|
||||
|
||||
export type MaterializedObject = {
|
||||
readonly domain: string;
|
||||
readonly object: string;
|
||||
readonly columns: readonly MaterializedColumn[];
|
||||
readonly primaryKey: readonly string[];
|
||||
};
|
||||
|
||||
export type SchemaChange =
|
||||
| { readonly kind: 'create-table'; readonly object: MergedObject }
|
||||
| { readonly kind: 'add-column'; readonly field: MergedField }
|
||||
| { readonly kind: 'widen-column'; readonly field: MergedField; readonly from: LedgerFieldType };
|
||||
|
||||
export type SchemaPlan = {
|
||||
readonly changes: readonly SchemaChange[];
|
||||
readonly notices: readonly MergeNotice[];
|
||||
readonly conflicts: readonly MergeConflict[];
|
||||
};
|
||||
|
||||
/**
|
||||
* 差分:目标 schema(合并结果)相对已物化 schema 的增量。
|
||||
* **永不产出删列、缩窄或改主键的变更** —— 那三样是破坏,由数据管理的治理动作承担,不经声明发生。
|
||||
*/
|
||||
export function planSchemaChanges(
|
||||
target: MergedObject,
|
||||
current: MaterializedObject | undefined,
|
||||
): SchemaPlan {
|
||||
const notices: MergeNotice[] = [];
|
||||
const conflicts: MergeConflict[] = [];
|
||||
|
||||
if (current === undefined) {
|
||||
return { changes: [{ kind: 'create-table', object: target }], notices, conflicts };
|
||||
}
|
||||
|
||||
// 主键一经建立不得由声明变更 —— 新增主键字段是破坏性变更
|
||||
const currentPk = [...current.primaryKey].sort();
|
||||
const targetPk = [...target.primaryKey].sort();
|
||||
const addedPk = targetPk.filter((k) => !currentPk.includes(k));
|
||||
if (addedPk.length > 0) {
|
||||
conflicts.push({
|
||||
kind: 'primary-key-divergent',
|
||||
field: addedPk.join(','),
|
||||
message: `主键已建立为 (${currentPk.join(', ')}),声明试图新增主键字段 ${addedPk.join(', ')} —— 只增不破坏,交数据管理裁决`,
|
||||
});
|
||||
}
|
||||
|
||||
const columns = new Map(current.columns.map((c) => [c.name, c]));
|
||||
const changes: SchemaChange[] = [];
|
||||
|
||||
for (const field of target.fields) {
|
||||
const existing = columns.get(field.name);
|
||||
if (existing === undefined) {
|
||||
changes.push({ kind: 'add-column', field });
|
||||
continue;
|
||||
}
|
||||
const w = widen(existing.type, field.type);
|
||||
if (!w.ok) {
|
||||
conflicts.push({ kind: 'type-incompatible', field: field.name, message: w.reason });
|
||||
continue;
|
||||
}
|
||||
if (w.type !== existing.type) {
|
||||
notices.push({
|
||||
kind: 'type-widened',
|
||||
field: field.name,
|
||||
message: `已物化 ${existing.type},声明需要 ${field.type} → 加宽为 ${w.type}`,
|
||||
});
|
||||
changes.push({ kind: 'widen-column', field: { ...field, type: w.type }, from: existing.type });
|
||||
}
|
||||
}
|
||||
|
||||
return { changes, notices, conflicts };
|
||||
}
|
||||
|
||||
/** 声明只增不破坏的机检:计划里不得出现任何缩表动作 */
|
||||
export function planIsNonDestructive(plan: SchemaPlan): boolean {
|
||||
return plan.changes.every(
|
||||
(c) => c.kind === 'create-table' || c.kind === 'add-column' || c.kind === 'widen-column',
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user