@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,749 +1,749 @@
1
- import {
2
- canonicalJson,
3
- hashArtifactValue as hashValue,
4
- } from "../../datarc-semantic-core/scripts/canonical.mjs";
5
- import {
6
- authoritiesForCaseIds,
7
- canonicalDatasetId,
8
- claimStepCaseIds,
9
- coalesceNamedOperation,
10
- compact,
11
- fail,
12
- isRecord,
13
- listAllPages,
14
- listOf,
15
- matchesAuthority,
16
- normalizeText,
17
- normalizeServerWord,
18
- requiredText,
19
- statesEqual,
20
- validateMutationCaseIds,
21
- } from "../../datarc-semantic-core/scripts/shared.mjs";
22
- import {
23
- hashDatasetPreflightInput,
24
- runDatasetPreflight,
25
- } from "./dataset-preflight.mjs";
26
-
27
- const DEFAULT_DATASET_TIME_ZONE = "Asia/Shanghai";
28
- export async function planDataset(
29
- client,
30
- plan,
31
- operation,
32
- planningTime,
33
- options,
34
- ) {
35
- const name = normalizeDatasetName(operation.name);
36
- const content = validateDatasetOperation(operation, planningTime);
37
- const preflightInput = datasetPreflightInput(
38
- plan.workspaceId,
39
- operation,
40
- content,
41
- planningTime,
42
- );
43
- const { pairs, result: preflightResult } = await collectDatasetPreflight(
44
- client,
45
- preflightInput,
46
- options,
47
- );
48
- const collection = datasetCollection(plan.workspaceId);
49
- const rows = await listAllPages(
50
- client,
51
- collection,
52
- operation.id === undefined ? { q: name } : {},
53
- );
54
- const matches = rows.filter((row) =>
55
- operation.id === undefined
56
- ? normalizeText(row.name) === normalizeText(name)
57
- : String(row.id) === String(operation.id),
58
- );
59
- if (matches.length > 1)
60
- fail(
61
- "DATASET_IDENTITY_AMBIGUOUS",
62
- "multiple datasets match the requested exact identity",
63
- );
64
- const existing = matches[0];
65
- if (operation.id !== undefined && !existing)
66
- fail("DATASET_NOT_FOUND", "the selected dataset no longer exists");
67
- const before = existing ? semanticDataset(existing) : null;
68
- const after = compact({
69
- ...(existing ? { id: existing.id } : {}),
70
- name,
71
- content,
72
- question: structuredClone(pairs),
73
- tuids: structuredClone(operation.tuids),
74
- columns: structuredClone(operation.columns),
75
- metadata: structuredClone(operation.metadata),
76
- });
77
- recordDatasetPreflightWarning(plan);
78
- if (before !== null && statesEqual(before, after)) {
79
- plan.summaries.push({
80
- kind: operation.kind,
81
- status: "noop",
82
- name,
83
- caseIds: structuredClone(operation.caseIds),
84
- });
85
- return;
86
- }
87
- plan.steps.push({
88
- kind: operation.kind,
89
- caseIds: structuredClone(operation.caseIds),
90
- endpoint: existing ? `${collection}${existing.id}/` : collection,
91
- operation: existing ? "PUT" : "POST",
92
- before,
93
- after,
94
- preconditions: {
95
- datasetTime: structuredClone(planningTime),
96
- preflightInput: structuredClone(preflightInput),
97
- preflightResult: structuredClone(preflightResult),
98
- pairsHash: hashValue(pairs),
99
- },
100
- dictionarySyncRequired: true,
101
- });
102
- plan.summaries.push({
103
- kind: operation.kind,
104
- status: "planned",
105
- name,
106
- caseIds: structuredClone(operation.caseIds),
107
- });
108
- }
109
-
110
- export async function readDatasetState(client, workspaceId, step) {
111
- const name = step.after?.name ?? step.before?.name;
112
- const id = step.after?.id ?? step.before?.id;
113
- const rows = await listAllPages(
114
- client,
115
- datasetCollection(workspaceId),
116
- id === undefined ? { q: name } : {},
117
- );
118
- const matches = rows.filter((item) =>
119
- id === undefined
120
- ? normalizeText(item.name) === normalizeText(name)
121
- : String(item.id) === String(id),
122
- );
123
- if (matches.length > 1)
124
- fail(
125
- "DATASET_IDENTITY_AMBIGUOUS",
126
- "multiple datasets match the planned exact identity",
127
- );
128
- return matches[0] ? semanticDataset(matches[0]) : null;
129
- }
130
-
131
- export function semanticDataset(value) {
132
- return compact({
133
- id: value.id,
134
- name: value.name,
135
- content: value.content,
136
- question: structuredClone(value.question),
137
- tuids: structuredClone(value.tuids),
138
- columns: structuredClone(value.columns),
139
- metadata: structuredClone(value.metadata),
140
- });
141
- }
142
-
143
- export function datasetBody(value) {
144
- return compact({
145
- name: value.name,
146
- content: value.content,
147
- question: structuredClone(value.question),
148
- tuids: structuredClone(value.tuids),
149
- columns: structuredClone(value.columns),
150
- metadata: structuredClone(value.metadata),
151
- });
152
- }
153
-
154
- export function validateDatasetOperation(operation, planningTime) {
155
- const allowed = new Set([
156
- "caseId",
157
- "caseIds",
158
- "columns",
159
- "content",
160
- "id",
161
- "kind",
162
- "metadata",
163
- "modelingEvidence",
164
- "name",
165
- "tuids",
166
- ]);
167
- if (
168
- !isRecord(operation) ||
169
- Object.keys(operation).some((field) => !allowed.has(field))
170
- )
171
- fail(
172
- "INVALID_DATASET_INPUT",
173
- "dataset input contains unsupported caller-provided authority",
174
- );
175
- const content = requiredText(operation.content, "content");
176
- if ([...content].length > 256)
177
- fail(
178
- "INVALID_DATASET_INPUT",
179
- "dataset content must contain at most 256 characters",
180
- );
181
- if (
182
- !Array.isArray(operation.tuids) ||
183
- operation.tuids.length !== 1 ||
184
- typeof operation.tuids[0] !== "string" ||
185
- !operation.tuids[0].trim() ||
186
- operation.tuids[0] !== operation.tuids[0].trim() ||
187
- operation.tuids[0].includes("/") ||
188
- !Array.isArray(operation.columns) ||
189
- operation.columns.length !== 1 ||
190
- !/^d[1-9]\d*$/u.test(operation.columns[0]) ||
191
- !isRecord(operation.modelingEvidence)
192
- )
193
- fail(
194
- "INVALID_DATASET_INPUT",
195
- "dataset requires one model, one identity prop, and structured modeling evidence",
196
- );
197
- if (
198
- !isRecord(operation.metadata) ||
199
- operation.metadata.timePolicy !== "internal_fixed" ||
200
- operation.metadata.anchoredOn !== planningTime.executionDate
201
- )
202
- fail(
203
- "UNSAFE_DATASET_TIME_POLICY",
204
- "dataset metadata must use internal_fixed and the current execution date",
205
- );
206
- if (operation.id !== undefined) canonicalDatasetId(operation.id);
207
- return content;
208
- }
209
-
210
- export function datasetPreflightInput(
211
- workspaceId,
212
- operation,
213
- content,
214
- planningTime,
215
- ) {
216
- const body = {
217
- version: 1,
218
- workspaceId,
219
- caseId: operation.caseId,
220
- executionDate: planningTime.executionDate,
221
- timeZone: planningTime.timeZone,
222
- modelUid: operation.tuids[0],
223
- questionText: content,
224
- modelingEvidence: structuredClone(operation.modelingEvidence),
225
- };
226
- return { ...body, inputHash: hashDatasetPreflightInput(body) };
227
- }
228
-
229
- export async function collectDatasetPreflight(client, input, options) {
230
- let pairs;
231
- const result = await runDatasetPreflight(client, input, {
232
- ...options,
233
- onRuntimeAuthority(runtimePairs) {
234
- pairs = normalizeDatasetQuestion(runtimePairs);
235
- },
236
- });
237
- if (!Array.isArray(pairs) || pairs.length === 0)
238
- fail(
239
- "INVALID_DATASET_PREFLIGHT",
240
- "dataset preflight returned no runtime authority",
241
- );
242
- return { pairs, result };
243
- }
244
-
245
- export function recordDatasetPreflightWarning(plan) {
246
- if (
247
- plan.warnings.some((warning) =>
248
- warning.startsWith("Dataset planning preflight"),
249
- )
250
- )
251
- return;
252
- plan.warnings.push(
253
- "Dataset planning preflight creates taskType8 AsyncTask records as an unavoidable read-computation side effect; its permission proof applies only to the current administrator.",
254
- );
255
- }
256
-
257
- export function datasetPlanningContext(
258
- now,
259
- timeZone = DEFAULT_DATASET_TIME_ZONE,
260
- ) {
261
- if (typeof timeZone !== "string" || !timeZone.trim())
262
- fail("INVALID_TIME_ZONE", "Dataset planning requires a valid time zone");
263
- let formatter;
264
- try {
265
- formatter = new Intl.DateTimeFormat("en-US", {
266
- timeZone: timeZone.trim(),
267
- year: "numeric",
268
- month: "2-digit",
269
- day: "2-digit",
270
- });
271
- } catch {
272
- fail("INVALID_TIME_ZONE", "Dataset planning requires a valid time zone");
273
- }
274
- const value = typeof now === "function" ? now() : new Date();
275
- const date = value instanceof Date ? value : new Date(value);
276
- if (!Number.isFinite(date.getTime()))
277
- fail("INVALID_CLOCK", "planning clock must return a valid date");
278
- const parts = Object.fromEntries(
279
- formatter
280
- .formatToParts(date)
281
- .filter(({ type }) => ["year", "month", "day"].includes(type))
282
- .map(({ type, value: part }) => [type, part]),
283
- );
284
- return {
285
- time: {
286
- executionDate: `${parts.year}-${parts.month}-${parts.day}`,
287
- timeZone: formatter.resolvedOptions().timeZone,
288
- },
289
- now: () => new Date(date.getTime()),
290
- };
291
- }
292
-
293
- export function normalizeDatasetName(value) {
294
- if (typeof value !== "string")
295
- fail("INVALID_INPUT", "dataset name must be a nonempty string");
296
- const name = value
297
- .toLowerCase()
298
- .replace(
299
- /^[\p{White_Space}\u001c-\u001f]+|[\p{White_Space}\u001c-\u001f]+$/gu,
300
- "",
301
- );
302
- if (!name) fail("INVALID_INPUT", "dataset name must be a nonempty string");
303
- return name;
304
- }
305
-
306
- export function normalizeDatasetQuestion(pairs) {
307
- return structuredClone(pairs).map((pair) => ({
308
- ...pair,
309
- word: pair.word.toLowerCase(),
310
- }));
311
- }
312
-
313
- export async function revalidateDatasetStep(
314
- client,
315
- workspaceId,
316
- step,
317
- options,
318
- ) {
319
- const expected = step.preconditions;
320
- const { pairs, result } = await collectDatasetPreflight(
321
- client,
322
- structuredClone(expected.preflightInput),
323
- options,
324
- );
325
- if (
326
- canonicalJson(result) !== canonicalJson(expected.preflightResult) ||
327
- hashValue(pairs) !== expected.pairsHash ||
328
- canonicalJson(pairs) !== canonicalJson(step.after.question)
329
- )
330
- fail(
331
- "DATASET_PREFLIGHT_DRIFT",
332
- "dataset runtime authority changed after planning",
333
- );
334
- return readDatasetState(client, workspaceId, step);
335
- }
336
-
337
- export function datasetAuthorityTargetFromStep(after, preconditions) {
338
- const operation = {
339
- columns: structuredClone(after.columns),
340
- content: after.content,
341
- metadata: structuredClone(after.metadata),
342
- modelingEvidence: structuredClone(
343
- preconditions.preflightInput.modelingEvidence,
344
- ),
345
- name: after.name,
346
- tuids: structuredClone(after.tuids),
347
- ...(after.id === undefined ? {} : { id: after.id }),
348
- };
349
- return {
350
- ...(after.id === undefined ? {} : { id: after.id }),
351
- name: after.name,
352
- desiredHash: datasetAuthorityHash(operation),
353
- };
354
- }
355
-
356
- export function validateDatasetStepStructure(step, workspaceId) {
357
- const allowedStepFields = new Set([
358
- "after",
359
- "before",
360
- "caseIds",
361
- "dictionarySyncRequired",
362
- "endpoint",
363
- "kind",
364
- "operation",
365
- "preconditions",
366
- ]);
367
- if (
368
- Object.keys(step).some((field) => !allowedStepFields.has(field)) ||
369
- [...allowedStepFields].some((field) => !Object.hasOwn(step, field)) ||
370
- step.dictionarySyncRequired !== true
371
- )
372
- fail("INVALID_DATASET_PLAN", "dataset step fields are invalid");
373
-
374
- const collection = datasetCollection(workspaceId);
375
- const after = validateDatasetSnapshot(step.after, "after", true);
376
- let before = null;
377
- if (step.operation === "POST") {
378
- if (
379
- step.before !== null ||
380
- after.id !== undefined ||
381
- step.endpoint !== collection
382
- )
383
- fail(
384
- "INVALID_DATASET_PLAN",
385
- "dataset POST must create from the collection",
386
- );
387
- } else if (step.operation === "PUT") {
388
- before = validateDatasetSnapshot(step.before, "before", false);
389
- const beforeId = canonicalDatasetId(before.id);
390
- const afterId = canonicalDatasetId(after.id);
391
- if (
392
- beforeId !== afterId ||
393
- step.endpoint !== `${collection}${beforeId}/` ||
394
- statesEqual(before, after)
395
- )
396
- fail(
397
- "INVALID_DATASET_PLAN",
398
- "dataset PUT identity or desired state is invalid",
399
- );
400
- } else fail("INVALID_DATASET_PLAN", "dataset operation is invalid");
401
-
402
- const caseIds = validateMutationCaseIds(step.caseIds, "INVALID_DATASET_PLAN");
403
- const preconditions = step.preconditions;
404
- if (
405
- !isRecord(preconditions) ||
406
- canonicalJson(Object.keys(preconditions).sort()) !==
407
- canonicalJson([
408
- "datasetTime",
409
- "pairsHash",
410
- "preflightInput",
411
- "preflightResult",
412
- ])
413
- )
414
- fail(
415
- "INVALID_DATASET_PREFLIGHT_EVIDENCE",
416
- "dataset preconditions are invalid",
417
- );
418
- validateDatasetPreflightEvidence(preconditions, after, workspaceId, caseIds);
419
- return { after, before, caseIds };
420
- }
421
-
422
- export function validateDatasetSnapshot(value, label, requireContent) {
423
- if (!isRecord(value))
424
- fail("INVALID_DATASET_PLAN", `dataset ${label} must be an object`);
425
- const allowed = new Set([
426
- "columns",
427
- "content",
428
- "id",
429
- "metadata",
430
- "name",
431
- "question",
432
- "tuids",
433
- ]);
434
- const required = ["columns", "metadata", "name", "question", "tuids"];
435
- if (requireContent) required.push("content");
436
- if (
437
- Object.keys(value).some((field) => !allowed.has(field)) ||
438
- required.some((field) => !Object.hasOwn(value, field))
439
- )
440
- fail("INVALID_DATASET_PLAN", `dataset ${label} fields are invalid`);
441
- if (value.id !== undefined) canonicalDatasetId(value.id);
442
- if (normalizeDatasetName(value.name) !== value.name)
443
- fail(
444
- "INVALID_DATASET_PLAN",
445
- `dataset ${label} name must match the server-normalized state`,
446
- );
447
- if (value.content !== undefined) {
448
- const content = requiredText(value.content, `${label}.content`);
449
- if (content !== value.content || [...content].length > 256)
450
- fail("INVALID_DATASET_PLAN", `dataset ${label} content is invalid`);
451
- }
452
- if (
453
- !Array.isArray(value.question) ||
454
- !Array.isArray(value.tuids) ||
455
- !Array.isArray(value.columns) ||
456
- !isRecord(value.metadata)
457
- )
458
- fail("INVALID_DATASET_PLAN", `dataset ${label} snapshot is invalid`);
459
- if (
460
- value.question.some(
461
- (pair) =>
462
- !isRecord(pair) ||
463
- typeof pair.word !== "string" ||
464
- pair.word.toLowerCase() !== pair.word,
465
- )
466
- )
467
- fail(
468
- "INVALID_DATASET_PLAN",
469
- `dataset ${label} question must match the server-normalized state`,
470
- );
471
- if (label === "after") {
472
- if (
473
- value.question.length === 0 ||
474
- value.question.length > 100 ||
475
- value.question.some(
476
- (pair) =>
477
- !isRecord(pair) ||
478
- canonicalJson(Object.keys(pair).sort()) !==
479
- canonicalJson(["prop", "word"]) ||
480
- typeof pair.word !== "string" ||
481
- !pair.word.trim() ||
482
- pair.word !== pair.word.trim() ||
483
- typeof pair.prop !== "string" ||
484
- !pair.prop.trim() ||
485
- pair.prop !== pair.prop.trim(),
486
- ) ||
487
- value.tuids.length !== 1 ||
488
- typeof value.tuids[0] !== "string" ||
489
- !value.tuids[0] ||
490
- value.tuids[0] !== value.tuids[0].trim() ||
491
- value.tuids[0].includes("/") ||
492
- value.columns.length !== 1 ||
493
- !/^d[1-9]\d*$/u.test(value.columns[0]) ||
494
- value.metadata.timePolicy !== "internal_fixed" ||
495
- !/^\d{4}-\d{2}-\d{2}$/u.test(value.metadata.anchoredOn)
496
- )
497
- fail("INVALID_DATASET_PLAN", "dataset after authority is invalid");
498
- }
499
- return value;
500
- }
501
-
502
- export function validateDatasetPreflightEvidence(
503
- preconditions,
504
- after,
505
- workspaceId,
506
- caseIds,
507
- ) {
508
- const datasetTime = preconditions.datasetTime;
509
- const input = preconditions.preflightInput;
510
- const result = preconditions.preflightResult;
511
- if (
512
- !isRecord(datasetTime) ||
513
- canonicalJson(Object.keys(datasetTime).sort()) !==
514
- canonicalJson(["executionDate", "timeZone"]) ||
515
- typeof datasetTime.timeZone !== "string" ||
516
- !datasetTime.timeZone ||
517
- !/^\d{4}-\d{2}-\d{2}$/u.test(datasetTime.executionDate) ||
518
- !isRecord(input) ||
519
- canonicalJson(Object.keys(input).sort()) !==
520
- canonicalJson([
521
- "caseId",
522
- "executionDate",
523
- "inputHash",
524
- "modelUid",
525
- "modelingEvidence",
526
- "questionText",
527
- "timeZone",
528
- "version",
529
- "workspaceId",
530
- ]) ||
531
- input.version !== 1 ||
532
- input.workspaceId !== workspaceId ||
533
- !caseIds.includes(input.caseId) ||
534
- input.executionDate !== datasetTime.executionDate ||
535
- input.timeZone !== datasetTime.timeZone ||
536
- input.modelUid !== after.tuids[0] ||
537
- input.questionText !== after.content ||
538
- !isRecord(input.modelingEvidence) ||
539
- input.inputHash !== hashDatasetPreflightInput(input) ||
540
- input.modelingEvidence.executionDate !== datasetTime.executionDate ||
541
- input.modelingEvidence.timeZone !== datasetTime.timeZone ||
542
- input.modelingEvidence.semantics?.customerIdentity?.dimensionProp !==
543
- after.columns[0] ||
544
- canonicalJson(input.modelingEvidence.topology?.modelUids) !==
545
- canonicalJson(after.tuids) ||
546
- after.metadata.anchoredOn !== datasetTime.executionDate
547
- )
548
- fail(
549
- "INVALID_DATASET_PREFLIGHT_EVIDENCE",
550
- "dataset preflight input is unbound",
551
- );
552
-
553
- const safeResultKeys = [
554
- "executionDate",
555
- "identityCount",
556
- "identityProp",
557
- "inputHash",
558
- "modelSnapshotHash",
559
- "modelUid",
560
- "permissionScope",
561
- "rowCount",
562
- "stable",
563
- "status",
564
- "timeZone",
565
- "unavoidableReadTaskSideEffect",
566
- "version",
567
- "workspaceId",
568
- ];
569
- if (
570
- !isRecord(result) ||
571
- canonicalJson(Object.keys(result).sort()) !==
572
- canonicalJson(safeResultKeys) ||
573
- result.version !== 1 ||
574
- result.status !== "ready" ||
575
- result.inputHash !== input.inputHash ||
576
- result.workspaceId !== workspaceId ||
577
- result.executionDate !== datasetTime.executionDate ||
578
- result.timeZone !== datasetTime.timeZone ||
579
- result.modelUid !== after.tuids[0] ||
580
- result.modelSnapshotHash !== input.modelingEvidence.modelSnapshotHash ||
581
- result.identityProp !== after.columns[0] ||
582
- !Number.isSafeInteger(result.rowCount) ||
583
- result.rowCount <= 0 ||
584
- result.rowCount >= 10_000 ||
585
- result.identityCount !== result.rowCount ||
586
- result.stable !== true ||
587
- result.permissionScope !== "current_admin_only" ||
588
- result.unavoidableReadTaskSideEffect !== true ||
589
- preconditions.pairsHash !== hashValue(after.question)
590
- )
591
- fail(
592
- "INVALID_DATASET_PREFLIGHT_EVIDENCE",
593
- "dataset preflight result is unbound",
594
- );
595
- }
596
-
597
- export function datasetCollection(workspaceId) {
598
- return `/api/v3/admin-projects/${workspaceId}/datasets/`;
599
- }
600
-
601
- export function datasetAuthorityHash(operation) {
602
- const desired = {
603
- columns: structuredClone(operation.columns),
604
- content: operation.content,
605
- kind: "dataset",
606
- metadata: structuredClone(operation.metadata),
607
- modelingEvidence: structuredClone(operation.modelingEvidence),
608
- name: operation.name,
609
- tuids: structuredClone(operation.tuids),
610
- ...(operation.id === undefined ? {} : { id: operation.id }),
611
- };
612
- return hashValue(desired);
613
- }
614
-
615
- function normalizeDatasetOperationAuthority(operation) {
616
- const name = normalizeDatasetName(operation.name);
617
- const normalized = { ...structuredClone(operation), name };
618
- if (operation.id !== undefined)
619
- normalized.id = canonicalDatasetId(operation.id);
620
- return normalized;
621
- }
622
-
623
- function datasetAuthorityTarget(operation) {
624
- const normalized = normalizeDatasetOperationAuthority(operation);
625
- return {
626
- ...(normalized.id === undefined ? {} : { id: normalized.id }),
627
- name: normalized.name,
628
- desiredHash: datasetAuthorityHash(normalized),
629
- };
630
- }
631
-
632
- function createDatasetCoalescer() {
633
- const groups = new Map();
634
- const names = new Map();
635
- return {
636
- add(operation, result) {
637
- const caseId = operation.caseId.trim();
638
- const normalized = normalizeDatasetOperationAuthority(operation);
639
- coalesceNamedOperation({
640
- caseId,
641
- operation: normalized,
642
- groups,
643
- names,
644
- result,
645
- conflictCode: "DATASET_CONFLICT",
646
- });
647
- return true;
648
- },
649
- };
650
- }
651
-
652
- function datasetPlan(client, plan, operation, options = {}) {
653
- return planDataset(client, plan, operation, options.planningContext.time, {
654
- ...options,
655
- now: options.planningContext.now,
656
- });
657
- }
658
-
659
- function datasetWriteDesired(client, step) {
660
- return client.request(step.operation, step.endpoint, {
661
- body: datasetBody(step.after),
662
- });
663
- }
664
-
665
- function datasetWriteBefore(client, step) {
666
- return client.request("PUT", step.endpoint, {
667
- body: datasetBody(step.before),
668
- });
669
- }
670
-
671
- function datasetRevalidate(client, workspaceId, step, ctx) {
672
- return revalidateDatasetStep(client, workspaceId, step, ctx.options);
673
- }
674
-
675
- async function datasetExactCreatedCandidates(client, workspaceId, step) {
676
- const name = step.after?.name;
677
- const rows = await listAllPages(client, datasetCollection(workspaceId), {
678
- q: name,
679
- });
680
- return rows
681
- .filter((row) => normalizeText(row.name) === normalizeText(name))
682
- .map(semanticDataset);
683
- }
684
-
685
- function validateDatasetAuthorityTarget(target) {
686
- const allowed = new Set(["desiredHash", "id", "name"]);
687
- if (
688
- Object.keys(target).some((field) => !allowed.has(field)) ||
689
- !Object.hasOwn(target, "desiredHash") ||
690
- !Object.hasOwn(target, "name") ||
691
- (target.id !== undefined &&
692
- canonicalDatasetId(target.id) !== target.id) ||
693
- normalizeDatasetName(target.name) !== target.name ||
694
- !/^[0-9a-f]{64}$/u.test(target.desiredHash)
695
- )
696
- fail("INVALID_PLAN_STRUCTURE", "Dataset authority target is invalid");
697
- }
698
-
699
- function validateDatasetPlanStep(step, plan, authorities, plannedCaseIds, usedCaseIds) {
700
- const { after, caseIds } = validateDatasetStepStructure(
701
- step,
702
- plan.workspaceId,
703
- );
704
- for (const caseId of caseIds)
705
- if (
706
- !matchesAuthority(
707
- authorities.get(caseId),
708
- "dataset",
709
- (target) =>
710
- canonicalJson(target) ===
711
- canonicalJson(
712
- datasetAuthorityTargetFromStep(after, step.preconditions),
713
- ),
714
- )
715
- )
716
- fail(
717
- "INVALID_DATASET_PLAN",
718
- "dataset step caseIds must match exact Dataset authorities",
719
- );
720
- claimStepCaseIds(usedCaseIds, caseIds);
721
- for (const caseId of caseIds) plannedCaseIds.add(caseId);
722
- }
723
-
724
- function datasetSummaryMatches(summary, authorityTargets) {
725
- const targets = authorityTargets.map(({ target }) => target);
726
- return targets.every((target) => summary.name === target.name);
727
- }
728
-
729
- export const datasetKind = {
730
- name: "dataset",
731
- planable: true,
732
- plan: datasetPlan,
733
- planningContext: (options = {}) =>
734
- datasetPlanningContext(options.now, options.timeZone),
735
- authorityTarget: datasetAuthorityTarget,
736
- createCoalescer: createDatasetCoalescer,
737
- writeDesired: datasetWriteDesired,
738
- writeBefore: datasetWriteBefore,
739
- readState: readDatasetState,
740
- preApplyRead: datasetRevalidate,
741
- exactCreatedCandidates: datasetExactCreatedCandidates,
742
- collection: datasetCollection,
743
- targetKey: (step) =>
744
- `dataset:${step.after?.id ?? normalizeText(step.after?.name)}`,
745
- validateAuthorityTarget: validateDatasetAuthorityTarget,
746
- validateStep: validateDatasetPlanStep,
747
- summaryField: ["name"],
748
- summaryMatches: datasetSummaryMatches,
749
- };
1
+ import {
2
+ canonicalJson,
3
+ hashArtifactValue as hashValue,
4
+ } from "../../datarc-semantic-core/scripts/canonical.mjs";
5
+ import {
6
+ authoritiesForCaseIds,
7
+ canonicalDatasetId,
8
+ claimStepCaseIds,
9
+ coalesceNamedOperation,
10
+ compact,
11
+ fail,
12
+ isRecord,
13
+ listAllPages,
14
+ listOf,
15
+ matchesAuthority,
16
+ normalizeText,
17
+ normalizeServerWord,
18
+ requiredText,
19
+ statesEqual,
20
+ validateMutationCaseIds,
21
+ } from "../../datarc-semantic-core/scripts/shared.mjs";
22
+ import {
23
+ hashDatasetPreflightInput,
24
+ runDatasetPreflight,
25
+ } from "./dataset-preflight.mjs";
26
+
27
+ const DEFAULT_DATASET_TIME_ZONE = "Asia/Shanghai";
28
+ export async function planDataset(
29
+ client,
30
+ plan,
31
+ operation,
32
+ planningTime,
33
+ options,
34
+ ) {
35
+ const name = normalizeDatasetName(operation.name);
36
+ const content = validateDatasetOperation(operation, planningTime);
37
+ const preflightInput = datasetPreflightInput(
38
+ plan.workspaceId,
39
+ operation,
40
+ content,
41
+ planningTime,
42
+ );
43
+ const { pairs, result: preflightResult } = await collectDatasetPreflight(
44
+ client,
45
+ preflightInput,
46
+ options,
47
+ );
48
+ const collection = datasetCollection(plan.workspaceId);
49
+ const rows = await listAllPages(
50
+ client,
51
+ collection,
52
+ operation.id === undefined ? { q: name } : {},
53
+ );
54
+ const matches = rows.filter((row) =>
55
+ operation.id === undefined
56
+ ? normalizeText(row.name) === normalizeText(name)
57
+ : String(row.id) === String(operation.id),
58
+ );
59
+ if (matches.length > 1)
60
+ fail(
61
+ "DATASET_IDENTITY_AMBIGUOUS",
62
+ "multiple datasets match the requested exact identity",
63
+ );
64
+ const existing = matches[0];
65
+ if (operation.id !== undefined && !existing)
66
+ fail("DATASET_NOT_FOUND", "the selected dataset no longer exists");
67
+ const before = existing ? semanticDataset(existing) : null;
68
+ const after = compact({
69
+ ...(existing ? { id: existing.id } : {}),
70
+ name,
71
+ content,
72
+ question: structuredClone(pairs),
73
+ tuids: structuredClone(operation.tuids),
74
+ columns: structuredClone(operation.columns),
75
+ metadata: structuredClone(operation.metadata),
76
+ });
77
+ recordDatasetPreflightWarning(plan);
78
+ if (before !== null && statesEqual(before, after)) {
79
+ plan.summaries.push({
80
+ kind: operation.kind,
81
+ status: "noop",
82
+ name,
83
+ caseIds: structuredClone(operation.caseIds),
84
+ });
85
+ return;
86
+ }
87
+ plan.steps.push({
88
+ kind: operation.kind,
89
+ caseIds: structuredClone(operation.caseIds),
90
+ endpoint: existing ? `${collection}${existing.id}/` : collection,
91
+ operation: existing ? "PUT" : "POST",
92
+ before,
93
+ after,
94
+ preconditions: {
95
+ datasetTime: structuredClone(planningTime),
96
+ preflightInput: structuredClone(preflightInput),
97
+ preflightResult: structuredClone(preflightResult),
98
+ pairsHash: hashValue(pairs),
99
+ },
100
+ dictionarySyncRequired: true,
101
+ });
102
+ plan.summaries.push({
103
+ kind: operation.kind,
104
+ status: "planned",
105
+ name,
106
+ caseIds: structuredClone(operation.caseIds),
107
+ });
108
+ }
109
+
110
+ export async function readDatasetState(client, workspaceId, step) {
111
+ const name = step.after?.name ?? step.before?.name;
112
+ const id = step.after?.id ?? step.before?.id;
113
+ const rows = await listAllPages(
114
+ client,
115
+ datasetCollection(workspaceId),
116
+ id === undefined ? { q: name } : {},
117
+ );
118
+ const matches = rows.filter((item) =>
119
+ id === undefined
120
+ ? normalizeText(item.name) === normalizeText(name)
121
+ : String(item.id) === String(id),
122
+ );
123
+ if (matches.length > 1)
124
+ fail(
125
+ "DATASET_IDENTITY_AMBIGUOUS",
126
+ "multiple datasets match the planned exact identity",
127
+ );
128
+ return matches[0] ? semanticDataset(matches[0]) : null;
129
+ }
130
+
131
+ export function semanticDataset(value) {
132
+ return compact({
133
+ id: value.id,
134
+ name: value.name,
135
+ content: value.content,
136
+ question: structuredClone(value.question),
137
+ tuids: structuredClone(value.tuids),
138
+ columns: structuredClone(value.columns),
139
+ metadata: structuredClone(value.metadata),
140
+ });
141
+ }
142
+
143
+ export function datasetBody(value) {
144
+ return compact({
145
+ name: value.name,
146
+ content: value.content,
147
+ question: structuredClone(value.question),
148
+ tuids: structuredClone(value.tuids),
149
+ columns: structuredClone(value.columns),
150
+ metadata: structuredClone(value.metadata),
151
+ });
152
+ }
153
+
154
+ export function validateDatasetOperation(operation, planningTime) {
155
+ const allowed = new Set([
156
+ "caseId",
157
+ "caseIds",
158
+ "columns",
159
+ "content",
160
+ "id",
161
+ "kind",
162
+ "metadata",
163
+ "modelingEvidence",
164
+ "name",
165
+ "tuids",
166
+ ]);
167
+ if (
168
+ !isRecord(operation) ||
169
+ Object.keys(operation).some((field) => !allowed.has(field))
170
+ )
171
+ fail(
172
+ "INVALID_DATASET_INPUT",
173
+ "dataset input contains unsupported caller-provided authority",
174
+ );
175
+ const content = requiredText(operation.content, "content");
176
+ if ([...content].length > 256)
177
+ fail(
178
+ "INVALID_DATASET_INPUT",
179
+ "dataset content must contain at most 256 characters",
180
+ );
181
+ if (
182
+ !Array.isArray(operation.tuids) ||
183
+ operation.tuids.length !== 1 ||
184
+ typeof operation.tuids[0] !== "string" ||
185
+ !operation.tuids[0].trim() ||
186
+ operation.tuids[0] !== operation.tuids[0].trim() ||
187
+ operation.tuids[0].includes("/") ||
188
+ !Array.isArray(operation.columns) ||
189
+ operation.columns.length !== 1 ||
190
+ !/^d[1-9]\d*$/u.test(operation.columns[0]) ||
191
+ !isRecord(operation.modelingEvidence)
192
+ )
193
+ fail(
194
+ "INVALID_DATASET_INPUT",
195
+ "dataset requires one model, one identity prop, and structured modeling evidence",
196
+ );
197
+ if (
198
+ !isRecord(operation.metadata) ||
199
+ operation.metadata.timePolicy !== "internal_fixed" ||
200
+ operation.metadata.anchoredOn !== planningTime.executionDate
201
+ )
202
+ fail(
203
+ "UNSAFE_DATASET_TIME_POLICY",
204
+ "dataset metadata must use internal_fixed and the current execution date",
205
+ );
206
+ if (operation.id !== undefined) canonicalDatasetId(operation.id);
207
+ return content;
208
+ }
209
+
210
+ export function datasetPreflightInput(
211
+ workspaceId,
212
+ operation,
213
+ content,
214
+ planningTime,
215
+ ) {
216
+ const body = {
217
+ version: 1,
218
+ workspaceId,
219
+ caseId: operation.caseId,
220
+ executionDate: planningTime.executionDate,
221
+ timeZone: planningTime.timeZone,
222
+ modelUid: operation.tuids[0],
223
+ questionText: content,
224
+ modelingEvidence: structuredClone(operation.modelingEvidence),
225
+ };
226
+ return { ...body, inputHash: hashDatasetPreflightInput(body) };
227
+ }
228
+
229
+ export async function collectDatasetPreflight(client, input, options) {
230
+ let pairs;
231
+ const result = await runDatasetPreflight(client, input, {
232
+ ...options,
233
+ onRuntimeAuthority(runtimePairs) {
234
+ pairs = normalizeDatasetQuestion(runtimePairs);
235
+ },
236
+ });
237
+ if (!Array.isArray(pairs) || pairs.length === 0)
238
+ fail(
239
+ "INVALID_DATASET_PREFLIGHT",
240
+ "dataset preflight returned no runtime authority",
241
+ );
242
+ return { pairs, result };
243
+ }
244
+
245
+ export function recordDatasetPreflightWarning(plan) {
246
+ if (
247
+ plan.warnings.some((warning) =>
248
+ warning.startsWith("Dataset planning preflight"),
249
+ )
250
+ )
251
+ return;
252
+ plan.warnings.push(
253
+ "Dataset planning preflight creates taskType8 AsyncTask records as an unavoidable read-computation side effect; its permission proof applies only to the current administrator.",
254
+ );
255
+ }
256
+
257
+ export function datasetPlanningContext(
258
+ now,
259
+ timeZone = DEFAULT_DATASET_TIME_ZONE,
260
+ ) {
261
+ if (typeof timeZone !== "string" || !timeZone.trim())
262
+ fail("INVALID_TIME_ZONE", "Dataset planning requires a valid time zone");
263
+ let formatter;
264
+ try {
265
+ formatter = new Intl.DateTimeFormat("en-US", {
266
+ timeZone: timeZone.trim(),
267
+ year: "numeric",
268
+ month: "2-digit",
269
+ day: "2-digit",
270
+ });
271
+ } catch {
272
+ fail("INVALID_TIME_ZONE", "Dataset planning requires a valid time zone");
273
+ }
274
+ const value = typeof now === "function" ? now() : new Date();
275
+ const date = value instanceof Date ? value : new Date(value);
276
+ if (!Number.isFinite(date.getTime()))
277
+ fail("INVALID_CLOCK", "planning clock must return a valid date");
278
+ const parts = Object.fromEntries(
279
+ formatter
280
+ .formatToParts(date)
281
+ .filter(({ type }) => ["year", "month", "day"].includes(type))
282
+ .map(({ type, value: part }) => [type, part]),
283
+ );
284
+ return {
285
+ time: {
286
+ executionDate: `${parts.year}-${parts.month}-${parts.day}`,
287
+ timeZone: formatter.resolvedOptions().timeZone,
288
+ },
289
+ now: () => new Date(date.getTime()),
290
+ };
291
+ }
292
+
293
+ export function normalizeDatasetName(value) {
294
+ if (typeof value !== "string")
295
+ fail("INVALID_INPUT", "dataset name must be a nonempty string");
296
+ const name = value
297
+ .toLowerCase()
298
+ .replace(
299
+ /^[\p{White_Space}\u001c-\u001f]+|[\p{White_Space}\u001c-\u001f]+$/gu,
300
+ "",
301
+ );
302
+ if (!name) fail("INVALID_INPUT", "dataset name must be a nonempty string");
303
+ return name;
304
+ }
305
+
306
+ export function normalizeDatasetQuestion(pairs) {
307
+ return structuredClone(pairs).map((pair) => ({
308
+ ...pair,
309
+ word: pair.word.toLowerCase(),
310
+ }));
311
+ }
312
+
313
+ export async function revalidateDatasetStep(
314
+ client,
315
+ workspaceId,
316
+ step,
317
+ options,
318
+ ) {
319
+ const expected = step.preconditions;
320
+ const { pairs, result } = await collectDatasetPreflight(
321
+ client,
322
+ structuredClone(expected.preflightInput),
323
+ options,
324
+ );
325
+ if (
326
+ canonicalJson(result) !== canonicalJson(expected.preflightResult) ||
327
+ hashValue(pairs) !== expected.pairsHash ||
328
+ canonicalJson(pairs) !== canonicalJson(step.after.question)
329
+ )
330
+ fail(
331
+ "DATASET_PREFLIGHT_DRIFT",
332
+ "dataset runtime authority changed after planning",
333
+ );
334
+ return readDatasetState(client, workspaceId, step);
335
+ }
336
+
337
+ export function datasetAuthorityTargetFromStep(after, preconditions) {
338
+ const operation = {
339
+ columns: structuredClone(after.columns),
340
+ content: after.content,
341
+ metadata: structuredClone(after.metadata),
342
+ modelingEvidence: structuredClone(
343
+ preconditions.preflightInput.modelingEvidence,
344
+ ),
345
+ name: after.name,
346
+ tuids: structuredClone(after.tuids),
347
+ ...(after.id === undefined ? {} : { id: after.id }),
348
+ };
349
+ return {
350
+ ...(after.id === undefined ? {} : { id: after.id }),
351
+ name: after.name,
352
+ desiredHash: datasetAuthorityHash(operation),
353
+ };
354
+ }
355
+
356
+ export function validateDatasetStepStructure(step, workspaceId) {
357
+ const allowedStepFields = new Set([
358
+ "after",
359
+ "before",
360
+ "caseIds",
361
+ "dictionarySyncRequired",
362
+ "endpoint",
363
+ "kind",
364
+ "operation",
365
+ "preconditions",
366
+ ]);
367
+ if (
368
+ Object.keys(step).some((field) => !allowedStepFields.has(field)) ||
369
+ [...allowedStepFields].some((field) => !Object.hasOwn(step, field)) ||
370
+ step.dictionarySyncRequired !== true
371
+ )
372
+ fail("INVALID_DATASET_PLAN", "dataset step fields are invalid");
373
+
374
+ const collection = datasetCollection(workspaceId);
375
+ const after = validateDatasetSnapshot(step.after, "after", true);
376
+ let before = null;
377
+ if (step.operation === "POST") {
378
+ if (
379
+ step.before !== null ||
380
+ after.id !== undefined ||
381
+ step.endpoint !== collection
382
+ )
383
+ fail(
384
+ "INVALID_DATASET_PLAN",
385
+ "dataset POST must create from the collection",
386
+ );
387
+ } else if (step.operation === "PUT") {
388
+ before = validateDatasetSnapshot(step.before, "before", false);
389
+ const beforeId = canonicalDatasetId(before.id);
390
+ const afterId = canonicalDatasetId(after.id);
391
+ if (
392
+ beforeId !== afterId ||
393
+ step.endpoint !== `${collection}${beforeId}/` ||
394
+ statesEqual(before, after)
395
+ )
396
+ fail(
397
+ "INVALID_DATASET_PLAN",
398
+ "dataset PUT identity or desired state is invalid",
399
+ );
400
+ } else fail("INVALID_DATASET_PLAN", "dataset operation is invalid");
401
+
402
+ const caseIds = validateMutationCaseIds(step.caseIds, "INVALID_DATASET_PLAN");
403
+ const preconditions = step.preconditions;
404
+ if (
405
+ !isRecord(preconditions) ||
406
+ canonicalJson(Object.keys(preconditions).sort()) !==
407
+ canonicalJson([
408
+ "datasetTime",
409
+ "pairsHash",
410
+ "preflightInput",
411
+ "preflightResult",
412
+ ])
413
+ )
414
+ fail(
415
+ "INVALID_DATASET_PREFLIGHT_EVIDENCE",
416
+ "dataset preconditions are invalid",
417
+ );
418
+ validateDatasetPreflightEvidence(preconditions, after, workspaceId, caseIds);
419
+ return { after, before, caseIds };
420
+ }
421
+
422
+ export function validateDatasetSnapshot(value, label, requireContent) {
423
+ if (!isRecord(value))
424
+ fail("INVALID_DATASET_PLAN", `dataset ${label} must be an object`);
425
+ const allowed = new Set([
426
+ "columns",
427
+ "content",
428
+ "id",
429
+ "metadata",
430
+ "name",
431
+ "question",
432
+ "tuids",
433
+ ]);
434
+ const required = ["columns", "metadata", "name", "question", "tuids"];
435
+ if (requireContent) required.push("content");
436
+ if (
437
+ Object.keys(value).some((field) => !allowed.has(field)) ||
438
+ required.some((field) => !Object.hasOwn(value, field))
439
+ )
440
+ fail("INVALID_DATASET_PLAN", `dataset ${label} fields are invalid`);
441
+ if (value.id !== undefined) canonicalDatasetId(value.id);
442
+ if (normalizeDatasetName(value.name) !== value.name)
443
+ fail(
444
+ "INVALID_DATASET_PLAN",
445
+ `dataset ${label} name must match the server-normalized state`,
446
+ );
447
+ if (value.content !== undefined) {
448
+ const content = requiredText(value.content, `${label}.content`);
449
+ if (content !== value.content || [...content].length > 256)
450
+ fail("INVALID_DATASET_PLAN", `dataset ${label} content is invalid`);
451
+ }
452
+ if (
453
+ !Array.isArray(value.question) ||
454
+ !Array.isArray(value.tuids) ||
455
+ !Array.isArray(value.columns) ||
456
+ !isRecord(value.metadata)
457
+ )
458
+ fail("INVALID_DATASET_PLAN", `dataset ${label} snapshot is invalid`);
459
+ if (
460
+ value.question.some(
461
+ (pair) =>
462
+ !isRecord(pair) ||
463
+ typeof pair.word !== "string" ||
464
+ pair.word.toLowerCase() !== pair.word,
465
+ )
466
+ )
467
+ fail(
468
+ "INVALID_DATASET_PLAN",
469
+ `dataset ${label} question must match the server-normalized state`,
470
+ );
471
+ if (label === "after") {
472
+ if (
473
+ value.question.length === 0 ||
474
+ value.question.length > 100 ||
475
+ value.question.some(
476
+ (pair) =>
477
+ !isRecord(pair) ||
478
+ canonicalJson(Object.keys(pair).sort()) !==
479
+ canonicalJson(["prop", "word"]) ||
480
+ typeof pair.word !== "string" ||
481
+ !pair.word.trim() ||
482
+ pair.word !== pair.word.trim() ||
483
+ typeof pair.prop !== "string" ||
484
+ !pair.prop.trim() ||
485
+ pair.prop !== pair.prop.trim(),
486
+ ) ||
487
+ value.tuids.length !== 1 ||
488
+ typeof value.tuids[0] !== "string" ||
489
+ !value.tuids[0] ||
490
+ value.tuids[0] !== value.tuids[0].trim() ||
491
+ value.tuids[0].includes("/") ||
492
+ value.columns.length !== 1 ||
493
+ !/^d[1-9]\d*$/u.test(value.columns[0]) ||
494
+ value.metadata.timePolicy !== "internal_fixed" ||
495
+ !/^\d{4}-\d{2}-\d{2}$/u.test(value.metadata.anchoredOn)
496
+ )
497
+ fail("INVALID_DATASET_PLAN", "dataset after authority is invalid");
498
+ }
499
+ return value;
500
+ }
501
+
502
+ export function validateDatasetPreflightEvidence(
503
+ preconditions,
504
+ after,
505
+ workspaceId,
506
+ caseIds,
507
+ ) {
508
+ const datasetTime = preconditions.datasetTime;
509
+ const input = preconditions.preflightInput;
510
+ const result = preconditions.preflightResult;
511
+ if (
512
+ !isRecord(datasetTime) ||
513
+ canonicalJson(Object.keys(datasetTime).sort()) !==
514
+ canonicalJson(["executionDate", "timeZone"]) ||
515
+ typeof datasetTime.timeZone !== "string" ||
516
+ !datasetTime.timeZone ||
517
+ !/^\d{4}-\d{2}-\d{2}$/u.test(datasetTime.executionDate) ||
518
+ !isRecord(input) ||
519
+ canonicalJson(Object.keys(input).sort()) !==
520
+ canonicalJson([
521
+ "caseId",
522
+ "executionDate",
523
+ "inputHash",
524
+ "modelUid",
525
+ "modelingEvidence",
526
+ "questionText",
527
+ "timeZone",
528
+ "version",
529
+ "workspaceId",
530
+ ]) ||
531
+ input.version !== 1 ||
532
+ input.workspaceId !== workspaceId ||
533
+ !caseIds.includes(input.caseId) ||
534
+ input.executionDate !== datasetTime.executionDate ||
535
+ input.timeZone !== datasetTime.timeZone ||
536
+ input.modelUid !== after.tuids[0] ||
537
+ input.questionText !== after.content ||
538
+ !isRecord(input.modelingEvidence) ||
539
+ input.inputHash !== hashDatasetPreflightInput(input) ||
540
+ input.modelingEvidence.executionDate !== datasetTime.executionDate ||
541
+ input.modelingEvidence.timeZone !== datasetTime.timeZone ||
542
+ input.modelingEvidence.semantics?.customerIdentity?.dimensionProp !==
543
+ after.columns[0] ||
544
+ canonicalJson(input.modelingEvidence.topology?.modelUids) !==
545
+ canonicalJson(after.tuids) ||
546
+ after.metadata.anchoredOn !== datasetTime.executionDate
547
+ )
548
+ fail(
549
+ "INVALID_DATASET_PREFLIGHT_EVIDENCE",
550
+ "dataset preflight input is unbound",
551
+ );
552
+
553
+ const safeResultKeys = [
554
+ "executionDate",
555
+ "identityCount",
556
+ "identityProp",
557
+ "inputHash",
558
+ "modelSnapshotHash",
559
+ "modelUid",
560
+ "permissionScope",
561
+ "rowCount",
562
+ "stable",
563
+ "status",
564
+ "timeZone",
565
+ "unavoidableReadTaskSideEffect",
566
+ "version",
567
+ "workspaceId",
568
+ ];
569
+ if (
570
+ !isRecord(result) ||
571
+ canonicalJson(Object.keys(result).sort()) !==
572
+ canonicalJson(safeResultKeys) ||
573
+ result.version !== 1 ||
574
+ result.status !== "ready" ||
575
+ result.inputHash !== input.inputHash ||
576
+ result.workspaceId !== workspaceId ||
577
+ result.executionDate !== datasetTime.executionDate ||
578
+ result.timeZone !== datasetTime.timeZone ||
579
+ result.modelUid !== after.tuids[0] ||
580
+ result.modelSnapshotHash !== input.modelingEvidence.modelSnapshotHash ||
581
+ result.identityProp !== after.columns[0] ||
582
+ !Number.isSafeInteger(result.rowCount) ||
583
+ result.rowCount <= 0 ||
584
+ result.rowCount >= 10_000 ||
585
+ result.identityCount !== result.rowCount ||
586
+ result.stable !== true ||
587
+ result.permissionScope !== "current_admin_only" ||
588
+ result.unavoidableReadTaskSideEffect !== true ||
589
+ preconditions.pairsHash !== hashValue(after.question)
590
+ )
591
+ fail(
592
+ "INVALID_DATASET_PREFLIGHT_EVIDENCE",
593
+ "dataset preflight result is unbound",
594
+ );
595
+ }
596
+
597
+ export function datasetCollection(workspaceId) {
598
+ return `/api/v3/admin-projects/${workspaceId}/datasets/`;
599
+ }
600
+
601
+ export function datasetAuthorityHash(operation) {
602
+ const desired = {
603
+ columns: structuredClone(operation.columns),
604
+ content: operation.content,
605
+ kind: "dataset",
606
+ metadata: structuredClone(operation.metadata),
607
+ modelingEvidence: structuredClone(operation.modelingEvidence),
608
+ name: operation.name,
609
+ tuids: structuredClone(operation.tuids),
610
+ ...(operation.id === undefined ? {} : { id: operation.id }),
611
+ };
612
+ return hashValue(desired);
613
+ }
614
+
615
+ function normalizeDatasetOperationAuthority(operation) {
616
+ const name = normalizeDatasetName(operation.name);
617
+ const normalized = { ...structuredClone(operation), name };
618
+ if (operation.id !== undefined)
619
+ normalized.id = canonicalDatasetId(operation.id);
620
+ return normalized;
621
+ }
622
+
623
+ function datasetAuthorityTarget(operation) {
624
+ const normalized = normalizeDatasetOperationAuthority(operation);
625
+ return {
626
+ ...(normalized.id === undefined ? {} : { id: normalized.id }),
627
+ name: normalized.name,
628
+ desiredHash: datasetAuthorityHash(normalized),
629
+ };
630
+ }
631
+
632
+ function createDatasetCoalescer() {
633
+ const groups = new Map();
634
+ const names = new Map();
635
+ return {
636
+ add(operation, result) {
637
+ const caseId = operation.caseId.trim();
638
+ const normalized = normalizeDatasetOperationAuthority(operation);
639
+ coalesceNamedOperation({
640
+ caseId,
641
+ operation: normalized,
642
+ groups,
643
+ names,
644
+ result,
645
+ conflictCode: "DATASET_CONFLICT",
646
+ });
647
+ return true;
648
+ },
649
+ };
650
+ }
651
+
652
+ function datasetPlan(client, plan, operation, options = {}) {
653
+ return planDataset(client, plan, operation, options.planningContext.time, {
654
+ ...options,
655
+ now: options.planningContext.now,
656
+ });
657
+ }
658
+
659
+ function datasetWriteDesired(client, step) {
660
+ return client.request(step.operation, step.endpoint, {
661
+ body: datasetBody(step.after),
662
+ });
663
+ }
664
+
665
+ function datasetWriteBefore(client, step) {
666
+ return client.request("PUT", step.endpoint, {
667
+ body: datasetBody(step.before),
668
+ });
669
+ }
670
+
671
+ function datasetRevalidate(client, workspaceId, step, ctx) {
672
+ return revalidateDatasetStep(client, workspaceId, step, ctx.options);
673
+ }
674
+
675
+ async function datasetExactCreatedCandidates(client, workspaceId, step) {
676
+ const name = step.after?.name;
677
+ const rows = await listAllPages(client, datasetCollection(workspaceId), {
678
+ q: name,
679
+ });
680
+ return rows
681
+ .filter((row) => normalizeText(row.name) === normalizeText(name))
682
+ .map(semanticDataset);
683
+ }
684
+
685
+ function validateDatasetAuthorityTarget(target) {
686
+ const allowed = new Set(["desiredHash", "id", "name"]);
687
+ if (
688
+ Object.keys(target).some((field) => !allowed.has(field)) ||
689
+ !Object.hasOwn(target, "desiredHash") ||
690
+ !Object.hasOwn(target, "name") ||
691
+ (target.id !== undefined &&
692
+ canonicalDatasetId(target.id) !== target.id) ||
693
+ normalizeDatasetName(target.name) !== target.name ||
694
+ !/^[0-9a-f]{64}$/u.test(target.desiredHash)
695
+ )
696
+ fail("INVALID_PLAN_STRUCTURE", "Dataset authority target is invalid");
697
+ }
698
+
699
+ function validateDatasetPlanStep(step, plan, authorities, plannedCaseIds, usedCaseIds) {
700
+ const { after, caseIds } = validateDatasetStepStructure(
701
+ step,
702
+ plan.workspaceId,
703
+ );
704
+ for (const caseId of caseIds)
705
+ if (
706
+ !matchesAuthority(
707
+ authorities.get(caseId),
708
+ "dataset",
709
+ (target) =>
710
+ canonicalJson(target) ===
711
+ canonicalJson(
712
+ datasetAuthorityTargetFromStep(after, step.preconditions),
713
+ ),
714
+ )
715
+ )
716
+ fail(
717
+ "INVALID_DATASET_PLAN",
718
+ "dataset step caseIds must match exact Dataset authorities",
719
+ );
720
+ claimStepCaseIds(usedCaseIds, caseIds);
721
+ for (const caseId of caseIds) plannedCaseIds.add(caseId);
722
+ }
723
+
724
+ function datasetSummaryMatches(summary, authorityTargets) {
725
+ const targets = authorityTargets.map(({ target }) => target);
726
+ return targets.every((target) => summary.name === target.name);
727
+ }
728
+
729
+ export const datasetKind = {
730
+ name: "dataset",
731
+ planable: true,
732
+ plan: datasetPlan,
733
+ planningContext: (options = {}) =>
734
+ datasetPlanningContext(options.now, options.timeZone),
735
+ authorityTarget: datasetAuthorityTarget,
736
+ createCoalescer: createDatasetCoalescer,
737
+ writeDesired: datasetWriteDesired,
738
+ writeBefore: datasetWriteBefore,
739
+ readState: readDatasetState,
740
+ preApplyRead: datasetRevalidate,
741
+ exactCreatedCandidates: datasetExactCreatedCandidates,
742
+ collection: datasetCollection,
743
+ targetKey: (step) =>
744
+ `dataset:${step.after?.id ?? normalizeText(step.after?.name)}`,
745
+ validateAuthorityTarget: validateDatasetAuthorityTarget,
746
+ validateStep: validateDatasetPlanStep,
747
+ summaryField: ["name"],
748
+ summaryMatches: datasetSummaryMatches,
749
+ };