@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,688 +1,688 @@
1
- import {
2
- canonicalJson,
3
- hashArtifactValue as hashValue,
4
- } from "../../datarc-semantic-core/scripts/canonical.mjs";
5
- import {
6
- authoritiesForCaseIds,
7
- canonicalSynonymId,
8
- claimStepCaseIds,
9
- compact,
10
- fail,
11
- hasCutAlternatives,
12
- isRecord,
13
- isServerChineseCharacter,
14
- normalizeServerWord,
15
- normalizeText,
16
- requiredText,
17
- validateMutationCaseIds,
18
- } from "../../datarc-semantic-core/scripts/shared.mjs";
19
-
20
- const DIMENSION_VALUE_PROP = /^d[1-9]\d*=[0-9A-Za-z+/-]+$/;
21
- const SYNONYM_MAX_LENGTH = 32;
22
- const RESERVED_SPACE = "Ὦ";
23
- export async function planSynonym(client, plan, operation) {
24
- const word = operation.word;
25
- const proposed = structuredClone(operation.synonyms);
26
- const canonicalCut = await inspectCanonicalSynonymCut(
27
- client,
28
- plan.workspaceId,
29
- word,
30
- );
31
- const candidateStates = new Map();
32
- for (const synonym of proposed)
33
- candidateStates.set(
34
- synonym,
35
- await inspectProposedSynonymCut(
36
- client,
37
- plan.workspaceId,
38
- synonym,
39
- canonicalCut.prop,
40
- ),
41
- );
42
-
43
- const { existing, ownerBySynonym } = await inspectSynonymOwnership(
44
- client,
45
- plan.workspaceId,
46
- word,
47
- proposed,
48
- );
49
-
50
- const before = existing ? semanticSynonym(existing) : null;
51
- const synonyms = before?.synonyms ?? [];
52
- const additions = proposed.filter(
53
- (synonym) =>
54
- candidateStates.get(synonym) === "unresolved" &&
55
- ownerBySynonym.get(synonym) === null &&
56
- !synonyms.some((value) => normalizeServerWord(value) === synonym),
57
- );
58
- bindSynonymAuthorityAdditions(plan.authorities, operation.caseIds, additions);
59
- if (additions.length === 0) {
60
- plan.summaries.push({
61
- kind: operation.kind,
62
- status: "noop",
63
- word,
64
- caseIds: structuredClone(operation.caseIds),
65
- });
66
- return;
67
- }
68
- const collection = synonymCollection(plan.workspaceId);
69
- plan.steps.push({
70
- kind: operation.kind,
71
- caseIds: structuredClone(operation.caseIds),
72
- endpoint: existing ? `${collection}${existing.id}/` : collection,
73
- operation: existing ? "PUT" : "POST",
74
- before,
75
- after: {
76
- ...(existing ? { id: existing.id } : {}),
77
- word,
78
- synonyms: [...synonyms, ...additions],
79
- },
80
- preconditions: {
81
- canonicalCut: canonicalCut.evidence,
82
- ownerHash: synonymOwnerHash(before, additions),
83
- },
84
- dictionarySyncRequired: true,
85
- requiresContrast: proposed.some(
86
- (synonym) => candidateStates.get(synonym) === "unresolved",
87
- ),
88
- });
89
- plan.summaries.push({
90
- kind: operation.kind,
91
- status: "planned",
92
- word,
93
- caseIds: structuredClone(operation.caseIds),
94
- });
95
- }
96
-
97
- export function bindSynonymAuthorityAdditions(authorities, caseIds, additions) {
98
- const additionSet = new Set(additions);
99
- const authorityByCaseId = new Map(
100
- authorities.map((authority) => [authority.caseId, authority]),
101
- );
102
- for (const caseId of caseIds) {
103
- const authority = authorityByCaseId.get(caseId);
104
- if (authority?.kind !== "dimension_value_synonym")
105
- fail(
106
- "INVALID_PLAN_STRUCTURE",
107
- "synonym operation is missing its case authority",
108
- );
109
- authority.target.additions = authority.target.synonyms.filter((synonym) =>
110
- additionSet.has(synonym),
111
- );
112
- }
113
- }
114
-
115
- export function semanticSynonym(value) {
116
- return compact({
117
- id: value.id,
118
- word: value.word,
119
- synonyms: structuredClone(value.synonyms ?? []),
120
- });
121
- }
122
-
123
- export function proposedSynonyms(operation, canonicalWord) {
124
- const values = [];
125
- if (operation.synonym !== undefined) values.push(operation.synonym);
126
- if (operation.synonyms !== undefined) {
127
- if (!Array.isArray(operation.synonyms))
128
- fail("INVALID_SYNONYM", "synonyms must be an array");
129
- values.push(...operation.synonyms);
130
- }
131
- if (values.length === 0)
132
- fail("INVALID_SYNONYM", "at least one synonym is required");
133
-
134
- const seen = new Set();
135
- const result = [];
136
- for (const value of values) {
137
- const synonym = normalizeProposedSynonym(value);
138
- if (synonym === canonicalWord || seen.has(synonym)) continue;
139
- seen.add(synonym);
140
- result.push(synonym);
141
- }
142
- return result;
143
- }
144
-
145
- export function normalizeProposedSynonym(value) {
146
- if (typeof value !== "string")
147
- fail("INVALID_SYNONYM", "synonym must be a string");
148
- const word = value.trim();
149
- if (!word || word.length > SYNONYM_MAX_LENGTH)
150
- fail("INVALID_SYNONYM", "synonym length is invalid");
151
- const pureDigits = /^\p{Decimal_Number}+$/u.test(word);
152
- if (pureDigits && word.length < 6)
153
- fail("INVALID_SYNONYM", "numeric synonyms require at least six digits");
154
-
155
- let hasLetterOrChinese = false;
156
- for (const character of word) {
157
- const asciiLetter = /^[A-Za-z]$/.test(character);
158
- const allowedAscii = /^[A-Za-z0-9/\\_.+\- ]$/.test(character);
159
- const chinese = isServerChineseCharacter(character);
160
- if (!allowedAscii && character !== RESERVED_SPACE && !chinese)
161
- fail("INVALID_SYNONYM", "synonym contains an invalid character");
162
- if (asciiLetter || chinese) hasLetterOrChinese = true;
163
- }
164
- if (!pureDigits && !hasLetterOrChinese)
165
- fail("INVALID_SYNONYM", "synonym requires a letter or Chinese character");
166
- return normalizeServerWord(word);
167
- }
168
-
169
- export async function inspectCanonicalSynonymCut(client, workspaceId, word) {
170
- const response = await requestSynonymCut(client, workspaceId, word);
171
- if (response.tokens.length !== 1)
172
- fail(
173
- "INVALID_SYNONYM_CUT",
174
- "canonical word must resolve to one dimension value",
175
- );
176
- const token = response.tokens[0];
177
- assertCertainCutToken(token, word);
178
- if (!DIMENSION_VALUE_PROP.test(token.prop))
179
- fail(
180
- "INVALID_SYNONYM_CUT",
181
- "canonical word did not resolve to a dimension value",
182
- );
183
- const identity = safeCutIdentity(response.identity, "identity");
184
- const momentIdentity = safeCutIdentity(
185
- response.momentIdentity,
186
- "momentIdentity",
187
- );
188
- const pairs = [{ word, prop: token.prop }];
189
- return {
190
- prop: token.prop,
191
- evidence: {
192
- prop: token.prop,
193
- pairsHash: hashValue(pairs),
194
- identity,
195
- momentIdentity,
196
- },
197
- };
198
- }
199
-
200
- export async function inspectProposedSynonymCut(
201
- client,
202
- workspaceId,
203
- word,
204
- canonicalProp,
205
- ) {
206
- const response = await requestSynonymCut(client, workspaceId, word);
207
- if (response.tokens.length === 0) return "unresolved";
208
- if (response.tokens.length !== 1)
209
- fail("INVALID_SYNONYM_CUT", "synonym cut returned multiple tokens");
210
- const token = response.tokens[0];
211
- assertCertainCutToken(token, word);
212
- if (
213
- token.prop === null ||
214
- token.prop === undefined ||
215
- token.prop === "unknown"
216
- )
217
- return "unresolved";
218
- if (token.prop === canonicalProp) return "canonical";
219
- fail("SYNONYM_CUT_CONFLICT", "synonym resolves to another semantic prop");
220
- }
221
-
222
- export async function requestSynonymCut(client, workspaceId, word) {
223
- const response = await client.request(
224
- "POST",
225
- `/api/v3/account-projects/${workspaceId}/cut/`,
226
- { body: { tokens: word } },
227
- );
228
- if (
229
- !isRecord(response) ||
230
- (response.status !== undefined && response.status !== "SUCCESS") ||
231
- !Array.isArray(response.tokens)
232
- )
233
- fail(
234
- "INVALID_SYNONYM_CUT",
235
- "cut must return an object with a tokens array",
236
- );
237
- return response;
238
- }
239
-
240
- export function assertCertainCutToken(token, expectedWord) {
241
- if (
242
- !isRecord(token) ||
243
- normalizeServerWord(token.word) !== expectedWord ||
244
- (token.invalidType !== undefined && token.invalidType !== null) ||
245
- hasCutAlternatives(token.choiceTokens) ||
246
- hasCutAlternatives(token.guessTokens)
247
- )
248
- fail(
249
- "INVALID_SYNONYM_CUT",
250
- "cut token is invalid, ambiguous, or belongs to another word",
251
- );
252
- }
253
-
254
- export function safeCutIdentity(value, field) {
255
- if (typeof value !== "string" || !value.trim())
256
- fail("INVALID_SYNONYM_CUT", `cut ${field} is required`);
257
- return value.trim();
258
- }
259
-
260
- export async function listAllSynonymPages(client, path, q) {
261
- const rows = [];
262
- const limit = 100;
263
- for (let offset = 0; ; offset += limit) {
264
- const page = await client.request("GET", path, {
265
- query: { q, offset, limit },
266
- });
267
- if (!Array.isArray(page))
268
- fail(
269
- "INVALID_SYNONYM_OWNER_STATE",
270
- "synonym lookup must return an array",
271
- );
272
- for (const row of page) {
273
- if (
274
- !isRecord(row) ||
275
- row.id === undefined ||
276
- typeof row.word !== "string" ||
277
- !Array.isArray(row.synonyms) ||
278
- row.synonyms.some((value) => typeof value !== "string")
279
- )
280
- fail(
281
- "INVALID_SYNONYM_OWNER_STATE",
282
- "synonym lookup returned a malformed row",
283
- );
284
- rows.push(row);
285
- }
286
- if (page.length < limit) return rows;
287
- }
288
- }
289
-
290
- export async function inspectSynonymOwnership(
291
- client,
292
- workspaceId,
293
- canonicalWord,
294
- synonyms,
295
- ) {
296
- const collection = synonymCollection(workspaceId);
297
- const canonicalOwners = exactSynonymOwners(
298
- await listAllSynonymPages(client, collection, canonicalWord),
299
- canonicalWord,
300
- );
301
- if (canonicalOwners.length > 1)
302
- fail(
303
- "SYNONYM_OWNER_CONFLICT",
304
- "multiple synonym rows own the canonical word",
305
- );
306
- const existing = canonicalOwners[0];
307
- if (existing && normalizeServerWord(existing.word) !== canonicalWord)
308
- fail(
309
- "SYNONYM_OWNER_CONFLICT",
310
- "the canonical word is a synonym of another row",
311
- );
312
-
313
- const ownerBySynonym = new Map();
314
- for (const synonym of synonyms) {
315
- const owners = exactSynonymOwners(
316
- await listAllSynonymPages(client, collection, synonym),
317
- synonym,
318
- );
319
- if (owners.length > 1)
320
- fail("SYNONYM_OWNER_CONFLICT", "a synonym is owned by multiple rows");
321
- const owner = owners[0];
322
- if (owner && normalizeServerWord(owner.word) !== canonicalWord)
323
- fail(
324
- "SYNONYM_OWNER_CONFLICT",
325
- "a synonym belongs to another canonical word",
326
- );
327
- if (owner && (!existing || String(owner.id) !== String(existing.id)))
328
- fail(
329
- "SYNONYM_OWNER_CONFLICT",
330
- "canonical synonym ownership is inconsistent",
331
- );
332
- ownerBySynonym.set(synonym, owner ?? null);
333
- }
334
- return { existing, ownerBySynonym };
335
- }
336
-
337
- export function exactSynonymOwners(rows, word) {
338
- return rows.filter(
339
- (row) =>
340
- normalizeServerWord(row.word) === word ||
341
- row.synonyms.some((value) => normalizeServerWord(value) === word),
342
- );
343
- }
344
-
345
- export function synonymOwnerHash(before, additions) {
346
- return hashValue({
347
- canonical: before,
348
- additions: additions.map((word) => ({ word, owner: null })),
349
- });
350
- }
351
-
352
- export async function revalidateSynonymStep(client, workspaceId, step) {
353
- const { additions, word } = validateSynonymStepStructure(step, workspaceId);
354
- const expectedCut = step.preconditions.canonicalCut;
355
- const freshCut = await inspectCanonicalSynonymCut(client, workspaceId, word);
356
- if (
357
- freshCut.prop !== expectedCut.prop ||
358
- freshCut.evidence.pairsHash !== expectedCut.pairsHash
359
- )
360
- fail("SYNONYM_CUT_DRIFT", "canonical synonym cut changed after planning");
361
- for (const synonym of additions) {
362
- const state = await inspectProposedSynonymCut(
363
- client,
364
- workspaceId,
365
- synonym,
366
- expectedCut.prop,
367
- );
368
- if (state !== "unresolved")
369
- fail("SYNONYM_CUT_DRIFT", "a planned synonym now resolves semantically", {
370
- synonym,
371
- });
372
- }
373
-
374
- const { existing, ownerBySynonym } = await inspectSynonymOwnership(
375
- client,
376
- workspaceId,
377
- word,
378
- additions,
379
- );
380
- if (additions.some((synonym) => ownerBySynonym.get(synonym) !== null))
381
- fail(
382
- "SYNONYM_OWNER_DRIFT",
383
- "a planned synonym acquired an owner after planning",
384
- );
385
- const current = existing ? semanticSynonym(existing) : null;
386
- if (synonymOwnerHash(current, additions) !== step.preconditions.ownerHash)
387
- fail(
388
- "SYNONYM_OWNER_DRIFT",
389
- "canonical synonym ownership changed after planning",
390
- );
391
- return current;
392
- }
393
-
394
- export function validateAuthoritySynonymList(values, canonicalWord) {
395
- if (!Array.isArray(values))
396
- fail("INVALID_PLAN_STRUCTURE", "synonym authority list is invalid");
397
- const seen = new Set();
398
- const normalized = [];
399
- for (const value of values) {
400
- const synonym = normalizeProposedSynonym(value);
401
- if (synonym === canonicalWord || synonym !== value || seen.has(synonym))
402
- fail("INVALID_PLAN_STRUCTURE", "synonym authority list is invalid");
403
- seen.add(synonym);
404
- normalized.push(synonym);
405
- }
406
- return normalized;
407
- }
408
-
409
- export function validateSynonymStepStructure(step, workspaceId) {
410
- const collection = synonymCollection(workspaceId);
411
- const allowedStepFields = new Set([
412
- "kind",
413
- "caseIds",
414
- "endpoint",
415
- "operation",
416
- "before",
417
- "after",
418
- "preconditions",
419
- "dictionarySyncRequired",
420
- "requiresContrast",
421
- ]);
422
- if (
423
- Object.keys(step).some((field) => !allowedStepFields.has(field)) ||
424
- step.dictionarySyncRequired !== true
425
- )
426
- fail("INVALID_SYNONYM_PLAN", "synonym step fields are invalid");
427
-
428
- const after = validateSynonymSnapshot(step.after, "after");
429
- const word = after.word;
430
- let before = null;
431
- if (step.operation === "POST") {
432
- if (
433
- step.before !== null ||
434
- after.id !== undefined ||
435
- step.endpoint !== collection
436
- )
437
- fail(
438
- "INVALID_SYNONYM_PLAN",
439
- "synonym POST must create from the collection",
440
- );
441
- } else if (step.operation === "PUT") {
442
- before = validateSynonymSnapshot(step.before, "before");
443
- const beforeId = canonicalSynonymId(before.id);
444
- const afterId = canonicalSynonymId(after.id);
445
- if (
446
- beforeId !== afterId ||
447
- step.endpoint !== `${collection}${beforeId}/` ||
448
- before.word !== word
449
- )
450
- fail(
451
- "INVALID_SYNONYM_PLAN",
452
- "synonym PUT identity does not match its snapshots",
453
- );
454
- } else fail("INVALID_SYNONYM_PLAN", "synonym operation is invalid");
455
-
456
- const beforeSynonyms = before?.synonyms ?? [];
457
- if (
458
- after.synonyms.length <= beforeSynonyms.length ||
459
- canonicalJson(after.synonyms.slice(0, beforeSynonyms.length)) !==
460
- canonicalJson(beforeSynonyms)
461
- )
462
- fail(
463
- "INVALID_SYNONYM_PLAN",
464
- "synonym steps must preserve the existing ordered prefix",
465
- );
466
- const seen = new Set();
467
- for (const synonym of after.synonyms) {
468
- const normalized = normalizeProposedSynonym(synonym);
469
- if (normalized !== synonym || synonym === word || seen.has(normalized))
470
- fail(
471
- "INVALID_SYNONYM_PLAN",
472
- "synonym values must be normalized, unique, and non-canonical",
473
- );
474
- seen.add(normalized);
475
- }
476
- const additions = after.synonyms.slice(beforeSynonyms.length);
477
-
478
- const caseIds = validateMutationCaseIds(step.caseIds, "INVALID_SYNONYM_PLAN");
479
- const preconditions = step.preconditions;
480
- if (
481
- !isRecord(preconditions) ||
482
- canonicalJson(Object.keys(preconditions).sort()) !==
483
- canonicalJson(["canonicalCut", "ownerHash"])
484
- )
485
- fail("INVALID_SYNONYM_EVIDENCE", "synonym preconditions are invalid");
486
- const cut = preconditions.canonicalCut;
487
- if (
488
- !isRecord(cut) ||
489
- !DIMENSION_VALUE_PROP.test(cut.prop) ||
490
- cut.pairsHash !== hashValue([{ word, prop: cut.prop }]) ||
491
- typeof cut.identity !== "string" ||
492
- !cut.identity.trim() ||
493
- cut.identity !== cut.identity.trim() ||
494
- typeof cut.momentIdentity !== "string" ||
495
- !cut.momentIdentity.trim() ||
496
- cut.momentIdentity !== cut.momentIdentity.trim() ||
497
- preconditions.ownerHash !== synonymOwnerHash(before, additions)
498
- )
499
- fail(
500
- "INVALID_SYNONYM_EVIDENCE",
501
- "synonym evidence does not match the planned mutation",
502
- );
503
- return { additions, after, before, caseIds, word };
504
- }
505
-
506
- export function validateSynonymSnapshot(value, label) {
507
- if (!isRecord(value))
508
- fail("INVALID_SYNONYM_PLAN", `synonym ${label} must be an object`);
509
- const allowed = new Set(["id", "word", "synonyms"]);
510
- if (
511
- Object.keys(value).some((field) => !allowed.has(field)) ||
512
- typeof value.word !== "string" ||
513
- !value.word ||
514
- normalizeServerWord(value.word) !== value.word ||
515
- !Array.isArray(value.synonyms)
516
- )
517
- fail("INVALID_SYNONYM_PLAN", `synonym ${label} snapshot is invalid`);
518
- return value;
519
- }
520
-
521
- export function synonymCollection(workspaceId) {
522
- return `/api/v2/admin-projects/${workspaceId}/synonym-words/`;
523
- }
524
-
525
- function synonymAuthorityTarget(operation) {
526
- const word = normalizeServerWord(requiredText(operation.word, "word"));
527
- return { additions: [], word, synonyms: proposedSynonyms(operation, word) };
528
- }
529
-
530
- function createSynonymCoalescer() {
531
- const groups = new Map();
532
- const targets = new Map();
533
- return {
534
- add(operation, result) {
535
- const caseId = operation.caseId.trim();
536
- const word = normalizeServerWord(requiredText(operation.word, "word"));
537
- const synonyms = proposedSynonyms(operation, word);
538
- const targetKey = `synonym:${word}`;
539
- for (const synonym of synonyms) {
540
- const previousTarget = targets.get(synonym);
541
- if (previousTarget !== undefined && previousTarget !== targetKey)
542
- fail(
543
- "SYNONYM_CONFLICT",
544
- "the synonym targets more than one canonical word",
545
- { synonym },
546
- );
547
- targets.set(synonym, targetKey);
548
- }
549
-
550
- let group = groups.get(targetKey);
551
- if (!group) {
552
- group = {
553
- ...structuredClone(operation),
554
- caseId,
555
- word,
556
- synonyms: [],
557
- caseIds: [],
558
- };
559
- delete group.synonym;
560
- delete group.canonicalEvidence;
561
- groups.set(targetKey, group);
562
- result.push(group);
563
- }
564
- group.caseIds.push(caseId);
565
- for (const synonym of synonyms)
566
- if (!group.synonyms.includes(synonym)) group.synonyms.push(synonym);
567
- return true;
568
- },
569
- };
570
- }
571
-
572
- function synonymWriteDesired(client, step) {
573
- return client.request(step.operation, step.endpoint, {
574
- body: { word: step.after.word, synonyms: step.after.synonyms },
575
- });
576
- }
577
-
578
- function synonymWriteBefore(client, step) {
579
- return client.request("PUT", step.endpoint, {
580
- body: { word: step.before.word, synonyms: step.before.synonyms },
581
- });
582
- }
583
-
584
- async function synonymReadState(client, workspaceId, step) {
585
- const word = step.after?.word ?? step.before?.word;
586
- const normalizedWord = normalizeServerWord(word);
587
- const rows = await listAllSynonymPages(
588
- client,
589
- synonymCollection(workspaceId),
590
- normalizedWord,
591
- );
592
- const id = step.after?.id ?? step.before?.id;
593
- const row =
594
- id === undefined
595
- ? exactSynonymOwners(rows, normalizedWord)[0]
596
- : rows.find((item) => String(item.id) === String(id));
597
- return row ? semanticSynonym(row) : null;
598
- }
599
-
600
- export async function synonymExactCreatedCandidates(client, workspaceId, step) {
601
- const word = step.after?.word;
602
- const rows = await listAllSynonymPages(
603
- client,
604
- synonymCollection(workspaceId),
605
- word,
606
- );
607
- return rows
608
- .filter((row) => normalizeText(row.word) === normalizeText(word))
609
- .map(semanticSynonym);
610
- }
611
-
612
- function validateSynonymAuthorityTarget(target) {
613
- const word = normalizeServerWord(
614
- requiredText(target.word, "authority.word"),
615
- );
616
- const synonyms = validateAuthoritySynonymList(target.synonyms, word);
617
- const additions = validateAuthoritySynonymList(target.additions, word);
618
- if (
619
- canonicalJson(Object.keys(target).sort()) !==
620
- canonicalJson(["additions", "synonyms", "word"]) ||
621
- target.word !== word ||
622
- canonicalJson(target.synonyms) !== canonicalJson(synonyms) ||
623
- canonicalJson(target.additions) !== canonicalJson(additions) ||
624
- additions.some((synonym) => !synonyms.includes(synonym))
625
- )
626
- fail("INVALID_PLAN_STRUCTURE", "synonym authority target is invalid");
627
- }
628
-
629
- function validateSynonymPlanStep(step, plan, authorities, plannedCaseIds, usedCaseIds) {
630
- const { after, caseIds, word } = validateSynonymStepStructure(
631
- step,
632
- plan.workspaceId,
633
- );
634
- const stepAuthorities = authoritiesForCaseIds(
635
- authorities,
636
- caseIds,
637
- "dimension_value_synonym",
638
- "INVALID_SYNONYM_PLAN",
639
- );
640
- const expectedAdditions = [];
641
- const expectedSet = new Set();
642
- for (const { target } of stepAuthorities) {
643
- if (target.word !== word)
644
- fail(
645
- "INVALID_SYNONYM_PLAN",
646
- "synonym step caseIds must match exact synonym authorities",
647
- );
648
- for (const synonym of target.additions)
649
- if (!expectedSet.has(synonym)) {
650
- expectedSet.add(synonym);
651
- expectedAdditions.push(synonym);
652
- }
653
- }
654
- const beforeLength = step.before?.synonyms?.length ?? 0;
655
- const actualAdditions = after.synonyms.slice(beforeLength);
656
- if (canonicalJson(actualAdditions) !== canonicalJson(expectedAdditions))
657
- fail(
658
- "INVALID_SYNONYM_PLAN",
659
- "synonym step additions must exactly match case authorities",
660
- );
661
- claimStepCaseIds(usedCaseIds, caseIds);
662
- for (const caseId of caseIds) plannedCaseIds.add(caseId);
663
- }
664
-
665
- function synonymSummaryMatches(summary, authorityTargets) {
666
- const targets = authorityTargets.map(({ target }) => target);
667
- return targets.every((target) => summary.word === target.word);
668
- }
669
-
670
- export const synonymKind = {
671
- name: "dimension_value_synonym",
672
- planable: true,
673
- plan: planSynonym,
674
- authorityTarget: synonymAuthorityTarget,
675
- createCoalescer: createSynonymCoalescer,
676
- writeDesired: synonymWriteDesired,
677
- writeBefore: synonymWriteBefore,
678
- readState: synonymReadState,
679
- preApplyRead: revalidateSynonymStep,
680
- exactCreatedCandidates: synonymExactCreatedCandidates,
681
- collection: synonymCollection,
682
- targetKey: (step) =>
683
- `synonym:${normalizeServerWord(step.after?.word ?? step.before?.word)}`,
684
- validateAuthorityTarget: validateSynonymAuthorityTarget,
685
- validateStep: validateSynonymPlanStep,
686
- summaryField: ["word"],
687
- summaryMatches: synonymSummaryMatches,
688
- };
1
+ import {
2
+ canonicalJson,
3
+ hashArtifactValue as hashValue,
4
+ } from "../../datarc-semantic-core/scripts/canonical.mjs";
5
+ import {
6
+ authoritiesForCaseIds,
7
+ canonicalSynonymId,
8
+ claimStepCaseIds,
9
+ compact,
10
+ fail,
11
+ hasCutAlternatives,
12
+ isRecord,
13
+ isServerChineseCharacter,
14
+ normalizeServerWord,
15
+ normalizeText,
16
+ requiredText,
17
+ validateMutationCaseIds,
18
+ } from "../../datarc-semantic-core/scripts/shared.mjs";
19
+
20
+ const DIMENSION_VALUE_PROP = /^d[1-9]\d*=[0-9A-Za-z+/-]+$/;
21
+ const SYNONYM_MAX_LENGTH = 32;
22
+ const RESERVED_SPACE = "Ὦ";
23
+ export async function planSynonym(client, plan, operation) {
24
+ const word = operation.word;
25
+ const proposed = structuredClone(operation.synonyms);
26
+ const canonicalCut = await inspectCanonicalSynonymCut(
27
+ client,
28
+ plan.workspaceId,
29
+ word,
30
+ );
31
+ const candidateStates = new Map();
32
+ for (const synonym of proposed)
33
+ candidateStates.set(
34
+ synonym,
35
+ await inspectProposedSynonymCut(
36
+ client,
37
+ plan.workspaceId,
38
+ synonym,
39
+ canonicalCut.prop,
40
+ ),
41
+ );
42
+
43
+ const { existing, ownerBySynonym } = await inspectSynonymOwnership(
44
+ client,
45
+ plan.workspaceId,
46
+ word,
47
+ proposed,
48
+ );
49
+
50
+ const before = existing ? semanticSynonym(existing) : null;
51
+ const synonyms = before?.synonyms ?? [];
52
+ const additions = proposed.filter(
53
+ (synonym) =>
54
+ candidateStates.get(synonym) === "unresolved" &&
55
+ ownerBySynonym.get(synonym) === null &&
56
+ !synonyms.some((value) => normalizeServerWord(value) === synonym),
57
+ );
58
+ bindSynonymAuthorityAdditions(plan.authorities, operation.caseIds, additions);
59
+ if (additions.length === 0) {
60
+ plan.summaries.push({
61
+ kind: operation.kind,
62
+ status: "noop",
63
+ word,
64
+ caseIds: structuredClone(operation.caseIds),
65
+ });
66
+ return;
67
+ }
68
+ const collection = synonymCollection(plan.workspaceId);
69
+ plan.steps.push({
70
+ kind: operation.kind,
71
+ caseIds: structuredClone(operation.caseIds),
72
+ endpoint: existing ? `${collection}${existing.id}/` : collection,
73
+ operation: existing ? "PUT" : "POST",
74
+ before,
75
+ after: {
76
+ ...(existing ? { id: existing.id } : {}),
77
+ word,
78
+ synonyms: [...synonyms, ...additions],
79
+ },
80
+ preconditions: {
81
+ canonicalCut: canonicalCut.evidence,
82
+ ownerHash: synonymOwnerHash(before, additions),
83
+ },
84
+ dictionarySyncRequired: true,
85
+ requiresContrast: proposed.some(
86
+ (synonym) => candidateStates.get(synonym) === "unresolved",
87
+ ),
88
+ });
89
+ plan.summaries.push({
90
+ kind: operation.kind,
91
+ status: "planned",
92
+ word,
93
+ caseIds: structuredClone(operation.caseIds),
94
+ });
95
+ }
96
+
97
+ export function bindSynonymAuthorityAdditions(authorities, caseIds, additions) {
98
+ const additionSet = new Set(additions);
99
+ const authorityByCaseId = new Map(
100
+ authorities.map((authority) => [authority.caseId, authority]),
101
+ );
102
+ for (const caseId of caseIds) {
103
+ const authority = authorityByCaseId.get(caseId);
104
+ if (authority?.kind !== "dimension_value_synonym")
105
+ fail(
106
+ "INVALID_PLAN_STRUCTURE",
107
+ "synonym operation is missing its case authority",
108
+ );
109
+ authority.target.additions = authority.target.synonyms.filter((synonym) =>
110
+ additionSet.has(synonym),
111
+ );
112
+ }
113
+ }
114
+
115
+ export function semanticSynonym(value) {
116
+ return compact({
117
+ id: value.id,
118
+ word: value.word,
119
+ synonyms: structuredClone(value.synonyms ?? []),
120
+ });
121
+ }
122
+
123
+ export function proposedSynonyms(operation, canonicalWord) {
124
+ const values = [];
125
+ if (operation.synonym !== undefined) values.push(operation.synonym);
126
+ if (operation.synonyms !== undefined) {
127
+ if (!Array.isArray(operation.synonyms))
128
+ fail("INVALID_SYNONYM", "synonyms must be an array");
129
+ values.push(...operation.synonyms);
130
+ }
131
+ if (values.length === 0)
132
+ fail("INVALID_SYNONYM", "at least one synonym is required");
133
+
134
+ const seen = new Set();
135
+ const result = [];
136
+ for (const value of values) {
137
+ const synonym = normalizeProposedSynonym(value);
138
+ if (synonym === canonicalWord || seen.has(synonym)) continue;
139
+ seen.add(synonym);
140
+ result.push(synonym);
141
+ }
142
+ return result;
143
+ }
144
+
145
+ export function normalizeProposedSynonym(value) {
146
+ if (typeof value !== "string")
147
+ fail("INVALID_SYNONYM", "synonym must be a string");
148
+ const word = value.trim();
149
+ if (!word || word.length > SYNONYM_MAX_LENGTH)
150
+ fail("INVALID_SYNONYM", "synonym length is invalid");
151
+ const pureDigits = /^\p{Decimal_Number}+$/u.test(word);
152
+ if (pureDigits && word.length < 6)
153
+ fail("INVALID_SYNONYM", "numeric synonyms require at least six digits");
154
+
155
+ let hasLetterOrChinese = false;
156
+ for (const character of word) {
157
+ const asciiLetter = /^[A-Za-z]$/.test(character);
158
+ const allowedAscii = /^[A-Za-z0-9/\\_.+\- ]$/.test(character);
159
+ const chinese = isServerChineseCharacter(character);
160
+ if (!allowedAscii && character !== RESERVED_SPACE && !chinese)
161
+ fail("INVALID_SYNONYM", "synonym contains an invalid character");
162
+ if (asciiLetter || chinese) hasLetterOrChinese = true;
163
+ }
164
+ if (!pureDigits && !hasLetterOrChinese)
165
+ fail("INVALID_SYNONYM", "synonym requires a letter or Chinese character");
166
+ return normalizeServerWord(word);
167
+ }
168
+
169
+ export async function inspectCanonicalSynonymCut(client, workspaceId, word) {
170
+ const response = await requestSynonymCut(client, workspaceId, word);
171
+ if (response.tokens.length !== 1)
172
+ fail(
173
+ "INVALID_SYNONYM_CUT",
174
+ "canonical word must resolve to one dimension value",
175
+ );
176
+ const token = response.tokens[0];
177
+ assertCertainCutToken(token, word);
178
+ if (!DIMENSION_VALUE_PROP.test(token.prop))
179
+ fail(
180
+ "INVALID_SYNONYM_CUT",
181
+ "canonical word did not resolve to a dimension value",
182
+ );
183
+ const identity = safeCutIdentity(response.identity, "identity");
184
+ const momentIdentity = safeCutIdentity(
185
+ response.momentIdentity,
186
+ "momentIdentity",
187
+ );
188
+ const pairs = [{ word, prop: token.prop }];
189
+ return {
190
+ prop: token.prop,
191
+ evidence: {
192
+ prop: token.prop,
193
+ pairsHash: hashValue(pairs),
194
+ identity,
195
+ momentIdentity,
196
+ },
197
+ };
198
+ }
199
+
200
+ export async function inspectProposedSynonymCut(
201
+ client,
202
+ workspaceId,
203
+ word,
204
+ canonicalProp,
205
+ ) {
206
+ const response = await requestSynonymCut(client, workspaceId, word);
207
+ if (response.tokens.length === 0) return "unresolved";
208
+ if (response.tokens.length !== 1)
209
+ fail("INVALID_SYNONYM_CUT", "synonym cut returned multiple tokens");
210
+ const token = response.tokens[0];
211
+ assertCertainCutToken(token, word);
212
+ if (
213
+ token.prop === null ||
214
+ token.prop === undefined ||
215
+ token.prop === "unknown"
216
+ )
217
+ return "unresolved";
218
+ if (token.prop === canonicalProp) return "canonical";
219
+ fail("SYNONYM_CUT_CONFLICT", "synonym resolves to another semantic prop");
220
+ }
221
+
222
+ export async function requestSynonymCut(client, workspaceId, word) {
223
+ const response = await client.request(
224
+ "POST",
225
+ `/api/v3/account-projects/${workspaceId}/cut/`,
226
+ { body: { tokens: word } },
227
+ );
228
+ if (
229
+ !isRecord(response) ||
230
+ (response.status !== undefined && response.status !== "SUCCESS") ||
231
+ !Array.isArray(response.tokens)
232
+ )
233
+ fail(
234
+ "INVALID_SYNONYM_CUT",
235
+ "cut must return an object with a tokens array",
236
+ );
237
+ return response;
238
+ }
239
+
240
+ export function assertCertainCutToken(token, expectedWord) {
241
+ if (
242
+ !isRecord(token) ||
243
+ normalizeServerWord(token.word) !== expectedWord ||
244
+ (token.invalidType !== undefined && token.invalidType !== null) ||
245
+ hasCutAlternatives(token.choiceTokens) ||
246
+ hasCutAlternatives(token.guessTokens)
247
+ )
248
+ fail(
249
+ "INVALID_SYNONYM_CUT",
250
+ "cut token is invalid, ambiguous, or belongs to another word",
251
+ );
252
+ }
253
+
254
+ export function safeCutIdentity(value, field) {
255
+ if (typeof value !== "string" || !value.trim())
256
+ fail("INVALID_SYNONYM_CUT", `cut ${field} is required`);
257
+ return value.trim();
258
+ }
259
+
260
+ export async function listAllSynonymPages(client, path, q) {
261
+ const rows = [];
262
+ const limit = 100;
263
+ for (let offset = 0; ; offset += limit) {
264
+ const page = await client.request("GET", path, {
265
+ query: { q, offset, limit },
266
+ });
267
+ if (!Array.isArray(page))
268
+ fail(
269
+ "INVALID_SYNONYM_OWNER_STATE",
270
+ "synonym lookup must return an array",
271
+ );
272
+ for (const row of page) {
273
+ if (
274
+ !isRecord(row) ||
275
+ row.id === undefined ||
276
+ typeof row.word !== "string" ||
277
+ !Array.isArray(row.synonyms) ||
278
+ row.synonyms.some((value) => typeof value !== "string")
279
+ )
280
+ fail(
281
+ "INVALID_SYNONYM_OWNER_STATE",
282
+ "synonym lookup returned a malformed row",
283
+ );
284
+ rows.push(row);
285
+ }
286
+ if (page.length < limit) return rows;
287
+ }
288
+ }
289
+
290
+ export async function inspectSynonymOwnership(
291
+ client,
292
+ workspaceId,
293
+ canonicalWord,
294
+ synonyms,
295
+ ) {
296
+ const collection = synonymCollection(workspaceId);
297
+ const canonicalOwners = exactSynonymOwners(
298
+ await listAllSynonymPages(client, collection, canonicalWord),
299
+ canonicalWord,
300
+ );
301
+ if (canonicalOwners.length > 1)
302
+ fail(
303
+ "SYNONYM_OWNER_CONFLICT",
304
+ "multiple synonym rows own the canonical word",
305
+ );
306
+ const existing = canonicalOwners[0];
307
+ if (existing && normalizeServerWord(existing.word) !== canonicalWord)
308
+ fail(
309
+ "SYNONYM_OWNER_CONFLICT",
310
+ "the canonical word is a synonym of another row",
311
+ );
312
+
313
+ const ownerBySynonym = new Map();
314
+ for (const synonym of synonyms) {
315
+ const owners = exactSynonymOwners(
316
+ await listAllSynonymPages(client, collection, synonym),
317
+ synonym,
318
+ );
319
+ if (owners.length > 1)
320
+ fail("SYNONYM_OWNER_CONFLICT", "a synonym is owned by multiple rows");
321
+ const owner = owners[0];
322
+ if (owner && normalizeServerWord(owner.word) !== canonicalWord)
323
+ fail(
324
+ "SYNONYM_OWNER_CONFLICT",
325
+ "a synonym belongs to another canonical word",
326
+ );
327
+ if (owner && (!existing || String(owner.id) !== String(existing.id)))
328
+ fail(
329
+ "SYNONYM_OWNER_CONFLICT",
330
+ "canonical synonym ownership is inconsistent",
331
+ );
332
+ ownerBySynonym.set(synonym, owner ?? null);
333
+ }
334
+ return { existing, ownerBySynonym };
335
+ }
336
+
337
+ export function exactSynonymOwners(rows, word) {
338
+ return rows.filter(
339
+ (row) =>
340
+ normalizeServerWord(row.word) === word ||
341
+ row.synonyms.some((value) => normalizeServerWord(value) === word),
342
+ );
343
+ }
344
+
345
+ export function synonymOwnerHash(before, additions) {
346
+ return hashValue({
347
+ canonical: before,
348
+ additions: additions.map((word) => ({ word, owner: null })),
349
+ });
350
+ }
351
+
352
+ export async function revalidateSynonymStep(client, workspaceId, step) {
353
+ const { additions, word } = validateSynonymStepStructure(step, workspaceId);
354
+ const expectedCut = step.preconditions.canonicalCut;
355
+ const freshCut = await inspectCanonicalSynonymCut(client, workspaceId, word);
356
+ if (
357
+ freshCut.prop !== expectedCut.prop ||
358
+ freshCut.evidence.pairsHash !== expectedCut.pairsHash
359
+ )
360
+ fail("SYNONYM_CUT_DRIFT", "canonical synonym cut changed after planning");
361
+ for (const synonym of additions) {
362
+ const state = await inspectProposedSynonymCut(
363
+ client,
364
+ workspaceId,
365
+ synonym,
366
+ expectedCut.prop,
367
+ );
368
+ if (state !== "unresolved")
369
+ fail("SYNONYM_CUT_DRIFT", "a planned synonym now resolves semantically", {
370
+ synonym,
371
+ });
372
+ }
373
+
374
+ const { existing, ownerBySynonym } = await inspectSynonymOwnership(
375
+ client,
376
+ workspaceId,
377
+ word,
378
+ additions,
379
+ );
380
+ if (additions.some((synonym) => ownerBySynonym.get(synonym) !== null))
381
+ fail(
382
+ "SYNONYM_OWNER_DRIFT",
383
+ "a planned synonym acquired an owner after planning",
384
+ );
385
+ const current = existing ? semanticSynonym(existing) : null;
386
+ if (synonymOwnerHash(current, additions) !== step.preconditions.ownerHash)
387
+ fail(
388
+ "SYNONYM_OWNER_DRIFT",
389
+ "canonical synonym ownership changed after planning",
390
+ );
391
+ return current;
392
+ }
393
+
394
+ export function validateAuthoritySynonymList(values, canonicalWord) {
395
+ if (!Array.isArray(values))
396
+ fail("INVALID_PLAN_STRUCTURE", "synonym authority list is invalid");
397
+ const seen = new Set();
398
+ const normalized = [];
399
+ for (const value of values) {
400
+ const synonym = normalizeProposedSynonym(value);
401
+ if (synonym === canonicalWord || synonym !== value || seen.has(synonym))
402
+ fail("INVALID_PLAN_STRUCTURE", "synonym authority list is invalid");
403
+ seen.add(synonym);
404
+ normalized.push(synonym);
405
+ }
406
+ return normalized;
407
+ }
408
+
409
+ export function validateSynonymStepStructure(step, workspaceId) {
410
+ const collection = synonymCollection(workspaceId);
411
+ const allowedStepFields = new Set([
412
+ "kind",
413
+ "caseIds",
414
+ "endpoint",
415
+ "operation",
416
+ "before",
417
+ "after",
418
+ "preconditions",
419
+ "dictionarySyncRequired",
420
+ "requiresContrast",
421
+ ]);
422
+ if (
423
+ Object.keys(step).some((field) => !allowedStepFields.has(field)) ||
424
+ step.dictionarySyncRequired !== true
425
+ )
426
+ fail("INVALID_SYNONYM_PLAN", "synonym step fields are invalid");
427
+
428
+ const after = validateSynonymSnapshot(step.after, "after");
429
+ const word = after.word;
430
+ let before = null;
431
+ if (step.operation === "POST") {
432
+ if (
433
+ step.before !== null ||
434
+ after.id !== undefined ||
435
+ step.endpoint !== collection
436
+ )
437
+ fail(
438
+ "INVALID_SYNONYM_PLAN",
439
+ "synonym POST must create from the collection",
440
+ );
441
+ } else if (step.operation === "PUT") {
442
+ before = validateSynonymSnapshot(step.before, "before");
443
+ const beforeId = canonicalSynonymId(before.id);
444
+ const afterId = canonicalSynonymId(after.id);
445
+ if (
446
+ beforeId !== afterId ||
447
+ step.endpoint !== `${collection}${beforeId}/` ||
448
+ before.word !== word
449
+ )
450
+ fail(
451
+ "INVALID_SYNONYM_PLAN",
452
+ "synonym PUT identity does not match its snapshots",
453
+ );
454
+ } else fail("INVALID_SYNONYM_PLAN", "synonym operation is invalid");
455
+
456
+ const beforeSynonyms = before?.synonyms ?? [];
457
+ if (
458
+ after.synonyms.length <= beforeSynonyms.length ||
459
+ canonicalJson(after.synonyms.slice(0, beforeSynonyms.length)) !==
460
+ canonicalJson(beforeSynonyms)
461
+ )
462
+ fail(
463
+ "INVALID_SYNONYM_PLAN",
464
+ "synonym steps must preserve the existing ordered prefix",
465
+ );
466
+ const seen = new Set();
467
+ for (const synonym of after.synonyms) {
468
+ const normalized = normalizeProposedSynonym(synonym);
469
+ if (normalized !== synonym || synonym === word || seen.has(normalized))
470
+ fail(
471
+ "INVALID_SYNONYM_PLAN",
472
+ "synonym values must be normalized, unique, and non-canonical",
473
+ );
474
+ seen.add(normalized);
475
+ }
476
+ const additions = after.synonyms.slice(beforeSynonyms.length);
477
+
478
+ const caseIds = validateMutationCaseIds(step.caseIds, "INVALID_SYNONYM_PLAN");
479
+ const preconditions = step.preconditions;
480
+ if (
481
+ !isRecord(preconditions) ||
482
+ canonicalJson(Object.keys(preconditions).sort()) !==
483
+ canonicalJson(["canonicalCut", "ownerHash"])
484
+ )
485
+ fail("INVALID_SYNONYM_EVIDENCE", "synonym preconditions are invalid");
486
+ const cut = preconditions.canonicalCut;
487
+ if (
488
+ !isRecord(cut) ||
489
+ !DIMENSION_VALUE_PROP.test(cut.prop) ||
490
+ cut.pairsHash !== hashValue([{ word, prop: cut.prop }]) ||
491
+ typeof cut.identity !== "string" ||
492
+ !cut.identity.trim() ||
493
+ cut.identity !== cut.identity.trim() ||
494
+ typeof cut.momentIdentity !== "string" ||
495
+ !cut.momentIdentity.trim() ||
496
+ cut.momentIdentity !== cut.momentIdentity.trim() ||
497
+ preconditions.ownerHash !== synonymOwnerHash(before, additions)
498
+ )
499
+ fail(
500
+ "INVALID_SYNONYM_EVIDENCE",
501
+ "synonym evidence does not match the planned mutation",
502
+ );
503
+ return { additions, after, before, caseIds, word };
504
+ }
505
+
506
+ export function validateSynonymSnapshot(value, label) {
507
+ if (!isRecord(value))
508
+ fail("INVALID_SYNONYM_PLAN", `synonym ${label} must be an object`);
509
+ const allowed = new Set(["id", "word", "synonyms"]);
510
+ if (
511
+ Object.keys(value).some((field) => !allowed.has(field)) ||
512
+ typeof value.word !== "string" ||
513
+ !value.word ||
514
+ normalizeServerWord(value.word) !== value.word ||
515
+ !Array.isArray(value.synonyms)
516
+ )
517
+ fail("INVALID_SYNONYM_PLAN", `synonym ${label} snapshot is invalid`);
518
+ return value;
519
+ }
520
+
521
+ export function synonymCollection(workspaceId) {
522
+ return `/api/v2/admin-projects/${workspaceId}/synonym-words/`;
523
+ }
524
+
525
+ function synonymAuthorityTarget(operation) {
526
+ const word = normalizeServerWord(requiredText(operation.word, "word"));
527
+ return { additions: [], word, synonyms: proposedSynonyms(operation, word) };
528
+ }
529
+
530
+ function createSynonymCoalescer() {
531
+ const groups = new Map();
532
+ const targets = new Map();
533
+ return {
534
+ add(operation, result) {
535
+ const caseId = operation.caseId.trim();
536
+ const word = normalizeServerWord(requiredText(operation.word, "word"));
537
+ const synonyms = proposedSynonyms(operation, word);
538
+ const targetKey = `synonym:${word}`;
539
+ for (const synonym of synonyms) {
540
+ const previousTarget = targets.get(synonym);
541
+ if (previousTarget !== undefined && previousTarget !== targetKey)
542
+ fail(
543
+ "SYNONYM_CONFLICT",
544
+ "the synonym targets more than one canonical word",
545
+ { synonym },
546
+ );
547
+ targets.set(synonym, targetKey);
548
+ }
549
+
550
+ let group = groups.get(targetKey);
551
+ if (!group) {
552
+ group = {
553
+ ...structuredClone(operation),
554
+ caseId,
555
+ word,
556
+ synonyms: [],
557
+ caseIds: [],
558
+ };
559
+ delete group.synonym;
560
+ delete group.canonicalEvidence;
561
+ groups.set(targetKey, group);
562
+ result.push(group);
563
+ }
564
+ group.caseIds.push(caseId);
565
+ for (const synonym of synonyms)
566
+ if (!group.synonyms.includes(synonym)) group.synonyms.push(synonym);
567
+ return true;
568
+ },
569
+ };
570
+ }
571
+
572
+ function synonymWriteDesired(client, step) {
573
+ return client.request(step.operation, step.endpoint, {
574
+ body: { word: step.after.word, synonyms: step.after.synonyms },
575
+ });
576
+ }
577
+
578
+ function synonymWriteBefore(client, step) {
579
+ return client.request("PUT", step.endpoint, {
580
+ body: { word: step.before.word, synonyms: step.before.synonyms },
581
+ });
582
+ }
583
+
584
+ async function synonymReadState(client, workspaceId, step) {
585
+ const word = step.after?.word ?? step.before?.word;
586
+ const normalizedWord = normalizeServerWord(word);
587
+ const rows = await listAllSynonymPages(
588
+ client,
589
+ synonymCollection(workspaceId),
590
+ normalizedWord,
591
+ );
592
+ const id = step.after?.id ?? step.before?.id;
593
+ const row =
594
+ id === undefined
595
+ ? exactSynonymOwners(rows, normalizedWord)[0]
596
+ : rows.find((item) => String(item.id) === String(id));
597
+ return row ? semanticSynonym(row) : null;
598
+ }
599
+
600
+ export async function synonymExactCreatedCandidates(client, workspaceId, step) {
601
+ const word = step.after?.word;
602
+ const rows = await listAllSynonymPages(
603
+ client,
604
+ synonymCollection(workspaceId),
605
+ word,
606
+ );
607
+ return rows
608
+ .filter((row) => normalizeText(row.word) === normalizeText(word))
609
+ .map(semanticSynonym);
610
+ }
611
+
612
+ function validateSynonymAuthorityTarget(target) {
613
+ const word = normalizeServerWord(
614
+ requiredText(target.word, "authority.word"),
615
+ );
616
+ const synonyms = validateAuthoritySynonymList(target.synonyms, word);
617
+ const additions = validateAuthoritySynonymList(target.additions, word);
618
+ if (
619
+ canonicalJson(Object.keys(target).sort()) !==
620
+ canonicalJson(["additions", "synonyms", "word"]) ||
621
+ target.word !== word ||
622
+ canonicalJson(target.synonyms) !== canonicalJson(synonyms) ||
623
+ canonicalJson(target.additions) !== canonicalJson(additions) ||
624
+ additions.some((synonym) => !synonyms.includes(synonym))
625
+ )
626
+ fail("INVALID_PLAN_STRUCTURE", "synonym authority target is invalid");
627
+ }
628
+
629
+ function validateSynonymPlanStep(step, plan, authorities, plannedCaseIds, usedCaseIds) {
630
+ const { after, caseIds, word } = validateSynonymStepStructure(
631
+ step,
632
+ plan.workspaceId,
633
+ );
634
+ const stepAuthorities = authoritiesForCaseIds(
635
+ authorities,
636
+ caseIds,
637
+ "dimension_value_synonym",
638
+ "INVALID_SYNONYM_PLAN",
639
+ );
640
+ const expectedAdditions = [];
641
+ const expectedSet = new Set();
642
+ for (const { target } of stepAuthorities) {
643
+ if (target.word !== word)
644
+ fail(
645
+ "INVALID_SYNONYM_PLAN",
646
+ "synonym step caseIds must match exact synonym authorities",
647
+ );
648
+ for (const synonym of target.additions)
649
+ if (!expectedSet.has(synonym)) {
650
+ expectedSet.add(synonym);
651
+ expectedAdditions.push(synonym);
652
+ }
653
+ }
654
+ const beforeLength = step.before?.synonyms?.length ?? 0;
655
+ const actualAdditions = after.synonyms.slice(beforeLength);
656
+ if (canonicalJson(actualAdditions) !== canonicalJson(expectedAdditions))
657
+ fail(
658
+ "INVALID_SYNONYM_PLAN",
659
+ "synonym step additions must exactly match case authorities",
660
+ );
661
+ claimStepCaseIds(usedCaseIds, caseIds);
662
+ for (const caseId of caseIds) plannedCaseIds.add(caseId);
663
+ }
664
+
665
+ function synonymSummaryMatches(summary, authorityTargets) {
666
+ const targets = authorityTargets.map(({ target }) => target);
667
+ return targets.every((target) => summary.word === target.word);
668
+ }
669
+
670
+ export const synonymKind = {
671
+ name: "dimension_value_synonym",
672
+ planable: true,
673
+ plan: planSynonym,
674
+ authorityTarget: synonymAuthorityTarget,
675
+ createCoalescer: createSynonymCoalescer,
676
+ writeDesired: synonymWriteDesired,
677
+ writeBefore: synonymWriteBefore,
678
+ readState: synonymReadState,
679
+ preApplyRead: revalidateSynonymStep,
680
+ exactCreatedCandidates: synonymExactCreatedCandidates,
681
+ collection: synonymCollection,
682
+ targetKey: (step) =>
683
+ `synonym:${normalizeServerWord(step.after?.word ?? step.before?.word)}`,
684
+ validateAuthorityTarget: validateSynonymAuthorityTarget,
685
+ validateStep: validateSynonymPlanStep,
686
+ summaryField: ["word"],
687
+ summaryMatches: synonymSummaryMatches,
688
+ };