@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,683 +1,683 @@
1
- import {
2
- canonicalJson,
3
- hashArtifactValue as hashValue,
4
- withoutId,
5
- } from "../../datarc-semantic-core/scripts/canonical.mjs";
6
- import {
7
- assertState,
8
- authoritiesForCaseIds,
9
- canonicalSynonymId,
10
- claimStepCaseIds,
11
- compact,
12
- fail,
13
- hasCutAlternatives,
14
- listAllPages,
15
- isRecord,
16
- listOf,
17
- matchesAuthority,
18
- normalizeText,
19
- requiredText,
20
- resolveCompletedStep,
21
- statesEqual,
22
- validateMutationCaseIds,
23
- } from "../../datarc-semantic-core/scripts/shared.mjs";
24
-
25
- const CALIBRATION_ORIGIN_MAX_LENGTH = 120;
26
- const CALIBRATION_EXPECTED_MAX_LENGTH = 255;
27
- const CALIBRATION_SYNONYM_MAX_LENGTH = 120;
28
- const CALIBRATION_SYNONYM_MAX_COUNT = 100;
29
- export async function planCalibration(client, plan, operation) {
30
- const originText = boundedCalibrationText(
31
- operation.originText,
32
- "originText",
33
- CALIBRATION_ORIGIN_MAX_LENGTH,
34
- );
35
- const expectedText = boundedCalibrationText(
36
- operation.expectedText,
37
- "expectedText",
38
- CALIBRATION_EXPECTED_MAX_LENGTH,
39
- );
40
- const liveCut = await inspectCalibrationCut(
41
- client,
42
- plan.workspaceId,
43
- expectedText,
44
- );
45
- for (const assertion of operation.expectedTokenAssertions)
46
- if (canonicalJson(assertion) !== canonicalJson(liveCut.pairs))
47
- fail(
48
- "CALIBRATION_TOKEN_ASSERTION_FAILED",
49
- "supplied expectedTokens do not exactly match the fresh ordered cut",
50
- );
51
- const collection = feedbackCollection(plan.workspaceId);
52
- const rows = await listAllPages(client, collection, { q: originText });
53
- const exact = rows.filter(
54
- (row) =>
55
- typeof row?.originText === "string" &&
56
- normalizeCalibrationIdentity(row.originText) ===
57
- normalizeCalibrationIdentity(originText),
58
- );
59
- if (exact.length > 1)
60
- fail(
61
- "CALIBRATION_IDENTITY_AMBIGUOUS",
62
- "multiple feedback rows have the same case-insensitive origin identity",
63
- { originText },
64
- );
65
- const existing = exact[0];
66
- const before = existing ? semanticCalibration(existing) : null;
67
- const after = {
68
- originText,
69
- expectedText,
70
- expectedTokens: structuredClone(liveCut.pairs),
71
- synonyms: structuredClone(operation.synonyms ?? []),
72
- };
73
- if (before !== null && statesEqual(withoutId(before), after)) {
74
- plan.summaries.push({
75
- kind: operation.kind,
76
- status: "noop",
77
- originText,
78
- caseIds: structuredClone(operation.caseIds),
79
- });
80
- return;
81
- }
82
- plan.steps.push({
83
- kind: operation.kind,
84
- caseIds: structuredClone(operation.caseIds),
85
- endpoint: collection,
86
- operation: "POST",
87
- before,
88
- after,
89
- preconditions: { calibrationCut: liveCut.evidence },
90
- dictionarySyncRequired: true,
91
- });
92
- plan.summaries.push({
93
- kind: operation.kind,
94
- status: "planned",
95
- originText,
96
- caseIds: structuredClone(operation.caseIds),
97
- });
98
- }
99
-
100
- export function semanticCalibration(value) {
101
- return compact({
102
- id: value.id,
103
- originText: value.originText,
104
- expectedText: value.expectedText,
105
- expectedTokens: structuredClone(value.expectedTokens ?? []),
106
- synonyms: structuredClone(value.synonyms ?? []),
107
- });
108
- }
109
-
110
- export function calibrationBody(value) {
111
- return compact({
112
- originText: value.originText,
113
- ...(value.expectedText === null
114
- ? {}
115
- : { expectedText: value.expectedText }),
116
- expectedTokens: structuredClone(value.expectedTokens),
117
- synonyms: structuredClone(value.synonyms),
118
- });
119
- }
120
-
121
- export async function inspectCalibrationCut(client, workspaceId, expectedText) {
122
- const response = await client.request(
123
- "POST",
124
- `/api/v3/account-projects/${workspaceId}/cut/`,
125
- { body: { tokens: expectedText } },
126
- );
127
- if (
128
- !isRecord(response) ||
129
- Object.hasOwn(response, "status") ||
130
- !Array.isArray(response.tokens)
131
- )
132
- fail(
133
- "INVALID_CALIBRATION_CUT",
134
- "calibration cut must return an object with a tokens array",
135
- );
136
- if (response.tokens.length <= 1 || response.tokens.length > 100)
137
- fail(
138
- "CALIBRATION_NOT_PERSISTENT",
139
- "semantic calibration requires between two and one hundred fresh tokens",
140
- );
141
- const pairs = response.tokens.map((token) => {
142
- if (
143
- !isRecord(token) ||
144
- typeof token.word !== "string" ||
145
- !token.word.trim() ||
146
- typeof token.prop !== "string" ||
147
- !token.prop.trim() ||
148
- (token.invalidType !== undefined && token.invalidType !== null) ||
149
- hasCutAlternatives(token.choiceTokens) ||
150
- hasCutAlternatives(token.guessTokens)
151
- )
152
- fail(
153
- "INVALID_CALIBRATION_CUT",
154
- "calibration cut token is invalid, ambiguous, or empty",
155
- );
156
- return { word: token.word, prop: token.prop };
157
- });
158
- return {
159
- pairs,
160
- evidence: {
161
- pairsHash: hashValue(pairs),
162
- identity: safeCalibrationCutIdentity(response.identity, "identity"),
163
- momentIdentity: safeCalibrationCutIdentity(
164
- response.momentIdentity,
165
- "momentIdentity",
166
- ),
167
- expectedTextHash: hashValue(expectedText),
168
- },
169
- };
170
- }
171
-
172
- export function safeCalibrationCutIdentity(value, field) {
173
- if (typeof value !== "string" || !value.trim())
174
- fail("INVALID_CALIBRATION_CUT", `cut ${field} is required`);
175
- return value.trim();
176
- }
177
-
178
- export function boundedCalibrationText(value, field, maxLength) {
179
- if (typeof value !== "string" || !value.trim())
180
- fail("INVALID_CALIBRATION", `${field} must be a nonempty string`);
181
- const text = value.trim();
182
- if (text.length > maxLength)
183
- fail(
184
- "INVALID_CALIBRATION",
185
- `${field} must contain at most ${maxLength} characters`,
186
- );
187
- return text;
188
- }
189
-
190
- export function normalizeCalibrationIdentity(value) {
191
- return String(value ?? "")
192
- .trim()
193
- .toLowerCase();
194
- }
195
-
196
- export function normalizeCalibrationSynonyms(
197
- values,
198
- originText,
199
- code = "INVALID_CALIBRATION",
200
- ) {
201
- if (values === undefined) return [];
202
- if (!Array.isArray(values) || values.length > CALIBRATION_SYNONYM_MAX_COUNT)
203
- fail(code, "calibration synonyms must be an array of at most 100 items");
204
-
205
- const origin = normalizeCalibrationIdentity(originText);
206
- const seen = new Set();
207
- const synonyms = [];
208
- for (const value of values) {
209
- if (typeof value !== "string")
210
- fail(code, "calibration synonym must be a string");
211
- const trimmed = value.trim();
212
- if (!trimmed) continue;
213
- if ([...trimmed].length > CALIBRATION_SYNONYM_MAX_LENGTH)
214
- fail(code, "calibration synonym must contain at most 120 characters");
215
- const synonym = trimmed.toLowerCase();
216
- if (synonym === origin || seen.has(synonym)) continue;
217
- seen.add(synonym);
218
- synonyms.push(synonym);
219
- }
220
- return synonyms;
221
- }
222
-
223
- export async function revalidateCalibrationStep(client, workspaceId, step) {
224
- const liveCut = await inspectCalibrationCut(
225
- client,
226
- workspaceId,
227
- step.after.expectedText,
228
- );
229
- if (
230
- canonicalJson(liveCut.pairs) !== canonicalJson(step.after.expectedTokens) ||
231
- liveCut.evidence.pairsHash !== step.preconditions.calibrationCut.pairsHash
232
- )
233
- fail("CALIBRATION_CUT_DRIFT", "calibration cut changed after planning");
234
- return readCalibrationState(client, workspaceId, step.after.originText);
235
- }
236
-
237
- export function calibrationAuthorityTargetFromStep(after) {
238
- const originText = boundedCalibrationText(
239
- after?.originText,
240
- "authority.originText",
241
- CALIBRATION_ORIGIN_MAX_LENGTH,
242
- );
243
- const expectedText = boundedCalibrationText(
244
- after?.expectedText,
245
- "authority.expectedText",
246
- CALIBRATION_EXPECTED_MAX_LENGTH,
247
- );
248
- return {
249
- expectedText,
250
- originText,
251
- synonyms: normalizeCalibrationSynonyms(
252
- after?.synonyms,
253
- originText,
254
- "INVALID_PLAN_STRUCTURE",
255
- ),
256
- };
257
- }
258
-
259
- export function validateCalibrationStepStructure(step, workspaceId) {
260
- const allowedStepFields = new Set([
261
- "kind",
262
- "caseIds",
263
- "endpoint",
264
- "operation",
265
- "before",
266
- "after",
267
- "preconditions",
268
- "dictionarySyncRequired",
269
- ]);
270
- if (
271
- Object.keys(step).some((field) => !allowedStepFields.has(field)) ||
272
- step.endpoint !== feedbackCollection(workspaceId) ||
273
- step.operation !== "POST" ||
274
- step.dictionarySyncRequired !== true
275
- )
276
- fail("INVALID_CALIBRATION_PLAN", "calibration step fields are invalid");
277
-
278
- const after = validateCalibrationSnapshot(step.after, "after", false);
279
- let before = null;
280
- if (step.before !== null) {
281
- before = validateCalibrationSnapshot(step.before, "before", true);
282
- if (
283
- normalizeCalibrationIdentity(before.originText) !==
284
- normalizeCalibrationIdentity(after.originText)
285
- )
286
- fail(
287
- "INVALID_CALIBRATION_PLAN",
288
- "calibration snapshots must share one origin identity",
289
- );
290
- }
291
-
292
- const caseIds = validateMutationCaseIds(
293
- step.caseIds,
294
- "INVALID_CALIBRATION_PLAN",
295
- );
296
- const preconditions = step.preconditions;
297
- if (
298
- !isRecord(preconditions) ||
299
- canonicalJson(Object.keys(preconditions).sort()) !==
300
- canonicalJson(["calibrationCut"])
301
- )
302
- fail(
303
- "INVALID_CALIBRATION_EVIDENCE",
304
- "calibration preconditions are invalid",
305
- );
306
- const cut = preconditions.calibrationCut;
307
- if (
308
- !isRecord(cut) ||
309
- canonicalJson(Object.keys(cut).sort()) !==
310
- canonicalJson([
311
- "expectedTextHash",
312
- "identity",
313
- "momentIdentity",
314
- "pairsHash",
315
- ]) ||
316
- cut.pairsHash !== hashValue(after.expectedTokens) ||
317
- cut.expectedTextHash !== hashValue(after.expectedText) ||
318
- typeof cut.identity !== "string" ||
319
- !cut.identity.trim() ||
320
- cut.identity !== cut.identity.trim() ||
321
- typeof cut.momentIdentity !== "string" ||
322
- !cut.momentIdentity.trim() ||
323
- cut.momentIdentity !== cut.momentIdentity.trim()
324
- )
325
- fail(
326
- "INVALID_CALIBRATION_EVIDENCE",
327
- "calibration evidence does not match the planned mutation",
328
- );
329
- return { after, before, caseIds };
330
- }
331
-
332
- export function validateCalibrationSnapshot(value, label, requireId) {
333
- if (!isRecord(value))
334
- fail("INVALID_CALIBRATION_PLAN", `calibration ${label} must be an object`);
335
- const allowed = new Set([
336
- ...(requireId ? ["id"] : []),
337
- "originText",
338
- "expectedText",
339
- "expectedTokens",
340
- "synonyms",
341
- ]);
342
- const required = [...allowed];
343
- if (
344
- Object.keys(value).some((field) => !allowed.has(field)) ||
345
- required.some((field) => !Object.hasOwn(value, field))
346
- )
347
- fail("INVALID_CALIBRATION_PLAN", `calibration ${label} fields are invalid`);
348
- if (requireId) canonicalSynonymId(value.id);
349
- const originText = boundedCalibrationText(
350
- value.originText,
351
- `${label}.originText`,
352
- CALIBRATION_ORIGIN_MAX_LENGTH,
353
- );
354
- if (originText !== value.originText)
355
- fail(
356
- "INVALID_CALIBRATION_PLAN",
357
- `calibration ${label} originText must be trimmed`,
358
- );
359
- if (label === "after") {
360
- const expectedText = boundedCalibrationText(
361
- value.expectedText,
362
- `${label}.expectedText`,
363
- CALIBRATION_EXPECTED_MAX_LENGTH,
364
- );
365
- if (expectedText !== value.expectedText)
366
- fail(
367
- "INVALID_CALIBRATION_PLAN",
368
- "calibration after expectedText must be trimmed",
369
- );
370
- } else if (
371
- value.expectedText !== null &&
372
- (typeof value.expectedText !== "string" ||
373
- value.expectedText.length > CALIBRATION_EXPECTED_MAX_LENGTH)
374
- )
375
- fail(
376
- "INVALID_CALIBRATION_PLAN",
377
- "calibration before expectedText is invalid",
378
- );
379
- validateCalibrationTokens(value.expectedTokens, label, label === "after");
380
- if (!Array.isArray(value.synonyms))
381
- fail(
382
- "INVALID_CALIBRATION_PLAN",
383
- `calibration ${label} synonyms are invalid`,
384
- );
385
- if (
386
- label === "after" &&
387
- canonicalJson(
388
- normalizeCalibrationSynonyms(
389
- value.synonyms,
390
- value.originText,
391
- "INVALID_CALIBRATION_PLAN",
392
- ),
393
- ) !== canonicalJson(value.synonyms)
394
- )
395
- fail(
396
- "INVALID_CALIBRATION_PLAN",
397
- "calibration after synonyms must use canonical server formatting",
398
- );
399
- if (
400
- label === "before" &&
401
- value.synonyms.some((synonym) => typeof synonym !== "string")
402
- )
403
- fail("INVALID_CALIBRATION_PLAN", "calibration before synonyms are invalid");
404
- return value;
405
- }
406
-
407
- export function validateCalibrationTokens(tokens, label, persistent) {
408
- if (
409
- !Array.isArray(tokens) ||
410
- tokens.length > 100 ||
411
- (persistent && tokens.length <= 1)
412
- )
413
- fail("INVALID_CALIBRATION_PLAN", `calibration ${label} tokens are invalid`);
414
- for (const token of tokens)
415
- if (
416
- !isRecord(token) ||
417
- canonicalJson(Object.keys(token).sort()) !==
418
- canonicalJson(["prop", "word"]) ||
419
- typeof token.word !== "string" ||
420
- !token.word.trim() ||
421
- typeof token.prop !== "string" ||
422
- !token.prop.trim()
423
- )
424
- fail("INVALID_CALIBRATION_PLAN", `calibration ${label} token is invalid`);
425
- }
426
-
427
- export function feedbackCollection(workspaceId) {
428
- return `/api/v2/admin-projects/${workspaceId}/feedbacks/`;
429
- }
430
-
431
- export function calibrationPossibleStates(step) {
432
- return step.before === null
433
- ? [null, withoutId(step.after)]
434
- : [withoutId(step.before), withoutId(step.after)];
435
- }
436
-
437
- export async function readCalibrationState(client, workspaceId, originText) {
438
- const rows = await listAllPages(client, feedbackCollection(workspaceId), {
439
- q: originText,
440
- });
441
- const exact = rows.filter(
442
- (row) =>
443
- typeof row?.originText === "string" &&
444
- normalizeCalibrationIdentity(row.originText) ===
445
- normalizeCalibrationIdentity(originText),
446
- );
447
- if (exact.length > 1)
448
- fail(
449
- "CALIBRATION_IDENTITY_AMBIGUOUS",
450
- "multiple feedback rows have the same case-insensitive origin identity",
451
- { originText },
452
- );
453
- return exact[0] ? semanticCalibration(exact[0]) : null;
454
- }
455
-
456
- function calibrationAuthorityTarget(operation) {
457
- const originText = boundedCalibrationText(
458
- operation.originText,
459
- "originText",
460
- CALIBRATION_ORIGIN_MAX_LENGTH,
461
- );
462
- const expectedText = boundedCalibrationText(
463
- operation.expectedText,
464
- "expectedText",
465
- CALIBRATION_EXPECTED_MAX_LENGTH,
466
- );
467
- return {
468
- expectedText,
469
- originText,
470
- synonyms: normalizeCalibrationSynonyms(operation.synonyms, originText),
471
- };
472
- }
473
-
474
- function createCalibrationCoalescer() {
475
- const groups = new Map();
476
- return {
477
- add(operation, result) {
478
- const caseId = operation.caseId.trim();
479
- const originText = boundedCalibrationText(
480
- operation.originText,
481
- "originText",
482
- CALIBRATION_ORIGIN_MAX_LENGTH,
483
- );
484
- const expectedText = boundedCalibrationText(
485
- operation.expectedText,
486
- "expectedText",
487
- CALIBRATION_EXPECTED_MAX_LENGTH,
488
- );
489
- if (
490
- operation.expectedTokens !== undefined &&
491
- !Array.isArray(operation.expectedTokens)
492
- )
493
- fail(
494
- "INVALID_CALIBRATION",
495
- "calibration expectedTokens must be an array when supplied",
496
- );
497
- const synonyms = normalizeCalibrationSynonyms(
498
- operation.synonyms,
499
- originText,
500
- );
501
- const targetKey = `calibration:${normalizeCalibrationIdentity(
502
- originText,
503
- )}`;
504
- const desiredKey = canonicalJson({ expectedText, synonyms });
505
- let group = groups.get(targetKey);
506
- if (!group) {
507
- group = {
508
- ...structuredClone(operation),
509
- caseId,
510
- originText,
511
- expectedText,
512
- synonyms,
513
- expectedTokenAssertions: [],
514
- desiredKey,
515
- caseIds: [],
516
- };
517
- delete group.expectedTokens;
518
- groups.set(targetKey, group);
519
- result.push(group);
520
- } else if (group.desiredKey !== desiredKey)
521
- fail(
522
- "CALIBRATION_CONFLICT",
523
- "one calibration origin cannot target different desired states",
524
- { originText },
525
- );
526
- group.caseIds.push(caseId);
527
- if (operation.expectedTokens !== undefined) {
528
- const assertion = structuredClone(operation.expectedTokens);
529
- if (
530
- group.expectedTokenAssertions.length > 0 &&
531
- canonicalJson(group.expectedTokenAssertions[0]) !==
532
- canonicalJson(assertion)
533
- )
534
- fail(
535
- "CALIBRATION_CONFLICT",
536
- "one calibration origin has conflicting token assertions",
537
- { originText },
538
- );
539
- group.expectedTokenAssertions.push(assertion);
540
- }
541
- return true;
542
- },
543
- };
544
- }
545
-
546
- function calibrationWriteDesired(client, step) {
547
- return client.request("POST", step.endpoint, {
548
- body: calibrationBody(step.after),
549
- });
550
- }
551
-
552
- function calibrationReadState(client, workspaceId, step) {
553
- const originText = step.after?.originText ?? step.before?.originText;
554
- return readCalibrationState(client, workspaceId, originText);
555
- }
556
-
557
- async function calibrationApplyStep(client, workspaceId, step, ctx) {
558
- const possibleAfter = calibrationPossibleStates(step);
559
- let response;
560
- try {
561
- response = await client.request("POST", step.endpoint, {
562
- body: calibrationBody(step.after),
563
- });
564
- } catch (error) {
565
- error.partialStep = ctx.partialStep(step, undefined, possibleAfter);
566
- throw error;
567
- }
568
- const completed = resolveCompletedStep(step, response);
569
- let resolved = completed;
570
- let current;
571
- try {
572
- current = await calibrationReadState(client, workspaceId, resolved);
573
- resolved = resolveCompletedStep(resolved, current);
574
- assertState(current, step.after, "WRITE_VERIFICATION_FAILED", step);
575
- } catch (error) {
576
- error.partialStep = ctx.partialStep(resolved, undefined, possibleAfter);
577
- throw error;
578
- }
579
- return { ...resolved, after: current };
580
- }
581
-
582
- async function calibrationRestoreStep(client, workspaceId, step, currentState) {
583
- const collection = feedbackCollection(workspaceId);
584
- if (currentState && statesEqual(currentState, withoutId(step.before)))
585
- return { id: currentState.id ?? step.before.id, noOp: true };
586
- const response = await client.request("POST", collection, {
587
- body: calibrationBody(step.before),
588
- });
589
- const recreated = resolveCompletedStep(
590
- { ...step, endpoint: collection, after: withoutId(step.before) },
591
- response,
592
- );
593
- const current = await calibrationReadState(client, workspaceId, recreated);
594
- assertState(
595
- current,
596
- withoutId(step.before),
597
- "ROLLBACK_VERIFICATION_FAILED",
598
- step,
599
- );
600
- return { id: step.before.id, recreatedId: current?.id };
601
- }
602
-
603
- async function calibrationExactCreatedCandidates(client, workspaceId, step) {
604
- const originText = step.after?.originText;
605
- const rows = await listAllPages(client, feedbackCollection(workspaceId), {
606
- q: originText,
607
- });
608
- return rows
609
- .filter(
610
- (row) =>
611
- normalizeText(row.originText) === normalizeText(originText),
612
- )
613
- .map(semanticCalibration);
614
- }
615
-
616
- function validateCalibrationAuthorityTarget(target) {
617
- const normalized = calibrationAuthorityTargetFromStep(target);
618
- if (
619
- canonicalJson(Object.keys(target).sort()) !==
620
- canonicalJson(["expectedText", "originText", "synonyms"]) ||
621
- canonicalJson(target) !== canonicalJson(normalized)
622
- )
623
- fail("INVALID_PLAN_STRUCTURE", "calibration authority target is invalid");
624
- }
625
-
626
- function validateCalibrationPlanStep(step, plan, authorities, plannedCaseIds, usedCaseIds) {
627
- const { after, caseIds } = validateCalibrationStepStructure(
628
- step,
629
- plan.workspaceId,
630
- );
631
- for (const caseId of caseIds)
632
- if (
633
- !matchesAuthority(
634
- authorities.get(caseId),
635
- "semantic_calibration",
636
- (target) =>
637
- target.expectedText === after.expectedText &&
638
- normalizeCalibrationIdentity(target.originText) ===
639
- normalizeCalibrationIdentity(after.originText) &&
640
- canonicalJson(target.synonyms) === canonicalJson(after.synonyms),
641
- )
642
- )
643
- fail(
644
- "INVALID_CALIBRATION_PLAN",
645
- "calibration step caseIds must match exact calibration authorities",
646
- );
647
- claimStepCaseIds(usedCaseIds, caseIds);
648
- for (const caseId of caseIds) plannedCaseIds.add(caseId);
649
- }
650
-
651
- function calibrationSummaryMatches(summary, authorityTargets) {
652
- const targets = authorityTargets.map(({ target }) => target);
653
- return targets.every(
654
- (target) =>
655
- normalizeCalibrationIdentity(summary.originText) ===
656
- normalizeCalibrationIdentity(target.originText),
657
- );
658
- }
659
-
660
- export const calibrationKind = {
661
- name: "semantic_calibration",
662
- planable: true,
663
- plan: planCalibration,
664
- authorityTarget: calibrationAuthorityTarget,
665
- createCoalescer: createCalibrationCoalescer,
666
- applyStep: calibrationApplyStep,
667
- restoreStep: calibrationRestoreStep,
668
- writeDesired: calibrationWriteDesired,
669
- readState: calibrationReadState,
670
- preApplyRead: revalidateCalibrationStep,
671
- exactCreatedCandidates: calibrationExactCreatedCandidates,
672
- collection: feedbackCollection,
673
- targetKey: (step) =>
674
- `calibration:${normalizeText(
675
- step.after?.originText ?? step.before?.originText,
676
- )}`,
677
- matchesBefore: (step, current) => statesEqual(current, withoutId(step.before)),
678
- possibleAfter: calibrationPossibleStates,
679
- validateAuthorityTarget: validateCalibrationAuthorityTarget,
680
- validateStep: validateCalibrationPlanStep,
681
- summaryField: ["originText"],
682
- summaryMatches: calibrationSummaryMatches,
683
- };
1
+ import {
2
+ canonicalJson,
3
+ hashArtifactValue as hashValue,
4
+ withoutId,
5
+ } from "../../datarc-semantic-core/scripts/canonical.mjs";
6
+ import {
7
+ assertState,
8
+ authoritiesForCaseIds,
9
+ canonicalSynonymId,
10
+ claimStepCaseIds,
11
+ compact,
12
+ fail,
13
+ hasCutAlternatives,
14
+ listAllPages,
15
+ isRecord,
16
+ listOf,
17
+ matchesAuthority,
18
+ normalizeText,
19
+ requiredText,
20
+ resolveCompletedStep,
21
+ statesEqual,
22
+ validateMutationCaseIds,
23
+ } from "../../datarc-semantic-core/scripts/shared.mjs";
24
+
25
+ const CALIBRATION_ORIGIN_MAX_LENGTH = 120;
26
+ const CALIBRATION_EXPECTED_MAX_LENGTH = 255;
27
+ const CALIBRATION_SYNONYM_MAX_LENGTH = 120;
28
+ const CALIBRATION_SYNONYM_MAX_COUNT = 100;
29
+ export async function planCalibration(client, plan, operation) {
30
+ const originText = boundedCalibrationText(
31
+ operation.originText,
32
+ "originText",
33
+ CALIBRATION_ORIGIN_MAX_LENGTH,
34
+ );
35
+ const expectedText = boundedCalibrationText(
36
+ operation.expectedText,
37
+ "expectedText",
38
+ CALIBRATION_EXPECTED_MAX_LENGTH,
39
+ );
40
+ const liveCut = await inspectCalibrationCut(
41
+ client,
42
+ plan.workspaceId,
43
+ expectedText,
44
+ );
45
+ for (const assertion of operation.expectedTokenAssertions)
46
+ if (canonicalJson(assertion) !== canonicalJson(liveCut.pairs))
47
+ fail(
48
+ "CALIBRATION_TOKEN_ASSERTION_FAILED",
49
+ "supplied expectedTokens do not exactly match the fresh ordered cut",
50
+ );
51
+ const collection = feedbackCollection(plan.workspaceId);
52
+ const rows = await listAllPages(client, collection, { q: originText });
53
+ const exact = rows.filter(
54
+ (row) =>
55
+ typeof row?.originText === "string" &&
56
+ normalizeCalibrationIdentity(row.originText) ===
57
+ normalizeCalibrationIdentity(originText),
58
+ );
59
+ if (exact.length > 1)
60
+ fail(
61
+ "CALIBRATION_IDENTITY_AMBIGUOUS",
62
+ "multiple feedback rows have the same case-insensitive origin identity",
63
+ { originText },
64
+ );
65
+ const existing = exact[0];
66
+ const before = existing ? semanticCalibration(existing) : null;
67
+ const after = {
68
+ originText,
69
+ expectedText,
70
+ expectedTokens: structuredClone(liveCut.pairs),
71
+ synonyms: structuredClone(operation.synonyms ?? []),
72
+ };
73
+ if (before !== null && statesEqual(withoutId(before), after)) {
74
+ plan.summaries.push({
75
+ kind: operation.kind,
76
+ status: "noop",
77
+ originText,
78
+ caseIds: structuredClone(operation.caseIds),
79
+ });
80
+ return;
81
+ }
82
+ plan.steps.push({
83
+ kind: operation.kind,
84
+ caseIds: structuredClone(operation.caseIds),
85
+ endpoint: collection,
86
+ operation: "POST",
87
+ before,
88
+ after,
89
+ preconditions: { calibrationCut: liveCut.evidence },
90
+ dictionarySyncRequired: true,
91
+ });
92
+ plan.summaries.push({
93
+ kind: operation.kind,
94
+ status: "planned",
95
+ originText,
96
+ caseIds: structuredClone(operation.caseIds),
97
+ });
98
+ }
99
+
100
+ export function semanticCalibration(value) {
101
+ return compact({
102
+ id: value.id,
103
+ originText: value.originText,
104
+ expectedText: value.expectedText,
105
+ expectedTokens: structuredClone(value.expectedTokens ?? []),
106
+ synonyms: structuredClone(value.synonyms ?? []),
107
+ });
108
+ }
109
+
110
+ export function calibrationBody(value) {
111
+ return compact({
112
+ originText: value.originText,
113
+ ...(value.expectedText === null
114
+ ? {}
115
+ : { expectedText: value.expectedText }),
116
+ expectedTokens: structuredClone(value.expectedTokens),
117
+ synonyms: structuredClone(value.synonyms),
118
+ });
119
+ }
120
+
121
+ export async function inspectCalibrationCut(client, workspaceId, expectedText) {
122
+ const response = await client.request(
123
+ "POST",
124
+ `/api/v3/account-projects/${workspaceId}/cut/`,
125
+ { body: { tokens: expectedText } },
126
+ );
127
+ if (
128
+ !isRecord(response) ||
129
+ Object.hasOwn(response, "status") ||
130
+ !Array.isArray(response.tokens)
131
+ )
132
+ fail(
133
+ "INVALID_CALIBRATION_CUT",
134
+ "calibration cut must return an object with a tokens array",
135
+ );
136
+ if (response.tokens.length <= 1 || response.tokens.length > 100)
137
+ fail(
138
+ "CALIBRATION_NOT_PERSISTENT",
139
+ "semantic calibration requires between two and one hundred fresh tokens",
140
+ );
141
+ const pairs = response.tokens.map((token) => {
142
+ if (
143
+ !isRecord(token) ||
144
+ typeof token.word !== "string" ||
145
+ !token.word.trim() ||
146
+ typeof token.prop !== "string" ||
147
+ !token.prop.trim() ||
148
+ (token.invalidType !== undefined && token.invalidType !== null) ||
149
+ hasCutAlternatives(token.choiceTokens) ||
150
+ hasCutAlternatives(token.guessTokens)
151
+ )
152
+ fail(
153
+ "INVALID_CALIBRATION_CUT",
154
+ "calibration cut token is invalid, ambiguous, or empty",
155
+ );
156
+ return { word: token.word, prop: token.prop };
157
+ });
158
+ return {
159
+ pairs,
160
+ evidence: {
161
+ pairsHash: hashValue(pairs),
162
+ identity: safeCalibrationCutIdentity(response.identity, "identity"),
163
+ momentIdentity: safeCalibrationCutIdentity(
164
+ response.momentIdentity,
165
+ "momentIdentity",
166
+ ),
167
+ expectedTextHash: hashValue(expectedText),
168
+ },
169
+ };
170
+ }
171
+
172
+ export function safeCalibrationCutIdentity(value, field) {
173
+ if (typeof value !== "string" || !value.trim())
174
+ fail("INVALID_CALIBRATION_CUT", `cut ${field} is required`);
175
+ return value.trim();
176
+ }
177
+
178
+ export function boundedCalibrationText(value, field, maxLength) {
179
+ if (typeof value !== "string" || !value.trim())
180
+ fail("INVALID_CALIBRATION", `${field} must be a nonempty string`);
181
+ const text = value.trim();
182
+ if (text.length > maxLength)
183
+ fail(
184
+ "INVALID_CALIBRATION",
185
+ `${field} must contain at most ${maxLength} characters`,
186
+ );
187
+ return text;
188
+ }
189
+
190
+ export function normalizeCalibrationIdentity(value) {
191
+ return String(value ?? "")
192
+ .trim()
193
+ .toLowerCase();
194
+ }
195
+
196
+ export function normalizeCalibrationSynonyms(
197
+ values,
198
+ originText,
199
+ code = "INVALID_CALIBRATION",
200
+ ) {
201
+ if (values === undefined) return [];
202
+ if (!Array.isArray(values) || values.length > CALIBRATION_SYNONYM_MAX_COUNT)
203
+ fail(code, "calibration synonyms must be an array of at most 100 items");
204
+
205
+ const origin = normalizeCalibrationIdentity(originText);
206
+ const seen = new Set();
207
+ const synonyms = [];
208
+ for (const value of values) {
209
+ if (typeof value !== "string")
210
+ fail(code, "calibration synonym must be a string");
211
+ const trimmed = value.trim();
212
+ if (!trimmed) continue;
213
+ if ([...trimmed].length > CALIBRATION_SYNONYM_MAX_LENGTH)
214
+ fail(code, "calibration synonym must contain at most 120 characters");
215
+ const synonym = trimmed.toLowerCase();
216
+ if (synonym === origin || seen.has(synonym)) continue;
217
+ seen.add(synonym);
218
+ synonyms.push(synonym);
219
+ }
220
+ return synonyms;
221
+ }
222
+
223
+ export async function revalidateCalibrationStep(client, workspaceId, step) {
224
+ const liveCut = await inspectCalibrationCut(
225
+ client,
226
+ workspaceId,
227
+ step.after.expectedText,
228
+ );
229
+ if (
230
+ canonicalJson(liveCut.pairs) !== canonicalJson(step.after.expectedTokens) ||
231
+ liveCut.evidence.pairsHash !== step.preconditions.calibrationCut.pairsHash
232
+ )
233
+ fail("CALIBRATION_CUT_DRIFT", "calibration cut changed after planning");
234
+ return readCalibrationState(client, workspaceId, step.after.originText);
235
+ }
236
+
237
+ export function calibrationAuthorityTargetFromStep(after) {
238
+ const originText = boundedCalibrationText(
239
+ after?.originText,
240
+ "authority.originText",
241
+ CALIBRATION_ORIGIN_MAX_LENGTH,
242
+ );
243
+ const expectedText = boundedCalibrationText(
244
+ after?.expectedText,
245
+ "authority.expectedText",
246
+ CALIBRATION_EXPECTED_MAX_LENGTH,
247
+ );
248
+ return {
249
+ expectedText,
250
+ originText,
251
+ synonyms: normalizeCalibrationSynonyms(
252
+ after?.synonyms,
253
+ originText,
254
+ "INVALID_PLAN_STRUCTURE",
255
+ ),
256
+ };
257
+ }
258
+
259
+ export function validateCalibrationStepStructure(step, workspaceId) {
260
+ const allowedStepFields = new Set([
261
+ "kind",
262
+ "caseIds",
263
+ "endpoint",
264
+ "operation",
265
+ "before",
266
+ "after",
267
+ "preconditions",
268
+ "dictionarySyncRequired",
269
+ ]);
270
+ if (
271
+ Object.keys(step).some((field) => !allowedStepFields.has(field)) ||
272
+ step.endpoint !== feedbackCollection(workspaceId) ||
273
+ step.operation !== "POST" ||
274
+ step.dictionarySyncRequired !== true
275
+ )
276
+ fail("INVALID_CALIBRATION_PLAN", "calibration step fields are invalid");
277
+
278
+ const after = validateCalibrationSnapshot(step.after, "after", false);
279
+ let before = null;
280
+ if (step.before !== null) {
281
+ before = validateCalibrationSnapshot(step.before, "before", true);
282
+ if (
283
+ normalizeCalibrationIdentity(before.originText) !==
284
+ normalizeCalibrationIdentity(after.originText)
285
+ )
286
+ fail(
287
+ "INVALID_CALIBRATION_PLAN",
288
+ "calibration snapshots must share one origin identity",
289
+ );
290
+ }
291
+
292
+ const caseIds = validateMutationCaseIds(
293
+ step.caseIds,
294
+ "INVALID_CALIBRATION_PLAN",
295
+ );
296
+ const preconditions = step.preconditions;
297
+ if (
298
+ !isRecord(preconditions) ||
299
+ canonicalJson(Object.keys(preconditions).sort()) !==
300
+ canonicalJson(["calibrationCut"])
301
+ )
302
+ fail(
303
+ "INVALID_CALIBRATION_EVIDENCE",
304
+ "calibration preconditions are invalid",
305
+ );
306
+ const cut = preconditions.calibrationCut;
307
+ if (
308
+ !isRecord(cut) ||
309
+ canonicalJson(Object.keys(cut).sort()) !==
310
+ canonicalJson([
311
+ "expectedTextHash",
312
+ "identity",
313
+ "momentIdentity",
314
+ "pairsHash",
315
+ ]) ||
316
+ cut.pairsHash !== hashValue(after.expectedTokens) ||
317
+ cut.expectedTextHash !== hashValue(after.expectedText) ||
318
+ typeof cut.identity !== "string" ||
319
+ !cut.identity.trim() ||
320
+ cut.identity !== cut.identity.trim() ||
321
+ typeof cut.momentIdentity !== "string" ||
322
+ !cut.momentIdentity.trim() ||
323
+ cut.momentIdentity !== cut.momentIdentity.trim()
324
+ )
325
+ fail(
326
+ "INVALID_CALIBRATION_EVIDENCE",
327
+ "calibration evidence does not match the planned mutation",
328
+ );
329
+ return { after, before, caseIds };
330
+ }
331
+
332
+ export function validateCalibrationSnapshot(value, label, requireId) {
333
+ if (!isRecord(value))
334
+ fail("INVALID_CALIBRATION_PLAN", `calibration ${label} must be an object`);
335
+ const allowed = new Set([
336
+ ...(requireId ? ["id"] : []),
337
+ "originText",
338
+ "expectedText",
339
+ "expectedTokens",
340
+ "synonyms",
341
+ ]);
342
+ const required = [...allowed];
343
+ if (
344
+ Object.keys(value).some((field) => !allowed.has(field)) ||
345
+ required.some((field) => !Object.hasOwn(value, field))
346
+ )
347
+ fail("INVALID_CALIBRATION_PLAN", `calibration ${label} fields are invalid`);
348
+ if (requireId) canonicalSynonymId(value.id);
349
+ const originText = boundedCalibrationText(
350
+ value.originText,
351
+ `${label}.originText`,
352
+ CALIBRATION_ORIGIN_MAX_LENGTH,
353
+ );
354
+ if (originText !== value.originText)
355
+ fail(
356
+ "INVALID_CALIBRATION_PLAN",
357
+ `calibration ${label} originText must be trimmed`,
358
+ );
359
+ if (label === "after") {
360
+ const expectedText = boundedCalibrationText(
361
+ value.expectedText,
362
+ `${label}.expectedText`,
363
+ CALIBRATION_EXPECTED_MAX_LENGTH,
364
+ );
365
+ if (expectedText !== value.expectedText)
366
+ fail(
367
+ "INVALID_CALIBRATION_PLAN",
368
+ "calibration after expectedText must be trimmed",
369
+ );
370
+ } else if (
371
+ value.expectedText !== null &&
372
+ (typeof value.expectedText !== "string" ||
373
+ value.expectedText.length > CALIBRATION_EXPECTED_MAX_LENGTH)
374
+ )
375
+ fail(
376
+ "INVALID_CALIBRATION_PLAN",
377
+ "calibration before expectedText is invalid",
378
+ );
379
+ validateCalibrationTokens(value.expectedTokens, label, label === "after");
380
+ if (!Array.isArray(value.synonyms))
381
+ fail(
382
+ "INVALID_CALIBRATION_PLAN",
383
+ `calibration ${label} synonyms are invalid`,
384
+ );
385
+ if (
386
+ label === "after" &&
387
+ canonicalJson(
388
+ normalizeCalibrationSynonyms(
389
+ value.synonyms,
390
+ value.originText,
391
+ "INVALID_CALIBRATION_PLAN",
392
+ ),
393
+ ) !== canonicalJson(value.synonyms)
394
+ )
395
+ fail(
396
+ "INVALID_CALIBRATION_PLAN",
397
+ "calibration after synonyms must use canonical server formatting",
398
+ );
399
+ if (
400
+ label === "before" &&
401
+ value.synonyms.some((synonym) => typeof synonym !== "string")
402
+ )
403
+ fail("INVALID_CALIBRATION_PLAN", "calibration before synonyms are invalid");
404
+ return value;
405
+ }
406
+
407
+ export function validateCalibrationTokens(tokens, label, persistent) {
408
+ if (
409
+ !Array.isArray(tokens) ||
410
+ tokens.length > 100 ||
411
+ (persistent && tokens.length <= 1)
412
+ )
413
+ fail("INVALID_CALIBRATION_PLAN", `calibration ${label} tokens are invalid`);
414
+ for (const token of tokens)
415
+ if (
416
+ !isRecord(token) ||
417
+ canonicalJson(Object.keys(token).sort()) !==
418
+ canonicalJson(["prop", "word"]) ||
419
+ typeof token.word !== "string" ||
420
+ !token.word.trim() ||
421
+ typeof token.prop !== "string" ||
422
+ !token.prop.trim()
423
+ )
424
+ fail("INVALID_CALIBRATION_PLAN", `calibration ${label} token is invalid`);
425
+ }
426
+
427
+ export function feedbackCollection(workspaceId) {
428
+ return `/api/v2/admin-projects/${workspaceId}/feedbacks/`;
429
+ }
430
+
431
+ export function calibrationPossibleStates(step) {
432
+ return step.before === null
433
+ ? [null, withoutId(step.after)]
434
+ : [withoutId(step.before), withoutId(step.after)];
435
+ }
436
+
437
+ export async function readCalibrationState(client, workspaceId, originText) {
438
+ const rows = await listAllPages(client, feedbackCollection(workspaceId), {
439
+ q: originText,
440
+ });
441
+ const exact = rows.filter(
442
+ (row) =>
443
+ typeof row?.originText === "string" &&
444
+ normalizeCalibrationIdentity(row.originText) ===
445
+ normalizeCalibrationIdentity(originText),
446
+ );
447
+ if (exact.length > 1)
448
+ fail(
449
+ "CALIBRATION_IDENTITY_AMBIGUOUS",
450
+ "multiple feedback rows have the same case-insensitive origin identity",
451
+ { originText },
452
+ );
453
+ return exact[0] ? semanticCalibration(exact[0]) : null;
454
+ }
455
+
456
+ function calibrationAuthorityTarget(operation) {
457
+ const originText = boundedCalibrationText(
458
+ operation.originText,
459
+ "originText",
460
+ CALIBRATION_ORIGIN_MAX_LENGTH,
461
+ );
462
+ const expectedText = boundedCalibrationText(
463
+ operation.expectedText,
464
+ "expectedText",
465
+ CALIBRATION_EXPECTED_MAX_LENGTH,
466
+ );
467
+ return {
468
+ expectedText,
469
+ originText,
470
+ synonyms: normalizeCalibrationSynonyms(operation.synonyms, originText),
471
+ };
472
+ }
473
+
474
+ function createCalibrationCoalescer() {
475
+ const groups = new Map();
476
+ return {
477
+ add(operation, result) {
478
+ const caseId = operation.caseId.trim();
479
+ const originText = boundedCalibrationText(
480
+ operation.originText,
481
+ "originText",
482
+ CALIBRATION_ORIGIN_MAX_LENGTH,
483
+ );
484
+ const expectedText = boundedCalibrationText(
485
+ operation.expectedText,
486
+ "expectedText",
487
+ CALIBRATION_EXPECTED_MAX_LENGTH,
488
+ );
489
+ if (
490
+ operation.expectedTokens !== undefined &&
491
+ !Array.isArray(operation.expectedTokens)
492
+ )
493
+ fail(
494
+ "INVALID_CALIBRATION",
495
+ "calibration expectedTokens must be an array when supplied",
496
+ );
497
+ const synonyms = normalizeCalibrationSynonyms(
498
+ operation.synonyms,
499
+ originText,
500
+ );
501
+ const targetKey = `calibration:${normalizeCalibrationIdentity(
502
+ originText,
503
+ )}`;
504
+ const desiredKey = canonicalJson({ expectedText, synonyms });
505
+ let group = groups.get(targetKey);
506
+ if (!group) {
507
+ group = {
508
+ ...structuredClone(operation),
509
+ caseId,
510
+ originText,
511
+ expectedText,
512
+ synonyms,
513
+ expectedTokenAssertions: [],
514
+ desiredKey,
515
+ caseIds: [],
516
+ };
517
+ delete group.expectedTokens;
518
+ groups.set(targetKey, group);
519
+ result.push(group);
520
+ } else if (group.desiredKey !== desiredKey)
521
+ fail(
522
+ "CALIBRATION_CONFLICT",
523
+ "one calibration origin cannot target different desired states",
524
+ { originText },
525
+ );
526
+ group.caseIds.push(caseId);
527
+ if (operation.expectedTokens !== undefined) {
528
+ const assertion = structuredClone(operation.expectedTokens);
529
+ if (
530
+ group.expectedTokenAssertions.length > 0 &&
531
+ canonicalJson(group.expectedTokenAssertions[0]) !==
532
+ canonicalJson(assertion)
533
+ )
534
+ fail(
535
+ "CALIBRATION_CONFLICT",
536
+ "one calibration origin has conflicting token assertions",
537
+ { originText },
538
+ );
539
+ group.expectedTokenAssertions.push(assertion);
540
+ }
541
+ return true;
542
+ },
543
+ };
544
+ }
545
+
546
+ function calibrationWriteDesired(client, step) {
547
+ return client.request("POST", step.endpoint, {
548
+ body: calibrationBody(step.after),
549
+ });
550
+ }
551
+
552
+ function calibrationReadState(client, workspaceId, step) {
553
+ const originText = step.after?.originText ?? step.before?.originText;
554
+ return readCalibrationState(client, workspaceId, originText);
555
+ }
556
+
557
+ async function calibrationApplyStep(client, workspaceId, step, ctx) {
558
+ const possibleAfter = calibrationPossibleStates(step);
559
+ let response;
560
+ try {
561
+ response = await client.request("POST", step.endpoint, {
562
+ body: calibrationBody(step.after),
563
+ });
564
+ } catch (error) {
565
+ error.partialStep = ctx.partialStep(step, undefined, possibleAfter);
566
+ throw error;
567
+ }
568
+ const completed = resolveCompletedStep(step, response);
569
+ let resolved = completed;
570
+ let current;
571
+ try {
572
+ current = await calibrationReadState(client, workspaceId, resolved);
573
+ resolved = resolveCompletedStep(resolved, current);
574
+ assertState(current, step.after, "WRITE_VERIFICATION_FAILED", step);
575
+ } catch (error) {
576
+ error.partialStep = ctx.partialStep(resolved, undefined, possibleAfter);
577
+ throw error;
578
+ }
579
+ return { ...resolved, after: current };
580
+ }
581
+
582
+ async function calibrationRestoreStep(client, workspaceId, step, currentState) {
583
+ const collection = feedbackCollection(workspaceId);
584
+ if (currentState && statesEqual(currentState, withoutId(step.before)))
585
+ return { id: currentState.id ?? step.before.id, noOp: true };
586
+ const response = await client.request("POST", collection, {
587
+ body: calibrationBody(step.before),
588
+ });
589
+ const recreated = resolveCompletedStep(
590
+ { ...step, endpoint: collection, after: withoutId(step.before) },
591
+ response,
592
+ );
593
+ const current = await calibrationReadState(client, workspaceId, recreated);
594
+ assertState(
595
+ current,
596
+ withoutId(step.before),
597
+ "ROLLBACK_VERIFICATION_FAILED",
598
+ step,
599
+ );
600
+ return { id: step.before.id, recreatedId: current?.id };
601
+ }
602
+
603
+ async function calibrationExactCreatedCandidates(client, workspaceId, step) {
604
+ const originText = step.after?.originText;
605
+ const rows = await listAllPages(client, feedbackCollection(workspaceId), {
606
+ q: originText,
607
+ });
608
+ return rows
609
+ .filter(
610
+ (row) =>
611
+ normalizeText(row.originText) === normalizeText(originText),
612
+ )
613
+ .map(semanticCalibration);
614
+ }
615
+
616
+ function validateCalibrationAuthorityTarget(target) {
617
+ const normalized = calibrationAuthorityTargetFromStep(target);
618
+ if (
619
+ canonicalJson(Object.keys(target).sort()) !==
620
+ canonicalJson(["expectedText", "originText", "synonyms"]) ||
621
+ canonicalJson(target) !== canonicalJson(normalized)
622
+ )
623
+ fail("INVALID_PLAN_STRUCTURE", "calibration authority target is invalid");
624
+ }
625
+
626
+ function validateCalibrationPlanStep(step, plan, authorities, plannedCaseIds, usedCaseIds) {
627
+ const { after, caseIds } = validateCalibrationStepStructure(
628
+ step,
629
+ plan.workspaceId,
630
+ );
631
+ for (const caseId of caseIds)
632
+ if (
633
+ !matchesAuthority(
634
+ authorities.get(caseId),
635
+ "semantic_calibration",
636
+ (target) =>
637
+ target.expectedText === after.expectedText &&
638
+ normalizeCalibrationIdentity(target.originText) ===
639
+ normalizeCalibrationIdentity(after.originText) &&
640
+ canonicalJson(target.synonyms) === canonicalJson(after.synonyms),
641
+ )
642
+ )
643
+ fail(
644
+ "INVALID_CALIBRATION_PLAN",
645
+ "calibration step caseIds must match exact calibration authorities",
646
+ );
647
+ claimStepCaseIds(usedCaseIds, caseIds);
648
+ for (const caseId of caseIds) plannedCaseIds.add(caseId);
649
+ }
650
+
651
+ function calibrationSummaryMatches(summary, authorityTargets) {
652
+ const targets = authorityTargets.map(({ target }) => target);
653
+ return targets.every(
654
+ (target) =>
655
+ normalizeCalibrationIdentity(summary.originText) ===
656
+ normalizeCalibrationIdentity(target.originText),
657
+ );
658
+ }
659
+
660
+ export const calibrationKind = {
661
+ name: "semantic_calibration",
662
+ planable: true,
663
+ plan: planCalibration,
664
+ authorityTarget: calibrationAuthorityTarget,
665
+ createCoalescer: createCalibrationCoalescer,
666
+ applyStep: calibrationApplyStep,
667
+ restoreStep: calibrationRestoreStep,
668
+ writeDesired: calibrationWriteDesired,
669
+ readState: calibrationReadState,
670
+ preApplyRead: revalidateCalibrationStep,
671
+ exactCreatedCandidates: calibrationExactCreatedCandidates,
672
+ collection: feedbackCollection,
673
+ targetKey: (step) =>
674
+ `calibration:${normalizeText(
675
+ step.after?.originText ?? step.before?.originText,
676
+ )}`,
677
+ matchesBefore: (step, current) => statesEqual(current, withoutId(step.before)),
678
+ possibleAfter: calibrationPossibleStates,
679
+ validateAuthorityTarget: validateCalibrationAuthorityTarget,
680
+ validateStep: validateCalibrationPlanStep,
681
+ summaryField: ["originText"],
682
+ summaryMatches: calibrationSummaryMatches,
683
+ };