@arcticdata/dsh-datarc-assistant 26.39.0 → 26.39.1

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 (149) hide show
  1. package/README.md +45 -10
  2. package/api-operations.js +404 -0
  3. package/client.js +452 -87
  4. package/cordis.patch.yml +4 -4
  5. package/entry/SKILL.md +34 -0
  6. package/icon.png +0 -0
  7. package/index.js +35 -47
  8. package/locale/en.json +6 -6
  9. package/locale/zh.json +6 -6
  10. package/native-api.mjs +326 -0
  11. package/native-contracts.js +195 -0
  12. package/native-execution.js +184 -0
  13. package/native-runner.mjs +107 -0
  14. package/native-state.js +67 -0
  15. package/native-tools.js +241 -0
  16. package/operations.js +1260 -0
  17. package/package.json +65 -51
  18. package/{skills → runtime}/datarc-access-permissions/SKILL.md +30 -30
  19. package/{skills → runtime}/datarc-access-permissions/references/api.md +31 -31
  20. package/{skills → runtime}/datarc-access-permissions/references/write-order.md +16 -16
  21. package/{skills → runtime}/datarc-analysis-report/SKILL.md +125 -125
  22. package/{skills → runtime}/datarc-analysis-report/agents/openai.yaml +6 -6
  23. package/{skills → runtime}/datarc-analysis-report/references/analyst-frameworks.md +215 -215
  24. package/{skills → runtime}/datarc-analysis-report/references/api-contracts.md +478 -478
  25. package/{skills → runtime}/datarc-analysis-report/references/direct-card-fallback-design.md +66 -66
  26. package/{skills → runtime}/datarc-analysis-report/references/human-in-the-loop.md +142 -142
  27. package/{skills → runtime}/datarc-analysis-report/references/loop-personalization-policy.md +138 -138
  28. package/{skills → runtime}/datarc-analysis-report/references/manifest-example.json +779 -779
  29. package/{skills → runtime}/datarc-analysis-report/references/narrative-schema.md +160 -160
  30. package/{skills → runtime}/datarc-analysis-report/references/question-syntax.md +151 -151
  31. package/{skills → runtime}/datarc-analysis-report/scripts/run_analysis_report.py +2225 -2225
  32. package/{skills → runtime}/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -1914
  33. package/{skills → runtime}/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -5295
  34. package/{skills → runtime}/datarc-data-search/SKILL.md +243 -243
  35. package/{skills → runtime}/datarc-data-search/scripts/calculate.py +116 -116
  36. package/{skills → runtime}/datarc-data-search/scripts/data-search.mjs +628 -628
  37. package/{skills/datarc-dataseek-search → runtime/datarc-data-search}/scripts/datarc-client.mjs +464 -464
  38. package/{skills → runtime}/datarc-data-search/scripts/search-result.mjs +211 -211
  39. package/{skills → runtime}/datarc-dataseek-batch-evaluation/SKILL.md +59 -59
  40. package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -36
  41. package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -30
  42. package/{skills/datarc-data-search → runtime/datarc-dataseek-batch-evaluation}/scripts/datarc-client.mjs +464 -464
  43. package/{skills → runtime}/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -1020
  44. package/{skills → runtime}/datarc-dataseek-search/SKILL.md +96 -96
  45. package/{skills/datarc-dataseek-batch-evaluation → runtime/datarc-dataseek-search}/scripts/datarc-client.mjs +464 -464
  46. package/{skills → runtime}/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -257
  47. package/{skills → runtime}/datarc-dataseek-semantic-debugging/SKILL.md +44 -44
  48. package/{skills → runtime}/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -4
  49. package/{skills → runtime}/datarc-dataseek-semantic-debugging/evals/evals.json +165 -165
  50. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/dataset.md +77 -77
  51. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -93
  52. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/interventions.md +64 -64
  53. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -47
  54. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/rollback.md +11 -11
  55. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -95
  56. package/{skills → runtime}/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -29
  57. package/{skills → runtime}/datarc-dataseek-testset-generation/SKILL.md +47 -47
  58. package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -464
  59. package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -526
  60. package/{skills → runtime}/datarc-datasource/SKILL.md +97 -97
  61. package/{skills → runtime}/datarc-oauth/SKILL.md +50 -50
  62. package/{skills → runtime}/datarc-oauth/scripts/auth.mjs +192 -192
  63. package/{skills → runtime}/datarc-oauth/scripts/credentials.mjs +237 -237
  64. package/{skills → runtime}/datarc-report-add-card/SKILL.md +90 -90
  65. package/{skills → runtime}/datarc-report-add-card/agents/openai.yaml +4 -4
  66. package/runtime/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
  67. package/{skills → runtime}/datarc-report-add-card/scripts/report-card.mjs +439 -439
  68. package/{skills → runtime}/datarc-semantic-alias/SKILL.md +20 -20
  69. package/{skills → runtime}/datarc-semantic-alias/scripts/alias-plan.mjs +422 -422
  70. package/{skills → runtime}/datarc-semantic-alias/scripts/alias.mjs +11 -11
  71. package/{skills → runtime}/datarc-semantic-calibration/SKILL.md +20 -20
  72. package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -683
  73. package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration.mjs +11 -11
  74. package/{skills → runtime}/datarc-semantic-core/SKILL.md +12 -12
  75. package/{skills → runtime}/datarc-semantic-core/scripts/artifact-journal.mjs +853 -830
  76. package/{skills → runtime}/datarc-semantic-core/scripts/canonical.mjs +48 -48
  77. package/{skills → runtime}/datarc-semantic-core/scripts/case-model.mjs +608 -608
  78. package/{skills → runtime}/datarc-semantic-core/scripts/cli.mjs +180 -180
  79. package/{skills → runtime}/datarc-semantic-core/scripts/datarc-client.mjs +180 -180
  80. package/{skills → runtime}/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -57
  81. package/{skills → runtime}/datarc-semantic-core/scripts/interventions.mjs +693 -693
  82. package/{skills → runtime}/datarc-semantic-core/scripts/live-resolution.mjs +305 -305
  83. package/{skills → runtime}/datarc-semantic-core/scripts/model-scope.mjs +49 -49
  84. package/{skills → runtime}/datarc-semantic-core/scripts/reproduction.mjs +330 -330
  85. package/{skills → runtime}/datarc-semantic-core/scripts/semantic-cli.mjs +799 -740
  86. package/{skills → runtime}/datarc-semantic-core/scripts/shared.mjs +312 -312
  87. package/{skills → runtime}/datarc-semantic-core/scripts/verification.mjs +1111 -1014
  88. package/{skills → runtime}/datarc-semantic-dataset/SKILL.md +20 -20
  89. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -749
  90. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -813
  91. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset.mjs +11 -11
  92. package/{skills → runtime}/datarc-semantic-knowledge/SKILL.md +38 -38
  93. package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -61
  94. package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-generation.json +16 -16
  95. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -347
  96. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -848
  97. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -31
  98. package/{skills → runtime}/datarc-semantic-prompt/SKILL.md +20 -20
  99. package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt-plan.mjs +598 -447
  100. package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt.mjs +15 -15
  101. package/{skills → runtime}/datarc-semantic-synonym/SKILL.md +20 -20
  102. package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -688
  103. package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym.mjs +11 -11
  104. package/{skills → runtime}/datarc-viz-analysis-report/SKILL.md +108 -108
  105. package/{skills → runtime}/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -8
  106. package/{skills → runtime}/datarc-viz-analysis-report/assets/echarts.min.js +45 -45
  107. package/{skills → runtime}/datarc-viz-analysis-report/references/api-contracts.md +163 -163
  108. package/{skills → runtime}/datarc-viz-analysis-report/references/derivation-log.md +157 -157
  109. package/{skills → runtime}/datarc-viz-analysis-report/references/evidence-framework.md +76 -76
  110. package/{skills → runtime}/datarc-viz-analysis-report/references/html-template.md +92 -92
  111. package/{skills → runtime}/datarc-viz-analysis-report/references/provenance-format.md +56 -56
  112. package/{skills → runtime}/datarc-viz-analysis-report/references/question-syntax.md +151 -151
  113. package/{skills → runtime}/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -1708
  114. package/{skills → runtime}/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -964
  115. package/{skills → runtime}/datarc-workspace-configuration/SKILL.md +59 -59
  116. package/{skills → runtime}/datarc-workspace-configuration/references/artifacts.md +75 -75
  117. package/{skills → runtime}/datarc-workspace-configuration/references/verification.md +20 -20
  118. package/{skills → runtime}/datarc-workspace-configuration/scripts/configuration.mjs +722 -662
  119. package/{skills → runtime}/datarc-workspace-context/SKILL.md +43 -43
  120. package/{skills → runtime}/datarc-workspace-context/agents/openai.yaml +4 -4
  121. package/{skills → runtime}/datarc-workspace-context/scripts/datarc-client.mjs +31 -31
  122. package/{skills → runtime}/datarc-workspace-context/scripts/query-display.mjs +114 -114
  123. package/{skills → runtime}/datarc-workspace-context/scripts/workspace-context.mjs +58 -58
  124. package/{skills → runtime}/datarc-workspace-custom-tables/SKILL.md +89 -89
  125. package/{skills → runtime}/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -165
  126. package/{skills → runtime}/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -601
  127. package/{skills → runtime}/datarc-workspace-keywords/SKILL.md +197 -197
  128. package/{skills → runtime}/datarc-workspace-keywords/agents/openai.yaml +4 -4
  129. package/{skills → runtime}/datarc-workspace-keywords/references/api-fields.md +79 -79
  130. package/{skills → runtime}/datarc-workspace-keywords/references/derived-measures.md +177 -177
  131. package/{skills → runtime}/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -145
  132. package/{skills → runtime}/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -2421
  133. package/{skills → runtime}/datarc-workspace-membership/SKILL.md +29 -29
  134. package/{skills → runtime}/datarc-workspace-membership/references/api.md +19 -19
  135. package/{skills → runtime}/datarc-workspace-modeling/SKILL.md +209 -209
  136. package/{skills → runtime}/datarc-workspace-modeling/agents/openai.yaml +4 -4
  137. package/{skills → runtime}/datarc-workspace-modeling/references/join-preview.md +38 -38
  138. package/{skills → runtime}/datarc-workspace-modeling/references/model-plan.md +300 -300
  139. package/{skills → runtime}/datarc-workspace-modeling/references/model-tags.md +95 -95
  140. package/{skills → runtime}/datarc-workspace-modeling/references/modeling-contract.json +29 -29
  141. package/{skills → runtime}/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -2423
  142. package/{skills → runtime}/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -137
  143. package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -238
  144. package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -1261
  145. package/skills-provider.js +51 -0
  146. package/workflow-index.json +434 -0
  147. package/icon.svg +0 -4
  148. package/skills/datarc-report-add-card/scripts/datarc-client.mjs +0 -464
  149. package/skills-index.json +0 -194
@@ -1,693 +1,693 @@
1
- import {
2
- canonicalJson,
3
- hashArtifactValue as hashValue,
4
- withHash,
5
- } from "./canonical.mjs";
6
- import { DatarcError } from "./datarc-client.mjs";
7
- import {
8
- assertEnvelopeHash,
9
- assertPossibleState,
10
- assertState,
11
- bindSummaryAuthorityTargets,
12
- fail,
13
- isRecord,
14
- listOf,
15
- requireClient,
16
- resolveCompletedStep,
17
- statesEqual,
18
- uniqueStates,
19
- validateMutationCaseIds,
20
- } from "./shared.mjs";
21
-
22
- export const PLAN_VERSION = 1;
23
-
24
- export function createEngine(kinds) {
25
- const REGISTRY = new Map(kinds.map((kind) => [kind.name, kind]));
26
- const MUTATION_KINDS = new Set(
27
- [...REGISTRY.values()]
28
- .filter((kind) => kind.planable)
29
- .map((kind) => kind.name),
30
- );
31
- const ALL_PLAN_KINDS = new Set(REGISTRY.keys());
32
-
33
- function requireKind(kindName) {
34
- const kind = REGISTRY.get(kindName);
35
- if (!kind)
36
- fail("UNSUPPORTED_INTERVENTION", `unsupported intervention: ${kindName}`);
37
- return kind;
38
- }
39
-
40
- async function preparePlan(client, input, options = {}) {
41
- requireClient(client);
42
- const workspaceId = input?.workspaceId;
43
- if (!Number.isSafeInteger(workspaceId) || workspaceId <= 0)
44
- fail("INVALID_INPUT", "workspaceId must be a positive integer");
45
- if (!Array.isArray(input?.operations) || input.operations.length === 0)
46
- fail("INVALID_INPUT", "operations must be a non-empty array");
47
- const authorities = caseAuthorities(input.operations);
48
- const operations = coalesceOperations(input.operations);
49
-
50
- const plan = {
51
- version: PLAN_VERSION,
52
- workspaceId,
53
- authorities,
54
- steps: [],
55
- summaries: [],
56
- warnings: [],
57
- impact: [],
58
- promptChanges: [],
59
- };
60
- const kindCtx = new Map();
61
- for (const operation of operations) {
62
- if (!MUTATION_KINDS.has(operation?.kind))
63
- fail(
64
- "UNSUPPORTED_INTERVENTION",
65
- `unsupported intervention: ${operation?.kind}`,
66
- );
67
- if (!kindCtx.has(operation.kind))
68
- kindCtx.set(
69
- operation.kind,
70
- requireKind(operation.kind).planningContext?.(options) ?? {},
71
- );
72
- }
73
- for (const operation of operations) {
74
- await requireKind(operation.kind).plan(client, plan, operation, {
75
- ...options,
76
- planningEvidence: input.planningEvidence,
77
- planningContext: kindCtx.get(operation.kind),
78
- });
79
- }
80
- assertUniqueMutationTargets(plan.steps);
81
- bindSummaryAuthorityTargets(plan);
82
- return withHash(plan, "planHash");
83
- }
84
-
85
- async function applyPlan(client, plan, confirmation, options = {}) {
86
- requireClient(client);
87
- validateApplyPlan(plan, confirmation);
88
- const receipt = {
89
- version: PLAN_VERSION,
90
- workspaceId: plan.workspaceId,
91
- planHash: plan.planHash,
92
- completedSteps: [],
93
- };
94
- let durableReceipt = withHash(receipt, "receiptHash");
95
-
96
- if (plan.steps.length === 0)
97
- durableReceipt = await reportProgress(
98
- options,
99
- durableReceipt,
100
- durableReceipt,
101
- );
102
- for (const [stepIndex, step] of plan.steps.entries()) {
103
- let current;
104
- try {
105
- const kind = requireKind(step.kind);
106
- current = kind.preApplyRead
107
- ? await kind.preApplyRead(client, plan.workspaceId, step, {
108
- options,
109
- authorities: plan.authorities,
110
- })
111
- : await kind.readState(client, plan.workspaceId, step);
112
- assertState(current, step.before, "CONCURRENT_CHANGE", step);
113
- if (kind.postApplyRead)
114
- await kind.postApplyRead(client, plan.workspaceId, step, {
115
- options,
116
- authorities: plan.authorities,
117
- });
118
- } catch (error) {
119
- throw attachReceipt(error, durableReceipt);
120
- }
121
- const pendingReceipt = withHash(
122
- { ...receipt, pendingStep: pendingStep(step, stepIndex) },
123
- "receiptHash",
124
- );
125
- durableReceipt = await reportProgress(
126
- options,
127
- pendingReceipt,
128
- durableReceipt,
129
- );
130
-
131
- let completed;
132
- try {
133
- completed = await applyStep(client, plan.workspaceId, step);
134
- } catch (error) {
135
- if (!error.partialStep) throw attachReceipt(error, durableReceipt);
136
- const partialReceipt = withHash(
137
- {
138
- ...receipt,
139
- completedSteps: [
140
- ...receipt.completedSteps,
141
- bindReceiptStep(error.partialStep, step, stepIndex),
142
- ],
143
- },
144
- "receiptHash",
145
- );
146
- try {
147
- durableReceipt = await reportProgress(
148
- options,
149
- partialReceipt,
150
- durableReceipt,
151
- );
152
- } catch (progressError) {
153
- throw progressError;
154
- }
155
- throw attachReceipt(error, durableReceipt);
156
- }
157
- completed = bindReceiptStep(completed, step, stepIndex);
158
- const completedReceipt = withHash(
159
- {
160
- ...receipt,
161
- completedSteps: [...receipt.completedSteps, completed],
162
- },
163
- "receiptHash",
164
- );
165
- durableReceipt = await reportProgress(
166
- options,
167
- completedReceipt,
168
- durableReceipt,
169
- );
170
- receipt.completedSteps.push(completed);
171
- }
172
- return durableReceipt;
173
- }
174
-
175
- function validateApplyPlan(plan, confirmation) {
176
- assertEnvelopeHash(plan, "planHash", confirmation, "APPLY");
177
- validatePlanMutationStructure(plan);
178
- assertSingleMutationKind(plan);
179
- }
180
-
181
- function assertSingleMutationKind(plan) {
182
- const kinds = new Set(plan.steps.map((step) => step.kind));
183
- if (kinds.size > 1)
184
- fail(
185
- "MIXED_KIND_PLAN",
186
- "a plan must target a single resource kind; split cross-kind changes into separate plans",
187
- { kinds: [...kinds] },
188
- );
189
- }
190
-
191
- async function rollbackReceipt(
192
- client,
193
- receipt,
194
- confirmation,
195
- options = {},
196
- ) {
197
- requireClient(client);
198
- assertEnvelopeHash(receipt, "receiptHash", confirmation, "ROLLBACK");
199
- if (
200
- options.beforeDictionaryMutation !== undefined &&
201
- typeof options.beforeDictionaryMutation !== "function"
202
- )
203
- fail(
204
- "INVALID_ROLLBACK_HOOK",
205
- "beforeDictionaryMutation must be a function",
206
- );
207
- const restored = [];
208
- let dictionaryMutations = 0;
209
- let dictionaryMutationPrepared = false;
210
- const rollbackSteps = [
211
- ...(receipt.pendingStep === undefined ? [] : [receipt.pendingStep]),
212
- ...[...receipt.completedSteps].reverse(),
213
- ];
214
- for (const recorded of rollbackSteps) {
215
- let completed = recorded;
216
- let current;
217
- if (completed.before === null) {
218
- if (!hasResolvedItemEndpoint(completed, receipt.workspaceId)) {
219
- const resolution = await resolvePendingCreation(
220
- client,
221
- receipt.workspaceId,
222
- completed,
223
- );
224
- if (resolution.absent) {
225
- restored.push({ kind: completed.kind, resourceId: null, noOp: true });
226
- continue;
227
- }
228
- completed = resolution.step;
229
- current = resolution.current;
230
- } else {
231
- current = await readCreatedStateFromCollection(
232
- client,
233
- receipt.workspaceId,
234
- completed,
235
- );
236
- }
237
- } else {
238
- current = await readStepState(client, receipt.workspaceId, completed);
239
- }
240
- if (matchesBefore(completed, current)) {
241
- restored.push({
242
- kind: completed.kind,
243
- resourceId:
244
- current?.id ?? completed.after?.id ?? completed.before?.id ?? null,
245
- noOp: true,
246
- });
247
- continue;
248
- }
249
- if (completed.state === "uncertain")
250
- assertPossibleState(
251
- current,
252
- completed.possibleAfter,
253
- "ROLLBACK_DRIFT",
254
- completed,
255
- );
256
- else assertState(current, completed.after, "ROLLBACK_DRIFT", completed);
257
- if (
258
- completed.dictionarySyncRequired === true &&
259
- !dictionaryMutationPrepared
260
- ) {
261
- if (typeof options.beforeDictionaryMutation === "function")
262
- await options.beforeDictionaryMutation({ kind: completed.kind });
263
- dictionaryMutationPrepared = true;
264
- }
265
- const result = await restoreStep(
266
- client,
267
- receipt.workspaceId,
268
- completed,
269
- current,
270
- );
271
- restored.push({
272
- kind: completed.kind,
273
- resourceId:
274
- result?.id ?? completed.after?.id ?? completed.before?.id ?? null,
275
- ...(result?.noOp === true ? { noOp: true } : {}),
276
- ...(result?.recreatedId === undefined
277
- ? {}
278
- : { recreatedId: result.recreatedId }),
279
- });
280
- if (completed.dictionarySyncRequired === true) dictionaryMutations += 1;
281
- }
282
- return {
283
- planHash: receipt.planHash,
284
- receiptHash: receipt.receiptHash,
285
- restored,
286
- dictionaryMutations,
287
- };
288
- }
289
-
290
- function caseAuthorities(operations) {
291
- const seen = new Set();
292
- return operations.map((operation, index) => {
293
- const caseId =
294
- typeof operation?.caseId === "string" ? operation.caseId.trim() : "";
295
- if (!caseId)
296
- fail("CASE_ID_REQUIRED", "each operation requires a nonempty caseId", {
297
- index,
298
- });
299
- if (seen.has(caseId))
300
- fail(
301
- "DUPLICATE_CASE_AUTHORITY",
302
- "one caseId cannot authorize multiple operations",
303
- { caseId, index },
304
- );
305
- seen.add(caseId);
306
- return {
307
- caseId,
308
- kind: operation?.kind,
309
- target: caseAuthorityTarget(operation),
310
- };
311
- });
312
- }
313
-
314
- function caseAuthorityTarget(operation) {
315
- const kind = requireKind(operation?.kind);
316
- if (!kind.authorityTarget)
317
- fail(
318
- "UNSUPPORTED_INTERVENTION",
319
- `unsupported intervention: ${operation?.kind}`,
320
- );
321
- return kind.authorityTarget(operation);
322
- }
323
-
324
- function coalesceOperations(operations) {
325
- const result = [];
326
- const coalescers = new Map();
327
- for (const operation of operations) {
328
- const kind = REGISTRY.get(operation?.kind);
329
- let coalescer = coalescers.get(operation?.kind);
330
- if (kind && !coalescer) {
331
- coalescer = kind.createCoalescer?.();
332
- coalescers.set(operation?.kind, coalescer);
333
- }
334
- if (coalescer && coalescer.add(operation, result)) continue;
335
- const caseId = operation?.caseId?.trim() ?? "";
336
- result.push({
337
- ...structuredClone(operation),
338
- caseId,
339
- caseIds: [caseId],
340
- });
341
- }
342
- for (const operation of result)
343
- if (["dataset", "knowledge"].includes(operation.kind))
344
- delete operation.desiredKey;
345
- return result;
346
- }
347
-
348
- function matchesBefore(step, current) {
349
- if (step.before === null) return current === null;
350
- return (
351
- requireKind(step.kind).matchesBefore?.(step, current) ??
352
- statesEqual(current, step.before)
353
- );
354
- }
355
-
356
- async function reportProgress(options, progressReceipt, durableReceipt) {
357
- if (typeof options?.onProgress !== "function") return progressReceipt;
358
- try {
359
- await options.onProgress(progressReceipt);
360
- return progressReceipt;
361
- } catch (error) {
362
- throw attachReceipt(error, durableReceipt);
363
- }
364
- }
365
-
366
- function attachReceipt(error, receipt) {
367
- const result =
368
- error && typeof error === "object"
369
- ? error
370
- : new DatarcError("apply progress failed", "APPLY_FAILED");
371
- result.receipt = receipt;
372
- if (!result.details || typeof result.details !== "object")
373
- result.details = {};
374
- result.details.partialReceipt = receipt;
375
- return result;
376
- }
377
-
378
- function pendingStep(step, stepIndex) {
379
- const possibleAfter =
380
- requireKind(step.kind).possibleAfter?.(step) ?? [step.before, step.after];
381
- return bindReceiptStep(
382
- {
383
- ...structuredClone(step),
384
- state: "uncertain",
385
- possibleAfter: uniqueStates(possibleAfter),
386
- identityResolved: step.before !== null || hasResolvedItemEndpoint(step),
387
- },
388
- step,
389
- stepIndex,
390
- );
391
- }
392
-
393
- function bindReceiptStep(runtimeStep, planStep, planStepIndex) {
394
- return {
395
- ...structuredClone(runtimeStep),
396
- planStepIndex,
397
- planStepHash: hashValue(planStep),
398
- };
399
- }
400
-
401
- async function applyStep(client, workspaceId, step) {
402
- const kind = requireKind(step.kind);
403
- if (kind.applyStep) {
404
- const applied = await kind.applyStep(client, workspaceId, step, {
405
- partialStep,
406
- });
407
- if (applied !== undefined) return applied;
408
- }
409
- let response;
410
- try {
411
- response = await kind.writeDesired(client, step);
412
- } catch (error) {
413
- error.partialStep = partialStep(step, undefined, [step.before, step.after]);
414
- throw error;
415
- }
416
- let completed = resolveCompletedStep(step, response);
417
- let current;
418
- try {
419
- current = await kind.readState(client, workspaceId, completed);
420
- completed = resolveCompletedStep(completed, current);
421
- assertState(current, step.after, "WRITE_VERIFICATION_FAILED", step);
422
- } catch (error) {
423
- error.partialStep = partialStep(completed, current, [completed.after]);
424
- throw error;
425
- }
426
- return { ...completed, after: current };
427
- }
428
-
429
- async function restoreStep(client, workspaceId, step, currentState) {
430
- const kind = requireKind(step.kind);
431
- if (step.before === null) {
432
- assertItemEndpoint(workspaceId, step);
433
- await client.request("DELETE", step.endpoint);
434
- const current = await readCreatedStateFromCollection(
435
- client,
436
- workspaceId,
437
- step,
438
- );
439
- assertState(current, null, "ROLLBACK_VERIFICATION_FAILED", step);
440
- return { id: step.after?.id };
441
- }
442
- if (kind.restoreStep)
443
- return kind.restoreStep(client, workspaceId, step, currentState, {
444
- partialStep,
445
- });
446
- await kind.writeBefore(client, step);
447
- const current = await kind.readState(client, workspaceId, step);
448
- assertState(current, step.before, "ROLLBACK_VERIFICATION_FAILED", step);
449
- return { id: current?.id };
450
- }
451
-
452
- function readStepState(client, workspaceId, step) {
453
- return requireKind(step.kind).readState(client, workspaceId, step);
454
- }
455
-
456
- function readCreatedStateFromCollection(client, workspaceId, step) {
457
- const kind = requireKind(step.kind);
458
- return kind.readCreatedState
459
- ? kind.readCreatedState(client, workspaceId, step)
460
- : kind.readState(client, workspaceId, step);
461
- }
462
-
463
- async function resolvePendingCreation(client, workspaceId, step) {
464
- const kind = requireKind(step.kind);
465
- if (!kind.exactCreatedCandidates)
466
- fail(
467
- "ROLLBACK_IDENTITY_UNRESOLVED",
468
- "created resource has no resolvable semantic identity",
469
- { kind: step.kind },
470
- );
471
- const candidates = await kind.exactCreatedCandidates(
472
- client,
473
- workspaceId,
474
- step,
475
- );
476
- if (candidates.length === 0) return { absent: true };
477
- if (candidates.length > 1)
478
- fail(
479
- "ROLLBACK_IDENTITY_AMBIGUOUS",
480
- "multiple resources match the pending semantic identity",
481
- { kind: step.kind },
482
- );
483
- const current = candidates[0];
484
- assertPossibleState(current, step.possibleAfter, "ROLLBACK_DRIFT", step);
485
- const collection = collectionForKind(workspaceId, step.kind);
486
- const id = current.id;
487
- if (collection === null || id === undefined)
488
- fail(
489
- "ROLLBACK_IDENTITY_UNRESOLVED",
490
- "created resource identity is unresolved; refusing to delete a collection",
491
- { kind: step.kind, endpoint: step.endpoint },
492
- );
493
- return {
494
- absent: false,
495
- current,
496
- step: {
497
- ...structuredClone(step),
498
- endpoint: `${collection}${id}/`,
499
- after: { ...structuredClone(step.after), id },
500
- identityResolved: true,
501
- },
502
- };
503
- }
504
-
505
- function partialStep(step, current, possibleAfter) {
506
- const knownStates = current === undefined ? possibleAfter : [current];
507
- return {
508
- ...step,
509
- after: current ?? step.after,
510
- state: current === undefined ? "uncertain" : "verified",
511
- possibleAfter: uniqueStates(knownStates),
512
- identityResolved: step.before !== null || hasResolvedItemEndpoint(step),
513
- };
514
- }
515
-
516
- function assertItemEndpoint(workspaceId, step) {
517
- if (hasResolvedItemEndpoint(step, workspaceId)) return;
518
- fail(
519
- "ROLLBACK_IDENTITY_UNRESOLVED",
520
- "created resource identity is unresolved; refusing to delete a collection",
521
- { kind: step.kind, endpoint: step.endpoint },
522
- );
523
- }
524
-
525
- function hasResolvedItemEndpoint(step, workspaceId) {
526
- const id = step.after?.id;
527
- if (id === undefined) return false;
528
- if (workspaceId === undefined) return step.endpoint.endsWith(`/${id}/`);
529
- const collection = collectionForKind(workspaceId, step.kind);
530
- return collection !== null && step.endpoint === `${collection}${id}/`;
531
- }
532
-
533
- function collectionForKind(workspaceId, kind) {
534
- return requireKind(kind).collection?.(workspaceId) ?? null;
535
- }
536
-
537
- function assertUniqueMutationTargets(steps) {
538
- const seen = new Set();
539
- for (const step of steps) {
540
- const key = mutationTargetKey(step);
541
- if (seen.has(key))
542
- fail(
543
- "DUPLICATE_MUTATION_TARGET",
544
- "a plan cannot mutate the same semantic target more than once",
545
- { kind: step.kind },
546
- );
547
- seen.add(key);
548
- }
549
- }
550
-
551
- function mutationTargetKey(step) {
552
- return (
553
- requireKind(step.kind).targetKey?.(step) ??
554
- `${step.kind}:${step.endpoint}`
555
- );
556
- }
557
-
558
- function validatePlanMutationStructure(plan) {
559
- if (
560
- !isRecord(plan) ||
561
- plan.version !== PLAN_VERSION ||
562
- !Number.isSafeInteger(plan.workspaceId) ||
563
- plan.workspaceId <= 0 ||
564
- !Array.isArray(plan.steps) ||
565
- !Array.isArray(plan.summaries) ||
566
- !Array.isArray(plan.warnings) ||
567
- !Array.isArray(plan.impact)
568
- )
569
- fail("INVALID_PLAN_STRUCTURE", "plan root structure is invalid");
570
- const authorities = validatePlanAuthorities(plan.authorities);
571
- assertUniqueMutationTargets(plan.steps);
572
- const usedCaseIds = new Set();
573
- const plannedCaseIds = new Set();
574
- for (const step of plan.steps) {
575
- if (!step || typeof step !== "object" || Array.isArray(step))
576
- fail("INVALID_PLAN_STRUCTURE", "each plan step must be an object");
577
- const validator = requireKind(step.kind).validateStep;
578
- if (!validator)
579
- fail(
580
- "UNSUPPORTED_INTERVENTION",
581
- "plan contains an unsupported intervention step",
582
- );
583
- validator(step, plan, authorities, plannedCaseIds, usedCaseIds);
584
- }
585
- validatePlanSummaries(plan.summaries, authorities, plannedCaseIds);
586
- }
587
-
588
- function validatePlanAuthorities(authorities) {
589
- if (!Array.isArray(authorities))
590
- fail("INVALID_PLAN_STRUCTURE", "plan authorities must be an array");
591
- const seen = new Map();
592
- for (const authority of authorities) {
593
- const caseId = authority?.caseId;
594
- if (
595
- !isRecord(authority) ||
596
- canonicalJson(Object.keys(authority).sort()) !==
597
- canonicalJson(["caseId", "kind", "target"]) ||
598
- typeof caseId !== "string" ||
599
- !caseId ||
600
- caseId !== caseId.trim() ||
601
- typeof authority.kind !== "string" ||
602
- !authority.kind ||
603
- !ALL_PLAN_KINDS.has(authority.kind) ||
604
- seen.has(caseId)
605
- )
606
- fail("INVALID_PLAN_STRUCTURE", "plan case authorities are invalid");
607
- validateCaseAuthorityTarget(authority.kind, authority.target);
608
- seen.set(caseId, authority);
609
- }
610
- return seen;
611
- }
612
-
613
- function validateCaseAuthorityTarget(kind, target) {
614
- if (!isRecord(target))
615
- fail("INVALID_PLAN_STRUCTURE", "plan authority target is invalid");
616
- const validator = requireKind(kind).validateAuthorityTarget;
617
- if (!validator)
618
- fail("INVALID_PLAN_STRUCTURE", "plan authority kind is invalid");
619
- validator(target);
620
- }
621
-
622
- function validatePlanSummaries(summaries, authorities, plannedCaseIds) {
623
- const summarized = new Set();
624
- for (const summary of summaries) {
625
- if (
626
- !isRecord(summary) ||
627
- !ALL_PLAN_KINDS.has(summary.kind) ||
628
- !new Set(["planned", "noop"]).has(summary.status)
629
- )
630
- fail("INVALID_PLAN_STRUCTURE", "plan summary is invalid");
631
- const caseIds = validateMutationCaseIds(
632
- summary.caseIds,
633
- "INVALID_PLAN_STRUCTURE",
634
- );
635
- const expectedAuthorityTargets = caseIds.map((caseId) => ({
636
- caseId,
637
- target: structuredClone(authorities.get(caseId)?.target),
638
- }));
639
- const displayField = requireKind(summary.kind).summaryField;
640
- if (
641
- canonicalJson(Object.keys(summary).sort()) !==
642
- canonicalJson(
643
- [
644
- "authorityTargets",
645
- "caseIds",
646
- "kind",
647
- "status",
648
- ...displayField,
649
- ].sort(),
650
- ) ||
651
- !Array.isArray(summary.authorityTargets) ||
652
- canonicalJson(summary.authorityTargets) !==
653
- canonicalJson(expectedAuthorityTargets) ||
654
- !requireKind(summary.kind).summaryMatches(
655
- summary,
656
- expectedAuthorityTargets,
657
- )
658
- )
659
- fail(
660
- "INVALID_PLAN_STRUCTURE",
661
- "plan summary targets must match their case authorities",
662
- );
663
- for (const caseId of caseIds) {
664
- if (
665
- summarized.has(caseId) ||
666
- authorities.get(caseId)?.kind !== summary.kind ||
667
- (summary.status === "planned") !== plannedCaseIds.has(caseId)
668
- )
669
- fail(
670
- "INVALID_PLAN_STRUCTURE",
671
- "plan summaries do not bind every case authority exactly once",
672
- );
673
- summarized.add(caseId);
674
- }
675
- }
676
- if (
677
- summarized.size !== authorities.size ||
678
- [...authorities.keys()].some((caseId) => !summarized.has(caseId))
679
- )
680
- fail(
681
- "INVALID_PLAN_STRUCTURE",
682
- "plan summaries must account for every case authority",
683
- );
684
- }
685
-
686
- return {
687
- preparePlan,
688
- applyPlan,
689
- rollbackReceipt,
690
- validateApplyPlan,
691
- kinds,
692
- };
693
- }
1
+ import {
2
+ canonicalJson,
3
+ hashArtifactValue as hashValue,
4
+ withHash,
5
+ } from "./canonical.mjs";
6
+ import { DatarcError } from "./datarc-client.mjs";
7
+ import {
8
+ assertEnvelopeHash,
9
+ assertPossibleState,
10
+ assertState,
11
+ bindSummaryAuthorityTargets,
12
+ fail,
13
+ isRecord,
14
+ listOf,
15
+ requireClient,
16
+ resolveCompletedStep,
17
+ statesEqual,
18
+ uniqueStates,
19
+ validateMutationCaseIds,
20
+ } from "./shared.mjs";
21
+
22
+ export const PLAN_VERSION = 1;
23
+
24
+ export function createEngine(kinds) {
25
+ const REGISTRY = new Map(kinds.map((kind) => [kind.name, kind]));
26
+ const MUTATION_KINDS = new Set(
27
+ [...REGISTRY.values()]
28
+ .filter((kind) => kind.planable)
29
+ .map((kind) => kind.name),
30
+ );
31
+ const ALL_PLAN_KINDS = new Set(REGISTRY.keys());
32
+
33
+ function requireKind(kindName) {
34
+ const kind = REGISTRY.get(kindName);
35
+ if (!kind)
36
+ fail("UNSUPPORTED_INTERVENTION", `unsupported intervention: ${kindName}`);
37
+ return kind;
38
+ }
39
+
40
+ async function preparePlan(client, input, options = {}) {
41
+ requireClient(client);
42
+ const workspaceId = input?.workspaceId;
43
+ if (!Number.isSafeInteger(workspaceId) || workspaceId <= 0)
44
+ fail("INVALID_INPUT", "workspaceId must be a positive integer");
45
+ if (!Array.isArray(input?.operations) || input.operations.length === 0)
46
+ fail("INVALID_INPUT", "operations must be a non-empty array");
47
+ const authorities = caseAuthorities(input.operations);
48
+ const operations = coalesceOperations(input.operations);
49
+
50
+ const plan = {
51
+ version: PLAN_VERSION,
52
+ workspaceId,
53
+ authorities,
54
+ steps: [],
55
+ summaries: [],
56
+ warnings: [],
57
+ impact: [],
58
+ promptChanges: [],
59
+ };
60
+ const kindCtx = new Map();
61
+ for (const operation of operations) {
62
+ if (!MUTATION_KINDS.has(operation?.kind))
63
+ fail(
64
+ "UNSUPPORTED_INTERVENTION",
65
+ `unsupported intervention: ${operation?.kind}`,
66
+ );
67
+ if (!kindCtx.has(operation.kind))
68
+ kindCtx.set(
69
+ operation.kind,
70
+ requireKind(operation.kind).planningContext?.(options) ?? {},
71
+ );
72
+ }
73
+ for (const operation of operations) {
74
+ await requireKind(operation.kind).plan(client, plan, operation, {
75
+ ...options,
76
+ planningEvidence: input.planningEvidence,
77
+ planningContext: kindCtx.get(operation.kind),
78
+ });
79
+ }
80
+ assertUniqueMutationTargets(plan.steps);
81
+ bindSummaryAuthorityTargets(plan);
82
+ return withHash(plan, "planHash");
83
+ }
84
+
85
+ async function applyPlan(client, plan, confirmation, options = {}) {
86
+ requireClient(client);
87
+ validateApplyPlan(plan, confirmation);
88
+ const receipt = {
89
+ version: PLAN_VERSION,
90
+ workspaceId: plan.workspaceId,
91
+ planHash: plan.planHash,
92
+ completedSteps: [],
93
+ };
94
+ let durableReceipt = withHash(receipt, "receiptHash");
95
+
96
+ if (plan.steps.length === 0)
97
+ durableReceipt = await reportProgress(
98
+ options,
99
+ durableReceipt,
100
+ durableReceipt,
101
+ );
102
+ for (const [stepIndex, step] of plan.steps.entries()) {
103
+ let current;
104
+ try {
105
+ const kind = requireKind(step.kind);
106
+ current = kind.preApplyRead
107
+ ? await kind.preApplyRead(client, plan.workspaceId, step, {
108
+ options,
109
+ authorities: plan.authorities,
110
+ })
111
+ : await kind.readState(client, plan.workspaceId, step);
112
+ assertState(current, step.before, "CONCURRENT_CHANGE", step);
113
+ if (kind.postApplyRead)
114
+ await kind.postApplyRead(client, plan.workspaceId, step, {
115
+ options,
116
+ authorities: plan.authorities,
117
+ });
118
+ } catch (error) {
119
+ throw attachReceipt(error, durableReceipt);
120
+ }
121
+ const pendingReceipt = withHash(
122
+ { ...receipt, pendingStep: pendingStep(step, stepIndex) },
123
+ "receiptHash",
124
+ );
125
+ durableReceipt = await reportProgress(
126
+ options,
127
+ pendingReceipt,
128
+ durableReceipt,
129
+ );
130
+
131
+ let completed;
132
+ try {
133
+ completed = await applyStep(client, plan.workspaceId, step);
134
+ } catch (error) {
135
+ if (!error.partialStep) throw attachReceipt(error, durableReceipt);
136
+ const partialReceipt = withHash(
137
+ {
138
+ ...receipt,
139
+ completedSteps: [
140
+ ...receipt.completedSteps,
141
+ bindReceiptStep(error.partialStep, step, stepIndex),
142
+ ],
143
+ },
144
+ "receiptHash",
145
+ );
146
+ try {
147
+ durableReceipt = await reportProgress(
148
+ options,
149
+ partialReceipt,
150
+ durableReceipt,
151
+ );
152
+ } catch (progressError) {
153
+ throw progressError;
154
+ }
155
+ throw attachReceipt(error, durableReceipt);
156
+ }
157
+ completed = bindReceiptStep(completed, step, stepIndex);
158
+ const completedReceipt = withHash(
159
+ {
160
+ ...receipt,
161
+ completedSteps: [...receipt.completedSteps, completed],
162
+ },
163
+ "receiptHash",
164
+ );
165
+ durableReceipt = await reportProgress(
166
+ options,
167
+ completedReceipt,
168
+ durableReceipt,
169
+ );
170
+ receipt.completedSteps.push(completed);
171
+ }
172
+ return durableReceipt;
173
+ }
174
+
175
+ function validateApplyPlan(plan, confirmation) {
176
+ assertEnvelopeHash(plan, "planHash", confirmation, "APPLY");
177
+ validatePlanMutationStructure(plan);
178
+ assertSingleMutationKind(plan);
179
+ }
180
+
181
+ function assertSingleMutationKind(plan) {
182
+ const kinds = new Set(plan.steps.map((step) => step.kind));
183
+ if (kinds.size > 1)
184
+ fail(
185
+ "MIXED_KIND_PLAN",
186
+ "a plan must target a single resource kind; split cross-kind changes into separate plans",
187
+ { kinds: [...kinds] },
188
+ );
189
+ }
190
+
191
+ async function rollbackReceipt(
192
+ client,
193
+ receipt,
194
+ confirmation,
195
+ options = {},
196
+ ) {
197
+ requireClient(client);
198
+ assertEnvelopeHash(receipt, "receiptHash", confirmation, "ROLLBACK");
199
+ if (
200
+ options.beforeDictionaryMutation !== undefined &&
201
+ typeof options.beforeDictionaryMutation !== "function"
202
+ )
203
+ fail(
204
+ "INVALID_ROLLBACK_HOOK",
205
+ "beforeDictionaryMutation must be a function",
206
+ );
207
+ const restored = [];
208
+ let dictionaryMutations = 0;
209
+ let dictionaryMutationPrepared = false;
210
+ const rollbackSteps = [
211
+ ...(receipt.pendingStep === undefined ? [] : [receipt.pendingStep]),
212
+ ...[...receipt.completedSteps].reverse(),
213
+ ];
214
+ for (const recorded of rollbackSteps) {
215
+ let completed = recorded;
216
+ let current;
217
+ if (completed.before === null) {
218
+ if (!hasResolvedItemEndpoint(completed, receipt.workspaceId)) {
219
+ const resolution = await resolvePendingCreation(
220
+ client,
221
+ receipt.workspaceId,
222
+ completed,
223
+ );
224
+ if (resolution.absent) {
225
+ restored.push({ kind: completed.kind, resourceId: null, noOp: true });
226
+ continue;
227
+ }
228
+ completed = resolution.step;
229
+ current = resolution.current;
230
+ } else {
231
+ current = await readCreatedStateFromCollection(
232
+ client,
233
+ receipt.workspaceId,
234
+ completed,
235
+ );
236
+ }
237
+ } else {
238
+ current = await readStepState(client, receipt.workspaceId, completed);
239
+ }
240
+ if (matchesBefore(completed, current)) {
241
+ restored.push({
242
+ kind: completed.kind,
243
+ resourceId:
244
+ current?.id ?? completed.after?.id ?? completed.before?.id ?? null,
245
+ noOp: true,
246
+ });
247
+ continue;
248
+ }
249
+ if (completed.state === "uncertain")
250
+ assertPossibleState(
251
+ current,
252
+ completed.possibleAfter,
253
+ "ROLLBACK_DRIFT",
254
+ completed,
255
+ );
256
+ else assertState(current, completed.after, "ROLLBACK_DRIFT", completed);
257
+ if (
258
+ completed.dictionarySyncRequired === true &&
259
+ !dictionaryMutationPrepared
260
+ ) {
261
+ if (typeof options.beforeDictionaryMutation === "function")
262
+ await options.beforeDictionaryMutation({ kind: completed.kind });
263
+ dictionaryMutationPrepared = true;
264
+ }
265
+ const result = await restoreStep(
266
+ client,
267
+ receipt.workspaceId,
268
+ completed,
269
+ current,
270
+ );
271
+ restored.push({
272
+ kind: completed.kind,
273
+ resourceId:
274
+ result?.id ?? completed.after?.id ?? completed.before?.id ?? null,
275
+ ...(result?.noOp === true ? { noOp: true } : {}),
276
+ ...(result?.recreatedId === undefined
277
+ ? {}
278
+ : { recreatedId: result.recreatedId }),
279
+ });
280
+ if (completed.dictionarySyncRequired === true) dictionaryMutations += 1;
281
+ }
282
+ return {
283
+ planHash: receipt.planHash,
284
+ receiptHash: receipt.receiptHash,
285
+ restored,
286
+ dictionaryMutations,
287
+ };
288
+ }
289
+
290
+ function caseAuthorities(operations) {
291
+ const seen = new Set();
292
+ return operations.map((operation, index) => {
293
+ const caseId =
294
+ typeof operation?.caseId === "string" ? operation.caseId.trim() : "";
295
+ if (!caseId)
296
+ fail("CASE_ID_REQUIRED", "each operation requires a nonempty caseId", {
297
+ index,
298
+ });
299
+ if (seen.has(caseId))
300
+ fail(
301
+ "DUPLICATE_CASE_AUTHORITY",
302
+ "one caseId cannot authorize multiple operations",
303
+ { caseId, index },
304
+ );
305
+ seen.add(caseId);
306
+ return {
307
+ caseId,
308
+ kind: operation?.kind,
309
+ target: caseAuthorityTarget(operation),
310
+ };
311
+ });
312
+ }
313
+
314
+ function caseAuthorityTarget(operation) {
315
+ const kind = requireKind(operation?.kind);
316
+ if (!kind.authorityTarget)
317
+ fail(
318
+ "UNSUPPORTED_INTERVENTION",
319
+ `unsupported intervention: ${operation?.kind}`,
320
+ );
321
+ return kind.authorityTarget(operation);
322
+ }
323
+
324
+ function coalesceOperations(operations) {
325
+ const result = [];
326
+ const coalescers = new Map();
327
+ for (const operation of operations) {
328
+ const kind = REGISTRY.get(operation?.kind);
329
+ let coalescer = coalescers.get(operation?.kind);
330
+ if (kind && !coalescer) {
331
+ coalescer = kind.createCoalescer?.();
332
+ coalescers.set(operation?.kind, coalescer);
333
+ }
334
+ if (coalescer && coalescer.add(operation, result)) continue;
335
+ const caseId = operation?.caseId?.trim() ?? "";
336
+ result.push({
337
+ ...structuredClone(operation),
338
+ caseId,
339
+ caseIds: [caseId],
340
+ });
341
+ }
342
+ for (const operation of result)
343
+ if (["dataset", "knowledge"].includes(operation.kind))
344
+ delete operation.desiredKey;
345
+ return result;
346
+ }
347
+
348
+ function matchesBefore(step, current) {
349
+ if (step.before === null) return current === null;
350
+ return (
351
+ requireKind(step.kind).matchesBefore?.(step, current) ??
352
+ statesEqual(current, step.before)
353
+ );
354
+ }
355
+
356
+ async function reportProgress(options, progressReceipt, durableReceipt) {
357
+ if (typeof options?.onProgress !== "function") return progressReceipt;
358
+ try {
359
+ await options.onProgress(progressReceipt);
360
+ return progressReceipt;
361
+ } catch (error) {
362
+ throw attachReceipt(error, durableReceipt);
363
+ }
364
+ }
365
+
366
+ function attachReceipt(error, receipt) {
367
+ const result =
368
+ error && typeof error === "object"
369
+ ? error
370
+ : new DatarcError("apply progress failed", "APPLY_FAILED");
371
+ result.receipt = receipt;
372
+ if (!result.details || typeof result.details !== "object")
373
+ result.details = {};
374
+ result.details.partialReceipt = receipt;
375
+ return result;
376
+ }
377
+
378
+ function pendingStep(step, stepIndex) {
379
+ const possibleAfter =
380
+ requireKind(step.kind).possibleAfter?.(step) ?? [step.before, step.after];
381
+ return bindReceiptStep(
382
+ {
383
+ ...structuredClone(step),
384
+ state: "uncertain",
385
+ possibleAfter: uniqueStates(possibleAfter),
386
+ identityResolved: step.before !== null || hasResolvedItemEndpoint(step),
387
+ },
388
+ step,
389
+ stepIndex,
390
+ );
391
+ }
392
+
393
+ function bindReceiptStep(runtimeStep, planStep, planStepIndex) {
394
+ return {
395
+ ...structuredClone(runtimeStep),
396
+ planStepIndex,
397
+ planStepHash: hashValue(planStep),
398
+ };
399
+ }
400
+
401
+ async function applyStep(client, workspaceId, step) {
402
+ const kind = requireKind(step.kind);
403
+ if (kind.applyStep) {
404
+ const applied = await kind.applyStep(client, workspaceId, step, {
405
+ partialStep,
406
+ });
407
+ if (applied !== undefined) return applied;
408
+ }
409
+ let response;
410
+ try {
411
+ response = await kind.writeDesired(client, step);
412
+ } catch (error) {
413
+ error.partialStep = partialStep(step, undefined, [step.before, step.after]);
414
+ throw error;
415
+ }
416
+ let completed = resolveCompletedStep(step, response);
417
+ let current;
418
+ try {
419
+ current = await kind.readState(client, workspaceId, completed);
420
+ completed = resolveCompletedStep(completed, current);
421
+ assertState(current, step.after, "WRITE_VERIFICATION_FAILED", step);
422
+ } catch (error) {
423
+ error.partialStep = partialStep(completed, current, [completed.after]);
424
+ throw error;
425
+ }
426
+ return { ...completed, after: current };
427
+ }
428
+
429
+ async function restoreStep(client, workspaceId, step, currentState) {
430
+ const kind = requireKind(step.kind);
431
+ if (step.before === null) {
432
+ assertItemEndpoint(workspaceId, step);
433
+ await client.request("DELETE", step.endpoint);
434
+ const current = await readCreatedStateFromCollection(
435
+ client,
436
+ workspaceId,
437
+ step,
438
+ );
439
+ assertState(current, null, "ROLLBACK_VERIFICATION_FAILED", step);
440
+ return { id: step.after?.id };
441
+ }
442
+ if (kind.restoreStep)
443
+ return kind.restoreStep(client, workspaceId, step, currentState, {
444
+ partialStep,
445
+ });
446
+ await kind.writeBefore(client, step);
447
+ const current = await kind.readState(client, workspaceId, step);
448
+ assertState(current, step.before, "ROLLBACK_VERIFICATION_FAILED", step);
449
+ return { id: current?.id };
450
+ }
451
+
452
+ function readStepState(client, workspaceId, step) {
453
+ return requireKind(step.kind).readState(client, workspaceId, step);
454
+ }
455
+
456
+ function readCreatedStateFromCollection(client, workspaceId, step) {
457
+ const kind = requireKind(step.kind);
458
+ return kind.readCreatedState
459
+ ? kind.readCreatedState(client, workspaceId, step)
460
+ : kind.readState(client, workspaceId, step);
461
+ }
462
+
463
+ async function resolvePendingCreation(client, workspaceId, step) {
464
+ const kind = requireKind(step.kind);
465
+ if (!kind.exactCreatedCandidates)
466
+ fail(
467
+ "ROLLBACK_IDENTITY_UNRESOLVED",
468
+ "created resource has no resolvable semantic identity",
469
+ { kind: step.kind },
470
+ );
471
+ const candidates = await kind.exactCreatedCandidates(
472
+ client,
473
+ workspaceId,
474
+ step,
475
+ );
476
+ if (candidates.length === 0) return { absent: true };
477
+ if (candidates.length > 1)
478
+ fail(
479
+ "ROLLBACK_IDENTITY_AMBIGUOUS",
480
+ "multiple resources match the pending semantic identity",
481
+ { kind: step.kind },
482
+ );
483
+ const current = candidates[0];
484
+ assertPossibleState(current, step.possibleAfter, "ROLLBACK_DRIFT", step);
485
+ const collection = collectionForKind(workspaceId, step.kind);
486
+ const id = current.id;
487
+ if (collection === null || id === undefined)
488
+ fail(
489
+ "ROLLBACK_IDENTITY_UNRESOLVED",
490
+ "created resource identity is unresolved; refusing to delete a collection",
491
+ { kind: step.kind, endpoint: step.endpoint },
492
+ );
493
+ return {
494
+ absent: false,
495
+ current,
496
+ step: {
497
+ ...structuredClone(step),
498
+ endpoint: `${collection}${id}/`,
499
+ after: { ...structuredClone(step.after), id },
500
+ identityResolved: true,
501
+ },
502
+ };
503
+ }
504
+
505
+ function partialStep(step, current, possibleAfter) {
506
+ const knownStates = current === undefined ? possibleAfter : [current];
507
+ return {
508
+ ...step,
509
+ after: current ?? step.after,
510
+ state: current === undefined ? "uncertain" : "verified",
511
+ possibleAfter: uniqueStates(knownStates),
512
+ identityResolved: step.before !== null || hasResolvedItemEndpoint(step),
513
+ };
514
+ }
515
+
516
+ function assertItemEndpoint(workspaceId, step) {
517
+ if (hasResolvedItemEndpoint(step, workspaceId)) return;
518
+ fail(
519
+ "ROLLBACK_IDENTITY_UNRESOLVED",
520
+ "created resource identity is unresolved; refusing to delete a collection",
521
+ { kind: step.kind, endpoint: step.endpoint },
522
+ );
523
+ }
524
+
525
+ function hasResolvedItemEndpoint(step, workspaceId) {
526
+ const id = step.after?.id;
527
+ if (id === undefined) return false;
528
+ if (workspaceId === undefined) return step.endpoint.endsWith(`/${id}/`);
529
+ const collection = collectionForKind(workspaceId, step.kind);
530
+ return collection !== null && step.endpoint === `${collection}${id}/`;
531
+ }
532
+
533
+ function collectionForKind(workspaceId, kind) {
534
+ return requireKind(kind).collection?.(workspaceId) ?? null;
535
+ }
536
+
537
+ function assertUniqueMutationTargets(steps) {
538
+ const seen = new Set();
539
+ for (const step of steps) {
540
+ const key = mutationTargetKey(step);
541
+ if (seen.has(key))
542
+ fail(
543
+ "DUPLICATE_MUTATION_TARGET",
544
+ "a plan cannot mutate the same semantic target more than once",
545
+ { kind: step.kind },
546
+ );
547
+ seen.add(key);
548
+ }
549
+ }
550
+
551
+ function mutationTargetKey(step) {
552
+ return (
553
+ requireKind(step.kind).targetKey?.(step) ??
554
+ `${step.kind}:${step.endpoint}`
555
+ );
556
+ }
557
+
558
+ function validatePlanMutationStructure(plan) {
559
+ if (
560
+ !isRecord(plan) ||
561
+ plan.version !== PLAN_VERSION ||
562
+ !Number.isSafeInteger(plan.workspaceId) ||
563
+ plan.workspaceId <= 0 ||
564
+ !Array.isArray(plan.steps) ||
565
+ !Array.isArray(plan.summaries) ||
566
+ !Array.isArray(plan.warnings) ||
567
+ !Array.isArray(plan.impact)
568
+ )
569
+ fail("INVALID_PLAN_STRUCTURE", "plan root structure is invalid");
570
+ const authorities = validatePlanAuthorities(plan.authorities);
571
+ assertUniqueMutationTargets(plan.steps);
572
+ const usedCaseIds = new Set();
573
+ const plannedCaseIds = new Set();
574
+ for (const step of plan.steps) {
575
+ if (!step || typeof step !== "object" || Array.isArray(step))
576
+ fail("INVALID_PLAN_STRUCTURE", "each plan step must be an object");
577
+ const validator = requireKind(step.kind).validateStep;
578
+ if (!validator)
579
+ fail(
580
+ "UNSUPPORTED_INTERVENTION",
581
+ "plan contains an unsupported intervention step",
582
+ );
583
+ validator(step, plan, authorities, plannedCaseIds, usedCaseIds);
584
+ }
585
+ validatePlanSummaries(plan.summaries, authorities, plannedCaseIds);
586
+ }
587
+
588
+ function validatePlanAuthorities(authorities) {
589
+ if (!Array.isArray(authorities))
590
+ fail("INVALID_PLAN_STRUCTURE", "plan authorities must be an array");
591
+ const seen = new Map();
592
+ for (const authority of authorities) {
593
+ const caseId = authority?.caseId;
594
+ if (
595
+ !isRecord(authority) ||
596
+ canonicalJson(Object.keys(authority).sort()) !==
597
+ canonicalJson(["caseId", "kind", "target"]) ||
598
+ typeof caseId !== "string" ||
599
+ !caseId ||
600
+ caseId !== caseId.trim() ||
601
+ typeof authority.kind !== "string" ||
602
+ !authority.kind ||
603
+ !ALL_PLAN_KINDS.has(authority.kind) ||
604
+ seen.has(caseId)
605
+ )
606
+ fail("INVALID_PLAN_STRUCTURE", "plan case authorities are invalid");
607
+ validateCaseAuthorityTarget(authority.kind, authority.target);
608
+ seen.set(caseId, authority);
609
+ }
610
+ return seen;
611
+ }
612
+
613
+ function validateCaseAuthorityTarget(kind, target) {
614
+ if (!isRecord(target))
615
+ fail("INVALID_PLAN_STRUCTURE", "plan authority target is invalid");
616
+ const validator = requireKind(kind).validateAuthorityTarget;
617
+ if (!validator)
618
+ fail("INVALID_PLAN_STRUCTURE", "plan authority kind is invalid");
619
+ validator(target);
620
+ }
621
+
622
+ function validatePlanSummaries(summaries, authorities, plannedCaseIds) {
623
+ const summarized = new Set();
624
+ for (const summary of summaries) {
625
+ if (
626
+ !isRecord(summary) ||
627
+ !ALL_PLAN_KINDS.has(summary.kind) ||
628
+ !new Set(["planned", "noop"]).has(summary.status)
629
+ )
630
+ fail("INVALID_PLAN_STRUCTURE", "plan summary is invalid");
631
+ const caseIds = validateMutationCaseIds(
632
+ summary.caseIds,
633
+ "INVALID_PLAN_STRUCTURE",
634
+ );
635
+ const expectedAuthorityTargets = caseIds.map((caseId) => ({
636
+ caseId,
637
+ target: structuredClone(authorities.get(caseId)?.target),
638
+ }));
639
+ const displayField = requireKind(summary.kind).summaryField;
640
+ if (
641
+ canonicalJson(Object.keys(summary).sort()) !==
642
+ canonicalJson(
643
+ [
644
+ "authorityTargets",
645
+ "caseIds",
646
+ "kind",
647
+ "status",
648
+ ...displayField,
649
+ ].sort(),
650
+ ) ||
651
+ !Array.isArray(summary.authorityTargets) ||
652
+ canonicalJson(summary.authorityTargets) !==
653
+ canonicalJson(expectedAuthorityTargets) ||
654
+ !requireKind(summary.kind).summaryMatches(
655
+ summary,
656
+ expectedAuthorityTargets,
657
+ )
658
+ )
659
+ fail(
660
+ "INVALID_PLAN_STRUCTURE",
661
+ "plan summary targets must match their case authorities",
662
+ );
663
+ for (const caseId of caseIds) {
664
+ if (
665
+ summarized.has(caseId) ||
666
+ authorities.get(caseId)?.kind !== summary.kind ||
667
+ (summary.status === "planned") !== plannedCaseIds.has(caseId)
668
+ )
669
+ fail(
670
+ "INVALID_PLAN_STRUCTURE",
671
+ "plan summaries do not bind every case authority exactly once",
672
+ );
673
+ summarized.add(caseId);
674
+ }
675
+ }
676
+ if (
677
+ summarized.size !== authorities.size ||
678
+ [...authorities.keys()].some((caseId) => !summarized.has(caseId))
679
+ )
680
+ fail(
681
+ "INVALID_PLAN_STRUCTURE",
682
+ "plan summaries must account for every case authority",
683
+ );
684
+ }
685
+
686
+ return {
687
+ preparePlan,
688
+ applyPlan,
689
+ rollbackReceipt,
690
+ validateApplyPlan,
691
+ kinds,
692
+ };
693
+ }