feat(db,contracts): full v0.1 data model migrations and shared zod contracts (W1-1)

- migrations 0002-0012 split by domain (foundation/instances/content/identity/
  sources/assets/policy/execution/agent/ops/organization): 41 tables, uuid pk,
  created_at/updated_at + touch trigger, text+CHECK status sets, pgcrypto/pg_trgm
- key constraints: source_release(site_id, site_release_id), observation(feed_id, guid),
  external_identity accepted partial unique, download_task(instance_id, torrent_hash),
  one active acquisition_plan per slot, one active path_binding per entity/season,
  asset_location root+path uniqueness, organization_record change_seq/change_xid cursor
- secret table (ciphertext/nonce/kdf) + secret_ref columns; outbox dispatch fields (ADR-002)
- src/types.ts generated from the migrated schema (scripts/gen-types.ts), drift-checked in tests;
  int8 -> number, date -> string parsers; migrator accepts migrationTableSchema
- contracts: Row/Create/Update schemas per domain, public organization-record API
  (changeSeq cursor), GlobalSettings, CapabilityDescriptor + 14 capability IO schemas,
  typed SSE events, Api endpoint table
- tests: migration up/down round trip on real PG in an isolated schema, constraint checks,
  contracts<->db column/enum sync, positive/negative parse for every exported schema

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
rootandClaude Fable 5.1 committed 2026-09-27 18:11:37 +08:00
1 parent 7ba712ea55
commit cc8b3a7df4
42 files changed
+7026 -25

No files matched your search

+284
View File
@@ -0,0 +1,284 @@
import { z } from "zod";
import { EntityBase, Id, JsonObject, NonNegInt, SERVER_MANAGED, Timestamp } from "./common";
// 人工/AI 域:Agent 运行、证据/计划产物、待处理事项、审批、持续授权(REQ §10、§11.3、§11.4)
export const AgentTrigger = z.enum(["user", "event", "schedule", "subagent"]);
export type AgentTrigger = z.infer<typeof AgentTrigger>;
export const AgentRunStatus = z.enum([
"queued",
"running",
"waiting",
"succeeded",
"failed",
"cancelled",
"budget_exceeded",
]);
export type AgentRunStatus = z.infer<typeof AgentRunStatus>;
/** 单次运行预算(调用次数/token/时长/费用,REQ §10.5) */
export const AgentBudget = z.object({
maxToolCalls: z.number().int().positive().optional(),
maxTokens: z.number().int().positive().optional(),
maxDurationSec: z.number().int().positive().optional(),
maxCostUsd: z.number().nonnegative().optional(),
});
export type AgentBudget = z.infer<typeof AgentBudget>;
export const AgentUsage = z.object({
inputTokens: NonNegInt.optional(),
outputTokens: NonNegInt.optional(),
cacheReadTokens: NonNegInt.optional(),
cacheWriteTokens: NonNegInt.optional(),
costUsd: z.number().nonnegative().optional(),
durationMs: NonNegInt.optional(),
});
export type AgentUsage = z.infer<typeof AgentUsage>;
export const AgentRun = EntityBase.extend({
taskId: Id.nullable(),
parentRunId: Id.nullable(),
trigger: AgentTrigger,
goal: z.string().min(1),
status: AgentRunStatus,
provider: z.string().nullable(),
model: z.string().nullable(),
thinkingLevel: z.string().nullable(),
/** 授权范围(能力白名单、对象范围);子代理继承父任务上限 */
scope: JsonObject,
budget: AgentBudget,
usage: AgentUsage,
evidenceVersion: z.string().nullable(),
/** Pi 会话持久化状态;不对普通列表返回 */
sessionState: JsonObject.nullable(),
summary: z.string().nullable(),
toolCallCount: NonNegInt,
lastEventSeq: NonNegInt,
error: JsonObject.nullable(),
cancelRequestedAt: Timestamp.nullable(),
startedAt: Timestamp.nullable(),
finishedAt: Timestamp.nullable(),
createdBy: z.string().nullable(),
});
export type AgentRun = z.infer<typeof AgentRun>;
export const AgentRunCreate = AgentRun.pick({
taskId: true,
parentRunId: true,
trigger: true,
goal: true,
scope: true,
budget: true,
}).partial({ taskId: true, parentRunId: true, trigger: true, scope: true, budget: true });
export type AgentRunCreate = z.infer<typeof AgentRunCreate>;
export const AgentRunUpdate = AgentRun.pick({
status: true,
provider: true,
model: true,
thinkingLevel: true,
usage: true,
evidenceVersion: true,
sessionState: true,
summary: true,
toolCallCount: true,
lastEventSeq: true,
error: true,
startedAt: true,
finishedAt: true,
}).partial();
export type AgentRunUpdate = z.infer<typeof AgentRunUpdate>;
export const ArtifactKind = z.enum(["evidence", "plan", "proposal", "report", "snapshot", "log"]);
export type ArtifactKind = z.infer<typeof ArtifactKind>;
/** 证据/计划/提案产物:提案不直接晋升为事实 */
export const Artifact = EntityBase.extend({
kind: ArtifactKind,
agentRunId: Id.nullable(),
taskId: Id.nullable(),
subjectType: z.string().nullable(),
subjectId: Id.nullable(),
title: z.string().min(1),
mimeType: z.string(),
content: JsonObject,
contentHash: z.string().min(1),
sizeBytes: NonNegInt.nullable(),
expiresAt: Timestamp.nullable(),
});
export type Artifact = z.infer<typeof Artifact>;
/** contentHash / sizeBytes 由服务端计算 */
export const ArtifactCreate = Artifact.omit({ ...SERVER_MANAGED, contentHash: true, sizeBytes: true }).partial({
agentRunId: true,
taskId: true,
subjectType: true,
subjectId: true,
mimeType: true,
expiresAt: true,
});
export type ArtifactCreate = z.infer<typeof ArtifactCreate>;
/** 产物内容不可变;只能调整过期时间 */
export const ArtifactUpdate = z.object({ expiresAt: Timestamp.nullable() });
export type ArtifactUpdate = z.infer<typeof ArtifactUpdate>;
export const DecisionKind = z.enum([
"identity_ambiguous",
"download_stalled",
"download_failed",
"path_conflict",
"space_insufficient",
"approval_required",
"metadata_conflict",
"source_unreachable",
"other",
]);
export type DecisionKind = z.infer<typeof DecisionKind>;
export const DecisionStatus = z.enum(["open", "investigating", "awaiting_user", "resolved", "dismissed", "expired"]);
export type DecisionStatus = z.infer<typeof DecisionStatus>;
export const Severity = z.enum(["info", "warning", "critical"]);
export type Severity = z.infer<typeof Severity>;
export const DecisionOption = z.object({
key: z.string().min(1),
label: z.string().min(1),
description: z.string().optional(),
/** 选择后执行的能力与参数(仍经授权校验) */
capabilityId: z.string().optional(),
input: JsonObject.optional(),
});
export type DecisionOption = z.infer<typeof DecisionOption>;
/** 待处理中心条目;同一 dedupeKey 同时只有一个未关闭条目 */
export const Decision = EntityBase.extend({
kind: DecisionKind,
status: DecisionStatus,
severity: Severity,
title: z.string().min(1),
summary: z.string().nullable(),
subjectType: z.string().nullable(),
subjectId: Id.nullable(),
dedupeKey: z.string().min(1),
evidence: JsonObject,
options: z.array(DecisionOption),
resolution: JsonObject.nullable(),
taskId: Id.nullable(),
agentRunId: Id.nullable(),
attempts: NonNegInt,
nextReviewAt: Timestamp.nullable(),
resolvedBy: z.string().nullable(),
resolvedAt: Timestamp.nullable(),
});
export type Decision = z.infer<typeof Decision>;
export const DecisionCreate = Decision.pick({
kind: true,
severity: true,
title: true,
summary: true,
subjectType: true,
subjectId: true,
dedupeKey: true,
evidence: true,
options: true,
taskId: true,
agentRunId: true,
nextReviewAt: true,
}).partial({
severity: true,
summary: true,
subjectType: true,
subjectId: true,
evidence: true,
options: true,
taskId: true,
agentRunId: true,
nextReviewAt: true,
});
export type DecisionCreate = z.infer<typeof DecisionCreate>;
export const DecisionUpdate = Decision.pick({
status: true,
severity: true,
summary: true,
evidence: true,
options: true,
agentRunId: true,
nextReviewAt: true,
}).partial();
export type DecisionUpdate = z.infer<typeof DecisionUpdate>;
/** 用户处理待处理事项:选一个选项或关闭 */
export const DecisionResolveInput = z.object({
optionKey: z.string().min(1).optional(),
dismiss: z.boolean().optional(),
note: z.string().max(2000).optional(),
});
export type DecisionResolveInput = z.infer<typeof DecisionResolveInput>;
export const ApprovalStatus = z.enum(["pending", "approved", "rejected", "revoked", "expired", "consumed"]);
export type ApprovalStatus = z.infer<typeof ApprovalStatus>;
/** 单次审批:绑定 planType+planId + payloadHash + expectedRevision;换候选/路径后旧审批失效 */
export const Approval = EntityBase.extend({
planType: z.string().min(1),
planId: Id,
payloadHash: z.string().min(1),
expectedRevision: z.number().int().min(0),
scope: JsonObject,
status: ApprovalStatus,
decisionId: Id.nullable(),
requestedBy: z.string().min(1),
decidedBy: z.string().nullable(),
decidedAt: Timestamp.nullable(),
expiresAt: Timestamp.nullable(),
reason: z.string().nullable(),
});
export type Approval = z.infer<typeof Approval>;
export const ApprovalCreate = Approval.pick({
planType: true,
planId: true,
payloadHash: true,
expectedRevision: true,
scope: true,
decisionId: true,
requestedBy: true,
expiresAt: true,
reason: true,
}).partial({ scope: true, decisionId: true, expiresAt: true, reason: true });
export type ApprovalCreate = z.infer<typeof ApprovalCreate>;
/** 批准/拒绝时回传 payloadHash,服务端比对防止审批被挪用到变更后的计划 */
export const ApprovalUpdate = z.object({
status: z.enum(["approved", "rejected", "revoked"]),
payloadHash: z.string().min(1),
reason: z.string().max(2000).optional(),
});
export type ApprovalUpdate = z.infer<typeof ApprovalUpdate>;
export const GrantStatus = z.enum(["active", "revoked", "expired"]);
export type GrantStatus = z.infer<typeof GrantStatus>;
/** 持续授权:绑定策略版本、动作、对象范围与预算 */
export const AutomationGrant = EntityBase.extend({
action: z.string().min(1),
policyRevisionId: Id.nullable(),
scope: JsonObject,
budget: JsonObject,
status: GrantStatus,
grantedBy: z.string().min(1),
reason: z.string().nullable(),
expiresAt: Timestamp.nullable(),
revokedAt: Timestamp.nullable(),
revokedBy: z.string().nullable(),
});
export type AutomationGrant = z.infer<typeof AutomationGrant>;
export const AutomationGrantCreate = AutomationGrant.pick({
action: true,
policyRevisionId: true,
scope: true,
budget: true,
reason: true,
expiresAt: true,
}).partial({ policyRevisionId: true, scope: true, budget: true, reason: true, expiresAt: true });
export type AutomationGrantCreate = z.infer<typeof AutomationGrantCreate>;
/** 只能撤销或缩短有效期,不能就地扩大范围(扩大 = 新授权) */
export const AutomationGrantUpdate = z.object({
status: z.literal("revoked").optional(),
expiresAt: Timestamp.nullable().optional(),
reason: z.string().max(2000).optional(),
});
export type AutomationGrantUpdate = z.infer<typeof AutomationGrantUpdate>;