@arcticdata/dsh-datarc-skills 0.0.0-stage → 26.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +20 -2
  2. package/cordis.patch.yml +4 -0
  3. package/icon.svg +4 -0
  4. package/index.js +35 -0
  5. package/locale/en.json +6 -0
  6. package/locale/zh.json +6 -0
  7. package/package.json +37 -4
  8. package/skills/datarc-access-permissions/SKILL.md +30 -0
  9. package/skills/datarc-access-permissions/references/api.md +31 -0
  10. package/skills/datarc-access-permissions/references/write-order.md +16 -0
  11. package/skills/datarc-analysis-report/SKILL.md +125 -0
  12. package/skills/datarc-analysis-report/agents/openai.yaml +6 -0
  13. package/skills/datarc-analysis-report/references/analyst-frameworks.md +215 -0
  14. package/skills/datarc-analysis-report/references/api-contracts.md +478 -0
  15. package/skills/datarc-analysis-report/references/direct-card-fallback-design.md +66 -0
  16. package/skills/datarc-analysis-report/references/human-in-the-loop.md +142 -0
  17. package/skills/datarc-analysis-report/references/loop-personalization-policy.md +138 -0
  18. package/skills/datarc-analysis-report/references/manifest-example.json +779 -0
  19. package/skills/datarc-analysis-report/references/narrative-schema.md +160 -0
  20. package/skills/datarc-analysis-report/references/question-syntax.md +151 -0
  21. package/skills/datarc-analysis-report/scripts/run_analysis_report.py +2225 -0
  22. package/skills/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -0
  23. package/skills/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -0
  24. package/skills/datarc-data-search/SKILL.md +243 -0
  25. package/skills/datarc-data-search/scripts/calculate.py +116 -0
  26. package/skills/datarc-data-search/scripts/data-search.mjs +628 -0
  27. package/skills/datarc-data-search/scripts/datarc-client.mjs +464 -0
  28. package/skills/datarc-data-search/scripts/search-result.mjs +211 -0
  29. package/skills/datarc-dataseek-batch-evaluation/SKILL.md +59 -0
  30. package/skills/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -0
  31. package/skills/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -0
  32. package/skills/datarc-dataseek-batch-evaluation/scripts/datarc-client.mjs +464 -0
  33. package/skills/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -0
  34. package/skills/datarc-dataseek-search/SKILL.md +96 -0
  35. package/skills/datarc-dataseek-search/scripts/datarc-client.mjs +464 -0
  36. package/skills/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -0
  37. package/skills/datarc-dataseek-semantic-debugging/SKILL.md +44 -0
  38. package/skills/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -0
  39. package/skills/datarc-dataseek-semantic-debugging/evals/evals.json +165 -0
  40. package/skills/datarc-dataseek-semantic-debugging/references/dataset.md +77 -0
  41. package/skills/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -0
  42. package/skills/datarc-dataseek-semantic-debugging/references/interventions.md +64 -0
  43. package/skills/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -0
  44. package/skills/datarc-dataseek-semantic-debugging/references/rollback.md +11 -0
  45. package/skills/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -0
  46. package/skills/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -0
  47. package/skills/datarc-dataseek-testset-generation/SKILL.md +47 -0
  48. package/skills/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -0
  49. package/skills/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -0
  50. package/skills/datarc-datasource/SKILL.md +97 -0
  51. package/skills/datarc-oauth/SKILL.md +47 -0
  52. package/skills/datarc-oauth/scripts/auth.mjs +130 -0
  53. package/skills/datarc-oauth/scripts/credentials.mjs +237 -0
  54. package/skills/datarc-report-add-card/SKILL.md +90 -0
  55. package/skills/datarc-report-add-card/agents/openai.yaml +4 -0
  56. package/skills/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
  57. package/skills/datarc-report-add-card/scripts/report-card.mjs +439 -0
  58. package/skills/datarc-semantic-alias/SKILL.md +20 -0
  59. package/skills/datarc-semantic-alias/scripts/alias-plan.mjs +422 -0
  60. package/skills/datarc-semantic-alias/scripts/alias.mjs +11 -0
  61. package/skills/datarc-semantic-calibration/SKILL.md +20 -0
  62. package/skills/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -0
  63. package/skills/datarc-semantic-calibration/scripts/calibration.mjs +11 -0
  64. package/skills/datarc-semantic-core/SKILL.md +12 -0
  65. package/skills/datarc-semantic-core/scripts/artifact-journal.mjs +830 -0
  66. package/skills/datarc-semantic-core/scripts/canonical.mjs +48 -0
  67. package/skills/datarc-semantic-core/scripts/case-model.mjs +608 -0
  68. package/skills/datarc-semantic-core/scripts/cli.mjs +180 -0
  69. package/skills/datarc-semantic-core/scripts/datarc-client.mjs +180 -0
  70. package/skills/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -0
  71. package/skills/datarc-semantic-core/scripts/interventions.mjs +693 -0
  72. package/skills/datarc-semantic-core/scripts/live-resolution.mjs +305 -0
  73. package/skills/datarc-semantic-core/scripts/model-scope.mjs +49 -0
  74. package/skills/datarc-semantic-core/scripts/reproduction.mjs +330 -0
  75. package/skills/datarc-semantic-core/scripts/semantic-cli.mjs +740 -0
  76. package/skills/datarc-semantic-core/scripts/shared.mjs +312 -0
  77. package/skills/datarc-semantic-core/scripts/verification.mjs +1014 -0
  78. package/skills/datarc-semantic-dataset/SKILL.md +20 -0
  79. package/skills/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -0
  80. package/skills/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -0
  81. package/skills/datarc-semantic-dataset/scripts/dataset.mjs +11 -0
  82. package/skills/datarc-semantic-knowledge/SKILL.md +38 -0
  83. package/skills/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -0
  84. package/skills/datarc-semantic-knowledge/references/knowledge-generation.json +16 -0
  85. package/skills/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -0
  86. package/skills/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -0
  87. package/skills/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -0
  88. package/skills/datarc-semantic-prompt/SKILL.md +20 -0
  89. package/skills/datarc-semantic-prompt/scripts/prompt-plan.mjs +447 -0
  90. package/skills/datarc-semantic-prompt/scripts/prompt.mjs +15 -0
  91. package/skills/datarc-semantic-synonym/SKILL.md +20 -0
  92. package/skills/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -0
  93. package/skills/datarc-semantic-synonym/scripts/synonym.mjs +11 -0
  94. package/skills/datarc-viz-analysis-report/SKILL.md +108 -0
  95. package/skills/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -0
  96. package/skills/datarc-viz-analysis-report/assets/echarts.min.js +45 -0
  97. package/skills/datarc-viz-analysis-report/references/api-contracts.md +163 -0
  98. package/skills/datarc-viz-analysis-report/references/derivation-log.md +157 -0
  99. package/skills/datarc-viz-analysis-report/references/evidence-framework.md +76 -0
  100. package/skills/datarc-viz-analysis-report/references/html-template.md +92 -0
  101. package/skills/datarc-viz-analysis-report/references/provenance-format.md +56 -0
  102. package/skills/datarc-viz-analysis-report/references/question-syntax.md +151 -0
  103. package/skills/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -0
  104. package/skills/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -0
  105. package/skills/datarc-workspace-configuration/SKILL.md +59 -0
  106. package/skills/datarc-workspace-configuration/references/artifacts.md +75 -0
  107. package/skills/datarc-workspace-configuration/references/verification.md +20 -0
  108. package/skills/datarc-workspace-configuration/scripts/configuration.mjs +662 -0
  109. package/skills/datarc-workspace-context/SKILL.md +43 -0
  110. package/skills/datarc-workspace-context/agents/openai.yaml +4 -0
  111. package/skills/datarc-workspace-context/scripts/datarc-client.mjs +31 -0
  112. package/skills/datarc-workspace-context/scripts/query-display.mjs +114 -0
  113. package/skills/datarc-workspace-context/scripts/workspace-context.mjs +58 -0
  114. package/skills/datarc-workspace-custom-tables/SKILL.md +89 -0
  115. package/skills/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -0
  116. package/skills/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -0
  117. package/skills/datarc-workspace-keywords/SKILL.md +197 -0
  118. package/skills/datarc-workspace-keywords/agents/openai.yaml +4 -0
  119. package/skills/datarc-workspace-keywords/references/api-fields.md +79 -0
  120. package/skills/datarc-workspace-keywords/references/derived-measures.md +177 -0
  121. package/skills/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -0
  122. package/skills/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -0
  123. package/skills/datarc-workspace-membership/SKILL.md +29 -0
  124. package/skills/datarc-workspace-membership/references/api.md +19 -0
  125. package/skills/datarc-workspace-modeling/SKILL.md +209 -0
  126. package/skills/datarc-workspace-modeling/agents/openai.yaml +4 -0
  127. package/skills/datarc-workspace-modeling/references/join-preview.md +38 -0
  128. package/skills/datarc-workspace-modeling/references/model-plan.md +300 -0
  129. package/skills/datarc-workspace-modeling/references/model-tags.md +95 -0
  130. package/skills/datarc-workspace-modeling/references/modeling-contract.json +29 -0
  131. package/skills/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -0
  132. package/skills/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -0
  133. package/skills/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -0
  134. package/skills/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -0
  135. package/skills-index.json +194 -0
@@ -0,0 +1,48 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export function canonicalize(value) {
4
+ if (Array.isArray(value)) return value.map(canonicalize);
5
+ if (!value || typeof value !== "object") return value;
6
+ return Object.fromEntries(
7
+ Object.keys(value)
8
+ .sort()
9
+ .map((key) => [key, canonicalize(value[key])]),
10
+ );
11
+ }
12
+
13
+ export function canonicalJson(value) {
14
+ return JSON.stringify(canonicalize(value));
15
+ }
16
+
17
+ export function sameCanonical(left, right) {
18
+ return canonicalJson(left) === canonicalJson(right);
19
+ }
20
+
21
+ export function hashArtifactValue(value) {
22
+ return createHash("sha256").update(canonicalJson(value)).digest("hex");
23
+ }
24
+
25
+ export function canonicalArtifactValue(value) {
26
+ return canonicalize(value);
27
+ }
28
+
29
+ export function hashPlanStep(step) {
30
+ return hashArtifactValue(step);
31
+ }
32
+
33
+ export function withoutId(value) {
34
+ if (!value || typeof value !== "object") return value;
35
+ const result = structuredClone(value);
36
+ delete result.id;
37
+ return result;
38
+ }
39
+
40
+ export function hashWithout(value, field) {
41
+ const body = structuredClone(value);
42
+ delete body[field];
43
+ return hashArtifactValue(body);
44
+ }
45
+
46
+ export function withHash(value, field) {
47
+ return { ...structuredClone(value), [field]: hashWithout(value, field) };
48
+ }
@@ -0,0 +1,608 @@
1
+ const SOURCE_TYPES = new Set([
2
+ "mapping_list",
3
+ "current_search_correction",
4
+ "reported_search_correction",
5
+ ]);
6
+
7
+ const RESOURCE_KIND_ALIASES = new Map([
8
+ ["dimension", "dimension"],
9
+ ["dimensions", "dimension"],
10
+ ["measure", "measure"],
11
+ ["measures", "measure"],
12
+ ["time_series", "time_series"],
13
+ ["timeseries", "time_series"],
14
+ ["timeSeries", "time_series"],
15
+ ["dataset", "dataset"],
16
+ ["datasets", "dataset"],
17
+ ["knowledge", "knowledge"],
18
+ ["model", "model"],
19
+ ["models", "model"],
20
+ ]);
21
+
22
+ const MIN_CONTAINS_CODEPOINTS = 2;
23
+ const MIN_EDIT_CODEPOINTS = 2;
24
+ const MIN_EDIT_REFERENCE_CODEPOINTS = 4;
25
+ const MAX_EDIT_DISTANCE = 2;
26
+
27
+ class CaseModelError extends Error {
28
+ constructor(message, code, details) {
29
+ super(message);
30
+ this.name = "CaseModelError";
31
+ this.code = code;
32
+ if (details !== undefined) this.details = details;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Convert one supported administrator-provided input shape into pure cases.
38
+ * The function neither reads another account's data nor attempts resolution.
39
+ */
40
+ export function normalizeCases(sourceType, input) {
41
+ if (!SOURCE_TYPES.has(sourceType))
42
+ throw new CaseModelError("不支持的案例来源", "INVALID_SOURCE_TYPE", {
43
+ sourceType,
44
+ });
45
+ if (sourceType === "mapping_list") return normalizeMappingList(input);
46
+ return [normalizeCorrection(input, sourceType)];
47
+ }
48
+
49
+ /** Produce a compact resource catalog used solely for deterministic matching. */
50
+ export function normalizeCatalog(resources) {
51
+ const entries = catalogEntries(resources);
52
+ return entries.map(({ kind, resource }) => normalizeResource(kind, resource));
53
+ }
54
+
55
+ /**
56
+ * Resolve explicit resource identifiers first. Names are suggestions only and
57
+ * consequently never make a result mutable without an administrator choice.
58
+ */
59
+ export function resolveTarget(hint, catalog, options = {}) {
60
+ const normalizedHint = normalizeTargetHint(hint);
61
+ const resources = normalizeCatalog(catalog);
62
+ const constrained = constrainKinds(resources, normalizedHint, options);
63
+ const selection = resolveAdministratorSelection(constrained, options);
64
+ if (selection) return selection;
65
+
66
+ const idMatches =
67
+ normalizedHint.id === undefined
68
+ ? []
69
+ : constrained.filter((resource) =>
70
+ sameIdentity(resource.id, normalizedHint.id),
71
+ );
72
+ const propMatches =
73
+ normalizedHint.prop === undefined
74
+ ? []
75
+ : constrained.filter((resource) => resource.prop === normalizedHint.prop);
76
+ const hardResolution = resolveHardEvidence(
77
+ normalizedHint,
78
+ idMatches,
79
+ propMatches,
80
+ );
81
+ if (hardResolution) return hardResolution;
82
+ return resolveNameHint(normalizedHint, constrained);
83
+ }
84
+
85
+ /** Reject duplicate and conflicting observations before cases are planned. */
86
+ export function validateCaseSet(cases) {
87
+ if (!Array.isArray(cases))
88
+ throw new CaseModelError("案例集必须是数组", "INVALID_CASE_SET");
89
+ const seen = new Map();
90
+ for (const [index, item] of cases.entries()) {
91
+ if (!item || typeof item !== "object" || !SOURCE_TYPES.has(item.sourceType))
92
+ throw new CaseModelError("案例来源不合法", "INVALID_CASE", { index });
93
+ const observed = requiredText(item.observed, "observed", { index });
94
+ const expected = requiredText(item.expected, "expected", { index });
95
+ const targetHint = normalizeTargetHint(item.targetHint);
96
+ const key = `${normalizeText(observed)}\u0000${targetHint.kind ?? ""}`;
97
+ const fingerprint = caseFingerprint(expected, targetHint);
98
+ const prior = seen.get(key);
99
+ if (prior?.fingerprint === fingerprint)
100
+ throw new CaseModelError("案例重复", "DUPLICATE_CASE", {
101
+ firstIndex: prior.index,
102
+ duplicateIndex: index,
103
+ });
104
+ if (prior)
105
+ throw new CaseModelError("同一映射存在冲突", "CONFLICTING_CASE", {
106
+ firstIndex: prior.index,
107
+ conflictIndex: index,
108
+ });
109
+ seen.set(key, { index, fingerprint });
110
+ }
111
+ return structuredClone(cases);
112
+ }
113
+
114
+ function normalizeMappingList(input) {
115
+ const mappings = Array.isArray(input) ? input : input?.mappings;
116
+ if (!Array.isArray(mappings))
117
+ throw new CaseModelError(
118
+ "mapping_list 需要 mappings 数组",
119
+ "INVALID_CASE_INPUT",
120
+ );
121
+ return mappings.map((mapping, sourceIndex) => {
122
+ if (!mapping || typeof mapping !== "object")
123
+ throw new CaseModelError("映射条目必须是对象", "INVALID_CASE_INPUT", {
124
+ sourceIndex,
125
+ });
126
+ const observed = requiredText(mapping.from ?? mapping.lhs, "from", {
127
+ sourceIndex,
128
+ });
129
+ const expected = requiredText(mapping.to ?? mapping.rhs, "to", {
130
+ sourceIndex,
131
+ });
132
+ const targetHint = normalizeTargetHint(
133
+ {
134
+ ...(mapping.target ?? {}),
135
+ name: mapping.target?.name ?? expected,
136
+ kind: mapping.target?.kind ?? mapping.kind,
137
+ },
138
+ { sourceIndex },
139
+ );
140
+ return {
141
+ sourceType: "mapping_list",
142
+ sourceIndex,
143
+ observed,
144
+ expected,
145
+ targetHint,
146
+ };
147
+ });
148
+ }
149
+
150
+ function normalizeCorrection(input, sourceType) {
151
+ if (!input || typeof input !== "object")
152
+ throw new CaseModelError("搜索更正必须是对象", "INVALID_CASE_INPUT", {
153
+ sourceType,
154
+ });
155
+ const reported = sourceType === "reported_search_correction";
156
+ const question = requiredText(
157
+ reported ? (input.reportedQuestion ?? input.question) : input.question,
158
+ reported ? "reportedQuestion" : "question",
159
+ );
160
+ const observed = requiredText(
161
+ reported
162
+ ? (input.reportedResult ?? input.actual ?? input.observed)
163
+ : (input.actual ?? input.observed),
164
+ reported ? "reportedResult" : "actual",
165
+ );
166
+ const expected = requiredText(
167
+ input.correction ?? input.expected,
168
+ "correction",
169
+ );
170
+ return {
171
+ sourceType,
172
+ sourceIndex: 0,
173
+ question,
174
+ observed,
175
+ expected,
176
+ targetHint: normalizeTargetHint(input.target),
177
+ };
178
+ }
179
+
180
+ function catalogEntries(resources) {
181
+ if (Array.isArray(resources))
182
+ return resources.map((resource) => ({ kind: resource?.kind, resource }));
183
+ if (!resources || typeof resources !== "object")
184
+ throw new CaseModelError("资源目录必须是对象或数组", "INVALID_CATALOG");
185
+ if (Array.isArray(resources.resources))
186
+ return resources.resources.map((resource) => ({
187
+ kind: resource?.kind,
188
+ resource,
189
+ }));
190
+ return Object.entries(resources).flatMap(([kind, values]) => {
191
+ if (!Array.isArray(values))
192
+ throw new CaseModelError("资源分类必须是数组", "INVALID_CATALOG", {
193
+ kind,
194
+ });
195
+ return values.map((resource) => ({
196
+ kind: resource?.kind ?? kind,
197
+ resource,
198
+ }));
199
+ });
200
+ }
201
+
202
+ function normalizeResource(kind, resource) {
203
+ const normalizedKind = normalizeKind(kind);
204
+ if (!resource || typeof resource !== "object")
205
+ throw new CaseModelError("资源必须是对象", "INVALID_CATALOG");
206
+ const id = resource.id ?? resource.uid;
207
+ if (id === undefined || id === null || String(id).trim() === "")
208
+ throw new CaseModelError("资源缺少 id 或 uid", "INVALID_CATALOG", {
209
+ kind: normalizedKind,
210
+ });
211
+ const names = uniqueNames([
212
+ ...(Array.isArray(resource.names) ? resource.names : []),
213
+ resource.name,
214
+ ]);
215
+ if (!names.length)
216
+ throw new CaseModelError("资源缺少名称", "INVALID_CATALOG", {
217
+ kind: normalizedKind,
218
+ id,
219
+ });
220
+ const result = { kind: normalizedKind, id, names };
221
+ if (resource.prop !== undefined && String(resource.prop).trim() !== "")
222
+ result.prop = String(resource.prop).trim();
223
+ return result;
224
+ }
225
+
226
+ function normalizeTargetHint(value, details) {
227
+ if (!value || typeof value !== "object" || Array.isArray(value))
228
+ throw new CaseModelError(
229
+ "目标提示必须是对象",
230
+ "INVALID_TARGET_HINT",
231
+ details,
232
+ );
233
+ const result = {};
234
+ if (
235
+ value.id !== undefined &&
236
+ value.id !== null &&
237
+ String(value.id).trim() !== ""
238
+ )
239
+ result.id = value.id;
240
+ if (
241
+ value.prop !== undefined &&
242
+ value.prop !== null &&
243
+ String(value.prop).trim() !== ""
244
+ )
245
+ result.prop = String(value.prop).trim();
246
+ if (
247
+ value.name !== undefined &&
248
+ value.name !== null &&
249
+ String(value.name).trim() !== ""
250
+ )
251
+ result.name = String(value.name).trim();
252
+ if (
253
+ value.kind !== undefined &&
254
+ value.kind !== null &&
255
+ String(value.kind).trim() !== ""
256
+ )
257
+ result.kind = normalizeKind(value.kind);
258
+ if (!Object.keys(result).some((key) => ["id", "prop", "name"].includes(key)))
259
+ throw new CaseModelError(
260
+ "目标提示需要 id、prop 或 name",
261
+ "INVALID_TARGET_HINT",
262
+ details,
263
+ );
264
+ return result;
265
+ }
266
+
267
+ function constrainKinds(resources, hint, options) {
268
+ const optionKinds =
269
+ options.allowedKinds === undefined
270
+ ? undefined
271
+ : new Set(options.allowedKinds.map(normalizeKind));
272
+ if (optionKinds !== undefined && optionKinds.size === 0)
273
+ throw new CaseModelError("allowedKinds 不能为空", "INVALID_TARGET_OPTIONS");
274
+ return resources.filter(
275
+ (resource) =>
276
+ (hint.kind === undefined || resource.kind === hint.kind) &&
277
+ (optionKinds === undefined || optionKinds.has(resource.kind)),
278
+ );
279
+ }
280
+
281
+ function resolveAdministratorSelection(resources, options) {
282
+ const hasId = options.selectedId !== undefined && options.selectedId !== null;
283
+ const hasProp =
284
+ options.selectedProp !== undefined && options.selectedProp !== null;
285
+ if (!hasId && !hasProp) return undefined;
286
+ const byId = hasId
287
+ ? resources.filter((resource) =>
288
+ sameIdentity(resource.id, options.selectedId),
289
+ )
290
+ : resources;
291
+ const byProp = hasProp
292
+ ? resources.filter(
293
+ (resource) => resource.prop === String(options.selectedProp),
294
+ )
295
+ : resources;
296
+ const matches = intersectResources(byId, byProp);
297
+ if (matches.length === 1)
298
+ return resolved(matches[0], "administrator_selection");
299
+ if (matches.length === 0)
300
+ return outcome("missing", "administrator_selection_missing", [], false);
301
+ return outcome(
302
+ "conflict",
303
+ "administrator_selection_ambiguous",
304
+ matches,
305
+ false,
306
+ );
307
+ }
308
+
309
+ function resolveHardEvidence(hint, idMatches, propMatches) {
310
+ if (!idMatches.length && !propMatches.length) {
311
+ if (hint.id !== undefined || hint.prop !== undefined)
312
+ return outcome("missing", "exact_identifier_missing", [], false);
313
+ return undefined;
314
+ }
315
+ const matches = intersectResources(
316
+ hint.id === undefined ? propMatches : idMatches,
317
+ hint.prop === undefined ? idMatches : propMatches,
318
+ );
319
+ if (hint.id !== undefined && hint.prop !== undefined && !matches.length)
320
+ return outcome(
321
+ "conflict",
322
+ "id_prop_disagree",
323
+ uniqueResources([...idMatches, ...propMatches]),
324
+ false,
325
+ );
326
+ if (matches.length === 1)
327
+ return resolved(
328
+ matches[0],
329
+ hint.id !== undefined && hint.prop !== undefined
330
+ ? "exact_id_and_prop"
331
+ : hint.id !== undefined
332
+ ? "exact_id"
333
+ : "exact_prop",
334
+ );
335
+ return outcome("conflict", "identifier_ambiguous", matches, false);
336
+ }
337
+
338
+ function resolveNameHint(hint, resources) {
339
+ if (hint.name === undefined)
340
+ return outcome("missing", "no_target_name", [], false);
341
+ const normalizedName = normalizeText(hint.name);
342
+ const exact = resources.filter((resource) =>
343
+ resource.names.some((name) => normalizeText(name) === normalizedName),
344
+ );
345
+ if (exact.length)
346
+ return outcome(
347
+ exact.length === 1 ? "proposed" : "needs_choice",
348
+ "exact_normalized_name",
349
+ exact,
350
+ false,
351
+ );
352
+
353
+ const forwardContains = rankContainsMatches(
354
+ resources,
355
+ normalizedName,
356
+ "catalog_contains_hint",
357
+ );
358
+ if (forwardContains.length)
359
+ return nameOutcome("name_contains", forwardContains, {
360
+ direction: "catalog_contains_hint",
361
+ });
362
+
363
+ const reverseContains = rankContainsMatches(
364
+ resources,
365
+ normalizedName,
366
+ "hint_contains_catalog",
367
+ );
368
+ if (reverseContains.length)
369
+ return nameOutcome("name_contains", reverseContains, {
370
+ direction: "hint_contains_catalog",
371
+ });
372
+
373
+ const editMatches = rankEditMatches(resources, normalizedName);
374
+ if (editMatches.length)
375
+ return nameOutcome("name_edit_similarity", editMatches, {
376
+ matches: editMatches.map(({ distance, maxDistance }, candidateIndex) => ({
377
+ candidateIndex,
378
+ distance,
379
+ maxDistance,
380
+ })),
381
+ });
382
+ return outcome("missing", "name_not_found", [], false);
383
+ }
384
+
385
+ function rankContainsMatches(resources, hint, direction) {
386
+ const hintLength = codepointLength(hint);
387
+ if (hintLength < MIN_CONTAINS_CODEPOINTS) return [];
388
+ return resources
389
+ .flatMap((resource, resourceIndex) => {
390
+ const lengths = resource.names.flatMap((name) => {
391
+ const normalized = normalizeText(name);
392
+ const nameLength = codepointLength(normalized);
393
+ if (nameLength < MIN_CONTAINS_CODEPOINTS) return [];
394
+ const matches =
395
+ direction === "catalog_contains_hint"
396
+ ? normalized.includes(hint)
397
+ : hint.includes(normalized);
398
+ return matches ? [Math.abs(nameLength - hintLength)] : [];
399
+ });
400
+ return lengths.length
401
+ ? [
402
+ {
403
+ resource,
404
+ resourceIndex,
405
+ lengthDelta: Math.min(...lengths),
406
+ },
407
+ ]
408
+ : [];
409
+ })
410
+ .sort(
411
+ (left, right) =>
412
+ left.lengthDelta - right.lengthDelta ||
413
+ left.resourceIndex - right.resourceIndex,
414
+ );
415
+ }
416
+
417
+ function rankEditMatches(resources, hint) {
418
+ return resources
419
+ .flatMap((resource, resourceIndex) => {
420
+ const matches = resource.names.flatMap((name) => {
421
+ const normalized = normalizeText(name);
422
+ const maxDistance = editDistanceLimit(hint, normalized);
423
+ if (maxDistance === 0) return [];
424
+ const distance = damerauLevenshtein(hint, normalized, maxDistance);
425
+ return distance <= maxDistance
426
+ ? [
427
+ {
428
+ distance,
429
+ maxDistance,
430
+ lengthDelta: Math.abs(
431
+ codepointLength(normalized) - codepointLength(hint),
432
+ ),
433
+ },
434
+ ]
435
+ : [];
436
+ });
437
+ if (!matches.length) return [];
438
+ matches.sort(
439
+ (left, right) =>
440
+ left.distance - right.distance ||
441
+ left.lengthDelta - right.lengthDelta,
442
+ );
443
+ return [{ resource, resourceIndex, ...matches[0] }];
444
+ })
445
+ .sort(
446
+ (left, right) =>
447
+ left.distance - right.distance ||
448
+ left.lengthDelta - right.lengthDelta ||
449
+ left.resourceIndex - right.resourceIndex,
450
+ );
451
+ }
452
+
453
+ function editDistanceLimit(left, right) {
454
+ const leftLength = codepointLength(left);
455
+ const rightLength = codepointLength(right);
456
+ const shorter = Math.min(leftLength, rightLength);
457
+ const longer = Math.max(leftLength, rightLength);
458
+ if (shorter < MIN_EDIT_CODEPOINTS || longer < MIN_EDIT_REFERENCE_CODEPOINTS)
459
+ return 0;
460
+ return Math.min(MAX_EDIT_DISTANCE, Math.floor(longer / 4));
461
+ }
462
+
463
+ function damerauLevenshtein(left, right, maxDistance) {
464
+ const source = [...left];
465
+ const target = [...right];
466
+ if (Math.abs(source.length - target.length) > maxDistance)
467
+ return maxDistance + 1;
468
+
469
+ let beforePrevious;
470
+ let previous = Array.from({ length: target.length + 1 }, (_, index) => index);
471
+ for (let sourceIndex = 1; sourceIndex <= source.length; sourceIndex += 1) {
472
+ const current = [sourceIndex];
473
+ for (let targetIndex = 1; targetIndex <= target.length; targetIndex += 1) {
474
+ const substitution =
475
+ previous[targetIndex - 1] +
476
+ (source[sourceIndex - 1] === target[targetIndex - 1] ? 0 : 1);
477
+ current[targetIndex] = Math.min(
478
+ previous[targetIndex] + 1,
479
+ current[targetIndex - 1] + 1,
480
+ substitution,
481
+ );
482
+ if (
483
+ beforePrevious &&
484
+ sourceIndex > 1 &&
485
+ targetIndex > 1 &&
486
+ source[sourceIndex - 1] === target[targetIndex - 2] &&
487
+ source[sourceIndex - 2] === target[targetIndex - 1]
488
+ )
489
+ current[targetIndex] = Math.min(
490
+ current[targetIndex],
491
+ beforePrevious[targetIndex - 2] + 1,
492
+ );
493
+ }
494
+ beforePrevious = previous;
495
+ previous = current;
496
+ }
497
+ return previous[target.length];
498
+ }
499
+
500
+ function codepointLength(value) {
501
+ return [...value].length;
502
+ }
503
+
504
+ function nameOutcome(tier, matches, evidence = {}) {
505
+ return outcome(
506
+ matches.length === 1 ? "proposed" : "needs_choice",
507
+ tier,
508
+ matches.map(({ resource }) => resource),
509
+ false,
510
+ evidence,
511
+ );
512
+ }
513
+
514
+ function resolved(resource, tier) {
515
+ const target = structuredClone(resource);
516
+ return {
517
+ status: "resolved",
518
+ evidence: { tier },
519
+ target,
520
+ candidates: [target],
521
+ mutationAllowed: true,
522
+ };
523
+ }
524
+
525
+ function outcome(status, tier, candidates, mutationAllowed, evidence = {}) {
526
+ return {
527
+ status,
528
+ evidence: { tier, ...evidence },
529
+ candidates: uniqueResources(candidates),
530
+ mutationAllowed,
531
+ };
532
+ }
533
+
534
+ function normalizeKind(value) {
535
+ const normalized = RESOURCE_KIND_ALIASES.get(String(value).trim());
536
+ if (!normalized)
537
+ throw new CaseModelError("资源类型不受支持", "INVALID_RESOURCE_KIND", {
538
+ kind: value,
539
+ });
540
+ return normalized;
541
+ }
542
+
543
+ function uniqueNames(values) {
544
+ const seen = new Set();
545
+ return values.flatMap((value) => {
546
+ if (value === undefined || value === null || String(value).trim() === "")
547
+ return [];
548
+ const name = String(value).trim();
549
+ const key = normalizeText(name);
550
+ if (seen.has(key)) return [];
551
+ seen.add(key);
552
+ return [name];
553
+ });
554
+ }
555
+
556
+ function uniqueResources(resources) {
557
+ const seen = new Set();
558
+ return resources.flatMap((resource) => {
559
+ const key = resourceKey(resource);
560
+ if (seen.has(key)) return [];
561
+ seen.add(key);
562
+ return [structuredClone(resource)];
563
+ });
564
+ }
565
+
566
+ function intersectResources(left, right) {
567
+ const rightKeys = new Set(right.map(resourceKey));
568
+ return uniqueResources(
569
+ left.filter((resource) => rightKeys.has(resourceKey(resource))),
570
+ );
571
+ }
572
+
573
+ function resourceKey(resource) {
574
+ return `${resource.kind}\u0000${String(resource.id)}\u0000${resource.prop ?? ""}`;
575
+ }
576
+
577
+ function sameIdentity(left, right) {
578
+ return String(left) === String(right);
579
+ }
580
+
581
+ function caseFingerprint(expected, targetHint) {
582
+ return [
583
+ normalizeText(expected),
584
+ targetHint.id === undefined ? "" : `id:${String(targetHint.id)}`,
585
+ targetHint.prop === undefined ? "" : `prop:${targetHint.prop}`,
586
+ targetHint.name === undefined
587
+ ? ""
588
+ : `name:${normalizeText(targetHint.name)}`,
589
+ ].join("\u0000");
590
+ }
591
+
592
+ function requiredText(value, field, details) {
593
+ if (value === undefined || value === null || String(value).trim() === "")
594
+ throw new CaseModelError(
595
+ `${field} 不能为空`,
596
+ "INVALID_CASE_INPUT",
597
+ details,
598
+ );
599
+ return String(value).trim();
600
+ }
601
+
602
+ function normalizeText(value) {
603
+ return String(value)
604
+ .normalize("NFKC")
605
+ .trim()
606
+ .replace(/\s+/gu, " ")
607
+ .toLowerCase();
608
+ }