@arcticdata/dsh-datarc-skills 0.0.0-stage → 26.39.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 (135) hide show
  1. package/README.md +20 -2
  2. package/cordis.patch.yml +4 -0
  3. package/icon.svg +4 -0
  4. package/index.js +35 -0
  5. package/locale/en.json +6 -0
  6. package/locale/zh.json +6 -0
  7. package/package.json +37 -4
  8. package/skills/datarc-access-permissions/SKILL.md +30 -0
  9. package/skills/datarc-access-permissions/references/api.md +31 -0
  10. package/skills/datarc-access-permissions/references/write-order.md +16 -0
  11. package/skills/datarc-analysis-report/SKILL.md +125 -0
  12. package/skills/datarc-analysis-report/agents/openai.yaml +6 -0
  13. package/skills/datarc-analysis-report/references/analyst-frameworks.md +215 -0
  14. package/skills/datarc-analysis-report/references/api-contracts.md +478 -0
  15. package/skills/datarc-analysis-report/references/direct-card-fallback-design.md +66 -0
  16. package/skills/datarc-analysis-report/references/human-in-the-loop.md +142 -0
  17. package/skills/datarc-analysis-report/references/loop-personalization-policy.md +138 -0
  18. package/skills/datarc-analysis-report/references/manifest-example.json +779 -0
  19. package/skills/datarc-analysis-report/references/narrative-schema.md +160 -0
  20. package/skills/datarc-analysis-report/references/question-syntax.md +151 -0
  21. package/skills/datarc-analysis-report/scripts/run_analysis_report.py +2225 -0
  22. package/skills/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -0
  23. package/skills/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -0
  24. package/skills/datarc-data-search/SKILL.md +243 -0
  25. package/skills/datarc-data-search/scripts/calculate.py +116 -0
  26. package/skills/datarc-data-search/scripts/data-search.mjs +628 -0
  27. package/skills/datarc-data-search/scripts/datarc-client.mjs +464 -0
  28. package/skills/datarc-data-search/scripts/search-result.mjs +211 -0
  29. package/skills/datarc-dataseek-batch-evaluation/SKILL.md +59 -0
  30. package/skills/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -0
  31. package/skills/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -0
  32. package/skills/datarc-dataseek-batch-evaluation/scripts/datarc-client.mjs +464 -0
  33. package/skills/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -0
  34. package/skills/datarc-dataseek-search/SKILL.md +96 -0
  35. package/skills/datarc-dataseek-search/scripts/datarc-client.mjs +464 -0
  36. package/skills/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -0
  37. package/skills/datarc-dataseek-semantic-debugging/SKILL.md +44 -0
  38. package/skills/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -0
  39. package/skills/datarc-dataseek-semantic-debugging/evals/evals.json +165 -0
  40. package/skills/datarc-dataseek-semantic-debugging/references/dataset.md +77 -0
  41. package/skills/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -0
  42. package/skills/datarc-dataseek-semantic-debugging/references/interventions.md +64 -0
  43. package/skills/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -0
  44. package/skills/datarc-dataseek-semantic-debugging/references/rollback.md +11 -0
  45. package/skills/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -0
  46. package/skills/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -0
  47. package/skills/datarc-dataseek-testset-generation/SKILL.md +47 -0
  48. package/skills/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -0
  49. package/skills/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -0
  50. package/skills/datarc-datasource/SKILL.md +97 -0
  51. package/skills/datarc-oauth/SKILL.md +47 -0
  52. package/skills/datarc-oauth/scripts/auth.mjs +130 -0
  53. package/skills/datarc-oauth/scripts/credentials.mjs +237 -0
  54. package/skills/datarc-report-add-card/SKILL.md +90 -0
  55. package/skills/datarc-report-add-card/agents/openai.yaml +4 -0
  56. package/skills/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
  57. package/skills/datarc-report-add-card/scripts/report-card.mjs +439 -0
  58. package/skills/datarc-semantic-alias/SKILL.md +20 -0
  59. package/skills/datarc-semantic-alias/scripts/alias-plan.mjs +422 -0
  60. package/skills/datarc-semantic-alias/scripts/alias.mjs +11 -0
  61. package/skills/datarc-semantic-calibration/SKILL.md +20 -0
  62. package/skills/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -0
  63. package/skills/datarc-semantic-calibration/scripts/calibration.mjs +11 -0
  64. package/skills/datarc-semantic-core/SKILL.md +12 -0
  65. package/skills/datarc-semantic-core/scripts/artifact-journal.mjs +830 -0
  66. package/skills/datarc-semantic-core/scripts/canonical.mjs +48 -0
  67. package/skills/datarc-semantic-core/scripts/case-model.mjs +608 -0
  68. package/skills/datarc-semantic-core/scripts/cli.mjs +180 -0
  69. package/skills/datarc-semantic-core/scripts/datarc-client.mjs +180 -0
  70. package/skills/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -0
  71. package/skills/datarc-semantic-core/scripts/interventions.mjs +693 -0
  72. package/skills/datarc-semantic-core/scripts/live-resolution.mjs +305 -0
  73. package/skills/datarc-semantic-core/scripts/model-scope.mjs +49 -0
  74. package/skills/datarc-semantic-core/scripts/reproduction.mjs +330 -0
  75. package/skills/datarc-semantic-core/scripts/semantic-cli.mjs +740 -0
  76. package/skills/datarc-semantic-core/scripts/shared.mjs +312 -0
  77. package/skills/datarc-semantic-core/scripts/verification.mjs +1014 -0
  78. package/skills/datarc-semantic-dataset/SKILL.md +20 -0
  79. package/skills/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -0
  80. package/skills/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -0
  81. package/skills/datarc-semantic-dataset/scripts/dataset.mjs +11 -0
  82. package/skills/datarc-semantic-knowledge/SKILL.md +38 -0
  83. package/skills/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -0
  84. package/skills/datarc-semantic-knowledge/references/knowledge-generation.json +16 -0
  85. package/skills/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -0
  86. package/skills/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -0
  87. package/skills/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -0
  88. package/skills/datarc-semantic-prompt/SKILL.md +20 -0
  89. package/skills/datarc-semantic-prompt/scripts/prompt-plan.mjs +447 -0
  90. package/skills/datarc-semantic-prompt/scripts/prompt.mjs +15 -0
  91. package/skills/datarc-semantic-synonym/SKILL.md +20 -0
  92. package/skills/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -0
  93. package/skills/datarc-semantic-synonym/scripts/synonym.mjs +11 -0
  94. package/skills/datarc-viz-analysis-report/SKILL.md +108 -0
  95. package/skills/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -0
  96. package/skills/datarc-viz-analysis-report/assets/echarts.min.js +45 -0
  97. package/skills/datarc-viz-analysis-report/references/api-contracts.md +163 -0
  98. package/skills/datarc-viz-analysis-report/references/derivation-log.md +157 -0
  99. package/skills/datarc-viz-analysis-report/references/evidence-framework.md +76 -0
  100. package/skills/datarc-viz-analysis-report/references/html-template.md +92 -0
  101. package/skills/datarc-viz-analysis-report/references/provenance-format.md +56 -0
  102. package/skills/datarc-viz-analysis-report/references/question-syntax.md +151 -0
  103. package/skills/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -0
  104. package/skills/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -0
  105. package/skills/datarc-workspace-configuration/SKILL.md +59 -0
  106. package/skills/datarc-workspace-configuration/references/artifacts.md +75 -0
  107. package/skills/datarc-workspace-configuration/references/verification.md +20 -0
  108. package/skills/datarc-workspace-configuration/scripts/configuration.mjs +662 -0
  109. package/skills/datarc-workspace-context/SKILL.md +43 -0
  110. package/skills/datarc-workspace-context/agents/openai.yaml +4 -0
  111. package/skills/datarc-workspace-context/scripts/datarc-client.mjs +31 -0
  112. package/skills/datarc-workspace-context/scripts/query-display.mjs +114 -0
  113. package/skills/datarc-workspace-context/scripts/workspace-context.mjs +58 -0
  114. package/skills/datarc-workspace-custom-tables/SKILL.md +89 -0
  115. package/skills/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -0
  116. package/skills/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -0
  117. package/skills/datarc-workspace-keywords/SKILL.md +197 -0
  118. package/skills/datarc-workspace-keywords/agents/openai.yaml +4 -0
  119. package/skills/datarc-workspace-keywords/references/api-fields.md +79 -0
  120. package/skills/datarc-workspace-keywords/references/derived-measures.md +177 -0
  121. package/skills/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -0
  122. package/skills/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -0
  123. package/skills/datarc-workspace-membership/SKILL.md +29 -0
  124. package/skills/datarc-workspace-membership/references/api.md +19 -0
  125. package/skills/datarc-workspace-modeling/SKILL.md +209 -0
  126. package/skills/datarc-workspace-modeling/agents/openai.yaml +4 -0
  127. package/skills/datarc-workspace-modeling/references/join-preview.md +38 -0
  128. package/skills/datarc-workspace-modeling/references/model-plan.md +300 -0
  129. package/skills/datarc-workspace-modeling/references/model-tags.md +95 -0
  130. package/skills/datarc-workspace-modeling/references/modeling-contract.json +29 -0
  131. package/skills/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -0
  132. package/skills/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -0
  133. package/skills/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -0
  134. package/skills/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -0
  135. package/skills-index.json +194 -0
@@ -0,0 +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
+ }