@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,813 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ import { hashArtifactValue as hashValue } from "../../datarc-semantic-core/scripts/canonical.mjs";
4
+ import { isRecord } from "../../datarc-semantic-core/scripts/shared.mjs";
5
+
6
+ const VERSION = 1;
7
+ const TASK_TYPE_QUERY_DATA = 8;
8
+ const TASK_STATUS_SUCCESS = 2;
9
+ const TASK_PENDING_STATUSES = new Set([0, 1]);
10
+ const MAX_DATASET_ROWS = 10_000;
11
+
12
+ export class DatasetPreflightError extends Error {
13
+ constructor(message, code = "DATASET_PREFLIGHT_FAILED") {
14
+ super(message);
15
+ this.name = "DatasetPreflightError";
16
+ this.code = code;
17
+ }
18
+ }
19
+
20
+ export function hashDatasetModelSnapshot(model) {
21
+ return hashValue(model);
22
+ }
23
+
24
+ export function hashDatasetPreflightInput(input) {
25
+ const body = structuredClone(input);
26
+ delete body.inputHash;
27
+ return hashValue(body);
28
+ }
29
+
30
+ export async function runDatasetPreflight(client, input, options = {}) {
31
+ if (!client || typeof client.request !== "function")
32
+ fail("INVALID_CLIENT", "client.request is required");
33
+ validateInput(input, options);
34
+
35
+ const workspaceId = input.workspaceId;
36
+ const modelUid = input.modelUid;
37
+ const evidence = input.modelingEvidence;
38
+ const model = await safeRequest(
39
+ client,
40
+ "GET",
41
+ `/api/v2/admin-projects/${workspaceId}/models/${modelUid}/`,
42
+ );
43
+ assertModelEvidence(model, modelUid, evidence);
44
+
45
+ const cut = await safeRequest(
46
+ client,
47
+ "POST",
48
+ `/api/v3/account-projects/${workspaceId}/cut/`,
49
+ { body: { tokens: input.questionText } },
50
+ );
51
+ const pairs = runtimePairs(cut);
52
+ assertSemanticEvidence(pairs, evidence);
53
+
54
+ const card = await safeRequest(
55
+ client,
56
+ "POST",
57
+ `/api/v3/account-projects/${workspaceId}/card/`,
58
+ {
59
+ body: {
60
+ question: structuredClone(pairs),
61
+ params: { tuids: [modelUid] },
62
+ },
63
+ },
64
+ );
65
+ const { identityIndex, identityProp, qKey } = cardContract(
66
+ card,
67
+ modelUid,
68
+ evidence.semantics.customerIdentity.dimensionProp,
69
+ );
70
+
71
+ const taskCollection = `/api/v2/account-projects/${workspaceId}/async-tasks/`;
72
+ const nonce = nonceFactory(options.nonce);
73
+ const count = await queryData(
74
+ client,
75
+ taskCollection,
76
+ qKey,
77
+ { count: true, _semanticPreflightNonce: nonce() },
78
+ options,
79
+ );
80
+ if (!Number.isFinite(count) || !Number.isInteger(count) || count <= 0)
81
+ fail("INVALID_DATASET_COUNT", "dataset count must be a positive integer");
82
+ if (count >= MAX_DATASET_ROWS)
83
+ fail("DATASET_CARDINALITY_LIMIT", "dataset count must be below 10000");
84
+
85
+ const rows = await queryData(
86
+ client,
87
+ taskCollection,
88
+ qKey,
89
+ { offset: 0, limit: count + 1, _semanticPreflightNonce: nonce() },
90
+ options,
91
+ );
92
+ const identityCount = uniqueIdentityCount(rows, count, identityIndex);
93
+ const recount = await queryData(
94
+ client,
95
+ taskCollection,
96
+ qKey,
97
+ { count: true, _semanticPreflightNonce: nonce() },
98
+ options,
99
+ );
100
+ if (recount !== count)
101
+ fail("DATASET_RESULT_DRIFT", "dataset count changed during preflight");
102
+
103
+ const result = {
104
+ version: VERSION,
105
+ status: "ready",
106
+ inputHash: input.inputHash,
107
+ workspaceId,
108
+ executionDate: input.executionDate,
109
+ timeZone: input.timeZone,
110
+ modelUid,
111
+ modelSnapshotHash: evidence.modelSnapshotHash,
112
+ identityProp,
113
+ rowCount: count,
114
+ identityCount,
115
+ stable: true,
116
+ permissionScope: "current_admin_only",
117
+ unavoidableReadTaskSideEffect: true,
118
+ };
119
+ if (options.onRuntimeAuthority !== undefined) {
120
+ if (typeof options.onRuntimeAuthority !== "function")
121
+ fail(
122
+ "INVALID_RUNTIME_AUTHORITY_CALLBACK",
123
+ "onRuntimeAuthority must be a function",
124
+ );
125
+ try {
126
+ await options.onRuntimeAuthority(structuredClone(pairs));
127
+ } catch {
128
+ fail(
129
+ "RUNTIME_AUTHORITY_CALLBACK_FAILED",
130
+ "runtime authority callback failed",
131
+ );
132
+ }
133
+ }
134
+ return result;
135
+ }
136
+
137
+ function validateInput(input, options) {
138
+ const inputCode = "INVALID_PREFLIGHT_INPUT";
139
+ if (!isRecord(input))
140
+ fail(inputCode, "dataset preflight input must be an object");
141
+ exactKeys(
142
+ input,
143
+ [
144
+ "caseId",
145
+ "executionDate",
146
+ "inputHash",
147
+ "modelUid",
148
+ "modelingEvidence",
149
+ "questionText",
150
+ "timeZone",
151
+ "version",
152
+ "workspaceId",
153
+ ],
154
+ inputCode,
155
+ );
156
+ if (input.version !== VERSION)
157
+ fail(inputCode, "dataset preflight version is invalid");
158
+ if (!Number.isSafeInteger(input.workspaceId) || input.workspaceId <= 0)
159
+ fail(inputCode, "dataset workspaceId must be a positive integer");
160
+ boundedTrimmed(input.caseId, 200, inputCode, "dataset caseId is invalid");
161
+ boundedTrimmed(input.modelUid, 128, inputCode, "dataset modelUid is invalid");
162
+ boundedTrimmed(
163
+ input.questionText,
164
+ 2_000,
165
+ inputCode,
166
+ "dataset questionText is invalid",
167
+ );
168
+ if (input.modelUid.includes("/"))
169
+ fail(inputCode, "dataset modelUid is invalid");
170
+ const executionDate = zonedExecutionDate(input.timeZone, options.now);
171
+ if (input.executionDate !== executionDate)
172
+ fail(inputCode, "dataset executionDate is not current in its time zone");
173
+ if (
174
+ !/^[0-9a-f]{64}$/.test(input.inputHash) ||
175
+ input.inputHash !== hashDatasetPreflightInput(input)
176
+ )
177
+ fail(inputCode, "dataset preflight input hash is invalid");
178
+ validateEvidenceStructure(input);
179
+ }
180
+
181
+ function validateEvidenceStructure(input) {
182
+ const code = "MODELING_EVIDENCE_REQUIRED";
183
+ const evidence = input.modelingEvidence;
184
+ if (!isRecord(evidence))
185
+ fail(code, "structured modeling evidence is required");
186
+ exactKeys(
187
+ evidence,
188
+ ["executionDate", "modelSnapshotHash", "semantics", "timeZone", "topology"],
189
+ code,
190
+ );
191
+ if (
192
+ evidence.executionDate !== input.executionDate ||
193
+ evidence.timeZone !== input.timeZone ||
194
+ typeof evidence.modelSnapshotHash !== "string" ||
195
+ !/^[0-9a-f]{64}$/.test(evidence.modelSnapshotHash)
196
+ )
197
+ fail(code, "modeling evidence is stale or unbound");
198
+
199
+ const semantics = evidence.semantics;
200
+ if (!isRecord(semantics))
201
+ fail(code, "semantic modeling evidence is required");
202
+ exactKeys(
203
+ semantics,
204
+ ["activity", "currentStatus", "customerIdentity", "rollingWindow"],
205
+ code,
206
+ );
207
+ const rolling = semantics.rollingWindow;
208
+ const activity = semantics.activity;
209
+ const status = semantics.currentStatus;
210
+ const customerIdentity = semantics.customerIdentity;
211
+ if (![rolling, activity, status, customerIdentity].every(isRecord))
212
+ fail(code, "semantic modeling evidence is incomplete");
213
+ exactKeys(rolling, ["anchor", "days", "kind", "tokenProp"], code);
214
+ exactKeys(
215
+ activity,
216
+ ["kind", "measureProp", "operatorProp", "threshold", "valueProp"],
217
+ code,
218
+ );
219
+ const statusKeys = [
220
+ "dimensionProp",
221
+ "excludedValue",
222
+ "kind",
223
+ "operatorProp",
224
+ "temporalScope",
225
+ "valueProp",
226
+ ];
227
+ exactKeys(
228
+ status,
229
+ status.sourceKind === undefined
230
+ ? statusKeys
231
+ : status.sourceKind === "dimension_table"
232
+ ? [...statusKeys, "dimensionTableUid", "sourceKind"]
233
+ : [...statusKeys, "sourceKind"],
234
+ code,
235
+ );
236
+ exactKeys(
237
+ customerIdentity,
238
+ ["dimensionProp", "kind", "level", "uniqueness"],
239
+ code,
240
+ );
241
+ if (
242
+ rolling.kind !== "rolling_days" ||
243
+ rolling.days !== 30 ||
244
+ rolling.tokenProp !== "dateBefore_30d" ||
245
+ rolling.anchor !== "execution_date" ||
246
+ activity.kind !== "measure_threshold" ||
247
+ !/^m[1-9]\d*$/.test(activity.measureProp) ||
248
+ activity.operatorProp !== "$gt" ||
249
+ activity.threshold !== 0 ||
250
+ typeof activity.valueProp !== "string" ||
251
+ !activity.valueProp ||
252
+ status.kind !== "dimension_exclusion" ||
253
+ ![undefined, "fact", "dimension_table"].includes(status.sourceKind) ||
254
+ !/^d[1-9]\d*$/.test(status.dimensionProp) ||
255
+ status.operatorProp !== "$ne" ||
256
+ status.excludedValue !== "注销" ||
257
+ typeof status.valueProp !== "string" ||
258
+ !status.valueProp ||
259
+ status.temporalScope !== "current" ||
260
+ customerIdentity.kind !== "dimension_grouping" ||
261
+ !/^d[1-9]\d*$/.test(customerIdentity.dimensionProp) ||
262
+ customerIdentity.level !== 1 ||
263
+ customerIdentity.uniqueness !== "runtime_count_detail_recount"
264
+ )
265
+ fail(code, "semantic modeling evidence is contradictory");
266
+
267
+ const topology = evidence.topology;
268
+ if (!isRecord(topology)) fail(code, "topology modeling evidence is required");
269
+ exactKeys(topology, ["identity", "joins", "modelUids"], code);
270
+ if (
271
+ !Array.isArray(topology.modelUids) ||
272
+ topology.modelUids.length !== 1 ||
273
+ topology.modelUids[0] !== input.modelUid ||
274
+ !Array.isArray(topology.joins) ||
275
+ !isRecord(topology.identity)
276
+ )
277
+ fail(code, "topology modeling evidence is incomplete");
278
+ const seenTables = new Set();
279
+ for (const join of topology.joins) {
280
+ if (!isRecord(join)) fail(code, "join modeling evidence is invalid");
281
+ exactKeys(
282
+ join,
283
+ ["dimensionKeyConstraint", "dimensionTableUid", "fanout", "relationship"],
284
+ code,
285
+ );
286
+ if (
287
+ typeof join.dimensionTableUid !== "string" ||
288
+ !join.dimensionTableUid ||
289
+ seenTables.has(join.dimensionTableUid) ||
290
+ join.relationship !== "many_to_one" ||
291
+ join.dimensionKeyConstraint !== "unique" ||
292
+ join.fanout !== "forbidden"
293
+ )
294
+ fail(code, "join modeling evidence is invalid");
295
+ seenTables.add(join.dimensionTableUid);
296
+ }
297
+ const identityKeys =
298
+ topology.identity.sourceKind === "fact"
299
+ ? ["dimensionId", "dimensionProp", "grouping", "sourceKind"]
300
+ : topology.identity.sourceKind === "dimension_table"
301
+ ? [
302
+ "dimensionId",
303
+ "dimensionProp",
304
+ "dimensionTableUid",
305
+ "grouping",
306
+ "sourceKind",
307
+ ]
308
+ : ["dimensionId", "dimensionProp", "dimensionTableUid", "grouping"];
309
+ exactKeys(topology.identity, identityKeys, code);
310
+ const identityId = dimensionId(topology.identity.dimensionProp);
311
+ const identitySource = topology.identity.sourceKind ?? "dimension_table";
312
+ if (
313
+ topology.identity.dimensionId !== identityId ||
314
+ topology.identity.dimensionProp !== customerIdentity.dimensionProp ||
315
+ !["fact", "dimension_table"].includes(identitySource) ||
316
+ (identitySource === "dimension_table" &&
317
+ (typeof topology.identity.dimensionTableUid !== "string" ||
318
+ !seenTables.has(topology.identity.dimensionTableUid))) ||
319
+ topology.identity.grouping !== "single_identity"
320
+ )
321
+ fail(code, "identity modeling evidence is contradictory");
322
+ if (
323
+ status.sourceKind === "dimension_table" &&
324
+ (typeof status.dimensionTableUid !== "string" ||
325
+ !seenTables.has(status.dimensionTableUid))
326
+ )
327
+ fail(code, "status modeling evidence is contradictory");
328
+ }
329
+
330
+ function assertModelEvidence(model, modelUid, evidence) {
331
+ if (
332
+ !isRecord(model) ||
333
+ model.uid !== modelUid ||
334
+ model.ready !== true ||
335
+ model.disable === true ||
336
+ evidence.modelSnapshotHash !== hashDatasetModelSnapshot(model)
337
+ )
338
+ fail(
339
+ "MODELING_EVIDENCE_REQUIRED",
340
+ "fresh model snapshot does not match modeling evidence",
341
+ );
342
+
343
+ const topology = evidence.topology;
344
+ const identity = topology.identity;
345
+ const identityId = dimensionId(identity.dimensionProp);
346
+ if (
347
+ identity.dimensionId !== identityId ||
348
+ identity.grouping !== "single_identity" ||
349
+ topology.modelUids.length !== 1 ||
350
+ topology.modelUids[0] !== modelUid
351
+ )
352
+ fail(
353
+ "MODELING_EVIDENCE_REQUIRED",
354
+ "modeling evidence does not prove one identity model",
355
+ );
356
+ const activityId = measureId(evidence.semantics.activity.measureProp);
357
+ if (
358
+ !Array.isArray(model.measures) ||
359
+ !model.measures.some((item) => Number(item.id) === activityId)
360
+ )
361
+ fail(
362
+ "MODELING_EVIDENCE_REQUIRED",
363
+ "model snapshot does not contain the semantic bindings",
364
+ );
365
+ const dimensionTables = Array.isArray(model.dimensionTables)
366
+ ? model.dimensionTables
367
+ : [];
368
+ const tableReferences = new Map();
369
+ for (const table of dimensionTables) {
370
+ if (
371
+ !isRecord(table) ||
372
+ typeof table.uid !== "string" ||
373
+ !table.uid ||
374
+ tableReferences.has(table.uid)
375
+ )
376
+ fail(
377
+ "MODELING_EVIDENCE_REQUIRED",
378
+ "model snapshot contains invalid dimension-table references",
379
+ );
380
+ tableReferences.set(table.uid, table);
381
+ }
382
+ const joins = new Map(
383
+ topology.joins.map((join) => [join.dimensionTableUid, join]),
384
+ );
385
+ for (const [dimensionTableUid] of joins) {
386
+ const reference = tableReferences.get(dimensionTableUid);
387
+ if (!reference || !validJoinFields(reference.joinFields))
388
+ fail(
389
+ "MODELING_EVIDENCE_REQUIRED",
390
+ "declared join is not backed by the fresh model snapshot",
391
+ );
392
+ }
393
+
394
+ const factDimensionIds = dimensionIdSet(model.dimensions);
395
+ const allDimensionIds = new Set([
396
+ ...factDimensionIds,
397
+ ...dimensionIdSet(model.dimensionIds),
398
+ ...dimensionTables.flatMap((table) => [
399
+ ...dimensionIdSet(table.dimensions),
400
+ ]),
401
+ ]);
402
+ assertDimensionBinding(
403
+ {
404
+ dimensionId: identityId,
405
+ sourceKind: identity.sourceKind ?? "dimension_table",
406
+ dimensionTableUid: identity.dimensionTableUid,
407
+ },
408
+ { allDimensionIds, factDimensionIds, joins, tableReferences },
409
+ );
410
+
411
+ const status = evidence.semantics.currentStatus;
412
+ const statusId = dimensionId(status.dimensionProp);
413
+ let statusSourceKind = status.sourceKind;
414
+ let statusDimensionTableUid = status.dimensionTableUid;
415
+ if (statusSourceKind === undefined) {
416
+ if (factDimensionIds.has(statusId)) statusSourceKind = "fact";
417
+ else {
418
+ const expandedOwners = dimensionTables.filter((table) =>
419
+ dimensionIdSet(table.dimensions).has(statusId),
420
+ );
421
+ if (expandedOwners.length === 1) {
422
+ statusSourceKind = "dimension_table";
423
+ statusDimensionTableUid = expandedOwners[0].uid;
424
+ } else if (expandedOwners.length === 0 && joins.size === 1) {
425
+ statusSourceKind = "dimension_table";
426
+ statusDimensionTableUid = joins.keys().next().value;
427
+ } else
428
+ fail(
429
+ "MODELING_EVIDENCE_REQUIRED",
430
+ "legacy status evidence does not identify one dimension source",
431
+ );
432
+ }
433
+ }
434
+ assertDimensionBinding(
435
+ {
436
+ dimensionId: statusId,
437
+ sourceKind: statusSourceKind,
438
+ dimensionTableUid: statusDimensionTableUid,
439
+ },
440
+ { allDimensionIds, factDimensionIds, joins, tableReferences },
441
+ );
442
+ }
443
+
444
+ function assertDimensionBinding(binding, snapshot) {
445
+ if (binding.sourceKind === "fact") {
446
+ if (!snapshot.factDimensionIds.has(binding.dimensionId))
447
+ fail(
448
+ "MODELING_EVIDENCE_REQUIRED",
449
+ "fact-dimension evidence is not backed by the fresh model snapshot",
450
+ );
451
+ return;
452
+ }
453
+ const reference = snapshot.tableReferences.get(binding.dimensionTableUid);
454
+ if (
455
+ binding.sourceKind !== "dimension_table" ||
456
+ snapshot.factDimensionIds.has(binding.dimensionId) ||
457
+ !snapshot.allDimensionIds.has(binding.dimensionId) ||
458
+ !reference ||
459
+ !snapshot.joins.has(binding.dimensionTableUid) ||
460
+ !validJoinFields(reference.joinFields) ||
461
+ (Array.isArray(reference.dimensions) &&
462
+ !dimensionIdSet(reference.dimensions).has(binding.dimensionId)) ||
463
+ (!Array.isArray(reference.dimensions) &&
464
+ [...snapshot.tableReferences.keys()].some(
465
+ (dimensionTableUid) => !snapshot.joins.has(dimensionTableUid),
466
+ ))
467
+ )
468
+ fail(
469
+ "MODELING_EVIDENCE_REQUIRED",
470
+ "dimension-table evidence is not backed by the fresh model snapshot",
471
+ );
472
+ }
473
+
474
+ function dimensionIdSet(values) {
475
+ const result = new Set();
476
+ for (const value of Array.isArray(values) ? values : []) {
477
+ const id = Number(isRecord(value) ? value.id : value);
478
+ if (Number.isSafeInteger(id) && id > 0) result.add(id);
479
+ }
480
+ return result;
481
+ }
482
+
483
+ function validJoinFields(values) {
484
+ return (
485
+ Array.isArray(values) &&
486
+ values.length > 0 &&
487
+ values.every(
488
+ (field) =>
489
+ isRecord(field) &&
490
+ typeof field.src === "string" &&
491
+ field.src.trim() &&
492
+ typeof field.dst === "string" &&
493
+ field.dst.trim(),
494
+ )
495
+ );
496
+ }
497
+
498
+ function assertSemanticEvidence(pairs, evidence) {
499
+ const semantics = evidence.semantics;
500
+ const rolling = semantics.rollingWindow;
501
+ const activity = semantics.activity;
502
+ const status = semantics.currentStatus;
503
+ const identity = semantics.customerIdentity;
504
+ if (
505
+ rolling.kind !== "rolling_days" ||
506
+ rolling.days !== 30 ||
507
+ rolling.tokenProp !== "dateBefore_30d" ||
508
+ rolling.anchor !== "execution_date" ||
509
+ findPropSequence(pairs, [rolling.tokenProp]) < 0
510
+ )
511
+ fail(
512
+ "MODELING_EVIDENCE_REQUIRED",
513
+ "modeling evidence does not prove a rolling 30 day window",
514
+ );
515
+ if (
516
+ activity.kind !== "measure_threshold" ||
517
+ activity.operatorProp !== "$gt" ||
518
+ activity.threshold !== 0 ||
519
+ findPropSequence(pairs, [
520
+ activity.measureProp,
521
+ activity.operatorProp,
522
+ activity.valueProp,
523
+ ]) < 0
524
+ )
525
+ fail(
526
+ "MODELING_EVIDENCE_REQUIRED",
527
+ "modeling evidence does not prove positive activity",
528
+ );
529
+ const activityIndex = findPropSequence(pairs, [
530
+ activity.measureProp,
531
+ activity.operatorProp,
532
+ activity.valueProp,
533
+ ]);
534
+ if (Number(pairs[activityIndex + 2].word.trim()) !== activity.threshold)
535
+ fail(
536
+ "MODELING_EVIDENCE_REQUIRED",
537
+ "fresh cut contradicts the activity threshold evidence",
538
+ );
539
+ if (
540
+ status.kind !== "dimension_exclusion" ||
541
+ status.operatorProp !== "$ne" ||
542
+ status.excludedValue !== "注销" ||
543
+ status.temporalScope !== "current" ||
544
+ findPropSequence(pairs, [
545
+ status.dimensionProp,
546
+ status.operatorProp,
547
+ status.valueProp,
548
+ ]) < 0
549
+ )
550
+ fail(
551
+ "MODELING_EVIDENCE_REQUIRED",
552
+ "modeling evidence does not prove current-status exclusion",
553
+ );
554
+ const statusIndex = findPropSequence(pairs, [
555
+ status.dimensionProp,
556
+ status.operatorProp,
557
+ status.valueProp,
558
+ ]);
559
+ if (pairs[statusIndex + 2].word.trim() !== status.excludedValue)
560
+ fail(
561
+ "MODELING_EVIDENCE_REQUIRED",
562
+ "fresh cut contradicts the excluded status evidence",
563
+ );
564
+ if (
565
+ identity.kind !== "dimension_grouping" ||
566
+ identity.level !== 1 ||
567
+ identity.uniqueness !== "runtime_count_detail_recount" ||
568
+ findPropSequence(pairs, [identity.dimensionProp]) < 0
569
+ )
570
+ fail(
571
+ "MODELING_EVIDENCE_REQUIRED",
572
+ "modeling evidence does not prove customer identity grouping",
573
+ );
574
+ }
575
+
576
+ function runtimePairs(cut) {
577
+ if (
578
+ !isRecord(cut) ||
579
+ typeof cut.identity !== "string" ||
580
+ !cut.identity.trim() ||
581
+ typeof cut.momentIdentity !== "string" ||
582
+ !cut.momentIdentity.trim() ||
583
+ !Array.isArray(cut.tokens) ||
584
+ cut.tokens.length === 0
585
+ )
586
+ fail("INVALID_CUT_RESPONSE", "fresh cut returned no runtime tokens");
587
+ return cut.tokens.map((token) => {
588
+ if (
589
+ !isRecord(token) ||
590
+ hasNonemptyCandidateList(token.choiceTokens) ||
591
+ hasNonemptyCandidateList(token.guessTokens) ||
592
+ token.invalidType != null ||
593
+ typeof token.word !== "string" ||
594
+ !token.word.trim() ||
595
+ token.word !== token.word.trim() ||
596
+ typeof token.prop !== "string" ||
597
+ !token.prop.trim() ||
598
+ token.prop !== token.prop.trim()
599
+ )
600
+ fail("INVALID_CUT_RESPONSE", "fresh cut returned an invalid token");
601
+ return { word: token.word, prop: token.prop };
602
+ });
603
+ }
604
+
605
+ function hasNonemptyCandidateList(value) {
606
+ if (value === undefined || value === null || value === "") return false;
607
+ return !Array.isArray(value) || value.length > 0;
608
+ }
609
+
610
+ function cardContract(card, modelUid, expectedIdentityProp) {
611
+ if (
612
+ !isRecord(card) ||
613
+ !Array.isArray(card.tuids) ||
614
+ card.tuids.length !== 1 ||
615
+ card.tuids[0] !== modelUid ||
616
+ card.blendData != null ||
617
+ !Array.isArray(card.data) ||
618
+ card.data.length !== 1
619
+ )
620
+ fail(
621
+ "INVALID_DATASET_CARD",
622
+ "fresh card must resolve one unblended model and one data series",
623
+ );
624
+ const series = card.data[0];
625
+ if (!isRecord(series) || !Array.isArray(series.columns))
626
+ fail("INVALID_DATASET_CARD", "fresh card has invalid columns");
627
+ const identities = series.columns
628
+ .map((column) => ({ column }))
629
+ .filter(
630
+ ({ column }) =>
631
+ isRecord(column) &&
632
+ column._nes === expectedIdentityProp &&
633
+ column._l === 1,
634
+ );
635
+ if (identities.length !== 1)
636
+ fail(
637
+ "INVALID_DATASET_CARD",
638
+ "fresh card must expose exactly one level-one identity column",
639
+ );
640
+ if (
641
+ !Number.isSafeInteger(identities[0].column._o) ||
642
+ identities[0].column._o < 0
643
+ )
644
+ fail("INVALID_DATASET_CARD", "fresh card identity offset is invalid");
645
+ const qKey = series.data?.qKey;
646
+ if (typeof qKey !== "string" || !qKey)
647
+ fail("INVALID_DATASET_CARD", "fresh card is missing query authority");
648
+ return {
649
+ identityIndex: identities[0].column._o,
650
+ identityProp: identities[0].column._nes,
651
+ qKey,
652
+ };
653
+ }
654
+
655
+ async function queryData(client, collection, qKey, params, options) {
656
+ const created = await safeRequest(client, "POST", collection, {
657
+ body: { taskType: TASK_TYPE_QUERY_DATA, params: { qKey, params } },
658
+ });
659
+ const uid = created?.uid;
660
+ if (
661
+ typeof uid !== "string" ||
662
+ !uid ||
663
+ uid.includes("/") ||
664
+ Number(created?.taskType) !== TASK_TYPE_QUERY_DATA
665
+ )
666
+ fail("INVALID_TASK_RESPONSE", "query task creation returned no valid uid");
667
+ const taskPath = `${collection}${encodeURIComponent(uid)}/`;
668
+ const attempts = Number(options.maxPollAttempts ?? 300);
669
+ const sleep =
670
+ options.sleep ??
671
+ ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
672
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
673
+ const task = await safeRequest(client, "GET", taskPath);
674
+ const status = Number(task?.status);
675
+ if (status === TASK_STATUS_SUCCESS) {
676
+ if (
677
+ Number(task?.taskType) !== TASK_TYPE_QUERY_DATA ||
678
+ !isRecord(task.result) ||
679
+ task.result.status !== "SUCCESS" ||
680
+ !Object.hasOwn(task.result, "data")
681
+ )
682
+ fail("INVALID_TASK_RESULT", "query task succeeded without safe data");
683
+ return task.result.data;
684
+ }
685
+ if (!TASK_PENDING_STATUSES.has(status))
686
+ fail("QUERY_TASK_FAILED", "query task did not complete successfully");
687
+ await sleep(Number(options.pollIntervalMs ?? 2_000));
688
+ }
689
+ fail("QUERY_TASK_TIMEOUT", "query task did not complete in time");
690
+ }
691
+
692
+ async function safeRequest(client, method, path, options) {
693
+ try {
694
+ return await client.request(method, path, options);
695
+ } catch {
696
+ fail(
697
+ "DATASET_PREFLIGHT_API_FAILED",
698
+ "dataset preflight API request failed",
699
+ );
700
+ }
701
+ }
702
+
703
+ function uniqueIdentityCount(rows, expectedCount, identityIndex) {
704
+ if (!Array.isArray(rows) || rows.length !== expectedCount)
705
+ fail(
706
+ "INVALID_DATASET_DETAIL",
707
+ "dataset detail row count does not match count",
708
+ );
709
+ const identities = new Set();
710
+ for (const row of rows) {
711
+ if (!Array.isArray(row) || identityIndex >= row.length)
712
+ fail("INVALID_DATASET_DETAIL", "dataset detail row is invalid");
713
+ const value = row[identityIndex];
714
+ if (!["string", "number"].includes(typeof value) || !String(value).trim())
715
+ fail("INVALID_DATASET_DETAIL", "dataset identity is empty");
716
+ identities.add(`${typeof value}:${String(value)}`);
717
+ }
718
+ if (identities.size !== expectedCount)
719
+ fail("INVALID_DATASET_DETAIL", "dataset identities are not unique");
720
+ return identities.size;
721
+ }
722
+
723
+ function nonceFactory(factory = randomUUID) {
724
+ const used = new Set();
725
+ return () => {
726
+ const nonce = factory();
727
+ if (typeof nonce !== "string" || !nonce || used.has(nonce))
728
+ fail("INVALID_NONCE", "query nonce must be nonempty and unique");
729
+ used.add(nonce);
730
+ return nonce;
731
+ };
732
+ }
733
+
734
+ function dimensionId(prop) {
735
+ const match = typeof prop === "string" ? /^d([1-9]\d*)$/.exec(prop) : null;
736
+ if (!match)
737
+ fail(
738
+ "MODELING_EVIDENCE_REQUIRED",
739
+ "identity evidence must reference a dimension prop",
740
+ );
741
+ return Number(match[1]);
742
+ }
743
+
744
+ function measureId(prop) {
745
+ const match = typeof prop === "string" ? /^m([1-9]\d*)$/.exec(prop) : null;
746
+ if (!match)
747
+ fail(
748
+ "MODELING_EVIDENCE_REQUIRED",
749
+ "activity evidence must reference a measure prop",
750
+ );
751
+ return Number(match[1]);
752
+ }
753
+
754
+ function zonedExecutionDate(timeZone, now) {
755
+ if (
756
+ typeof timeZone !== "string" ||
757
+ !timeZone.trim() ||
758
+ timeZone !== timeZone.trim()
759
+ )
760
+ fail("INVALID_PREFLIGHT_INPUT", "dataset timeZone is invalid");
761
+ let formatter;
762
+ try {
763
+ formatter = new Intl.DateTimeFormat("en-US", {
764
+ timeZone,
765
+ year: "numeric",
766
+ month: "2-digit",
767
+ day: "2-digit",
768
+ });
769
+ } catch {
770
+ fail("INVALID_PREFLIGHT_INPUT", "dataset timeZone is invalid");
771
+ }
772
+ const value = typeof now === "function" ? now() : (now ?? new Date());
773
+ const date = value instanceof Date ? value : new Date(value);
774
+ if (!Number.isFinite(date.getTime()))
775
+ fail("INVALID_PREFLIGHT_INPUT", "dataset clock is invalid");
776
+ const parts = Object.fromEntries(
777
+ formatter
778
+ .formatToParts(date)
779
+ .filter(({ type }) => ["day", "month", "year"].includes(type))
780
+ .map(({ type, value: part }) => [type, part]),
781
+ );
782
+ return `${parts.year}-${parts.month}-${parts.day}`;
783
+ }
784
+
785
+ function boundedTrimmed(value, maxLength, code, message) {
786
+ if (
787
+ typeof value !== "string" ||
788
+ !value ||
789
+ value !== value.trim() ||
790
+ [...value].length > maxLength
791
+ )
792
+ fail(code, message);
793
+ return value;
794
+ }
795
+
796
+ function exactKeys(value, keys, code, message = "object fields are invalid") {
797
+ if (
798
+ !isRecord(value) ||
799
+ JSON.stringify(Object.keys(value).sort()) !==
800
+ JSON.stringify([...keys].sort())
801
+ )
802
+ fail(code, message);
803
+ }
804
+
805
+ function findPropSequence(pairs, props) {
806
+ return pairs.findIndex((_, index) =>
807
+ props.every((prop, offset) => pairs[index + offset]?.prop === prop),
808
+ );
809
+ }
810
+
811
+ function fail(code, message) {
812
+ throw new DatasetPreflightError(message, code);
813
+ }