@openplanr/protocol 0.6.1 → 0.7.0

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.
Files changed (58) hide show
  1. package/README.md +10 -0
  2. package/lib/dashboard/closed-json-contract.mjs +99 -109
  3. package/lib/dashboard/operate-experience-audit-display-contract.d.mts +128 -153
  4. package/lib/dashboard/operate-experience-audit-display-contract.mjs +530 -585
  5. package/lib/dashboard/operate-experience-display-contract.d.mts +415 -437
  6. package/lib/dashboard/operate-experience-display-contract.mjs +777 -831
  7. package/lib/dashboard/operate-experience-surface-contract.d.mts +143 -148
  8. package/lib/dashboard/operate-experience-surface-contract.mjs +72 -73
  9. package/lib/dashboard/operate-review-contract.d.mts +7 -14
  10. package/lib/dashboard/operate-review-contract.mjs +46 -42
  11. package/lib/dashboard/operate-review-display-workspace-contract.d.mts +2 -5
  12. package/lib/dashboard/operate-review-display-workspace-contract.mjs +158 -104
  13. package/lib/dashboard/operate-review-payload-safety.mjs +4 -2
  14. package/lib/dashboard/operate-review-workspace-projection-v2.d.mts +47 -33
  15. package/lib/protocol/index.d.ts +2647 -543
  16. package/package.json +1 -1
  17. package/registries/artifact-theme.json +64 -0
  18. package/registries/commands.json +40 -40
  19. package/registries/skills.json +5 -5
  20. package/schemas/v1.14.0/artifact-theme.schema.json +316 -0
  21. package/src/browser-contracts.d.mts +4 -1
  22. package/src/browser-contracts.mjs +16 -5
  23. package/src/canonical-json.d.mts +6 -1
  24. package/src/canonical-json.mjs +100 -22
  25. package/src/compat/live-evidence-v2.mjs +1611 -485
  26. package/src/compat/operate-experience-live-patch.mjs +67 -15
  27. package/src/compat/operating-planning-contracts.mjs +183 -51
  28. package/src/contracts.d.mts +54 -13
  29. package/src/contracts.mjs +635 -343
  30. package/src/design-contracts.mjs +58 -21
  31. package/src/design-handoff-contracts.d.mts +67 -11
  32. package/src/design-handoff-contracts.mjs +236 -119
  33. package/src/design-publication-contracts.mjs +98 -33
  34. package/src/diagram-authoring-contracts.d.mts +422 -78
  35. package/src/diagram-authoring-contracts.mjs +1715 -335
  36. package/src/diagram-contracts.d.mts +4 -1
  37. package/src/diagram-contracts.mjs +16 -4
  38. package/src/enterprise-contracts.d.mts +211 -46
  39. package/src/enterprise-contracts.mjs +738 -184
  40. package/src/errors.mjs +4 -0
  41. package/src/generated/canonical-registries.mjs +45 -45
  42. package/src/index.d.mts +8 -8
  43. package/src/index.mjs +36 -20
  44. package/src/json-schema.d.mts +21 -6
  45. package/src/json-schema.mjs +66 -18
  46. package/src/planning-contracts.d.mts +8 -2
  47. package/src/planning-contracts.mjs +33 -7
  48. package/src/registries.d.mts +11 -3
  49. package/src/registries.mjs +369 -87
  50. package/src/review-experience-contracts.d.mts +7 -2
  51. package/src/review-experience-contracts.mjs +198 -49
  52. package/src/semver.mjs +5 -1
  53. package/src/skill-source-contracts.d.mts +36 -16
  54. package/src/skill-source-contracts.mjs +25 -6
  55. package/src/task-contracts.d.mts +13 -3
  56. package/src/task-contracts.mjs +181 -40
  57. package/src/workspace-contracts.d.mts +38 -10
  58. package/src/workspace-contracts.mjs +147 -33
@@ -1,23 +1,67 @@
1
- import { canonicalizeJson, sha256Hex } from './canonical-json.mjs';
1
+ // @ts-check
2
+ /**
3
+ * Enterprise collaboration contracts (Protocol 1.12.0): closed schemas and validators for access
4
+ * context, revisions, review threads, change proposals, evidence, sync state and agent handoffs,
5
+ * plus a fail-closed access policy, escaped handoff Markdown and semantic document diffs.
6
+ * Entry points: `assertEnterpriseContract`, `authorizeEnterpriseAccess`, `createEnterpriseHandoff`,
7
+ * `diffEnterpriseDocuments`, `applyEnterpriseOperations`. Identity verification, current grants
8
+ * and atomic revision writes belong to the caller's storage adapter.
9
+ */
10
+
11
+ import { canonicalizeJson, deepFreeze, sha256Hex } from './canonical-json.mjs';
2
12
  import { validateJson } from './json-schema.mjs';
3
13
 
14
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_CONTRACT_VERSION} */
4
15
  export const ENTERPRISE_CONTRACT_VERSION = '1.0.0';
16
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_PROTOCOL_VERSION} */
5
17
  export const ENTERPRISE_PROTOCOL_VERSION = '1.12.0';
18
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_CONTENT_DIGEST_HEADER} */
6
19
  export const ENTERPRISE_CONTENT_DIGEST_HEADER = 'X-OpenPlanr-Content-Digest';
20
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_ID_PATTERN} */
7
21
  export const ENTERPRISE_ID_PATTERN = '^[A-Za-z0-9][A-Za-z0-9_-]{0,127}(?![\\s\\S])';
8
- export const ENTERPRISE_REVIEW_CATEGORIES = Object.freeze(['question', 'suggestion', 'change-request', 'blocker']);
22
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_REVIEW_CATEGORIES} */
23
+ export const ENTERPRISE_REVIEW_CATEGORIES = Object.freeze([
24
+ 'question',
25
+ 'suggestion',
26
+ 'change-request',
27
+ 'blocker',
28
+ ]);
29
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_ACTIONS} */
9
30
  export const ENTERPRISE_ACTIONS = Object.freeze([
10
- 'organization.manage', 'ownership.transfer', 'billing.manage', 'audit.read', 'project.create', 'project.manage',
11
- 'artifact.read', 'artifact.author', 'artifact.export', 'review.write', 'review.resolve',
31
+ 'organization.manage',
32
+ 'ownership.transfer',
33
+ 'billing.manage',
34
+ 'audit.read',
35
+ 'project.create',
36
+ 'project.manage',
37
+ 'artifact.read',
38
+ 'artifact.author',
39
+ 'artifact.export',
40
+ 'review.write',
41
+ 'review.resolve',
12
42
  ]);
13
43
  const id = { type: 'string', pattern: ENTERPRISE_ID_PATTERN };
14
- const semanticId = { type: 'string', minLength: 1, maxLength: 512, pattern: '^[^\\s\\u0000-\\u001f\\u007f]+$' };
44
+ const semanticId = {
45
+ type: 'string',
46
+ minLength: 1,
47
+ maxLength: 512,
48
+ pattern: '^[^\\s\\u0000-\\u001f\\u007f]+$',
49
+ };
15
50
  const nullableId = { anyOf: [id, { type: 'null' }] };
16
51
  const digest = { type: 'string', minLength: 64, maxLength: 64, pattern: '^[a-f0-9]{64}$' };
17
- const timestamp = { type: 'string', format: 'date-time', pattern: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{3})?Z$' };
52
+ const timestamp = {
53
+ type: 'string',
54
+ format: 'date-time',
55
+ pattern: '^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{3})?Z$',
56
+ };
18
57
  const text = { type: 'string', minLength: 1, maxLength: 16384 };
19
58
  const title = { ...text, maxLength: 240 };
20
- const closed = (properties, required = Object.keys(properties)) => ({ type: 'object', additionalProperties: false, properties, required });
59
+ const closed = (properties, required = Object.keys(properties)) => ({
60
+ type: 'object',
61
+ additionalProperties: false,
62
+ properties,
63
+ required,
64
+ });
21
65
  const list = (items, maxItems = 1000) => ({ type: 'array', items, maxItems });
22
66
  const schema = (name, properties, required) => ({
23
67
  $schema: 'https://json-schema.org/draft/2020-12/schema',
@@ -25,96 +69,308 @@ const schema = (name, properties, required) => ({
25
69
  'x-openplanr-contract': { id: name, version: ENTERPRISE_PROTOCOL_VERSION },
26
70
  ...closed(properties, required),
27
71
  });
28
- const envelope = (kind) => ({ kind: { const: `openplanr-${kind}` }, schemaVersion: { const: ENTERPRISE_CONTRACT_VERSION } });
72
+ const envelope = (kind) => ({
73
+ kind: { const: `openplanr-${kind}` },
74
+ schemaVersion: { const: ENTERPRISE_CONTRACT_VERSION },
75
+ });
29
76
  const scoped = { organizationId: id, projectId: id };
30
77
  const versionedArtifact = { ...scoped, artifactId: id, revisionId: id };
31
78
  const activeStatus = { enum: ['active', 'revoked'] };
32
79
  const projectRole = { enum: ['maintainer', 'author', 'reviewer', 'viewer'] };
33
80
 
34
- export const ENTERPRISE_ACCESS_CONTEXT_SCHEMA = schema('enterprise-access-context', {
35
- actor: closed({ id, verified: { type: 'boolean' } }),
36
- organization: closed({ id, status: { enum: ['active', 'suspended'] } }),
37
- membership: closed({ organizationId: id, actorId: id, role: { enum: ['owner', 'admin', 'member'] }, status: activeStatus }),
38
- projectMembership: closed({ ...scoped, actorId: id, role: projectRole, status: activeStatus }),
39
- guestGrant: closed({ ...scoped, artifactId: id, actorId: id, role: { enum: ['reviewer', 'viewer'] }, status: activeStatus, expiresAt: timestamp }),
40
- resource: closed({ organizationId: id, projectId: id, artifactId: id }, ['organizationId']),
41
- action: { enum: ENTERPRISE_ACTIONS }, now: timestamp,
42
- }, ['actor', 'organization', 'resource', 'action', 'now']);
81
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_ACCESS_CONTEXT_SCHEMA} */
82
+ export const ENTERPRISE_ACCESS_CONTEXT_SCHEMA = schema(
83
+ 'enterprise-access-context',
84
+ {
85
+ actor: closed({ id, verified: { type: 'boolean' } }),
86
+ organization: closed({ id, status: { enum: ['active', 'suspended'] } }),
87
+ membership: closed({
88
+ organizationId: id,
89
+ actorId: id,
90
+ role: { enum: ['owner', 'admin', 'member'] },
91
+ status: activeStatus,
92
+ }),
93
+ projectMembership: closed({ ...scoped, actorId: id, role: projectRole, status: activeStatus }),
94
+ guestGrant: closed({
95
+ ...scoped,
96
+ artifactId: id,
97
+ actorId: id,
98
+ role: { enum: ['reviewer', 'viewer'] },
99
+ status: activeStatus,
100
+ expiresAt: timestamp,
101
+ }),
102
+ resource: closed({ organizationId: id, projectId: id, artifactId: id }, ['organizationId']),
103
+ action: { enum: ENTERPRISE_ACTIONS },
104
+ now: timestamp,
105
+ },
106
+ ['actor', 'organization', 'resource', 'action', 'now'],
107
+ );
43
108
 
109
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_ARTIFACT_REVISION_SCHEMA} */
44
110
  export const ENTERPRISE_ARTIFACT_REVISION_SCHEMA = schema('enterprise-artifact-revision', {
45
- ...envelope('enterprise-artifact-revision'), id, ...scoped, artifactId: id, parentRevisionId: nullableId,
46
- contentDigest: digest, contentType: { enum: ['application/json', 'text/markdown', 'image/svg+xml', 'text/html'] },
47
- byteLength: { type: 'integer', minimum: 0, maximum: 5 * 1024 * 1024 }, createdAt: timestamp, actorId: id,
111
+ ...envelope('enterprise-artifact-revision'),
112
+ id,
113
+ ...scoped,
114
+ artifactId: id,
115
+ parentRevisionId: nullableId,
116
+ contentDigest: digest,
117
+ contentType: { enum: ['application/json', 'text/markdown', 'image/svg+xml', 'text/html'] },
118
+ byteLength: { type: 'integer', minimum: 0, maximum: 5 * 1024 * 1024 },
119
+ createdAt: timestamp,
120
+ actorId: id,
48
121
  });
49
122
 
50
- export const ENTERPRISE_REVIEW_ANCHOR_SCHEMA = closed({
51
- revisionId: id, elementId: semanticId, screenId: semanticId, frameId: semanticId,
52
- x: { type: 'number', minimum: 0, maximum: 1 }, y: { type: 'number', minimum: 0, maximum: 1 },
53
- }, ['revisionId']);
54
- ENTERPRISE_REVIEW_ANCHOR_SCHEMA.anyOf = [{ required: ['elementId'] }, { required: ['screenId', 'frameId'] }, { required: ['x', 'y'] }];
55
- ENTERPRISE_REVIEW_ANCHOR_SCHEMA.allOf = [
56
- { if: { required: ['x'] }, then: { required: ['y'] } },
57
- { if: { required: ['y'] }, then: { required: ['x'] } },
58
- { if: { required: ['frameId'] }, then: { required: ['screenId'] } },
59
- ];
123
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_REVIEW_ANCHOR_SCHEMA} */
124
+ export const ENTERPRISE_REVIEW_ANCHOR_SCHEMA = {
125
+ ...closed(
126
+ {
127
+ revisionId: id,
128
+ elementId: semanticId,
129
+ screenId: semanticId,
130
+ frameId: semanticId,
131
+ x: { type: 'number', minimum: 0, maximum: 1 },
132
+ y: { type: 'number', minimum: 0, maximum: 1 },
133
+ },
134
+ ['revisionId'],
135
+ ),
136
+ anyOf: [
137
+ { required: ['elementId'] },
138
+ { required: ['screenId', 'frameId'] },
139
+ { required: ['x', 'y'] },
140
+ ],
141
+ allOf: [
142
+ { if: { required: ['x'] }, then: { required: ['y'] } },
143
+ { if: { required: ['y'] }, then: { required: ['x'] } },
144
+ { if: { required: ['frameId'] }, then: { required: ['screenId'] } },
145
+ ],
146
+ };
60
147
  const reply = closed({ id, authorId: id, body: text, createdAt: timestamp });
61
- export const ENTERPRISE_REVIEW_THREAD_SCHEMA = schema('enterprise-review-thread', {
62
- ...envelope('enterprise-review-thread'), id, ...scoped, artifactId: id, anchor: ENTERPRISE_REVIEW_ANCHOR_SCHEMA,
63
- category: { enum: ENTERPRISE_REVIEW_CATEGORIES }, status: { enum: ['open', 'addressed', 'resolved'] }, authorId: id,
64
- body: text, createdAt: timestamp, updatedAt: timestamp, replies: list(reply, 10000),
65
- assigneeId: nullableId, addressedRevisionId: id, resolvedAt: timestamp,
66
- }, ['kind', 'schemaVersion', 'id', 'organizationId', 'projectId', 'artifactId', 'anchor', 'category', 'status', 'authorId', 'body', 'createdAt', 'updatedAt', 'replies']);
67
- ENTERPRISE_REVIEW_THREAD_SCHEMA.allOf = [
68
- { if: { properties: { status: { const: 'addressed' } } }, then: { required: ['addressedRevisionId'], not: { required: ['resolvedAt'] } } },
69
- { if: { properties: { status: { const: 'resolved' } } }, then: { required: ['resolvedAt'] }, else: { not: { required: ['resolvedAt'] } } },
70
- ];
148
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_REVIEW_THREAD_SCHEMA} */
149
+ export const ENTERPRISE_REVIEW_THREAD_SCHEMA = {
150
+ ...schema(
151
+ 'enterprise-review-thread',
152
+ {
153
+ ...envelope('enterprise-review-thread'),
154
+ id,
155
+ ...scoped,
156
+ artifactId: id,
157
+ anchor: ENTERPRISE_REVIEW_ANCHOR_SCHEMA,
158
+ category: { enum: ENTERPRISE_REVIEW_CATEGORIES },
159
+ status: { enum: ['open', 'addressed', 'resolved'] },
160
+ authorId: id,
161
+ body: text,
162
+ createdAt: timestamp,
163
+ updatedAt: timestamp,
164
+ replies: list(reply, 10000),
165
+ assigneeId: nullableId,
166
+ addressedRevisionId: id,
167
+ resolvedAt: timestamp,
168
+ },
169
+ [
170
+ 'kind',
171
+ 'schemaVersion',
172
+ 'id',
173
+ 'organizationId',
174
+ 'projectId',
175
+ 'artifactId',
176
+ 'anchor',
177
+ 'category',
178
+ 'status',
179
+ 'authorId',
180
+ 'body',
181
+ 'createdAt',
182
+ 'updatedAt',
183
+ 'replies',
184
+ ],
185
+ ),
186
+ allOf: [
187
+ {
188
+ if: { properties: { status: { const: 'addressed' } } },
189
+ then: { required: ['addressedRevisionId'], not: { required: ['resolvedAt'] } },
190
+ },
191
+ {
192
+ if: { properties: { status: { const: 'resolved' } } },
193
+ then: { required: ['resolvedAt'] },
194
+ else: { not: { required: ['resolvedAt'] } },
195
+ },
196
+ ],
197
+ };
71
198
 
72
199
  const collection = { enum: ['nodes', 'relations', 'groups', 'events', 'items'] };
73
- export const ENTERPRISE_CHANGE_OPERATION_SCHEMA = { oneOf: [
74
- closed({ op: { const: 'replace-document' }, content: { type: 'object' } }),
75
- closed({ op: { const: 'set-field' }, targetId: semanticId, field: { enum: ['label', 'description', 'status', 'title'] }, value: { type: 'string', maxLength: 16384 } }),
76
- closed({ op: { const: 'add-element' }, collection, element: { type: 'object', required: ['id'], properties: { id: semanticId }, additionalProperties: true } }),
77
- closed({ op: { const: 'remove-element' }, collection, targetId: semanticId }),
78
- closed({ op: { const: 'set-layout' }, targetId: semanticId, x: { type: 'number', minimum: -1e7, maximum: 1e7 }, y: { type: 'number', minimum: -1e7, maximum: 1e7 } }),
79
- ] };
80
- export const ENTERPRISE_CHANGE_PROPOSAL_SCHEMA = schema('enterprise-change-proposal', {
81
- ...envelope('enterprise-change-proposal'), id, ...scoped, artifactId: id, baseRevisionId: id,
82
- authorId: id, createdAt: timestamp, status: { enum: ['draft', 'proposed', 'accepted', 'rejected', 'applied', 'conflicted'] },
83
- summary: title, operations: { ...list(ENTERPRISE_CHANGE_OPERATION_SCHEMA, 1000), minItems: 1 },
84
- validation: closed({ status: { enum: ['pending', 'passed', 'failed'] }, issues: list(closed({ code: id, message: text, targetId: semanticId }, ['code', 'message'])) }),
85
- application: closed({ revisionId: id, appliedAt: timestamp, actorId: id, gitCommit: { type: 'string', pattern: '^(?:[a-f0-9]{40}|[a-f0-9]{64})$' } }, ['revisionId', 'appliedAt', 'actorId']),
86
- }, ['kind', 'schemaVersion', 'id', 'organizationId', 'projectId', 'artifactId', 'baseRevisionId', 'authorId', 'createdAt', 'status', 'summary', 'operations', 'validation']);
87
- ENTERPRISE_CHANGE_PROPOSAL_SCHEMA.allOf = [
88
- { if: { properties: { status: { const: 'applied' } } }, then: { required: ['application'], properties: { validation: { properties: { status: { const: 'passed' } } } } }, else: { not: { required: ['application'] } } },
89
- { if: { properties: { status: { const: 'accepted' } } }, then: { properties: { validation: { properties: { status: { const: 'passed' } } } } } },
90
- ];
200
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_CHANGE_OPERATION_SCHEMA} */
201
+ export const ENTERPRISE_CHANGE_OPERATION_SCHEMA = {
202
+ oneOf: [
203
+ closed({ op: { const: 'replace-document' }, content: { type: 'object' } }),
204
+ closed({
205
+ op: { const: 'set-field' },
206
+ targetId: semanticId,
207
+ field: { enum: ['label', 'description', 'status', 'title'] },
208
+ value: { type: 'string', maxLength: 16384 },
209
+ }),
210
+ closed({
211
+ op: { const: 'add-element' },
212
+ collection,
213
+ element: {
214
+ type: 'object',
215
+ required: ['id'],
216
+ properties: { id: semanticId },
217
+ additionalProperties: true,
218
+ },
219
+ }),
220
+ closed({ op: { const: 'remove-element' }, collection, targetId: semanticId }),
221
+ closed({
222
+ op: { const: 'set-layout' },
223
+ targetId: semanticId,
224
+ x: { type: 'number', minimum: -1e7, maximum: 1e7 },
225
+ y: { type: 'number', minimum: -1e7, maximum: 1e7 },
226
+ }),
227
+ ],
228
+ };
229
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_CHANGE_PROPOSAL_SCHEMA} */
230
+ export const ENTERPRISE_CHANGE_PROPOSAL_SCHEMA = {
231
+ ...schema(
232
+ 'enterprise-change-proposal',
233
+ {
234
+ ...envelope('enterprise-change-proposal'),
235
+ id,
236
+ ...scoped,
237
+ artifactId: id,
238
+ baseRevisionId: id,
239
+ authorId: id,
240
+ createdAt: timestamp,
241
+ status: { enum: ['draft', 'proposed', 'accepted', 'rejected', 'applied', 'conflicted'] },
242
+ summary: title,
243
+ operations: { ...list(ENTERPRISE_CHANGE_OPERATION_SCHEMA, 1000), minItems: 1 },
244
+ validation: closed({
245
+ status: { enum: ['pending', 'passed', 'failed'] },
246
+ issues: list(
247
+ closed({ code: id, message: text, targetId: semanticId }, ['code', 'message']),
248
+ ),
249
+ }),
250
+ application: closed(
251
+ {
252
+ revisionId: id,
253
+ appliedAt: timestamp,
254
+ actorId: id,
255
+ gitCommit: { type: 'string', pattern: '^(?:[a-f0-9]{40}|[a-f0-9]{64})$' },
256
+ },
257
+ ['revisionId', 'appliedAt', 'actorId'],
258
+ ),
259
+ },
260
+ [
261
+ 'kind',
262
+ 'schemaVersion',
263
+ 'id',
264
+ 'organizationId',
265
+ 'projectId',
266
+ 'artifactId',
267
+ 'baseRevisionId',
268
+ 'authorId',
269
+ 'createdAt',
270
+ 'status',
271
+ 'summary',
272
+ 'operations',
273
+ 'validation',
274
+ ],
275
+ ),
276
+ allOf: [
277
+ {
278
+ if: { properties: { status: { const: 'applied' } } },
279
+ then: {
280
+ required: ['application'],
281
+ properties: { validation: { properties: { status: { const: 'passed' } } } },
282
+ },
283
+ else: { not: { required: ['application'] } },
284
+ },
285
+ {
286
+ if: { properties: { status: { const: 'accepted' } } },
287
+ then: { properties: { validation: { properties: { status: { const: 'passed' } } } } },
288
+ },
289
+ ],
290
+ };
91
291
 
92
- export const ENTERPRISE_EVIDENCE_REFERENCE_SCHEMA = schema('enterprise-evidence-reference', {
93
- ...envelope('enterprise-evidence-reference'), id, ...scoped,
94
- source: { oneOf: [
95
- closed({ kind: { const: 'repository' }, repositoryId: id, path: text, commit: { type: 'string', pattern: '^(?:[a-f0-9]{40}|[a-f0-9]{64})$' }, line: { type: 'integer', minimum: 1, maximum: 1e9 } }, ['kind', 'repositoryId', 'path', 'commit']),
96
- closed({ kind: { const: 'artifact' }, artifactId: id, revisionId: id, elementId: semanticId }, ['kind', 'artifactId', 'revisionId']),
97
- closed({ kind: { const: 'url' }, url: { type: 'string', minLength: 1, maxLength: 2048 } }),
98
- ] },
99
- capturedAt: timestamp, freshness: { enum: ['current', 'stale', 'unknown'] }, label: title, contentDigest: digest,
100
- }, ['kind', 'schemaVersion', 'id', 'organizationId', 'projectId', 'source', 'capturedAt', 'freshness', 'label']);
292
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_EVIDENCE_REFERENCE_SCHEMA} */
293
+ export const ENTERPRISE_EVIDENCE_REFERENCE_SCHEMA = schema(
294
+ 'enterprise-evidence-reference',
295
+ {
296
+ ...envelope('enterprise-evidence-reference'),
297
+ id,
298
+ ...scoped,
299
+ source: {
300
+ oneOf: [
301
+ closed(
302
+ {
303
+ kind: { const: 'repository' },
304
+ repositoryId: id,
305
+ path: text,
306
+ commit: { type: 'string', pattern: '^(?:[a-f0-9]{40}|[a-f0-9]{64})$' },
307
+ line: { type: 'integer', minimum: 1, maximum: 1e9 },
308
+ },
309
+ ['kind', 'repositoryId', 'path', 'commit'],
310
+ ),
311
+ closed(
312
+ { kind: { const: 'artifact' }, artifactId: id, revisionId: id, elementId: semanticId },
313
+ ['kind', 'artifactId', 'revisionId'],
314
+ ),
315
+ closed({ kind: { const: 'url' }, url: { type: 'string', minLength: 1, maxLength: 2048 } }),
316
+ ],
317
+ },
318
+ capturedAt: timestamp,
319
+ freshness: { enum: ['current', 'stale', 'unknown'] },
320
+ label: title,
321
+ contentDigest: digest,
322
+ },
323
+ [
324
+ 'kind',
325
+ 'schemaVersion',
326
+ 'id',
327
+ 'organizationId',
328
+ 'projectId',
329
+ 'source',
330
+ 'capturedAt',
331
+ 'freshness',
332
+ 'label',
333
+ ],
334
+ );
101
335
 
336
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_SYNC_STATE_SCHEMA} */
102
337
  export const ENTERPRISE_SYNC_STATE_SCHEMA = schema('enterprise-sync-state', {
103
- ...envelope('enterprise-sync-state'), ...scoped, repositoryId: id, direction: { enum: ['push', 'pull'] },
338
+ ...envelope('enterprise-sync-state'),
339
+ ...scoped,
340
+ repositoryId: id,
341
+ direction: { enum: ['push', 'pull'] },
104
342
  status: { enum: ['preview', 'pending', 'synchronized', 'failed', 'conflicted'] },
105
343
  scope: { ...list(id, 10000), uniqueItems: true },
106
- cursor: { type: ['string', 'null'], maxLength: 2048 }, operationId: id, updatedAt: timestamp,
107
- items: list(closed({ artifactId: id, baseRevisionId: nullableId, revisionId: nullableId, contentDigest: digest, action: { enum: ['create', 'update', 'unchanged', 'conflict'] } }), 10000),
344
+ cursor: { type: ['string', 'null'], maxLength: 2048 },
345
+ operationId: id,
346
+ updatedAt: timestamp,
347
+ items: list(
348
+ closed({
349
+ artifactId: id,
350
+ baseRevisionId: nullableId,
351
+ revisionId: nullableId,
352
+ contentDigest: digest,
353
+ action: { enum: ['create', 'update', 'unchanged', 'conflict'] },
354
+ }),
355
+ 10000,
356
+ ),
108
357
  issues: list(closed({ code: id, artifactId: id, message: text }, ['code', 'message'])),
109
358
  });
110
359
 
360
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_AGENT_HANDOFF_SCHEMA} */
111
361
  export const ENTERPRISE_AGENT_HANDOFF_SCHEMA = schema('enterprise-agent-handoff', {
112
- ...envelope('enterprise-agent-handoff'), ...versionedArtifact, generatedAt: timestamp,
113
- authority: { const: 'feedback-only' }, contentTrust: { const: 'untrusted' },
114
- threads: list(ENTERPRISE_REVIEW_THREAD_SCHEMA, 10000), evidence: list(ENTERPRISE_EVIDENCE_REFERENCE_SCHEMA, 10000),
115
- unresolvedUncertainties: list(text), contentDigest: digest,
362
+ ...envelope('enterprise-agent-handoff'),
363
+ ...versionedArtifact,
364
+ generatedAt: timestamp,
365
+ authority: { const: 'feedback-only' },
366
+ contentTrust: { const: 'untrusted' },
367
+ threads: list(ENTERPRISE_REVIEW_THREAD_SCHEMA, 10000),
368
+ evidence: list(ENTERPRISE_EVIDENCE_REFERENCE_SCHEMA, 10000),
369
+ unresolvedUncertainties: list(text),
370
+ contentDigest: digest,
116
371
  });
117
372
 
373
+ /** @type {typeof import('./enterprise-contracts.d.mts').ENTERPRISE_SCHEMAS} */
118
374
  export const ENTERPRISE_SCHEMAS = deepFreeze({
119
375
  'enterprise-access-context': ENTERPRISE_ACCESS_CONTEXT_SCHEMA,
120
376
  'enterprise-artifact-revision': ENTERPRISE_ARTIFACT_REVISION_SCHEMA,
@@ -125,24 +381,23 @@ export const ENTERPRISE_SCHEMAS = deepFreeze({
125
381
  'enterprise-agent-handoff': ENTERPRISE_AGENT_HANDOFF_SCHEMA,
126
382
  });
127
383
 
128
- function deepFreeze(value) {
129
- if (value && typeof value === 'object' && !Object.isFrozen(value)) {
130
- for (const nested of Object.values(value)) deepFreeze(nested);
131
- Object.freeze(value);
132
- }
133
- return value;
134
- }
135
-
136
384
  const unsafeKeys = new Set(['__proto__', 'prototype', 'constructor']);
137
385
  function assertPlainData(value, depth = 0, seen = new Set()) {
138
386
  if (depth > 64) throw new TypeError('Enterprise data exceeds the maximum nesting depth.');
139
387
  if (value === null || typeof value === 'string' || typeof value === 'boolean') return;
140
388
  if (typeof value === 'number' && Number.isFinite(value)) return;
141
- if (typeof value !== 'object' || seen.has(value)) throw new TypeError('Enterprise data must be finite, acyclic JSON.');
142
- if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError('Enterprise data must contain only plain JSON objects.');
389
+ if (typeof value !== 'object' || seen.has(value))
390
+ throw new TypeError('Enterprise data must be finite, acyclic JSON.');
391
+ if (
392
+ !Array.isArray(value) &&
393
+ Object.getPrototypeOf(value) !== Object.prototype &&
394
+ Object.getPrototypeOf(value) !== null
395
+ )
396
+ throw new TypeError('Enterprise data must contain only plain JSON objects.');
143
397
  seen.add(value);
144
398
  for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
145
- if (unsafeKeys.has(key) || !Object.hasOwn(descriptor, 'value')) throw new TypeError('Enterprise data contains a forbidden property.');
399
+ if (unsafeKeys.has(key) || !Object.hasOwn(descriptor, 'value'))
400
+ throw new TypeError('Enterprise data contains a forbidden property.');
146
401
  assertPlainData(descriptor.value, depth + 1, seen);
147
402
  }
148
403
  seen.delete(value);
@@ -150,132 +405,237 @@ function assertPlainData(value, depth = 0, seen = new Set()) {
150
405
  function validTimestamp(value) {
151
406
  if (typeof value !== 'string' || !new RegExp(timestamp.pattern).test(value)) return false;
152
407
  const parsed = new Date(value);
153
- return Number.isFinite(parsed.getTime()) && parsed.toISOString() === (value.includes('.') ? value : value.replace('Z', '.000Z'));
408
+ return (
409
+ Number.isFinite(parsed.getTime()) &&
410
+ parsed.toISOString() === (value.includes('.') ? value : value.replace('Z', '.000Z'))
411
+ );
154
412
  }
155
413
  function assertTimes(value, contract) {
156
- if (contract.format === 'date-time' && !validTimestamp(value)) throw new TypeError('Invalid enterprise timestamp.');
157
- if (Array.isArray(value) && contract.items) value.forEach(item => assertTimes(item, contract.items));
414
+ if (contract.format === 'date-time' && !validTimestamp(value))
415
+ throw new TypeError('Invalid enterprise timestamp.');
416
+ if (Array.isArray(value) && contract.items)
417
+ value.forEach((item) => assertTimes(item, contract.items));
158
418
  if (value && typeof value === 'object' && !Array.isArray(value)) {
159
419
  for (const [key, nested] of Object.entries(value)) {
160
420
  if (contract.properties?.[key]) assertTimes(nested, contract.properties[key]);
161
421
  }
162
422
  }
163
423
  for (const key of ['oneOf', 'anyOf', 'allOf']) {
164
- for (const branch of contract[key] ?? []) if (!validateJson(value, branch).length) assertTimes(value, branch);
424
+ for (const branch of contract[key] ?? [])
425
+ if (!validateJson(value, branch).length) assertTimes(value, branch);
165
426
  }
166
427
  }
167
428
  function distinct(items, key, label) {
168
- const values = items.map(item => item[key]);
429
+ const values = items.map((item) => item[key]);
169
430
  if (new Set(values).size !== values.length) throw new TypeError(`Duplicate ${label}.`);
170
431
  }
171
432
  function sameScope(value, expected) {
172
433
  return value.organizationId === expected.organizationId && value.projectId === expected.projectId;
173
434
  }
174
435
 
175
- /** Structural validation is not authentication, signature verification, or domain validation. */
436
+ /**
437
+ * Structural validation is not authentication, signature verification, or domain validation.
438
+ * @returns {ReturnType<typeof import('./enterprise-contracts.d.mts').assertEnterpriseContract>}
439
+ */
176
440
  export function assertEnterpriseContract(value, schemaOrName) {
177
- const contract = typeof schemaOrName === 'string' ? ENTERPRISE_SCHEMAS[schemaOrName] : schemaOrName;
441
+ const contract =
442
+ typeof schemaOrName === 'string' ? ENTERPRISE_SCHEMAS[schemaOrName] : schemaOrName;
178
443
  if (!contract) throw new TypeError('Unknown enterprise contract.');
179
444
  assertPlainData(value);
180
445
  canonicalizeJson(value);
181
446
  const errors = validateJson(value, contract);
182
447
  // Do not include field values: validation responses must not echo private content.
183
- if (errors.length) throw new TypeError(`Invalid ${contract['x-openplanr-contract']?.id ?? 'enterprise data'}: ${errors.slice(0, 5).map(error => `${error.path} (${error.rule})`).join('; ')}`);
448
+ if (errors.length)
449
+ throw new TypeError(
450
+ `Invalid ${contract['x-openplanr-contract']?.id ?? 'enterprise data'}: ${errors
451
+ .slice(0, 5)
452
+ .map((error) => `${error.path} (${error.rule})`)
453
+ .join('; ')}`,
454
+ );
184
455
  assertTimes(value, contract);
185
456
  return value;
186
457
  }
187
458
 
188
- /** Metadata immutability requires the storage adapter to compare-and-set IDs and recompute content digests. */
459
+ /**
460
+ * Metadata immutability requires the storage adapter to compare-and-set IDs and recompute content digests.
461
+ * @type {typeof import('./enterprise-contracts.d.mts').assertEnterpriseRevision}
462
+ */
189
463
  export function assertEnterpriseRevision(value) {
190
464
  assertEnterpriseContract(value, ENTERPRISE_ARTIFACT_REVISION_SCHEMA);
191
- if (value.id === value.parentRevisionId) throw new TypeError('A revision cannot be its own parent.');
465
+ if (value.id === value.parentRevisionId)
466
+ throw new TypeError('A revision cannot be its own parent.');
192
467
  return value;
193
468
  }
194
469
 
195
- /** Verify append identity and bytes; the adapter still performs the atomic compare-and-set. */
470
+ /**
471
+ * Verify append identity and bytes; the adapter still performs the atomic compare-and-set.
472
+ * @type {typeof import('./enterprise-contracts.d.mts').assertEnterpriseRevisionAppend}
473
+ */
196
474
  export function assertEnterpriseRevisionAppend(revision, previous, content) {
197
475
  assertEnterpriseRevision(revision);
198
476
  if (previous) {
199
477
  assertEnterpriseRevision(previous);
200
- if (!sameScope(revision, previous) || revision.artifactId !== previous.artifactId || revision.parentRevisionId !== previous.id || revision.id === previous.id) throw new TypeError('Revision append does not match the current artifact revision.');
201
- if (Date.parse(revision.createdAt) < Date.parse(previous.createdAt)) throw new TypeError('Revision append cannot precede its parent.');
202
- } else if (revision.parentRevisionId !== null) throw new TypeError('An initial revision cannot have a parent.');
478
+ if (
479
+ !sameScope(revision, previous) ||
480
+ revision.artifactId !== previous.artifactId ||
481
+ revision.parentRevisionId !== previous.id ||
482
+ revision.id === previous.id
483
+ )
484
+ throw new TypeError('Revision append does not match the current artifact revision.');
485
+ if (Date.parse(revision.createdAt) < Date.parse(previous.createdAt))
486
+ throw new TypeError('Revision append cannot precede its parent.');
487
+ } else if (revision.parentRevisionId !== null)
488
+ throw new TypeError('An initial revision cannot have a parent.');
203
489
  const bytes = typeof content === 'string' ? new TextEncoder().encode(content) : content;
204
- if (!(bytes instanceof Uint8Array) || revision.byteLength !== bytes.byteLength || revision.contentDigest !== sha256Hex(bytes)) throw new TypeError('Revision digest or size does not match its content.');
490
+ if (
491
+ !(bytes instanceof Uint8Array) ||
492
+ revision.byteLength !== bytes.byteLength ||
493
+ revision.contentDigest !== sha256Hex(bytes)
494
+ )
495
+ throw new TypeError('Revision digest or size does not match its content.');
205
496
  return revision;
206
497
  }
207
498
 
499
+ /** @type {typeof import('./enterprise-contracts.d.mts').assertEnterpriseReviewThread} */
208
500
  export function assertEnterpriseReviewThread(value) {
209
501
  assertEnterpriseContract(value, ENTERPRISE_REVIEW_THREAD_SCHEMA);
210
502
  distinct(value.replies, 'id', 'reply identity');
211
- if (value.replies.some(reply => reply.id === value.id)) throw new TypeError('A reply cannot reuse its thread identity.');
212
- const start = Date.parse(value.createdAt), end = Date.parse(value.updatedAt);
213
- if (end < start || value.replies.some(reply => Date.parse(reply.createdAt) < start || Date.parse(reply.createdAt) > end)) throw new TypeError('Review timestamps must stay within the thread lifetime.');
214
- if (value.resolvedAt && (Date.parse(value.resolvedAt) < start || Date.parse(value.resolvedAt) > end)) throw new TypeError('Resolution timestamp must stay within the thread lifetime.');
503
+ if (value.replies.some((reply) => reply.id === value.id))
504
+ throw new TypeError('A reply cannot reuse its thread identity.');
505
+ const start = Date.parse(value.createdAt),
506
+ end = Date.parse(value.updatedAt);
507
+ if (
508
+ end < start ||
509
+ value.replies.some(
510
+ (reply) => Date.parse(reply.createdAt) < start || Date.parse(reply.createdAt) > end,
511
+ )
512
+ )
513
+ throw new TypeError('Review timestamps must stay within the thread lifetime.');
514
+ if (
515
+ value.resolvedAt &&
516
+ (Date.parse(value.resolvedAt) < start || Date.parse(value.resolvedAt) > end)
517
+ )
518
+ throw new TypeError('Resolution timestamp must stay within the thread lifetime.');
215
519
  return value;
216
520
  }
217
521
 
522
+ /** @type {typeof import('./enterprise-contracts.d.mts').assertEnterpriseProposal} */
218
523
  export function assertEnterpriseProposal(value) {
219
524
  assertEnterpriseContract(value, ENTERPRISE_CHANGE_PROPOSAL_SCHEMA);
220
- if (new TextEncoder().encode(canonicalizeJson(value)).length > 5 * 1024 * 1024) throw new TypeError('Change proposal exceeds the content limit.');
221
- if (value.validation.status === 'passed' && value.validation.issues.length) throw new TypeError('A passed validation cannot contain unresolved issues.');
222
- if (value.operations.some(operation => operation.op === 'replace-document') && value.operations.length !== 1) throw new TypeError('Document replacement must be the only proposed operation.');
223
- if (value.application && (value.application.revisionId === value.baseRevisionId || Date.parse(value.application.appliedAt) < Date.parse(value.createdAt))) throw new TypeError('Application must identify a new revision after proposal creation.');
525
+ if (new TextEncoder().encode(canonicalizeJson(value)).length > 5 * 1024 * 1024)
526
+ throw new TypeError('Change proposal exceeds the content limit.');
527
+ if (value.validation.status === 'passed' && value.validation.issues.length)
528
+ throw new TypeError('A passed validation cannot contain unresolved issues.');
529
+ if (
530
+ value.operations.some((operation) => operation.op === 'replace-document') &&
531
+ value.operations.length !== 1
532
+ )
533
+ throw new TypeError('Document replacement must be the only proposed operation.');
534
+ if (
535
+ value.application &&
536
+ (value.application.revisionId === value.baseRevisionId ||
537
+ Date.parse(value.application.appliedAt) < Date.parse(value.createdAt))
538
+ )
539
+ throw new TypeError('Application must identify a new revision after proposal creation.');
224
540
  return value;
225
541
  }
226
542
 
543
+ /** @type {typeof import('./enterprise-contracts.d.mts').assertEnterpriseEvidence} */
227
544
  export function assertEnterpriseEvidence(value) {
228
545
  assertEnterpriseContract(value, ENTERPRISE_EVIDENCE_REFERENCE_SCHEMA);
229
- if (value.source.kind === 'repository' && !isEnterpriseRepositoryPath(value.source.path)) throw new TypeError('Evidence requires a repository-relative path.');
546
+ if (value.source.kind === 'repository' && !isEnterpriseRepositoryPath(value.source.path))
547
+ throw new TypeError('Evidence requires a repository-relative path.');
230
548
  if (value.source.kind === 'url') {
231
549
  let url;
232
- try { url = new URL(value.source.url); } catch { throw new TypeError('Evidence requires an HTTPS URL.'); }
233
- if (url.protocol !== 'https:' || url.username || url.password) throw new TypeError('Evidence requires an HTTPS URL without credentials.');
550
+ try {
551
+ url = new URL(value.source.url);
552
+ } catch {
553
+ throw new TypeError('Evidence requires an HTTPS URL.');
554
+ }
555
+ if (url.protocol !== 'https:' || url.username || url.password)
556
+ throw new TypeError('Evidence requires an HTTPS URL without credentials.');
234
557
  }
235
558
  return value;
236
559
  }
237
560
 
238
- /** A lexical check only; file application must also reject symlinks outside its repository root. */
561
+ /**
562
+ * A lexical check only; file application must also reject symlinks outside its repository root.
563
+ * @type {typeof import('./enterprise-contracts.d.mts').isEnterpriseRepositoryPath}
564
+ */
239
565
  export function isEnterpriseRepositoryPath(value) {
240
- return typeof value === 'string' && value.length > 0 && value.length <= 4096 &&
566
+ return (
567
+ typeof value === 'string' &&
568
+ value.length > 0 &&
569
+ value.length <= 4096 &&
241
570
  !/^[A-Za-z]:|^\/|[\\\x00-\x1f\x7f]/u.test(value) &&
242
- value.split('/').every(part => part && part !== '.' && part !== '..' && !unsafeKeys.has(part));
571
+ value.split('/').every((part) => part && part !== '.' && part !== '..' && !unsafeKeys.has(part))
572
+ );
243
573
  }
244
574
 
575
+ /** @type {typeof import('./enterprise-contracts.d.mts').assertEnterpriseSync} */
245
576
  export function assertEnterpriseSync(value) {
246
577
  assertEnterpriseContract(value, ENTERPRISE_SYNC_STATE_SCHEMA);
247
578
  distinct(value.items, 'artifactId', 'sync artifact identity');
248
579
  const scope = new Set(value.scope);
249
- if (value.items.some(item => !scope.has(item.artifactId)) || value.issues.some(issue => issue.artifactId && !scope.has(issue.artifactId))) throw new TypeError('Synchronization cannot expand the selected scope.');
250
- if (value.status === 'synchronized' && (value.issues.length || value.items.some(item => item.action === 'conflict'))) throw new TypeError('A conflicted synchronization cannot be marked synchronized.');
580
+ if (
581
+ value.items.some((item) => !scope.has(item.artifactId)) ||
582
+ value.issues.some((issue) => issue.artifactId && !scope.has(issue.artifactId))
583
+ )
584
+ throw new TypeError('Synchronization cannot expand the selected scope.');
585
+ if (
586
+ value.status === 'synchronized' &&
587
+ (value.issues.length || value.items.some((item) => item.action === 'conflict'))
588
+ )
589
+ throw new TypeError('A conflicted synchronization cannot be marked synchronized.');
251
590
  for (const item of value.items) {
252
- if (item.action === 'create' && item.baseRevisionId !== null) throw new TypeError('Creation cannot replace an existing base revision.');
253
- if (['update', 'unchanged'].includes(item.action) && item.baseRevisionId === null) throw new TypeError('An existing artifact needs a base revision.');
254
- if (item.action === 'unchanged' && item.baseRevisionId !== item.revisionId) throw new TypeError('An unchanged artifact must retain its revision.');
255
- if (value.status === 'synchronized' && item.revisionId === null) throw new TypeError('A synchronized artifact needs a revision.');
591
+ if (item.action === 'create' && item.baseRevisionId !== null)
592
+ throw new TypeError('Creation cannot replace an existing base revision.');
593
+ if (['update', 'unchanged'].includes(item.action) && item.baseRevisionId === null)
594
+ throw new TypeError('An existing artifact needs a base revision.');
595
+ if (item.action === 'unchanged' && item.baseRevisionId !== item.revisionId)
596
+ throw new TypeError('An unchanged artifact must retain its revision.');
597
+ if (value.status === 'synchronized' && item.revisionId === null)
598
+ throw new TypeError('A synchronized artifact needs a revision.');
256
599
  }
257
600
  return value;
258
601
  }
259
602
 
260
603
  const projectCapabilities = deepFreeze({
261
- maintainer: ['project.manage', 'artifact.read', 'artifact.author', 'artifact.export', 'review.write', 'review.resolve'],
604
+ maintainer: [
605
+ 'project.manage',
606
+ 'artifact.read',
607
+ 'artifact.author',
608
+ 'artifact.export',
609
+ 'review.write',
610
+ 'review.resolve',
611
+ ],
262
612
  author: ['artifact.read', 'artifact.author', 'artifact.export', 'review.write', 'review.resolve'],
263
613
  reviewer: ['artifact.read', 'artifact.export', 'review.write'],
264
614
  viewer: ['artifact.read', 'artifact.export'],
265
615
  });
616
+ /** @type {readonly import('./enterprise-contracts.d.mts').EnterpriseAction[]} */
266
617
  const noCapabilities = Object.freeze([]);
267
618
 
268
619
  /**
269
620
  * Stable UI projection for a server-verified project role. Callers must still
270
621
  * authorize every request at the resource boundary; this only describes which
271
622
  * controls the verified response may expose.
623
+ * @type {typeof import('./enterprise-contracts.d.mts').enterpriseProjectCapabilities}
272
624
  */
273
625
  export function enterpriseProjectCapabilities(role) {
274
626
  return projectCapabilities[role] ?? noCapabilities;
275
627
  }
628
+ /** @type {Readonly<Record<'owner' | 'admin' | 'member', readonly import('./enterprise-contracts.d.mts').EnterpriseAction[]>>} */
276
629
  const organizationCapabilities = deepFreeze({
277
- owner: ['organization.manage', 'ownership.transfer', 'billing.manage', 'audit.read', 'project.create'],
278
- admin: ['organization.manage', 'billing.manage', 'audit.read', 'project.create'], member: [],
630
+ owner: [
631
+ 'organization.manage',
632
+ 'ownership.transfer',
633
+ 'billing.manage',
634
+ 'audit.read',
635
+ 'project.create',
636
+ ],
637
+ admin: ['organization.manage', 'billing.manage', 'audit.read', 'project.create'],
638
+ member: [],
279
639
  });
280
640
  const decision = (allowed, code) => Object.freeze({ allowed, code });
281
641
 
@@ -283,108 +643,235 @@ const decision = (allowed, code) => Object.freeze({ allowed, code });
283
643
  * Pure fail-closed policy. The adapter must load current membership/grants itself
284
644
  * and verify actor identity. Never pass actor/ACL records supplied by a client.
285
645
  * Organization administrators do not implicitly gain project content access.
646
+ * @type {typeof import('./enterprise-contracts.d.mts').authorizeEnterpriseAccess}
286
647
  */
287
648
  export function authorizeEnterpriseAccess(context) {
288
- try { assertEnterpriseContract(context, ENTERPRISE_ACCESS_CONTEXT_SCHEMA); } catch { return decision(false, 'invalid-context'); }
289
- const { actor, organization, membership, projectMembership, guestGrant, resource, action, now } = context;
649
+ try {
650
+ assertEnterpriseContract(context, ENTERPRISE_ACCESS_CONTEXT_SCHEMA);
651
+ } catch {
652
+ return decision(false, 'invalid-context');
653
+ }
654
+ const { actor, organization, membership, projectMembership, guestGrant, resource, action, now } =
655
+ context;
290
656
  if (!actor.verified) return decision(false, 'unverified-actor');
291
657
  if (organization.id !== resource.organizationId) return decision(false, 'organization-mismatch');
292
658
  if (organization.status !== 'active') return decision(false, 'organization-inactive');
293
659
  if (resource.artifactId && !resource.projectId) return decision(false, 'project-required');
294
- if (membership && (membership.actorId !== actor.id || membership.organizationId !== organization.id)) return decision(false, 'membership-mismatch');
660
+ if (
661
+ membership &&
662
+ (membership.actorId !== actor.id || membership.organizationId !== organization.id)
663
+ )
664
+ return decision(false, 'membership-mismatch');
295
665
  if (membership && membership.status !== 'active') return decision(false, 'membership-revoked');
296
- if (action.startsWith('organization.') || ['ownership.transfer', 'billing.manage', 'audit.read', 'project.create'].includes(action)) {
297
- if (resource.projectId || resource.artifactId) return decision(false, 'organization-resource-required');
298
- return membership && organizationCapabilities[membership.role].includes(action) ? decision(true, 'allowed') : decision(false, 'insufficient-role');
666
+ if (
667
+ action.startsWith('organization.') ||
668
+ ['ownership.transfer', 'billing.manage', 'audit.read', 'project.create'].includes(action)
669
+ ) {
670
+ if (resource.projectId || resource.artifactId)
671
+ return decision(false, 'organization-resource-required');
672
+ return membership && organizationCapabilities[membership.role].includes(action)
673
+ ? decision(true, 'allowed')
674
+ : decision(false, 'insufficient-role');
299
675
  }
300
676
  if (!resource.projectId) return decision(false, 'project-required');
301
677
  if (projectMembership) {
302
- if (projectMembership.actorId !== actor.id || !sameScope(projectMembership, resource)) return decision(false, 'project-membership-mismatch');
678
+ if (projectMembership.actorId !== actor.id || !sameScope(projectMembership, resource))
679
+ return decision(false, 'project-membership-mismatch');
303
680
  if (projectMembership.status !== 'active') return decision(false, 'project-membership-revoked');
304
681
  if (!membership) return decision(false, 'membership-required');
305
- return enterpriseProjectCapabilities(projectMembership.role).includes(action) ? decision(true, 'allowed') : decision(false, 'insufficient-role');
682
+ return enterpriseProjectCapabilities(projectMembership.role).includes(action)
683
+ ? decision(true, 'allowed')
684
+ : decision(false, 'insufficient-role');
306
685
  }
307
686
  if (!guestGrant) return decision(false, 'project-membership-required');
308
- if (!resource.artifactId || !sameScope(guestGrant, resource) || guestGrant.artifactId !== resource.artifactId || guestGrant.actorId !== actor.id) return decision(false, 'guest-scope-mismatch');
309
- if (guestGrant.status !== 'active' || Date.parse(guestGrant.expiresAt) <= Date.parse(now)) return decision(false, 'guest-grant-expired-or-revoked');
310
- return enterpriseProjectCapabilities(guestGrant.role).includes(action) ? decision(true, 'allowed') : decision(false, 'insufficient-role');
687
+ if (
688
+ !resource.artifactId ||
689
+ !sameScope(guestGrant, resource) ||
690
+ guestGrant.artifactId !== resource.artifactId ||
691
+ guestGrant.actorId !== actor.id
692
+ )
693
+ return decision(false, 'guest-scope-mismatch');
694
+ if (guestGrant.status !== 'active' || Date.parse(guestGrant.expiresAt) <= Date.parse(now))
695
+ return decision(false, 'guest-grant-expired-or-revoked');
696
+ return enterpriseProjectCapabilities(guestGrant.role).includes(action)
697
+ ? decision(true, 'allowed')
698
+ : decision(false, 'insufficient-role');
311
699
  }
312
700
 
701
+ /** @type {typeof import('./enterprise-contracts.d.mts').assertEnterpriseHandoff} */
313
702
  export function assertEnterpriseHandoff(value) {
314
703
  assertEnterpriseContract(value, ENTERPRISE_AGENT_HANDOFF_SCHEMA);
315
- distinct(value.threads, 'id', 'thread identity'); distinct(value.evidence, 'id', 'evidence identity');
704
+ distinct(value.threads, 'id', 'thread identity');
705
+ distinct(value.evidence, 'id', 'evidence identity');
316
706
  for (const thread of value.threads) {
317
707
  assertEnterpriseReviewThread(thread);
318
- if (!sameScope(thread, value) || thread.artifactId !== value.artifactId) throw new TypeError('Handoff threads must belong to its artifact and project.');
319
- if (Date.parse(thread.updatedAt) > Date.parse(value.generatedAt)) throw new TypeError('Handoff cannot precede the exported feedback.');
708
+ if (!sameScope(thread, value) || thread.artifactId !== value.artifactId)
709
+ throw new TypeError('Handoff threads must belong to its artifact and project.');
710
+ if (Date.parse(thread.updatedAt) > Date.parse(value.generatedAt))
711
+ throw new TypeError('Handoff cannot precede the exported feedback.');
320
712
  }
321
713
  for (const evidence of value.evidence) {
322
714
  assertEnterpriseEvidence(evidence);
323
- if (!sameScope(evidence, value)) throw new TypeError('Handoff evidence must belong to its project.');
324
- if (Date.parse(evidence.capturedAt) > Date.parse(value.generatedAt)) throw new TypeError('Handoff cannot precede the exported evidence.');
715
+ if (!sameScope(evidence, value))
716
+ throw new TypeError('Handoff evidence must belong to its project.');
717
+ if (Date.parse(evidence.capturedAt) > Date.parse(value.generatedAt))
718
+ throw new TypeError('Handoff cannot precede the exported evidence.');
325
719
  }
326
720
  const { contentDigest, ...content } = value;
327
- if (sha256Hex(canonicalizeJson(content)) !== contentDigest) throw new TypeError('Handoff content digest does not match its content.');
721
+ if (sha256Hex(canonicalizeJson(content)) !== contentDigest)
722
+ throw new TypeError('Handoff content digest does not match its content.');
328
723
  return value;
329
724
  }
330
725
 
331
- export function createEnterpriseHandoff({ organizationId, projectId, artifactId, revisionId, generatedAt, threads = [], evidence = [], unresolvedUncertainties = [] }) {
726
+ /** @type {typeof import('./enterprise-contracts.d.mts').createEnterpriseHandoff} */
727
+ export function createEnterpriseHandoff({
728
+ organizationId,
729
+ projectId,
730
+ artifactId,
731
+ revisionId,
732
+ generatedAt,
733
+ threads = [],
734
+ evidence = [],
735
+ unresolvedUncertainties = [],
736
+ }) {
332
737
  // Validate before cloning so exotic objects or accessors cannot acquire authority.
333
- const content = { kind: 'openplanr-enterprise-agent-handoff', schemaVersion: ENTERPRISE_CONTRACT_VERSION, organizationId, projectId, artifactId, revisionId, generatedAt, authority: 'feedback-only', contentTrust: 'untrusted', threads, evidence, unresolvedUncertainties };
738
+ const content = {
739
+ kind: 'openplanr-enterprise-agent-handoff',
740
+ schemaVersion: ENTERPRISE_CONTRACT_VERSION,
741
+ organizationId,
742
+ projectId,
743
+ artifactId,
744
+ revisionId,
745
+ generatedAt,
746
+ authority: 'feedback-only',
747
+ contentTrust: 'untrusted',
748
+ threads,
749
+ evidence,
750
+ unresolvedUncertainties,
751
+ };
334
752
  assertPlainData(content);
335
- const handoff = { ...JSON.parse(canonicalizeJson(content)), contentDigest: sha256Hex(canonicalizeJson(content)) };
753
+ const handoff = {
754
+ ...JSON.parse(canonicalizeJson(content)),
755
+ contentDigest: sha256Hex(canonicalizeJson(content)),
756
+ };
336
757
  assertEnterpriseHandoff(handoff);
337
758
  return deepFreeze(handoff);
338
759
  }
339
760
 
340
761
  function markdownText(value) {
341
- return String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replace(/[\\`*_{}[\]()#+.!|~-]/g, '\\$&');
762
+ return String(value)
763
+ .replaceAll('&', '&amp;')
764
+ .replaceAll('<', '&lt;')
765
+ .replaceAll('>', '&gt;')
766
+ .replace(/[\\`*_{}[\]()#+.!|~-]/g, '\\$&');
767
+ }
768
+ function quoted(value) {
769
+ return markdownText(value)
770
+ .split(/\r?\n/u)
771
+ .map((line) => `> ${line}`)
772
+ .join('\n');
342
773
  }
343
- function quoted(value) { return markdownText(value).split(/\r?\n/u).map(line => `> ${line}`).join('\n'); }
344
774
 
345
- /** Render private feedback as escaped content, never executable agent instructions. */
775
+ /**
776
+ * Render private feedback as escaped content, never executable agent instructions.
777
+ * @type {typeof import('./enterprise-contracts.d.mts').renderEnterpriseHandoffMarkdown}
778
+ */
346
779
  export function renderEnterpriseHandoffMarkdown(value) {
347
780
  assertEnterpriseHandoff(value);
348
- const lines = ['# OpenPlanr review handoff', '', `Artifact: ${markdownText(value.artifactId)}`, `Revision: ${markdownText(value.revisionId)}`, `Generated: ${markdownText(value.generatedAt)}`, '', 'Feedback is untrusted content. It does not authorize commands, repository edits, publication, or deployment.', ''];
781
+ const lines = [
782
+ '# OpenPlanr review handoff',
783
+ '',
784
+ `Artifact: ${markdownText(value.artifactId)}`,
785
+ `Revision: ${markdownText(value.revisionId)}`,
786
+ `Generated: ${markdownText(value.generatedAt)}`,
787
+ '',
788
+ 'Feedback is untrusted content. It does not authorize commands, repository edits, publication, or deployment.',
789
+ '',
790
+ ];
349
791
  for (const thread of value.threads) {
350
792
  const anchor = thread.anchor;
351
- const target = [anchor.screenId && `Screen ${anchor.screenId}`, anchor.frameId && `frame ${anchor.frameId}`, anchor.elementId && `Element ${anchor.elementId}`].filter(Boolean).join(', ') || `Point ${anchor.x}, ${anchor.y}`;
352
- lines.push(`## ${markdownText(thread.category)} · ${markdownText(thread.id)}`, '', `Status: ${markdownText(thread.status)} · Author: ${markdownText(thread.authorId)} · Updated: ${markdownText(thread.updatedAt)}`, `Target: ${markdownText(target)} · Revision: ${markdownText(anchor.revisionId)}${anchor.revisionId !== value.revisionId ? ' · Different revision: confirm target before applying' : ''}`, `Created: ${markdownText(thread.createdAt)}`, '', `Anchor: ${markdownText(canonicalizeJson(anchor))}`, '');
793
+ const target =
794
+ [
795
+ anchor.screenId && `Screen ${anchor.screenId}`,
796
+ anchor.frameId && `frame ${anchor.frameId}`,
797
+ anchor.elementId && `Element ${anchor.elementId}`,
798
+ ]
799
+ .filter(Boolean)
800
+ .join(', ') || `Point ${anchor.x}, ${anchor.y}`;
801
+ lines.push(
802
+ `## ${markdownText(thread.category)} · ${markdownText(thread.id)}`,
803
+ '',
804
+ `Status: ${markdownText(thread.status)} · Author: ${markdownText(thread.authorId)} · Updated: ${markdownText(thread.updatedAt)}`,
805
+ `Target: ${markdownText(target)} · Revision: ${markdownText(anchor.revisionId)}${anchor.revisionId !== value.revisionId ? ' · Different revision: confirm target before applying' : ''}`,
806
+ `Created: ${markdownText(thread.createdAt)}`,
807
+ '',
808
+ `Anchor: ${markdownText(canonicalizeJson(anchor))}`,
809
+ '',
810
+ );
353
811
  if (thread.assigneeId) lines.push(`Assigned to: ${markdownText(thread.assigneeId)}`, '');
354
- if (thread.addressedRevisionId) lines.push(`Addressed in: ${markdownText(thread.addressedRevisionId)}`, '');
812
+ if (thread.addressedRevisionId)
813
+ lines.push(`Addressed in: ${markdownText(thread.addressedRevisionId)}`, '');
355
814
  if (thread.resolvedAt) lines.push(`Resolved: ${markdownText(thread.resolvedAt)}`, '');
356
815
  lines.push(quoted(thread.body), '');
357
- for (const reply of thread.replies) lines.push(`Reply ${markdownText(reply.id)} · ${markdownText(reply.authorId)} · ${markdownText(reply.createdAt)}`, '', quoted(reply.body), '');
816
+ for (const reply of thread.replies)
817
+ lines.push(
818
+ `Reply ${markdownText(reply.id)} · ${markdownText(reply.authorId)} · ${markdownText(reply.createdAt)}`,
819
+ '',
820
+ quoted(reply.body),
821
+ '',
822
+ );
358
823
  }
359
824
  if (value.evidence.length) lines.push('## Evidence', '');
360
- for (const evidence of value.evidence) lines.push(`- ${markdownText(evidence.label)} · ${markdownText(evidence.freshness)} · Captured ${markdownText(evidence.capturedAt)}`, '', quoted(canonicalizeJson(evidence.source)), '');
825
+ for (const evidence of value.evidence)
826
+ lines.push(
827
+ `- ${markdownText(evidence.label)} · ${markdownText(evidence.freshness)} · Captured ${markdownText(evidence.capturedAt)}`,
828
+ '',
829
+ quoted(canonicalizeJson(evidence.source)),
830
+ '',
831
+ );
361
832
  if (value.unresolvedUncertainties.length) lines.push('## Unresolved uncertainties', '');
362
833
  for (const uncertainty of value.unresolvedUncertainties) lines.push(quoted(uncertainty), '');
363
834
  return `${lines.join('\n').trim()}\n`;
364
835
  }
365
836
 
366
837
  const editableCollections = Object.freeze(['nodes', 'relations', 'groups', 'events', 'items']);
367
- const identityCollections = Object.freeze([...editableCollections, 'lanes', 'series', 'axes', 'sets', 'annotations']);
368
- const copyData = value => JSON.parse(canonicalizeJson(value));
838
+ const identityCollections = Object.freeze([
839
+ ...editableCollections,
840
+ 'lanes',
841
+ 'series',
842
+ 'axes',
843
+ 'sets',
844
+ 'annotations',
845
+ ]);
846
+ const copyData = (value) => JSON.parse(canonicalizeJson(value));
369
847
  function assertDocument(value) {
370
848
  assertPlainData(value);
371
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Semantic document must be a JSON object.');
849
+ if (!value || typeof value !== 'object' || Array.isArray(value))
850
+ throw new TypeError('Semantic document must be a JSON object.');
372
851
  canonicalizeJson(value);
373
852
  }
374
853
  function indexedElements(document) {
375
854
  const entries = new Map();
376
855
  const add = (targetId, element) => {
377
- if (typeof targetId !== 'string' || validateJson(targetId, semanticId).length || unsafeKeys.has(targetId)) throw new TypeError('Invalid semantic element identity.');
378
- if (entries.has(targetId)) throw new TypeError('Ambiguous or duplicate semantic element identity.');
856
+ if (
857
+ typeof targetId !== 'string' ||
858
+ validateJson(targetId, semanticId).length ||
859
+ unsafeKeys.has(targetId)
860
+ )
861
+ throw new TypeError('Invalid semantic element identity.');
862
+ if (entries.has(targetId))
863
+ throw new TypeError('Ambiguous or duplicate semantic element identity.');
379
864
  entries.set(targetId, element);
380
865
  };
381
866
  const rootId = document.id ?? document.diagramId;
382
867
  if (rootId !== undefined) add(rootId, document);
383
868
  for (const collection of identityCollections) {
384
869
  if (document[collection] === undefined) continue;
385
- if (!Array.isArray(document[collection])) throw new TypeError('Semantic element collections must be arrays.');
870
+ if (!Array.isArray(document[collection]))
871
+ throw new TypeError('Semantic element collections must be arrays.');
386
872
  for (const element of document[collection]) {
387
- if (!element || typeof element !== 'object' || Array.isArray(element)) throw new TypeError('Semantic elements must be JSON objects.');
873
+ if (!element || typeof element !== 'object' || Array.isArray(element))
874
+ throw new TypeError('Semantic elements must be JSON objects.');
388
875
  if (element.id !== undefined) add(element.id, element);
389
876
  }
390
877
  }
@@ -392,72 +879,139 @@ function indexedElements(document) {
392
879
  }
393
880
  function assertLayout(layout, entries) {
394
881
  assertPlainData(layout);
395
- if (!layout || typeof layout !== 'object' || Array.isArray(layout)) throw new TypeError('Layout must be an element-coordinate map.');
396
- const coordinateSchema = closed({ x: { type: 'number', minimum: -1e7, maximum: 1e7 }, y: { type: 'number', minimum: -1e7, maximum: 1e7 } });
882
+ if (!layout || typeof layout !== 'object' || Array.isArray(layout))
883
+ throw new TypeError('Layout must be an element-coordinate map.');
884
+ const coordinateSchema = closed({
885
+ x: { type: 'number', minimum: -1e7, maximum: 1e7 },
886
+ y: { type: 'number', minimum: -1e7, maximum: 1e7 },
887
+ });
397
888
  for (const [targetId, point] of Object.entries(layout)) {
398
- if (!entries.has(targetId) || validateJson(point, coordinateSchema).length) throw new TypeError('Layout must identify existing elements and finite coordinates.');
889
+ if (!entries.has(targetId) || validateJson(point, coordinateSchema).length)
890
+ throw new TypeError('Layout must identify existing elements and finite coordinates.');
399
891
  }
400
892
  }
401
893
  const equalData = (left, right) => canonicalizeJson(left) === canonicalizeJson(right);
402
894
 
403
- /** Compare stable element identities; documentDigest is derived metadata, not a semantic change. */
404
- export function diffEnterpriseDocuments(before, after, { beforeLayout = {}, afterLayout = {} } = {}) {
405
- assertDocument(before); assertDocument(after);
406
- const previousEntries = indexedElements(before), nextEntries = indexedElements(after);
407
- assertLayout(beforeLayout, previousEntries); assertLayout(afterLayout, nextEntries);
895
+ /**
896
+ * Compare stable element identities; documentDigest is derived metadata, not a semantic change.
897
+ * @returns {ReturnType<typeof import('./enterprise-contracts.d.mts').diffEnterpriseDocuments>}
898
+ */
899
+ export function diffEnterpriseDocuments(
900
+ before,
901
+ after,
902
+ { beforeLayout = {}, afterLayout = {} } = {},
903
+ ) {
904
+ assertDocument(before);
905
+ assertDocument(after);
906
+ const previousEntries = indexedElements(before),
907
+ nextEntries = indexedElements(after);
908
+ assertLayout(beforeLayout, previousEntries);
909
+ assertLayout(afterLayout, nextEntries);
408
910
  const changes = [];
409
911
  const delta = (left, right, descriptor, hasBefore = true, hasAfter = true) => {
410
912
  if (hasBefore && hasAfter && equalData(left, right)) return;
411
- changes.push({ ...descriptor, op: !hasBefore ? 'add' : !hasAfter ? 'remove' : 'replace', ...(hasBefore ? { before: copyData(left) } : {}), ...(hasAfter ? { after: copyData(right) } : {}) });
913
+ changes.push({
914
+ ...descriptor,
915
+ op: !hasBefore ? 'add' : !hasAfter ? 'remove' : 'replace',
916
+ ...(hasBefore ? { before: copyData(left) } : {}),
917
+ ...(hasAfter ? { after: copyData(right) } : {}),
918
+ });
412
919
  };
413
920
  for (const field of [...new Set([...Object.keys(before), ...Object.keys(after)])].sort()) {
414
921
  if (field === 'documentDigest') continue;
415
- const hasBefore = Object.hasOwn(before, field), hasAfter = Object.hasOwn(after, field);
416
- if (identityCollections.includes(field) && hasBefore && hasAfter && before[field].every(item => typeof item.id === 'string') && after[field].every(item => typeof item.id === 'string')) {
417
- const left = new Map(before[field].map(item => [item.id, item])), right = new Map(after[field].map(item => [item.id, item]));
418
- for (const targetId of [...new Set([...left.keys(), ...right.keys()])].sort()) delta(left.get(targetId), right.get(targetId), { plane: 'semantic', collection: field, targetId }, left.has(targetId), right.has(targetId));
922
+ const hasBefore = Object.hasOwn(before, field),
923
+ hasAfter = Object.hasOwn(after, field);
924
+ if (
925
+ identityCollections.includes(field) &&
926
+ hasBefore &&
927
+ hasAfter &&
928
+ before[field].every((item) => typeof item.id === 'string') &&
929
+ after[field].every((item) => typeof item.id === 'string')
930
+ ) {
931
+ const left = new Map(before[field].map((item) => [item.id, item])),
932
+ right = new Map(after[field].map((item) => [item.id, item]));
933
+ for (const targetId of [...new Set([...left.keys(), ...right.keys()])].sort())
934
+ delta(
935
+ left.get(targetId),
936
+ right.get(targetId),
937
+ { plane: 'semantic', collection: field, targetId },
938
+ left.has(targetId),
939
+ right.has(targetId),
940
+ );
419
941
  // Ordering matters for timelines and authored reading sequences.
420
942
  delta([...left.keys()], [...right.keys()], { plane: 'semantic', field: `${field}.order` });
421
- } else delta(before[field], after[field], { plane: field === 'layout' ? 'layout' : 'semantic', field }, hasBefore, hasAfter);
943
+ } else
944
+ delta(
945
+ before[field],
946
+ after[field],
947
+ { plane: field === 'layout' ? 'layout' : 'semantic', field },
948
+ hasBefore,
949
+ hasAfter,
950
+ );
422
951
  }
423
- for (const targetId of [...new Set([...Object.keys(beforeLayout), ...Object.keys(afterLayout)])].sort()) delta(beforeLayout[targetId], afterLayout[targetId], { plane: 'layout', targetId }, Object.hasOwn(beforeLayout, targetId), Object.hasOwn(afterLayout, targetId));
424
- return { semanticChanged: changes.some(change => change.plane === 'semantic'), layoutChanged: changes.some(change => change.plane === 'layout'), changes };
952
+ for (const targetId of [
953
+ ...new Set([...Object.keys(beforeLayout), ...Object.keys(afterLayout)]),
954
+ ].sort())
955
+ delta(
956
+ beforeLayout[targetId],
957
+ afterLayout[targetId],
958
+ { plane: 'layout', targetId },
959
+ Object.hasOwn(beforeLayout, targetId),
960
+ Object.hasOwn(afterLayout, targetId),
961
+ );
962
+ return {
963
+ semanticChanged: changes.some((change) => change.plane === 'semantic'),
964
+ layoutChanged: changes.some((change) => change.plane === 'layout'),
965
+ changes,
966
+ };
425
967
  }
426
968
 
427
969
  /**
428
970
  * Deterministic in-memory proposal preview. No authority or repository writes.
429
971
  * Callers must check the base revision, authorize application, validate the final
430
972
  * domain document (including all references), and restamp its derived digest.
973
+ * @type {typeof import('./enterprise-contracts.d.mts').applyEnterpriseOperations}
431
974
  */
432
975
  export function applyEnterpriseOperations(document, proposal, { layout = {} } = {}) {
433
- assertDocument(document); assertEnterpriseProposal(proposal);
434
- let next = copyData(document), nextLayout = copyData(layout);
976
+ assertDocument(document);
977
+ assertEnterpriseProposal(proposal);
978
+ let next = copyData(document),
979
+ nextLayout = copyData(layout);
435
980
  assertLayout(nextLayout, indexedElements(next));
436
981
  for (const operation of proposal.operations) {
437
982
  const entries = indexedElements(next);
438
983
  if (operation.op === 'replace-document') {
439
984
  next = copyData(operation.content);
440
985
  const newEntries = indexedElements(next);
441
- nextLayout = Object.fromEntries(Object.entries(nextLayout).filter(([targetId]) => newEntries.has(targetId)));
986
+ nextLayout = Object.fromEntries(
987
+ Object.entries(nextLayout).filter(([targetId]) => newEntries.has(targetId)),
988
+ );
442
989
  } else if (operation.op === 'add-element') {
443
- if (entries.has(operation.element.id)) throw new TypeError('Cannot add a duplicate semantic element.');
990
+ if (entries.has(operation.element.id))
991
+ throw new TypeError('Cannot add a duplicate semantic element.');
444
992
  next[operation.collection] ??= [];
445
- if (!Array.isArray(next[operation.collection])) throw new TypeError('Cannot add to a non-array collection.');
993
+ if (!Array.isArray(next[operation.collection]))
994
+ throw new TypeError('Cannot add to a non-array collection.');
446
995
  next[operation.collection].push(copyData(operation.element));
447
996
  } else if (operation.op === 'remove-element') {
448
997
  const items = next[operation.collection];
449
- if (!Array.isArray(items) || !items.some(item => item.id === operation.targetId)) throw new TypeError('Cannot remove an absent semantic element.');
450
- next[operation.collection] = items.filter(item => item.id !== operation.targetId);
998
+ if (!Array.isArray(items) || !items.some((item) => item.id === operation.targetId))
999
+ throw new TypeError('Cannot remove an absent semantic element.');
1000
+ next[operation.collection] = items.filter((item) => item.id !== operation.targetId);
451
1001
  delete nextLayout[operation.targetId];
452
1002
  } else {
453
1003
  const target = entries.get(operation.targetId);
454
1004
  if (!target) throw new TypeError('Operation target is absent from the semantic document.');
455
- if (operation.op === 'set-layout') nextLayout[operation.targetId] = { x: operation.x, y: operation.y };
1005
+ if (operation.op === 'set-layout')
1006
+ nextLayout[operation.targetId] = { x: operation.x, y: operation.y };
456
1007
  else target[operation.field] = operation.value;
457
1008
  }
458
1009
  }
459
1010
  // Detect ambiguous identities introduced by additions or document replacement.
460
1011
  indexedElements(next);
461
- const result = diffEnterpriseDocuments(document, next, { beforeLayout: layout, afterLayout: nextLayout });
1012
+ const result = diffEnterpriseDocuments(document, next, {
1013
+ beforeLayout: layout,
1014
+ afterLayout: nextLayout,
1015
+ });
462
1016
  return { document: next, layout: nextLayout, ...result };
463
1017
  }