openxiangda-skill-kit 2.0.0-alpha.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,67 @@
1
+ # AppSpec
2
+
3
+ AppSpec 是 OpenXiangda 2.0 应用仓库中的可选业务意图层。它帮助 AI 理解“为什么做、应当表现成
4
+ 什么、这次改变什么”,但不复制 `openxiangda.config.ts`、编译合同、代码、测试或部署状态,也
5
+ 不是发布门禁。
6
+
7
+ AppSpec 只使用 2.0 的 `appspec/`、文档 schema v1 与 context v2。绝不读取、识别、导入或迁移
8
+ 1.x 的 `openspec/`、SDD、表单、页面、函数和发布材料。
9
+
10
+ ## 何时读取
11
+
12
+ - 工作区存在 `appspec/` 时,在分析需求或修改行为前运行 `pnpm openxiangda spec context --json`,先读取
13
+ 有界索引。
14
+ - 从索引选择相关变更、能力、ADR 或历史变更 ID,再运行例如
15
+ `pnpm openxiangda spec context booking-window --json` 读取正文。
16
+ - AI-native 客户端可读取 `openxiangda://workspace/appspec` 或调用 `appspec_context`。
17
+ - 默认不加载全部正文;历史变更只在追查原因时用稳定 ID 按需读取。
18
+
19
+ ## 何时维护
20
+
21
+ | 风险 | 典型变化 | 最小维护量 |
22
+ | --- | --- | --- |
23
+ | L0 | 重构、格式、无行为变化 | 不创建 ChangeSpec |
24
+ | L1 | 文案、单字段、局部规则 | 一份短 ChangeSpec |
25
+ | L2 | 跨资源、权限、状态变化 | 加正反验收、数据与回滚 |
26
+ | L3 | 身份、迁移、并发、外部副作用 | 加失败/幂等、资源边界和 ADR |
27
+
28
+ 用户没有要求且变更是 L0 时,不要为了“流程完整”创建文档。小应用可以长期只维护 `app.md`。
29
+
30
+ ## 标准操作
31
+
32
+ ```bash
33
+ pnpm openxiangda spec init
34
+ pnpm openxiangda spec add-capability CAP-BOOKING --title "预约管理" --resources bookings
35
+ pnpm openxiangda spec new booking-window --title "限制可预约时段" --risk L1 \
36
+ --capabilities CAP-BOOKING --resources bookings
37
+ pnpm openxiangda spec context booking-window --json
38
+ pnpm openxiangda spec check
39
+ pnpm openxiangda spec close booking-window --current-spec merged \
40
+ --summary "已通过真实角色验收"
41
+ ```
42
+
43
+ `spec check` 是用户主动选择的严格检查;普通 `check/dev/deploy` 只给 advisory,不因 AppSpec
44
+ 缺失或不完整而失败。
45
+
46
+ 新 ChangeSpec 的 `currentSpec` 固定从 `pending` 开始。关闭前先把长期有效结果合入 `app.md` 或相关
47
+ CapabilitySpec,再由用户确认 `merged`;不改变长期规格时由用户确认 `not-applicable`。AI 可以列出
48
+ 未合入差异,但不能自行选择这两个值。稳定 REQ/AC 未进入当前规格、L2/L3 必需章节为空或保留默认
49
+ 占位内容时,`spec close` 不移动文件。
50
+
51
+ ## 写作边界
52
+
53
+ - `app.md` 记录长期目标、角色、范围、术语和跨能力约束。
54
+ - `capabilities/CAP-*.md` 记录当前有效需求,使用稳定 `REQ-*` 和可证伪 `AC-*`。
55
+ - `changes/active/*.md` 只记录本次 delta、风险、影响范围与验收;关闭前把仍有效的结论合入能力规格,
56
+ 并由用户确认 `currentSpec`。
57
+ - `decisions/ADR-*.md` 只用于架构显著决定,不为普通小改创建。
58
+ - 引用真实 2.0 resource/action code,不抄字段定义和权限矩阵的机器事实。
59
+ - AI 可以创建 `draft`、指出未确认问题和建议更新,不能自行把需求标记为 `confirmed`。
60
+ - 不因 AppSpec 与实现冲突就静默修改其中一方;明确指出冲突,由用户决定业务意图,技术事实以实时
61
+ 编译合同为准。
62
+
63
+ ## 可迁移程度
64
+
65
+ 完整 AppSpec 能显著提高另一个新项目复现业务逻辑的概率,但最终文档本身不等于可执行应用。
66
+ 需要接近原应用时,应同时提供 AppSpec、`openxiangda.config.ts`、必要自定义动作、测试和外部接口
67
+ 合同;历史 ChangeSpec 不是必需输入。
@@ -0,0 +1,7 @@
1
+ # OpenXiangda 2.0 Architecture
2
+
3
+ Keep one React application, one optional NestJS service and one platform-owned data contract. Application code directly depends only on `openxiangda`; use `openxiangda/config`, `openxiangda/core`, `openxiangda/field-kit`, `openxiangda/react`, `openxiangda/nest` and `openxiangda/testing` as the public subpaths. Do not import the physical `openxiangda-*` implementation packages.
4
+
5
+ Declare resources, routes, capabilities, row policies and operation-aware field policies once in `openxiangda.config.ts`. The compiler owns derived contracts; the root package owns Field Kit, CRUD Renderer, Shell, clients and Nest integration; the platform owns identity, authorization, data, environment Heads and deployment state.
6
+
7
+ Ordinary list, detail, create, update and delete operations go directly through Data API. Add a NestJS endpoint only for a business action that cannot be represented as CRUD. Run `pnpm openxiangda check` after every contract change.
@@ -0,0 +1,268 @@
1
+ # OpenXiangda 2.0 Backend
2
+
3
+ Read [Architecture](architecture.md) and [Data and authorization](data-authz.md)
4
+ before adding a backend. Finish with [Testing](testing.md).
5
+
6
+ Keep normal record CRUD in the platform Data API. Use `apps/server` only for typed business actions that need server-side logic. For an interactive request, the platform gateway supplies the verified current user, complete application-role union and capabilities. Controllers bind operations and capabilities through `openxiangda/nest`; workers continue to use their explicit application identity.
7
+
8
+ Every interactive business action uses `@OpenXiangdaOperation(operation)`. The
9
+ guard checks `operation.requiredCapability` once at App API ingress. Inside that
10
+ declared action, inject `OpenXiangdaBusinessDataApiService`,
11
+ `OpenXiangdaBusinessNotificationService`, or use
12
+ `OpenXiangdaStandardOperations`: Native Data and Notification Hub then run as the trusted backend
13
+ for this exact application, environment, version and operation. Do not forward
14
+ the caller's resource, row or field permissions into that internal Data call,
15
+ and do not author an `authorizationJSON` permission mirror. The platform still
16
+ records the initiating user and action code in records, files, events and audit.
17
+ The platform models this internal hop as the request-bounded
18
+ `native-business-action` principal. It is neither an OAuth client nor a Native
19
+ runtime credential: PostgreSQL accepts it only after the platform has verified
20
+ the signed Gateway invocation, exact target/Head, published
21
+ `code + requiredCapability`, application data scope and initiating user. Never
22
+ copy an invocation token into application data, construct the action headers
23
+ yourself, or fall back to `OpenXiangdaApplicationDataApiService` when this
24
+ channel is rejected; a rejection means the platform/package combination is not
25
+ compatible or the invocation is stale.
26
+
27
+ For an informational business notification, inject
28
+ `OpenXiangdaBusinessNotificationService` in the same declared action. The SDK
29
+ uses the short-lived gateway invocation, never the caller's original login
30
+ token. The platform rechecks the operation and capability, promotes the call to
31
+ the exact application/environment principal, and records the initiating user
32
+ and action. Do not grant ordinary users `app:notification2:send` and do not use
33
+ the privileged `OpenXiangdaNotificationService` as an application workaround.
34
+
35
+ ```ts
36
+ import { Inject } from '@nestjs/common';
37
+ import {
38
+ OPENXIANGDA_NOTIFICATION_BUSINESS_SEND_V2,
39
+ OPENXIANGDA_NOTIFICATION_EVENT_SEND_V2,
40
+ OpenXiangdaBusinessNotificationService,
41
+ } from 'openxiangda/nest';
42
+
43
+ constructor(
44
+ @Inject(OpenXiangdaBusinessNotificationService)
45
+ private readonly notifications: OpenXiangdaBusinessNotificationService,
46
+ ) {}
47
+
48
+ await this.notifications.send({
49
+ schemaVersion: OPENXIANGDA_NOTIFICATION_BUSINESS_SEND_V2,
50
+ eventId: body.eventId,
51
+ correlationId: `proposal:${proposal.id}`,
52
+ messageKey: `proposal:${proposal.id}:invite:${member.id}`,
53
+ sourceSequence: proposal.revision,
54
+ recipients: [{ userId: member.userId }],
55
+ title: '待您附议',
56
+ summary: proposal.title,
57
+ navigationTarget: {
58
+ kind: 'APP_ROUTE',
59
+ appCode: 'proposal_app',
60
+ routeCodes: {
61
+ desktop: 'proposal.detail',
62
+ mobile: 'proposal.detail-mobile',
63
+ },
64
+ pathParams: { id: proposal.id },
65
+ access: 'AUTHENTICATED',
66
+ },
67
+ idempotencyKey: `proposal:${proposal.id}:invite:${member.id}:v${proposal.revision}`,
68
+ });
69
+
70
+ ```
71
+
72
+ The fixed template accepts only `title` and optional `summary`. Reuse the same
73
+ `eventId` or `idempotencyKey` for retries. Reuse `messageKey` with increasing
74
+ `sourceSequence` for state convergence; do not generate a new logical message
75
+ for each retry.
76
+
77
+ The generated
78
+ `notificationTemplateCodes.applicationInformational` constant documents the
79
+ selected platform template; `send()` chooses it automatically and does not
80
+ accept a caller-supplied template code.
81
+
82
+ Inside a signed Application Events/date-trigger handler, call
83
+ `sendFromEvent()` on the same service. The SDK obtains the application
84
+ credential and forwards the current eventId, deliveryId and subscription code.
85
+ Declare only dot paths beneath the immutable event `data`; Notification Hub
86
+ resolves the actual Native user IDs and presentation text. Do not copy values
87
+ from the event into a caller-supplied `recipients` array and never manufacture a
88
+ user token.
89
+
90
+ ```ts
91
+ await this.notifications.sendFromEvent({
92
+ schemaVersion: OPENXIANGDA_NOTIFICATION_EVENT_SEND_V2,
93
+ correlationId: `proposal:${event.data.proposalId}`,
94
+ messageKey: `proposal:${event.data.proposalId}:reminder`,
95
+ sourceSequence: event.data.revision,
96
+ recipientPaths: ['assigneeUserIds'],
97
+ titlePath: 'notification.title',
98
+ summaryPath: 'notification.summary',
99
+ navigationTarget: {
100
+ kind: 'APP_ROUTE',
101
+ appCode: 'proposal_app',
102
+ routeCodes: {
103
+ desktop: 'proposal.detail',
104
+ mobile: 'proposal.detail-mobile',
105
+ },
106
+ pathParams: { id: event.data.proposalId },
107
+ access: 'AUTHENTICATED',
108
+ },
109
+ idempotencyKey: event.id,
110
+ });
111
+ ```
112
+
113
+ `OpenXiangdaDataApiService` deliberately retains ordinary current-user Data
114
+ authorization and automatically inherits the request Perspective for reads.
115
+ Its writes still authorize against the complete role union. Do not use it to
116
+ implement a declared business action. The
117
+ business facade also rejects routes without immutable `OpenXiangdaOperation`
118
+ metadata, so a controller cannot silently gain trusted Data access.
119
+
120
+ If a custom controller bypasses the standard Data API and reads Nest-owned SQL,
121
+ an external service or another datastore, inject `@CurrentPerspective()` and
122
+ apply the declared role-based read projection explicitly. Perspective is not a
123
+ credential and must never change mutation authorization. Prefer moving ordinary
124
+ reads back to `OpenXiangdaDataApiService`, where the platform owns the contract.
125
+
126
+ Do not duplicate resource persistence in controllers. Keep actions bounded and side-effect behavior explicit. Run `pnpm openxiangda dev` for the connected loop and `pnpm openxiangda check` before delivery.
127
+
128
+ Keep the generated `apps/server/src/main.ts` on
129
+ `bootstrapOpenXiangdaApplication(AppModule)`. Do not replace it with an
130
+ application-owned `NestFactory` or `FastifyAdapter`: the SDK bootstrap owns the
131
+ exact raw request bytes required by gateway signatures, proxy trust, shutdown
132
+ hooks, and the runtime listen contract.
133
+
134
+ Connected development and release builds deliberately use different compilers,
135
+ so application Nest classes must never depend on emitted constructor metadata.
136
+ Every constructor dependency in a `@Controller` or `@Injectable` class uses an
137
+ explicit token:
138
+
139
+ ```ts
140
+ import { Controller, Inject, Post } from '@nestjs/common';
141
+ import { appOperations } from '@app/contracts';
142
+ import {
143
+ OpenXiangdaBusinessDataApiService,
144
+ OpenXiangdaOperation,
145
+ } from 'openxiangda/nest';
146
+
147
+ @Controller()
148
+ export class VisitorReservationsController {
149
+ constructor(
150
+ @Inject(OpenXiangdaBusinessDataApiService)
151
+ private readonly data: OpenXiangdaBusinessDataApiService,
152
+ ) {}
153
+
154
+ @Post('/api/reservations/enroll')
155
+ @OpenXiangdaOperation(appOperations.reservationEnroll)
156
+ async enroll() {
157
+ return await this.data.create('visitor-reservations', { status: 'pending' });
158
+ }
159
+ }
160
+ ```
161
+
162
+ `openxiangda check` and `openxiangda dev` reject implicit constructor injection.
163
+ Do not silence that diagnostic or replace the connected-development compiler.
164
+
165
+ Backend routes are private to the application unless their operation declaration contains an explicit `ai` block. Never infer AI exposure or risk from the HTTP method. A write action declares its touched resources and non-empty side effects, for example:
166
+
167
+ Build operation request and response schemas through
168
+ `resourceRecordSchema`, `schemaRef` and `composeAppOperationSchemas` from
169
+ `openxiangda/config`. These helpers project canonical field value protocols
170
+ from the same Resource declaration and prevent repeated user, department,
171
+ resource-reference or managed-file shapes. Do not import a physical toolchain
172
+ package or copy the JSON protocol by hand.
173
+
174
+ ```ts
175
+ {
176
+ code: 'reservation.enroll',
177
+ method: 'POST',
178
+ path: '/api/reservations/enroll',
179
+ capability: 'app:visitor-app:reservation:enroll',
180
+ ...composeAppOperationSchemas({
181
+ request: resourceRecordSchema(visitorReservations, {
182
+ fields: ['visitorName', 'visitDate', 'startTime'],
183
+ }),
184
+ response: schemaRef('ReservationRecord'),
185
+ definitions: {
186
+ ReservationRecord: resourceRecordSchema(visitorReservations),
187
+ },
188
+ }),
189
+ ai: {
190
+ name: '预约访客',
191
+ description: '校验预约规则并创建访客预约',
192
+ risk: 'write',
193
+ resources: ['reservations'],
194
+ sideEffects: ['reservations:create'],
195
+ concurrency: 'none',
196
+ timeoutMs: 10000,
197
+ },
198
+ }
199
+ ```
200
+
201
+ Every custom operation capability is declared once in
202
+ `authz.capabilities` with `kind: 'backend'`, then referenced by the operation
203
+ and granted to every role allowed to call it. A capability string written only
204
+ on an operation or role is invalid. Resource CRUD capabilities remain generated
205
+ and must not be copied into this catalog.
206
+
207
+ Generated CRUD and custom actions use the same platform Catalog, current-user authorization, Preview/Confirm boundary and idempotent execution path. Do not create an application-owned MCP server, preview store, AI role or database client.
208
+
209
+ For visitor duplicates, meeting-time conflicts, and course capacity, use
210
+ `OpenXiangdaStandardOperations`. These helpers submit the whole rule as one
211
+ platform transaction. Do not query mutable rows before calling them and do not
212
+ calculate replacement counters in application code. Course selection is a
213
+ locked `record-assert` plus a bounded `increment`; replay must reach the
214
+ platform idempotency receipt even after the course becomes full.
215
+
216
+ The visitor helper has one exact command shape. `duplicateMatch` is the actual
217
+ field-to-submitted-value object used for equality matching; it is never a list
218
+ of field names:
219
+
220
+ ```ts
221
+ return this.operations.createVisitorReservation({
222
+ reservationResourceCode: 'visitor-reservations',
223
+ duplicateMatch: {
224
+ visitorIdentityNumber: body.visitorIdentityNumber,
225
+ visitDate: body.visitDate,
226
+ startTime: body.startTime,
227
+ },
228
+ data: {
229
+ visitorIdentityNumber: body.visitorIdentityNumber,
230
+ visitDate: body.visitDate,
231
+ startTime: body.startTime,
232
+ status: body.status,
233
+ },
234
+ idempotencyKey: body.idempotencyKey,
235
+ activeStatusField: 'status',
236
+ activeStatusValues: ['pending', 'approved'],
237
+ });
238
+ ```
239
+
240
+ Use only declared field codes in `duplicateMatch`. Its values and `data` come
241
+ from the same immutable request body.
242
+
243
+ An idempotency key and the complete command payload are one immutable pair.
244
+ Never put `new Date()`, `Date.now()`, `randomUUID()` or another changing value
245
+ inside a controller while constructing the transaction. If a business time is
246
+ part of the record, declare it as a required operation request field; the
247
+ caller creates it once together with the idempotency key and reuses both on
248
+ every retry. Platform-created record timestamps remain the source of truth
249
+ when no separate business time is required.
250
+
251
+ When declaring a lower-level transaction directly, use only the current
252
+ contract:
253
+
254
+ - every guard has a stable `OPENXIANGDA_*` `errorCode`;
255
+ - `query-empty` protects a business-key uniqueness rule;
256
+ - `record-exists` requires one visible record without forcing a mutation of it;
257
+ - `record-match` requires one visible record plus typed value/field assertions,
258
+ and may protect a mutation of another resource;
259
+ - `record-assert` locks one exact record and checks declared field values or
260
+ declared field-to-field comparisons;
261
+ - `databaseNowAssertion('publishAt', 'lte')` compares a declared `datetime`
262
+ field with the single PostgreSQL transaction time. Do not pass `Date.now()`,
263
+ an offset, a SQL function or a fallback timestamp; a successful idempotent
264
+ replay returns the original `evaluatedAt` without re-evaluating the guard;
265
+ - `increment` targets one declared integer field and must have a matching
266
+ same-resource, same-record `record-assert` guard;
267
+ - never send SQL, table names, expressions, old guards without `errorCode`, or
268
+ a pre-read/absolute-update fallback.
@@ -0,0 +1,21 @@
1
+ # OpenXiangda 2.0 Commands
2
+
3
+ > Generated from `DEVKIT_COMMANDS`. Do not edit manually.
4
+
5
+ | Command | Risk | Purpose |
6
+ | --- | --- | --- |
7
+ | `pnpm openxiangda create` | deploy | 创建、绑定并初始化应用 |
8
+ | `pnpm openxiangda dev` | write-local | 连接平台测试数据启动本地 Web 与 Nest |
9
+ | `pnpm openxiangda check` | write-local | 生成契约并在目标平台预检后执行检查、测试和构建 |
10
+ | `pnpm openxiangda accept` | deploy | 按计划准备可选的真实预发验收身份 |
11
+ | `pnpm openxiangda deploy` | deploy | 部署测试环境或显式复用测试版本部署生产 |
12
+ | `pnpm openxiangda status` | read | 查询最近或指定部署状态 |
13
+ | `pnpm openxiangda logs` | read | 查询最近或指定部署日志 |
14
+ | `pnpm openxiangda cancel` | deploy | 幂等取消尚未提交激活的部署 |
15
+ | `pnpm openxiangda retry` | deploy | 显式重试可恢复的失败部署 |
16
+ | `pnpm openxiangda start` | deploy | 从当前不可变版本启动应用环境 |
17
+ | `pnpm openxiangda stop` | deploy | 将应用环境缩容为零并保留数据 |
18
+ | `pnpm openxiangda rollback` | deploy | 回滚测试或生产环境 |
19
+ | `pnpm openxiangda login` | write-local | 通过平台浏览器授权登录 |
20
+ | `pnpm openxiangda skill` | write-local | 安装当前版本的 AI Skill |
21
+ | `pnpm openxiangda spec` | write-local | 维护可选的 AppSpec 需求与变更辅助 |
@@ -0,0 +1,270 @@
1
+ # OpenXiangda 2.0 Data and Authorization
2
+
3
+ Declare a resource and every field exactly once in `openxiangda.config.ts`.
4
+ Do not write `schemaVersion`, `appCode`, `schema`, `capabilities`, `surface` or
5
+ resource-level `fieldPolicies`; those are compiler projections, not application
6
+ source. Do not create `platform/data` modules.
7
+
8
+ ```ts
9
+ import {
10
+ currentUserDataPolicy,
11
+ dataPolicyExpression,
12
+ defineOpenXiangdaApp,
13
+ resourceCapabilityCodes,
14
+ resourceReadPolicy,
15
+ } from 'openxiangda/config';
16
+
17
+ const APP_CODE = 'visitor-center';
18
+ const reservations = resourceCapabilityCodes(APP_CODE, 'visitor-reservations');
19
+
20
+ const visitorReservations = {
21
+ code: 'visitor-reservations',
22
+ name: '访客预约',
23
+ dataPolicyCode: 'reservation-host',
24
+ fields: [
25
+ {
26
+ code: 'visitorName', type: 'text.short', label: '访客姓名', required: true,
27
+ indexed: true, list: true, filter: true, searchable: true, sortable: true,
28
+ section: '访客信息',
29
+ },
30
+ {
31
+ code: 'visitDate', type: 'date', label: '来访日期', required: true,
32
+ list: true, filter: true, sortable: true, section: '来访安排',
33
+ },
34
+ {
35
+ code: 'hostUserId', type: 'user.single', label: '接待人', required: true,
36
+ list: true, filter: true,
37
+ },
38
+ {
39
+ code: 'hostDepartmentId', type: 'department.single', label: '接待部门',
40
+ list: true, filter: true,
41
+ },
42
+ {
43
+ code: 'attachments', type: 'file', label: '附件',
44
+ file: { maxCount: 5, maxSizeMb: 20, accept: ['image/*', '.pdf'] },
45
+ },
46
+ {
47
+ code: 'internalNote', type: 'text.long', label: '内部备注',
48
+ access: { read: ['app:visitor-center:internal-note:read'], update: false },
49
+ },
50
+ ],
51
+ list: { defaultPageSize: 20, defaultSort: { field: 'visitDate', order: 'desc' } },
52
+ form: { layout: 'sections' }, detail: { layout: 'sections' },
53
+ mobile: { enabled: true },
54
+ };
55
+ ```
56
+
57
+ Put it in `data: { resources: [visitorReservations] }`. Resource CRUD
58
+ capabilities are derived by `resourceCapabilityCodes`; grant the needed values
59
+ to roles. Directory-backed roles also require
60
+ `app:<app-code>:directory:read`. Explicit field `access` capability codes are
61
+ also granted only to the intended roles. They are owned and exported by the
62
+ generated field policy, so do not repeat them in `authz.capabilities`.
63
+ `authz.capabilities` contains only explicit `backend` or `ui` capabilities.
64
+
65
+ Declare mutation ownership on the same resource with
66
+ `mutationOwner: 'native' | 'action' | 'readonly' | 'workflow'`. Native defaults
67
+ to generated list/detail/create/update/delete. Other owners default to readable
68
+ list/detail only and must use their named action or Workflow boundary for
69
+ mutation. Use `generated: { list, detail, create, update, delete }` to narrow
70
+ the generated page/operation surface. The compiler rejects Native mutation
71
+ pages, AI operations or role grants on a non-Native owner, and rejects
72
+ create/update when no writable business field exists. Do not grant a resource
73
+ create/update/delete capability to make an action-owned record editable.
74
+
75
+ Declare optional work Perspectives once at the application root. A Perspective
76
+ references existing role codes; the compiler derives its readable capability
77
+ projection, so never hand-author `capabilityCodes` or duplicate row filters:
78
+
79
+ ```ts
80
+ export default defineOpenXiangdaApp({
81
+ // ...identity, authz and data...
82
+ perspectives: [
83
+ {
84
+ code: 'reception-desk',
85
+ name: '接待人员视角',
86
+ roleCodes: ['reception_staff'],
87
+ default: true,
88
+ },
89
+ {
90
+ code: 'visitor-admin',
91
+ name: '访客管理员视角',
92
+ roleCodes: ['visitor_admin'],
93
+ },
94
+ ],
95
+ });
96
+ ```
97
+
98
+ The runtime offers only Perspectives whose `roleCodes` intersect the current
99
+ user's actual application-role union. Selecting one sends
100
+ `X-OpenXiangda-Perspective` on standard reads. Native Data intersects the
101
+ normal authorized role union with that Perspective before capability, field,
102
+ row-policy and RLS evaluation. Omit the header for the complete union. Never
103
+ use Perspective to guard writes, workflows or custom actions.
104
+
105
+ `required: true` owns both storage nullability and form validation. A field
106
+ without `access` inherits the resource read/create/update capability. Each
107
+ access array is all-of; `false` is explicit deny. The same arrays drive the
108
+ generated UI and platform field policies.
109
+
110
+ For `uuid` fields, omission never generates a value. Only the resource system
111
+ field `id` is platform-generated. An omitted optional UUID remains `null`; a
112
+ required UUID must be supplied explicitly and cannot rely on an implicit
113
+ database default.
114
+
115
+ Field types are semantic, not PostgreSQL storage aliases. Use the catalog in the generated `AGENTS.md`: for example `text.short`, `number.integer`, `user.single`, `department.multiple`, `resource-ref.single`, `file`, `address` and `subtable`. The compiler alone chooses storage columns and constraints. Reference fields store JSON display values. For `resource-ref.*`, `resourceCode`, `value`, `label`, optional `description` and optional `snapshot` are convenient historical display data only: the target resource remains authoritative, the platform does not create a foreign key or refresh/check the stored JSON, and business actions that need current target state must query it by `resourceCode` plus `value`. A resource source `labelField` must point to `text.short` or `text.long`; a `serial-number` field can be listed in `searchFields`, `descriptionFields` or `snapshotFields`, but it is not a display label. File limits exist only under `file`; `maxCount` owns the single/multiple bound and `maxSizeMb` owns the per-file size bound. There is no `file.multiple` key.
116
+
117
+ Generated list, detail, audit and preview surfaces render the stored canonical
118
+ `label` snapshots for `option.*`, `user.*`, `department.*` and
119
+ `resource-ref.*`, including multiple arrays and the first linked list column.
120
+ Do not add application formatters, directory re-queries or browser-side joins
121
+ for these standard fields.
122
+
123
+ Numeric bounds belong on the field declaration and are enforced by the
124
+ platform for every write path. They are inclusive, and only valid on
125
+ `number.integer` or `number.decimal`:
126
+
127
+ ```ts
128
+ { code: 'capacity', type: 'number.integer', label: '容量', required: true, min: 0, max: 10000 }
129
+ ```
130
+
131
+ Cross-field rules belong on the resource, not in a generated form callback.
132
+ Only bounded same-record field comparisons are supported; declare multiple
133
+ invariants when all must hold:
134
+
135
+ ```ts
136
+ {
137
+ code: 'sessions',
138
+ name: '场次',
139
+ fields: [
140
+ { code: 'startAt', type: 'datetime', label: '开始时间', required: true },
141
+ { code: 'endAt', type: 'datetime', label: '结束时间', required: true },
142
+ { code: 'capacity', type: 'number.integer', label: '容量', required: true, min: 0 },
143
+ { code: 'occupied', type: 'number.integer', label: '已占用', required: true, min: 0 },
144
+ ],
145
+ invariants: [
146
+ { code: 'time-order', expression: { leftField: 'startAt', operator: 'lt', rightField: 'endAt' } },
147
+ { code: 'capacity-not-exceeded', expression: { leftField: 'capacity', operator: 'gte', rightField: 'occupied' } },
148
+ ],
149
+ }
150
+ ```
151
+
152
+ `datetime-range` is always a non-empty half-open interval `[start, end)`.
153
+ Adjacent values such as `[10:00, 11:00)` and `[11:00, 12:00)` do not overlap.
154
+ Use the ordinary `overlaps` query operator or a `query-empty` transaction guard;
155
+ never add or subtract milliseconds at the boundary.
156
+
157
+ Do not author raw schema or storage words as field types. `string`, `text`,
158
+ `integer`, `decimal`, `boolean`, `date`, `datetime`, `uuid`, `json` and `file`
159
+ describe value or storage families only when the platform protocol says so;
160
+ their authored counterparts are the semantic catalog entries above (some names
161
+ such as `date`, `datetime`, `uuid`, `json` and `file` intentionally coincide).
162
+ In particular, `number` is not a field type: choose `number.integer` or
163
+ `number.decimal`.
164
+
165
+ Current-user row access has one spelling only:
166
+
167
+ ```ts
168
+ currentUserDataPolicy({
169
+ code: 'reservation-host',
170
+ name: '接待人员仅查看本人预约',
171
+ resourceCode: 'visitor-reservations',
172
+ field: 'hostUserId',
173
+ roleCodes: ['reception_staff'],
174
+ unrestrictedRoleCodes: ['visitor_admin'],
175
+ })
176
+ ```
177
+
178
+ Put that value in `authz.dataPolicies`, declare both roles, and set the
179
+ resource `dataPolicyCode` to the same code. Do not invent `current_user: true`,
180
+ lowercase match modes, a dotted value path, or policy-level `roleCodes`. The
181
+ compiler and platform know that `user.*` fields compare their stable `value`;
182
+ `field` remains the declared field root code.
183
+
184
+ For portal visibility windows, use the typed SDK expression and keep it a
185
+ server-enforced read policy:
186
+
187
+ ```ts
188
+ resourceReadPolicy({
189
+ code: 'published-articles',
190
+ name: '仅查看当前已发布内容',
191
+ resourceCode: 'articles',
192
+ matchMode: 'AND',
193
+ rules: [{ dimensionCode: 'organization', field: 'organizationId' }],
194
+ expression: dataPolicyExpression.allOf(
195
+ dataPolicyExpression.constant({
196
+ field: 'status', operator: 'eq', value: 'PUBLISHED',
197
+ }),
198
+ dataPolicyExpression.databaseNow({
199
+ field: 'publishAt', operator: 'lte',
200
+ }),
201
+ dataPolicyExpression.anyOf(
202
+ dataPolicyExpression.null({ field: 'expireAt', operator: 'is_null' }),
203
+ dataPolicyExpression.databaseNow({ field: 'expireAt', operator: 'gt' }),
204
+ ),
205
+ ),
206
+ })
207
+ ```
208
+
209
+ `db_now` is platform-owned PostgreSQL statement time and only accepts a
210
+ `datetime` field. Missing/null values match only `is_null`; they do not match
211
+ negative constants or time comparisons. The same bounded expression can
212
+ combine `currentUser`, `dimension`, `relation`, `constant`, `null`, and
213
+ `databaseNow` leaves under `allOf`/`anyOf`. Never duplicate this expression in
214
+ a page `where` filter and call it authorization: UI filters are optional
215
+ display state and cannot weaken or replace Native RLS.
216
+
217
+ `readExpression` is always added on top of the base `matchMode`/`rules`; those
218
+ base rules continue to restrict create/update/delete. If writes truly need no
219
+ row scope beyond capability checks, say so explicitly with
220
+ `writeBoundary: 'capability_only'` instead of `matchMode`/`rules`. Never use an
221
+ empty base implicitly: `check` rejects it so an AI cannot accidentally remove
222
+ write authorization while adding a portal read window.
223
+
224
+ When a business membership resource is the durable source of a package role or
225
+ RelationshipGrant, declare the projection instead of calling authorization
226
+ management endpoints from application code:
227
+
228
+ ```ts
229
+ authz: {
230
+ // ...capabilities, roles and policies...
231
+ roleMembershipSources: [{
232
+ code: 'venue-managers',
233
+ name: '场馆管理员角色成员',
234
+ resourceCode: 'venue-manager-relations',
235
+ userIdField: 'manager.value',
236
+ roleCode: 'venue_admin',
237
+ enabledField: 'enabled',
238
+ failureMode: 'strict',
239
+ }],
240
+ relationshipGrantSources: [{
241
+ code: 'venue-member-grants',
242
+ name: '场馆成员关系授权',
243
+ resourceCode: 'venue-manager-relations',
244
+ subject: { type: 'user', userIdField: 'manager.value' },
245
+ relationCode: 'member',
246
+ targetResourceCode: 'venues',
247
+ resourceIdField: 'venue.value',
248
+ operations: ['read', 'update'],
249
+ enabledField: 'enabled',
250
+ failureMode: 'strict',
251
+ }],
252
+ }
253
+ ```
254
+
255
+ The user path must be `user.single.value`; the target path is `id` only when the
256
+ source resource is also the target resource, or a `resource-ref.single.value`
257
+ that points at the declared target resource.
258
+ Operations are a bounded constant list. Create/update/delete the relationship
259
+ resource through the standard Data API; the platform converges and revokes only
260
+ the facts owned by that source. Projection failure is always strict because a
261
+ last-known-good grant could defeat revocation.
262
+
263
+ Use the SDK projection health call after deployment. A platform operator with
264
+ the existing authorization-management capability may run rebuild for historical
265
+ rows or recover a dead-letter job. Rebuild/recovery are idempotent and accept an
266
+ `operationId`; they never accept a user token, user id override or impersonation
267
+ input. Do not write `sourceCode`, canonical membership rows or relationship
268
+ grant rows yourself.
269
+
270
+ Run `pnpm openxiangda check` after every declaration or permission change.