@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,848 @@
1
+ import {
2
+ normalizeModelScope,
3
+ validateWorkspaceModelScope,
4
+ } from "../../datarc-semantic-core/scripts/model-scope.mjs";
5
+ import {
6
+ canonicalJson,
7
+ hashArtifactValue as hashValue,
8
+ withHash,
9
+ } from "../../datarc-semantic-core/scripts/canonical.mjs";
10
+ import {
11
+ assertState,
12
+ authoritiesForCaseIds,
13
+ canonicalDatasetId,
14
+ canonicalPlanResourceId,
15
+ claimStepCaseIds,
16
+ coalesceNamedOperation,
17
+ compact,
18
+ fail,
19
+ isRecord,
20
+ listAllPages,
21
+ listOf,
22
+ matchesAuthority,
23
+ normalizeText,
24
+ requireArrayResponse,
25
+ requiredText,
26
+ resolveCompletedStep,
27
+ statesEqual,
28
+ validateMutationCaseIds,
29
+ } from "../../datarc-semantic-core/scripts/shared.mjs";
30
+
31
+ export const KNOWLEDGE_SLOT = "{workspace_knowledge}";
32
+ export function normalizeKnowledgeOperation(operation) {
33
+ const allowed = new Set([
34
+ "active",
35
+ "caseId",
36
+ "caseIds",
37
+ "corpus",
38
+ "id",
39
+ "kind",
40
+ "name",
41
+ "scenes",
42
+ "tuids",
43
+ ]);
44
+ if (
45
+ !isRecord(operation) ||
46
+ Object.keys(operation).some((field) => !allowed.has(field))
47
+ )
48
+ fail("INVALID_KNOWLEDGE", "knowledge input contains unsupported fields");
49
+ const name = requiredText(operation.name, "name");
50
+ if ([...name].length > 256)
51
+ fail(
52
+ "INVALID_KNOWLEDGE",
53
+ "knowledge name must contain at most 256 characters",
54
+ );
55
+ const corpus = requiredText(operation.corpus, "corpus");
56
+ const scenes = normalizeKnowledgeScenes(operation.scenes);
57
+ if (typeof operation.active !== "boolean")
58
+ fail("INVALID_KNOWLEDGE", "knowledge active must be a boolean");
59
+ return {
60
+ ...structuredClone(operation),
61
+ name,
62
+ corpus,
63
+ scenes,
64
+ active: operation.active,
65
+ ...(Object.hasOwn(operation, "tuids")
66
+ ? { tuids: normalizeModelScope(operation.tuids) }
67
+ : {}),
68
+ ...(operation.id === undefined
69
+ ? {}
70
+ : { id: canonicalDatasetId(operation.id) }),
71
+ };
72
+ }
73
+
74
+ export function normalizeKnowledgeScenes(value) {
75
+ if (!Array.isArray(value) || value.length === 0)
76
+ fail("INVALID_KNOWLEDGE", "knowledge requires at least one scene");
77
+ const scenes = [];
78
+ const seen = new Set();
79
+ for (const scene of value) {
80
+ if (!Number.isSafeInteger(scene) || scene <= 0 || seen.has(scene))
81
+ fail(
82
+ "INVALID_KNOWLEDGE",
83
+ "knowledge scenes must be unique positive integers",
84
+ );
85
+ seen.add(scene);
86
+ scenes.push(scene);
87
+ }
88
+ return scenes;
89
+ }
90
+
91
+ export async function planKnowledge(client, plan, operation) {
92
+ const normalized = normalizeKnowledgeOperation(operation);
93
+ const { name, corpus, scenes, active } = normalized;
94
+ const caseIds = validateMutationCaseIds(
95
+ operation.caseIds,
96
+ "INVALID_KNOWLEDGE",
97
+ );
98
+ const collection = corpusCollection(plan.workspaceId);
99
+ const corpora = await listAllPages(client, collection);
100
+ const matches = corpora.filter((row) =>
101
+ normalized.id === undefined
102
+ ? normalizeText(row?.name) === normalizeText(name)
103
+ : String(row?.id) === String(normalized.id),
104
+ );
105
+ if (matches.length > 1)
106
+ fail(
107
+ "KNOWLEDGE_IDENTITY_AMBIGUOUS",
108
+ "multiple Knowledge resources match the exact identity",
109
+ );
110
+ const existing = matches[0]
111
+ ? await readFullKnowledge(client, plan.workspaceId, matches[0])
112
+ : null;
113
+ if (normalized.id !== undefined && existing === null)
114
+ fail(
115
+ "KNOWLEDGE_NOT_FOUND",
116
+ "the selected Knowledge resource no longer exists",
117
+ );
118
+ const scoped =
119
+ Object.hasOwn(normalized, "tuids") ||
120
+ (existing && Object.hasOwn(existing, "tuids"));
121
+ if (scoped && existing && !Object.hasOwn(existing, "tuids"))
122
+ fail(
123
+ "MODEL_SCOPE_UNVERIFIED",
124
+ "详情缺少模型范围,请更新服务或重新读取知识后再规划。",
125
+ );
126
+ const tuids = Object.hasOwn(normalized, "tuids")
127
+ ? normalized.tuids
128
+ : existing?.tuids;
129
+ if (scoped)
130
+ await validateWorkspaceModelScope(client, plan.workspaceId, tuids);
131
+ const before = existing ? semanticKnowledge(existing, scoped) : null;
132
+ const after = {
133
+ ...(existing ? { id: existing.id } : {}),
134
+ name,
135
+ corpus,
136
+ scenes: structuredClone(scenes),
137
+ active,
138
+ ...(scoped
139
+ ? { tuids: normalizeModelScope(tuids, { allowEmpty: true }) }
140
+ : {}),
141
+ };
142
+ if (scoped)
143
+ for (const authority of plan.authorities)
144
+ if (caseIds.includes(authority.caseId))
145
+ authority.target = knowledgeAuthorityTargetFromStep(after);
146
+ let planned = false;
147
+ if (!statesEqual(before, after)) {
148
+ plan.steps.push({
149
+ kind: operation.kind,
150
+ caseIds: structuredClone(caseIds),
151
+ endpoint: existing ? `${collection}${existing.id}/` : collection,
152
+ operation: existing ? "PATCH" : "POST",
153
+ before,
154
+ after,
155
+ dictionarySyncRequired: false,
156
+ requiresContrast: false,
157
+ });
158
+ planned = true;
159
+ }
160
+
161
+ const requestedScenes = new Set(scenes.map(String));
162
+ const impact = corpora
163
+ .filter(
164
+ (row) =>
165
+ row.active &&
166
+ String(row.corpus ?? row.description ?? "").trim() &&
167
+ listOf(row.scenes).some((scene) => requestedScenes.has(String(scene))),
168
+ )
169
+ .map(({ id, name: rowName, scenes }) => ({ id, name: rowName, scenes }));
170
+ if (
171
+ after.active &&
172
+ !impact.some((row) => existing && String(row.id) === String(existing.id))
173
+ )
174
+ impact.push({
175
+ id: existing?.id ?? null,
176
+ name: after.name,
177
+ scenes: after.scenes,
178
+ });
179
+ for (const row of impact)
180
+ if (
181
+ !plan.impact.some((item) => item.id === row.id && item.name === row.name)
182
+ )
183
+ plan.impact.push(row);
184
+
185
+ const lastStep = plan.steps[plan.steps.length - 1];
186
+ if (
187
+ lastStep?.kind === "knowledge" &&
188
+ impact.some(
189
+ (row) =>
190
+ row.id !== null &&
191
+ !(existing && String(row.id) === String(existing.id)),
192
+ )
193
+ )
194
+ lastStep.requiresContrast = true;
195
+
196
+ const promptCollection = promptCollectionPath(plan.workspaceId);
197
+ const prompts = after.active
198
+ ? requireArrayResponse(
199
+ await client.request("GET", promptCollection),
200
+ "INVALID_PROMPT_STATE",
201
+ "workspace Prompt list must be an array",
202
+ )
203
+ : [];
204
+ for (const scene of after.active ? scenes : []) {
205
+ const promptMatches = prompts.filter(
206
+ (prompt) => String(prompt?.scene) === String(scene),
207
+ );
208
+ if (promptMatches.length > 1)
209
+ fail(
210
+ "PROMPT_IDENTITY_AMBIGUOUS",
211
+ "multiple workspace Prompts match one scene",
212
+ );
213
+ const existingPrompt = promptMatches[0];
214
+ let promptBefore;
215
+ let source;
216
+ let desired;
217
+ if (existingPrompt) {
218
+ promptBefore = semanticPrompt(existingPrompt);
219
+ source = promptBridgeSource("workspace_override", promptBefore);
220
+ desired = {
221
+ id: existingPrompt.id,
222
+ scene: existingPrompt.scene,
223
+ prompt: bridgeLanguage(existingPrompt.prompt, scene, "prompt"),
224
+ promptEn: bridgeLanguage(existingPrompt.promptEn, scene, "promptEn"),
225
+ };
226
+ } else {
227
+ const defaults = await client.request(
228
+ "GET",
229
+ `${promptCollection}default/`,
230
+ {
231
+ query: { scene },
232
+ },
233
+ );
234
+ if (!isRecord(defaults))
235
+ fail("INVALID_PROMPT_STATE", "default Prompt response is invalid");
236
+ promptBefore = null;
237
+ source = promptBridgeSource("default", defaults);
238
+ desired = {
239
+ scene,
240
+ prompt: bridgeLanguage(defaults.prompt, scene, "prompt"),
241
+ promptEn: bridgeLanguage(defaults.promptEn, scene, "promptEn"),
242
+ };
243
+ }
244
+ if (
245
+ !String(desired.prompt ?? "").trim() &&
246
+ !String(desired.promptEn ?? "").trim()
247
+ )
248
+ continue;
249
+ if (statesEqual(promptBefore, desired)) continue;
250
+ const existingStep = plan.promptChanges.find(
251
+ (change) => String(change.after?.scene) === String(scene),
252
+ );
253
+ if (existingStep) {
254
+ if (
255
+ !statesEqual(existingStep.before, promptBefore) ||
256
+ !statesEqual(existingStep.after, desired) ||
257
+ canonicalJson(existingStep.source) !== canonicalJson(source)
258
+ )
259
+ fail(
260
+ "PROMPT_BRIDGE_CONFLICT",
261
+ "one Prompt scene cannot have different bridge states",
262
+ );
263
+ mergeCaseIds(existingStep.caseIds, caseIds);
264
+ existingStep.pairedKnowledge.caseIds = structuredClone(
265
+ existingStep.caseIds,
266
+ );
267
+ planned = true;
268
+ continue;
269
+ }
270
+ const dryRuns = await dryRunPromptChanges(
271
+ client,
272
+ promptCollection,
273
+ scene,
274
+ promptBefore,
275
+ desired,
276
+ );
277
+ plan.promptChanges.push({
278
+ caseIds: structuredClone(caseIds),
279
+ endpoint: existingPrompt
280
+ ? `${promptCollection}${existingPrompt.id}/`
281
+ : promptCollection,
282
+ operation: existingPrompt ? "PATCH" : "POST",
283
+ before: promptBefore,
284
+ after: desired,
285
+ pairedKnowledge: { caseIds: structuredClone(caseIds), scene },
286
+ source,
287
+ dryRuns,
288
+ });
289
+ planned = true;
290
+ }
291
+ plan.summaries.push({
292
+ kind: operation.kind,
293
+ status: planned ? "planned" : "noop",
294
+ name,
295
+ caseIds: structuredClone(caseIds),
296
+ });
297
+ }
298
+
299
+ export function promptBridgeSource(kind, value) {
300
+ return {
301
+ kind,
302
+ promptHash: hashValue(String(value?.prompt ?? "")),
303
+ promptEnHash: hashValue(String(value?.promptEn ?? "")),
304
+ };
305
+ }
306
+
307
+ export async function dryRunPromptChanges(
308
+ client,
309
+ promptCollection,
310
+ scene,
311
+ before,
312
+ desired,
313
+ ) {
314
+ const evidence = [];
315
+ for (const [field, language] of [
316
+ ["prompt", "zh-CN"],
317
+ ["promptEn", "en-US"],
318
+ ]) {
319
+ const prompt = String(desired[field] ?? "");
320
+ if (!prompt.trim() || (before !== null && prompt === before[field]))
321
+ continue;
322
+ const response = await client.request(
323
+ "POST",
324
+ `${promptCollection}dry-run/`,
325
+ {
326
+ body: { scene, prompt, language },
327
+ },
328
+ );
329
+ if (!isRecord(response) || typeof response.prompt !== "string")
330
+ fail("PROMPT_DRY_RUN_FAILED", "Prompt dry-run response is invalid");
331
+ evidence.push({
332
+ field,
333
+ language,
334
+ promptHash: hashValue(prompt),
335
+ status: "SUCCESS",
336
+ });
337
+ }
338
+ if (evidence.length === 0)
339
+ fail("PROMPT_DRY_RUN_REQUIRED", "changed Prompt languages require dry-run");
340
+ return evidence;
341
+ }
342
+
343
+ export function mergeCaseIds(target, additions) {
344
+ for (const caseId of additions)
345
+ if (!target.includes(caseId)) target.push(caseId);
346
+ }
347
+
348
+ export function semanticKnowledge(
349
+ value,
350
+ scoped = Object.hasOwn(value, "tuids"),
351
+ ) {
352
+ return compact({
353
+ id: value.id,
354
+ name: value.name,
355
+ corpus: value.corpus,
356
+ scenes: structuredClone(value.scenes),
357
+ active: value.active,
358
+ ...(scoped
359
+ ? { tuids: normalizeModelScope(value.tuids, { allowEmpty: true }) }
360
+ : {}),
361
+ });
362
+ }
363
+
364
+ export function semanticPrompt(value) {
365
+ return compact({
366
+ id: value.id,
367
+ scene: value.scene,
368
+ prompt: value.prompt,
369
+ promptEn: value.promptEn,
370
+ });
371
+ }
372
+
373
+ export function knowledgeBody(value, creating) {
374
+ return compact({
375
+ name: value.name,
376
+ corpus: value.corpus,
377
+ scenes: structuredClone(value.scenes),
378
+ ...(creating ? {} : { active: value.active }),
379
+ ...(Object.hasOwn(value, "tuids")
380
+ ? { tuids: structuredClone(value.tuids) }
381
+ : {}),
382
+ });
383
+ }
384
+
385
+ export function promptBody(value, creating) {
386
+ return compact({
387
+ ...(creating ? { scene: value.scene } : {}),
388
+ prompt: value.prompt,
389
+ promptEn: value.promptEn,
390
+ });
391
+ }
392
+
393
+ export function bridgeLanguage(value, scene, field) {
394
+ const text = String(value ?? "");
395
+ if (!text.trim()) return text;
396
+ const occurrences = text.split(KNOWLEDGE_SLOT).length - 1;
397
+ if (occurrences > 1)
398
+ fail(
399
+ "DUPLICATE_KNOWLEDGE_SLOT",
400
+ `${field} for scene ${scene} contains the slot more than once`,
401
+ );
402
+ return occurrences === 1 ? text : `${text}\n\n${KNOWLEDGE_SLOT}`;
403
+ }
404
+
405
+ export async function revalidatePairedKnowledge(
406
+ client,
407
+ workspaceId,
408
+ step,
409
+ authorities,
410
+ ) {
411
+ const authorityByCaseId = new Map(
412
+ authorities.map((authority) => [authority.caseId, authority]),
413
+ );
414
+ const rows = await listAllPages(client, corpusCollection(workspaceId));
415
+ for (const caseId of step.caseIds) {
416
+ const paired = step.pairedKnowledge?.knowledgeTarget;
417
+ const target = paired?.[caseId] ?? authorityByCaseId.get(caseId)?.target;
418
+ const matches = rows.filter((row) =>
419
+ target.id === undefined
420
+ ? normalizeText(row?.name) === normalizeText(target.name)
421
+ : String(row?.id) === String(target.id),
422
+ );
423
+ if (matches.length !== 1)
424
+ fail(
425
+ "KNOWLEDGE_STATE_DRIFT",
426
+ "Prompt bridge requires one exact current Knowledge target",
427
+ );
428
+ const current = semanticKnowledge(
429
+ await readFullKnowledge(client, workspaceId, matches[0]),
430
+ Object.hasOwn(target, "tuids"),
431
+ );
432
+ const actual = {
433
+ active: current.active,
434
+ corpusHash: hashValue(current.corpus),
435
+ ...(target.id === undefined
436
+ ? {}
437
+ : { id: canonicalDatasetId(current.id) }),
438
+ name: current.name,
439
+ scenes: structuredClone(current.scenes),
440
+ ...(Object.hasOwn(target, "tuids") ? { tuids: current.tuids } : {}),
441
+ };
442
+ if (canonicalJson(actual) !== canonicalJson(target))
443
+ fail(
444
+ "KNOWLEDGE_STATE_DRIFT",
445
+ "Knowledge changed before its Prompt bridge was applied",
446
+ );
447
+ }
448
+ }
449
+
450
+ export function knowledgeAuthorityTargetFromStep(after) {
451
+ return {
452
+ active: after.active,
453
+ corpusHash: hashValue(after.corpus),
454
+ ...(after.id === undefined ? {} : { id: after.id }),
455
+ name: after.name,
456
+ scenes: structuredClone(after.scenes),
457
+ ...(Object.hasOwn(after, "tuids")
458
+ ? { tuids: structuredClone(after.tuids) }
459
+ : {}),
460
+ };
461
+ }
462
+
463
+ export function validateKnowledgeStepStructure(step, workspaceId) {
464
+ const allowed = new Set([
465
+ "after",
466
+ "before",
467
+ "caseIds",
468
+ "dictionarySyncRequired",
469
+ "endpoint",
470
+ "kind",
471
+ "operation",
472
+ "requiresContrast",
473
+ ]);
474
+ if (
475
+ Object.keys(step).some((field) => !allowed.has(field)) ||
476
+ [...allowed].some((field) => !Object.hasOwn(step, field)) ||
477
+ step.kind !== "knowledge" ||
478
+ step.dictionarySyncRequired !== false
479
+ )
480
+ fail("INVALID_KNOWLEDGE_PLAN", "Knowledge step fields are invalid");
481
+ const collection = corpusCollection(workspaceId);
482
+ const after = validateKnowledgeSnapshot(
483
+ step.after,
484
+ "after",
485
+ step.operation === "PATCH",
486
+ );
487
+ let before = null;
488
+ if (step.operation === "POST") {
489
+ if (
490
+ step.before !== null ||
491
+ after.id !== undefined ||
492
+ step.endpoint !== collection
493
+ )
494
+ fail(
495
+ "INVALID_KNOWLEDGE_PLAN",
496
+ "Knowledge POST must create from the collection",
497
+ );
498
+ } else if (step.operation === "PATCH") {
499
+ before = validateKnowledgeSnapshot(step.before, "before", true);
500
+ if (Object.hasOwn(before, "tuids") !== Object.hasOwn(after, "tuids"))
501
+ fail(
502
+ "INVALID_KNOWLEDGE_PLAN",
503
+ "Knowledge snapshots must retain the same scope contract",
504
+ );
505
+ const beforeId = canonicalPlanResourceId(
506
+ before.id,
507
+ "INVALID_KNOWLEDGE_PLAN",
508
+ );
509
+ const afterId = canonicalPlanResourceId(after.id, "INVALID_KNOWLEDGE_PLAN");
510
+ if (
511
+ beforeId !== afterId ||
512
+ step.endpoint !== `${collection}${beforeId}/` ||
513
+ statesEqual(before, after)
514
+ )
515
+ fail(
516
+ "INVALID_KNOWLEDGE_PLAN",
517
+ "Knowledge PATCH identity or desired state is invalid",
518
+ );
519
+ } else fail("INVALID_KNOWLEDGE_PLAN", "Knowledge operation is invalid");
520
+ return {
521
+ after,
522
+ before,
523
+ caseIds: validateMutationCaseIds(step.caseIds, "INVALID_KNOWLEDGE_PLAN"),
524
+ };
525
+ }
526
+
527
+ export function validateKnowledgeSnapshot(value, label, requireId) {
528
+ if (!isRecord(value))
529
+ fail("INVALID_KNOWLEDGE_PLAN", `Knowledge ${label} must be an object`);
530
+ const required = new Set([
531
+ ...(requireId ? ["id"] : []),
532
+ "active",
533
+ "corpus",
534
+ "name",
535
+ "scenes",
536
+ ]);
537
+ const allowed = new Set([...required, "tuids"]);
538
+ if (
539
+ Object.keys(value).some((field) => !allowed.has(field)) ||
540
+ [...required].some((field) => !Object.hasOwn(value, field))
541
+ )
542
+ fail("INVALID_KNOWLEDGE_PLAN", `Knowledge ${label} fields are invalid`);
543
+ if (requireId) canonicalPlanResourceId(value.id, "INVALID_KNOWLEDGE_PLAN");
544
+ const name = requiredText(value.name, `${label}.name`);
545
+ const corpus = requiredText(value.corpus, `${label}.corpus`);
546
+ if (
547
+ name !== value.name ||
548
+ [...name].length > 256 ||
549
+ corpus !== value.corpus ||
550
+ typeof value.active !== "boolean"
551
+ )
552
+ fail("INVALID_KNOWLEDGE_PLAN", `Knowledge ${label} snapshot is invalid`);
553
+ validateKnowledgeSceneSnapshot(value.scenes, "INVALID_KNOWLEDGE_PLAN");
554
+ if (
555
+ Object.hasOwn(value, "tuids") &&
556
+ canonicalJson(normalizeModelScope(value.tuids, { allowEmpty: true })) !==
557
+ canonicalJson(value.tuids)
558
+ )
559
+ fail("INVALID_KNOWLEDGE_PLAN", "Knowledge model scope must be canonical");
560
+ return value;
561
+ }
562
+
563
+ export function validateKnowledgeSceneSnapshot(value, code) {
564
+ if (
565
+ !Array.isArray(value) ||
566
+ value.length === 0 ||
567
+ new Set(value).size !== value.length ||
568
+ value.some((scene) => !Number.isSafeInteger(scene) || scene <= 0)
569
+ )
570
+ fail(code, "Knowledge scenes are invalid");
571
+ }
572
+
573
+ export function corpusCollection(workspaceId) {
574
+ return `/api/v3/admin-projects/${workspaceId}/corpus/`;
575
+ }
576
+
577
+ export function promptCollectionPath(workspaceId) {
578
+ return `/api/v3/admin-projects/${workspaceId}/prompts/`;
579
+ }
580
+
581
+ function knowledgeAuthorityTarget(operation) {
582
+ const normalized = normalizeKnowledgeOperation(operation);
583
+ return {
584
+ active: normalized.active,
585
+ corpusHash: hashValue(normalized.corpus),
586
+ ...(normalized.id === undefined ? {} : { id: normalized.id }),
587
+ name: normalized.name,
588
+ scenes: structuredClone(normalized.scenes),
589
+ ...(Object.hasOwn(normalized, "tuids")
590
+ ? { tuids: structuredClone(normalized.tuids) }
591
+ : {}),
592
+ };
593
+ }
594
+
595
+ function createKnowledgeCoalescer() {
596
+ const groups = new Map();
597
+ const names = new Map();
598
+ return {
599
+ add(operation, result) {
600
+ const caseId = operation.caseId.trim();
601
+ const normalized = normalizeKnowledgeOperation(operation);
602
+ coalesceNamedOperation({
603
+ caseId,
604
+ operation: normalized,
605
+ groups,
606
+ names,
607
+ result,
608
+ conflictCode: "KNOWLEDGE_CONFLICT",
609
+ });
610
+ return true;
611
+ },
612
+ };
613
+ }
614
+
615
+ function knowledgeWriteDesired(client, step) {
616
+ return client.request(step.operation, step.endpoint, {
617
+ body: knowledgeBody(step.after, step.operation === "POST"),
618
+ });
619
+ }
620
+
621
+ async function knowledgeWriteBefore(client, step) {
622
+ if (Object.hasOwn(step.before, "tuids"))
623
+ await validateWorkspaceModelScope(
624
+ client,
625
+ workspaceIdFromStep(step),
626
+ step.before.tuids,
627
+ );
628
+ return client.request("PATCH", step.endpoint, {
629
+ body: knowledgeBody(step.before, false),
630
+ });
631
+ }
632
+
633
+ async function knowledgeReadState(client, workspaceId, step) {
634
+ const id = step.after?.id ?? step.before?.id;
635
+ if (id !== undefined)
636
+ return semanticKnowledge(
637
+ await client.request("GET", `${corpusCollection(workspaceId)}${id}/`),
638
+ Object.hasOwn(step.after, "tuids"),
639
+ );
640
+ const name = step.after?.name ?? step.before?.name;
641
+ const rows = await listAllPages(client, corpusCollection(workspaceId), {
642
+ q: name,
643
+ });
644
+ const matches = rows.filter(
645
+ (item) => normalizeText(item?.name) === normalizeText(name),
646
+ );
647
+ if (matches.length > 1)
648
+ fail(
649
+ "KNOWLEDGE_IDENTITY_AMBIGUOUS",
650
+ "multiple Knowledge resources match the exact identity",
651
+ );
652
+ return matches[0]
653
+ ? semanticKnowledge(
654
+ await readFullKnowledge(client, workspaceId, matches[0]),
655
+ Object.hasOwn(step.after, "tuids"),
656
+ )
657
+ : null;
658
+ }
659
+
660
+ async function knowledgeReadCreatedState(client, workspaceId, step) {
661
+ const id = step.after?.id;
662
+ const rows = await listAllPages(client, corpusCollection(workspaceId));
663
+ const row = rows.find((item) => String(item.id) === String(id));
664
+ return row
665
+ ? semanticKnowledge(
666
+ await readFullKnowledge(client, workspaceId, row),
667
+ Object.hasOwn(step.after, "tuids"),
668
+ )
669
+ : null;
670
+ }
671
+
672
+ async function knowledgeApplyStep(client, workspaceId, step, ctx) {
673
+ let response;
674
+ try {
675
+ response = await client.request("POST", step.endpoint, {
676
+ body: knowledgeBody(step.after, true),
677
+ });
678
+ } catch (error) {
679
+ error.partialStep = ctx.partialStep(step, undefined, [
680
+ null,
681
+ { ...step.after, active: true },
682
+ ]);
683
+ throw error;
684
+ }
685
+ let completed = resolveCompletedStep(step, response);
686
+ let current;
687
+ let possibleAfter = [{ ...completed.after, active: true }];
688
+ try {
689
+ current = await knowledgeReadState(client, workspaceId, completed);
690
+ completed = resolveCompletedStep(completed, current);
691
+ assertState(
692
+ current,
693
+ { ...step.after, active: true },
694
+ "WRITE_VERIFICATION_FAILED",
695
+ step,
696
+ );
697
+ possibleAfter = [current, { ...completed.after, active: false }];
698
+ current = undefined;
699
+ await client.request("PATCH", completed.endpoint, {
700
+ body: { active: false },
701
+ });
702
+ current = await knowledgeReadState(client, workspaceId, completed);
703
+ assertState(current, step.after, "WRITE_VERIFICATION_FAILED", step);
704
+ } catch (error) {
705
+ error.partialStep = ctx.partialStep(completed, current, possibleAfter);
706
+ throw error;
707
+ }
708
+ return { ...completed, after: current };
709
+ }
710
+
711
+ async function knowledgeExactCreatedCandidates(client, workspaceId, step) {
712
+ const name = step.after?.name;
713
+ const rows = await listAllPages(client, corpusCollection(workspaceId));
714
+ return Promise.all(
715
+ rows
716
+ .filter((row) => normalizeText(row.name) === normalizeText(name))
717
+ .map(async (row) =>
718
+ semanticKnowledge(
719
+ await readFullKnowledge(client, workspaceId, row),
720
+ Object.hasOwn(step.after, "tuids"),
721
+ ),
722
+ ),
723
+ );
724
+ }
725
+
726
+ function validateKnowledgeAuthorityTarget(target) {
727
+ const allowed = new Set([
728
+ "active",
729
+ "corpusHash",
730
+ "id",
731
+ "name",
732
+ "scenes",
733
+ "tuids",
734
+ ]);
735
+ if (
736
+ Object.keys(target).some((field) => !allowed.has(field)) ||
737
+ !Object.hasOwn(target, "active") ||
738
+ !Object.hasOwn(target, "corpusHash") ||
739
+ !Object.hasOwn(target, "name") ||
740
+ !Object.hasOwn(target, "scenes") ||
741
+ (target.id !== undefined && canonicalDatasetId(target.id) !== target.id) ||
742
+ requiredText(target.name, "authority.name") !== target.name ||
743
+ [...target.name].length > 256 ||
744
+ typeof target.active !== "boolean" ||
745
+ !/^[0-9a-f]{64}$/u.test(target.corpusHash)
746
+ )
747
+ fail("INVALID_PLAN_STRUCTURE", "Knowledge authority target is invalid");
748
+ validateKnowledgeSceneSnapshot(target.scenes, "INVALID_PLAN_STRUCTURE");
749
+ if (
750
+ Object.hasOwn(target, "tuids") &&
751
+ canonicalJson(normalizeModelScope(target.tuids, { allowEmpty: true })) !==
752
+ canonicalJson(target.tuids)
753
+ )
754
+ fail(
755
+ "INVALID_PLAN_STRUCTURE",
756
+ "Knowledge authority model scope is invalid",
757
+ );
758
+ }
759
+
760
+ function validateKnowledgePlanStep(
761
+ step,
762
+ plan,
763
+ authorities,
764
+ plannedCaseIds,
765
+ usedCaseIds,
766
+ ) {
767
+ const { after, caseIds } = validateKnowledgeStepStructure(
768
+ step,
769
+ plan.workspaceId,
770
+ );
771
+ for (const caseId of caseIds)
772
+ if (
773
+ !matchesAuthority(
774
+ authorities.get(caseId),
775
+ "knowledge",
776
+ (target) =>
777
+ canonicalJson(target) ===
778
+ canonicalJson(knowledgeAuthorityTargetFromStep(after)),
779
+ )
780
+ )
781
+ fail(
782
+ "INVALID_KNOWLEDGE_PLAN",
783
+ "Knowledge step caseIds must match exact Knowledge authorities",
784
+ );
785
+ claimStepCaseIds(usedCaseIds, caseIds);
786
+ for (const caseId of caseIds) plannedCaseIds.add(caseId);
787
+ }
788
+
789
+ function knowledgeSummaryMatches(summary, authorityTargets) {
790
+ const targets = authorityTargets.map(({ target }) => target);
791
+ return targets.every((target) => summary.name === target.name);
792
+ }
793
+
794
+ export const knowledgeKind = {
795
+ name: "knowledge",
796
+ planable: true,
797
+ plan: planKnowledge,
798
+ authorityTarget: knowledgeAuthorityTarget,
799
+ createCoalescer: createKnowledgeCoalescer,
800
+ applyStep: (client, workspaceId, step, ctx) =>
801
+ step.before === null && !step.after.active
802
+ ? knowledgeApplyStep(client, workspaceId, step, ctx)
803
+ : undefined,
804
+ writeDesired: knowledgeWriteDesired,
805
+ writeBefore: knowledgeWriteBefore,
806
+ readState: knowledgeReadState,
807
+ preApplyRead: async (client, workspaceId, step) => {
808
+ const current = await knowledgeReadState(client, workspaceId, step);
809
+ if (Object.hasOwn(step.after, "tuids"))
810
+ await validateWorkspaceModelScope(client, workspaceId, step.after.tuids);
811
+ return current;
812
+ },
813
+ readCreatedState: knowledgeReadCreatedState,
814
+ exactCreatedCandidates: knowledgeExactCreatedCandidates,
815
+ collection: corpusCollection,
816
+ targetKey: (step) =>
817
+ `knowledge:${step.after?.id ?? normalizeText(step.after?.name)}`,
818
+ possibleAfter: (step) =>
819
+ step.before === null && !step.after.active
820
+ ? [null, { ...step.after, active: true }, step.after]
821
+ : [step.before, step.after],
822
+ validateAuthorityTarget: validateKnowledgeAuthorityTarget,
823
+ validateStep: validateKnowledgePlanStep,
824
+ summaryField: ["name"],
825
+ summaryMatches: knowledgeSummaryMatches,
826
+ };
827
+
828
+ async function readFullKnowledge(client, workspaceId, row) {
829
+ if (typeof row.corpus === "string") return row;
830
+ const detail = await client.request(
831
+ "GET",
832
+ `${corpusCollection(workspaceId)}${canonicalDatasetId(row.id)}/`,
833
+ );
834
+ if (
835
+ String(detail?.id) !== String(row.id) ||
836
+ typeof detail?.corpus !== "string"
837
+ )
838
+ fail("INVALID_KNOWLEDGE_STATE", "无法读取完整知识,请刷新列表并重试。");
839
+ return detail;
840
+ }
841
+
842
+ function workspaceIdFromStep(step) {
843
+ const match = /^\/api\/v3\/admin-projects\/(\d+)\/corpus\//u.exec(
844
+ step.endpoint,
845
+ );
846
+ if (!match) fail("INVALID_KNOWLEDGE_PLAN", "Knowledge endpoint is invalid");
847
+ return Number(match[1]);
848
+ }