@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,447 +1,598 @@
1
- import {
2
- canonicalJson,
3
- hashArtifactValue as hashValue,
4
- withHash,
5
- } from "../../datarc-semantic-core/scripts/canonical.mjs";
6
- import {
7
- bindSummaryAuthorityTargets,
8
- canonicalPlanResourceId,
9
- fail,
10
- isRecord,
11
- requireArrayResponse,
12
- statesEqual,
13
- validateMutationCaseIds,
14
- } from "../../datarc-semantic-core/scripts/shared.mjs";
15
- import {
16
- bridgeLanguage,
17
- KNOWLEDGE_SLOT,
18
- promptBody,
19
- promptBridgeSource,
20
- promptCollectionPath,
21
- revalidatePairedKnowledge,
22
- semanticPrompt,
23
- } from "../../datarc-semantic-knowledge/scripts/knowledge-plan.mjs";
24
-
25
- const PLAN_VERSION = 1; // must match interventions PLAN_VERSION
26
- export function buildPromptPlan(knowledgePlan, workspaceId) {
27
- const caseIds = new Set(
28
- knowledgePlan.promptChanges.flatMap((change) => change.caseIds),
29
- );
30
- const scenesByCase = new Map();
31
- for (const change of knowledgePlan.promptChanges) {
32
- const scene = change.pairedKnowledge?.scene ?? change.after?.scene;
33
- for (const caseId of change.caseIds) {
34
- if (!scenesByCase.has(caseId)) scenesByCase.set(caseId, new Set());
35
- scenesByCase.get(caseId).add(scene);
36
- }
37
- }
38
- const authorities = knowledgePlan.authorities
39
- .filter((authority) => caseIds.has(authority.caseId))
40
- .map((authority) => ({
41
- ...authority,
42
- kind: "prompt_bridge",
43
- target: { scene: [...scenesByCase.get(authority.caseId)] },
44
- }));
45
- const steps = knowledgePlan.promptChanges.map((change) => ({
46
- kind: "prompt_bridge",
47
- caseIds: structuredClone(change.caseIds),
48
- endpoint: change.endpoint,
49
- operation: change.operation,
50
- before: change.before,
51
- after: change.after,
52
- dictionarySyncRequired: false,
53
- pairedKnowledge: structuredClone({
54
- ...change.pairedKnowledge,
55
- knowledgeTarget: Object.fromEntries(
56
- change.caseIds.map((caseId) => {
57
- const authority = knowledgePlan.authorities.find(
58
- (a) => a.caseId === caseId,
59
- );
60
- return [
61
- caseId,
62
- authority ? structuredClone(authority.target) : undefined,
63
- ];
64
- }),
65
- ),
66
- }),
67
- preconditions: { dryRuns: change.dryRuns, source: change.source },
68
- }));
69
- const plan = {
70
- version: PLAN_VERSION,
71
- workspaceId,
72
- authorities,
73
- steps,
74
- summaries: steps.map((step) => ({
75
- kind: "prompt_bridge",
76
- status: "planned",
77
- scene: step.after?.scene,
78
- caseIds: structuredClone(step.caseIds),
79
- })),
80
- warnings: [],
81
- impact: [],
82
- };
83
- bindSummaryAuthorityTargets(plan);
84
- return withHash(plan, "planHash");
85
- }
86
-
87
- export async function revalidatePromptBridgeStep(
88
- client,
89
- workspaceId,
90
- step,
91
- authorities,
92
- ) {
93
- const { dryRuns, source } = validatePromptBridgeStepStructure(
94
- step,
95
- workspaceId,
96
- );
97
- await revalidatePairedKnowledge(client, workspaceId, step, authorities);
98
- const collection = promptCollectionPath(workspaceId);
99
- if (source.kind === "default") {
100
- const defaults = await client.request("GET", `${collection}default/`, {
101
- query: { scene: step.after.scene },
102
- });
103
- if (
104
- !isRecord(defaults) ||
105
- canonicalJson(promptBridgeSource("default", defaults)) !==
106
- canonicalJson(source) ||
107
- bridgeLanguage(defaults.prompt, step.after.scene, "prompt") !==
108
- step.after.prompt ||
109
- bridgeLanguage(defaults.promptEn, step.after.scene, "promptEn") !==
110
- step.after.promptEn
111
- )
112
- fail(
113
- "PROMPT_SOURCE_DRIFT",
114
- "default Prompt changed after the bridge was planned",
115
- );
116
- }
117
- for (const evidence of dryRuns) {
118
- const response = await client.request("POST", `${collection}dry-run/`, {
119
- body: {
120
- scene: step.after.scene,
121
- prompt: step.after[evidence.field],
122
- language: evidence.language,
123
- },
124
- });
125
- if (!isRecord(response) || typeof response.prompt !== "string")
126
- fail("PROMPT_DRY_RUN_FAILED", "Prompt dry-run response is invalid");
127
- }
128
- }
129
-
130
- export function validatePromptBridgeStepStructure(step, workspaceId) {
131
- const allowed = new Set([
132
- "after",
133
- "before",
134
- "caseIds",
135
- "dictionarySyncRequired",
136
- "endpoint",
137
- "kind",
138
- "operation",
139
- "pairedKnowledge",
140
- "preconditions",
141
- ]);
142
- if (
143
- Object.keys(step).some((field) => !allowed.has(field)) ||
144
- [...allowed].some((field) => !Object.hasOwn(step, field)) ||
145
- step.kind !== "prompt_bridge" ||
146
- step.dictionarySyncRequired !== false
147
- )
148
- fail("INVALID_PROMPT_BRIDGE_PLAN", "Prompt bridge step fields are invalid");
149
- const collection = promptCollectionPath(workspaceId);
150
- const after = validatePromptSnapshot(
151
- step.after,
152
- "after",
153
- step.operation === "PATCH",
154
- );
155
- let before = null;
156
- if (step.operation === "POST") {
157
- if (
158
- step.before !== null ||
159
- after.id !== undefined ||
160
- step.endpoint !== collection
161
- )
162
- fail(
163
- "INVALID_PROMPT_BRIDGE_PLAN",
164
- "Prompt bridge POST must create from the collection",
165
- );
166
- } else if (step.operation === "PATCH") {
167
- before = validatePromptSnapshot(step.before, "before", true);
168
- const beforeId = canonicalPlanResourceId(
169
- before.id,
170
- "INVALID_PROMPT_BRIDGE_PLAN",
171
- );
172
- const afterId = canonicalPlanResourceId(
173
- after.id,
174
- "INVALID_PROMPT_BRIDGE_PLAN",
175
- );
176
- if (
177
- beforeId !== afterId ||
178
- before.scene !== after.scene ||
179
- step.endpoint !== `${collection}${beforeId}/` ||
180
- statesEqual(before, after)
181
- )
182
- fail(
183
- "INVALID_PROMPT_BRIDGE_PLAN",
184
- "Prompt bridge PATCH identity or desired state is invalid",
185
- );
186
- } else
187
- fail("INVALID_PROMPT_BRIDGE_PLAN", "Prompt bridge operation is invalid");
188
-
189
- const caseIds = validateMutationCaseIds(
190
- step.caseIds,
191
- "INVALID_PROMPT_BRIDGE_PLAN",
192
- );
193
- if (
194
- !isRecord(step.pairedKnowledge) ||
195
- !["caseIds", "scene"].every((field) =>
196
- Object.hasOwn(step.pairedKnowledge, field),
197
- ) ||
198
- Object.keys(step.pairedKnowledge).some(
199
- (field) => !["caseIds", "scene", "knowledgeTarget"].includes(field),
200
- ) ||
201
- step.pairedKnowledge.scene !== after.scene ||
202
- canonicalJson(step.pairedKnowledge.caseIds) !== canonicalJson(caseIds)
203
- )
204
- fail(
205
- "INVALID_PROMPT_BRIDGE_PLAN",
206
- "Prompt bridge is not bound to its Knowledge authorities",
207
- );
208
- const { dryRuns, source } = validatePromptBridgePreconditions(
209
- step.preconditions,
210
- before,
211
- after,
212
- );
213
- return { after, before, caseIds, dryRuns, source };
214
- }
215
-
216
- export function validatePromptSnapshot(value, label, requireId) {
217
- if (!isRecord(value))
218
- fail(
219
- "INVALID_PROMPT_BRIDGE_PLAN",
220
- `Prompt bridge ${label} must be an object`,
221
- );
222
- const allowed = new Set([
223
- ...(requireId ? ["id"] : []),
224
- "prompt",
225
- "promptEn",
226
- "scene",
227
- ]);
228
- if (
229
- Object.keys(value).some((field) => !allowed.has(field)) ||
230
- [...allowed].some((field) => !Object.hasOwn(value, field)) ||
231
- !Number.isSafeInteger(value.scene) ||
232
- value.scene <= 0 ||
233
- typeof value.prompt !== "string" ||
234
- typeof value.promptEn !== "string" ||
235
- (!value.prompt.trim() && !value.promptEn.trim())
236
- )
237
- fail(
238
- "INVALID_PROMPT_BRIDGE_PLAN",
239
- `Prompt bridge ${label} snapshot is invalid`,
240
- );
241
- if (requireId)
242
- canonicalPlanResourceId(value.id, "INVALID_PROMPT_BRIDGE_PLAN");
243
- for (const field of ["prompt", "promptEn"]) {
244
- const count = value[field].split(KNOWLEDGE_SLOT).length - 1;
245
- if (count > 1 || (label === "after" && value[field].trim() && count !== 1))
246
- fail(
247
- "INVALID_PROMPT_BRIDGE_PLAN",
248
- `Prompt bridge ${label} slot count is invalid`,
249
- );
250
- }
251
- return value;
252
- }
253
-
254
- export function validatePromptBridgePreconditions(
255
- preconditions,
256
- before,
257
- after,
258
- ) {
259
- if (
260
- !isRecord(preconditions) ||
261
- canonicalJson(Object.keys(preconditions).sort()) !==
262
- canonicalJson(["dryRuns", "source"]) ||
263
- !Array.isArray(preconditions.dryRuns) ||
264
- !isRecord(preconditions.source)
265
- )
266
- fail(
267
- "INVALID_PROMPT_BRIDGE_PLAN",
268
- "Prompt bridge preconditions are invalid",
269
- );
270
- const source = preconditions.source;
271
- if (
272
- canonicalJson(Object.keys(source).sort()) !==
273
- canonicalJson(["kind", "promptEnHash", "promptHash"]) ||
274
- !new Set(["default", "workspace_override"]).has(source.kind) ||
275
- !/^[0-9a-f]{64}$/u.test(source.promptHash) ||
276
- !/^[0-9a-f]{64}$/u.test(source.promptEnHash) ||
277
- (source.kind === "default") !== (before === null) ||
278
- (before !== null &&
279
- canonicalJson(source) !==
280
- canonicalJson(promptBridgeSource("workspace_override", before))) ||
281
- (before !== null &&
282
- (bridgeLanguage(before.prompt, after.scene, "prompt") !== after.prompt ||
283
- bridgeLanguage(before.promptEn, after.scene, "promptEn") !==
284
- after.promptEn))
285
- )
286
- fail(
287
- "INVALID_PROMPT_BRIDGE_PLAN",
288
- "Prompt bridge source evidence is invalid",
289
- );
290
- const expectedFields = ["prompt", "promptEn"].filter(
291
- (field) =>
292
- after[field].trim() &&
293
- (before === null || after[field] !== before[field]),
294
- );
295
- const seen = new Set();
296
- for (const evidence of preconditions.dryRuns) {
297
- if (
298
- !isRecord(evidence) ||
299
- canonicalJson(Object.keys(evidence).sort()) !==
300
- canonicalJson(["field", "language", "promptHash", "status"]) ||
301
- !expectedFields.includes(evidence.field) ||
302
- seen.has(evidence.field) ||
303
- evidence.language !== (evidence.field === "prompt" ? "zh-CN" : "en-US") ||
304
- evidence.promptHash !== hashValue(after[evidence.field]) ||
305
- evidence.status !== "SUCCESS"
306
- )
307
- fail(
308
- "INVALID_PROMPT_BRIDGE_PLAN",
309
- "Prompt bridge dry-run evidence is invalid",
310
- );
311
- seen.add(evidence.field);
312
- }
313
- if (
314
- seen.size !== expectedFields.length ||
315
- expectedFields.some((field) => !seen.has(field))
316
- )
317
- fail(
318
- "INVALID_PROMPT_BRIDGE_PLAN",
319
- "every changed Prompt language requires one dry-run",
320
- );
321
- return { dryRuns: preconditions.dryRuns, source };
322
- }
323
-
324
- function promptWriteDesired(client, step) {
325
- return client.request(step.operation, step.endpoint, {
326
- body: promptBody(step.after, step.operation === "POST"),
327
- });
328
- }
329
-
330
- function promptWriteBefore(client, step) {
331
- return client.request("PATCH", step.endpoint, {
332
- body: promptBody(step.before, false),
333
- });
334
- }
335
-
336
- async function promptReadState(client, workspaceId, step) {
337
- const id = step.after?.id ?? step.before?.id;
338
- if (id !== undefined)
339
- return semanticPrompt(
340
- await client.request(
341
- "GET",
342
- `${promptCollectionPath(workspaceId)}${id}/`,
343
- ),
344
- );
345
- const rows = requireArrayResponse(
346
- await client.request("GET", promptCollectionPath(workspaceId)),
347
- "INVALID_PROMPT_STATE",
348
- "workspace Prompt list must be an array",
349
- );
350
- const matches = rows.filter(
351
- (item) =>
352
- String(item.scene) === String(step.after?.scene ?? step.before?.scene),
353
- );
354
- if (matches.length > 1)
355
- fail(
356
- "PROMPT_IDENTITY_AMBIGUOUS",
357
- "multiple workspace Prompts match one scene",
358
- );
359
- return matches[0] ? semanticPrompt(matches[0]) : null;
360
- }
361
-
362
- async function promptReadCreatedState(client, workspaceId, step) {
363
- const id = step.after?.id;
364
- const rows = requireArrayResponse(
365
- await client.request("GET", promptCollectionPath(workspaceId)),
366
- "INVALID_PROMPT_STATE",
367
- "workspace Prompt list must be an array",
368
- );
369
- const row = rows.find((item) => String(item.id) === String(id));
370
- return row ? semanticPrompt(row) : null;
371
- }
372
-
373
- async function promptExactCreatedCandidates(client, workspaceId, step) {
374
- const scene = step.after?.scene;
375
- const rows = requireArrayResponse(
376
- await client.request("GET", promptCollectionPath(workspaceId)),
377
- "INVALID_PROMPT_STATE",
378
- "workspace Prompt list must be an array",
379
- );
380
- return rows
381
- .filter((row) => String(row.scene) === String(scene))
382
- .map(semanticPrompt);
383
- }
384
-
385
- function promptRevalidate(client, workspaceId, step, ctx) {
386
- return revalidatePromptBridgeStep(
387
- client,
388
- workspaceId,
389
- step,
390
- ctx.authorities,
391
- );
392
- }
393
-
394
- function validatePromptAuthorityTarget(target) {
395
- const allowed = new Set(["scene"]);
396
- if (
397
- Object.keys(target).some((field) => !allowed.has(field)) ||
398
- !Array.isArray(target.scene) ||
399
- target.scene.length === 0 ||
400
- target.scene.some((scene) => !Number.isSafeInteger(scene) || scene <= 0)
401
- )
402
- fail("INVALID_PLAN_STRUCTURE", "Prompt authority target is invalid");
403
- }
404
-
405
- function validatePromptPlanStep(step, plan, authorities, plannedCaseIds) {
406
- const { caseIds } = validatePromptBridgeStepStructure(
407
- step,
408
- plan.workspaceId,
409
- );
410
- for (const caseId of caseIds) {
411
- const authority = authorities.get(caseId);
412
- const matched =
413
- authority?.kind === "knowledge"
414
- ? authority.target.scenes.includes(step.after.scene)
415
- : authority?.kind === "prompt_bridge"
416
- ? authority.target.scene.includes(step.after.scene)
417
- : false;
418
- if (!matched)
419
- fail(
420
- "INVALID_PROMPT_BRIDGE_PLAN",
421
- "Prompt bridge caseIds must match exact Knowledge authorities",
422
- );
423
- plannedCaseIds.add(caseId);
424
- }
425
- }
426
-
427
- function promptSummaryMatches(summary, authorityTargets) {
428
- const targets = authorityTargets.map(({ target }) => target);
429
- return targets.every((target) => summary.name === target.name);
430
- }
431
-
432
- export const promptKind = {
433
- name: "prompt_bridge",
434
- planable: false,
435
- writeDesired: promptWriteDesired,
436
- writeBefore: promptWriteBefore,
437
- readState: promptReadState,
438
- readCreatedState: promptReadCreatedState,
439
- postApplyRead: promptRevalidate,
440
- exactCreatedCandidates: promptExactCreatedCandidates,
441
- collection: promptCollectionPath,
442
- targetKey: (step) => `prompt:${step.after?.id ?? step.after?.scene}`,
443
- validateAuthorityTarget: validatePromptAuthorityTarget,
444
- validateStep: validatePromptPlanStep,
445
- summaryField: ["scene"],
446
- summaryMatches: promptSummaryMatches,
447
- };
1
+ import {
2
+ canonicalJson,
3
+ hashArtifactValue as hashValue,
4
+ withHash,
5
+ } from "../../datarc-semantic-core/scripts/canonical.mjs";
6
+ import {
7
+ assertEnvelopeHash,
8
+ bindSummaryAuthorityTargets,
9
+ canonicalPlanResourceId,
10
+ fail,
11
+ isRecord,
12
+ listAllPages,
13
+ requireArrayResponse,
14
+ statesEqual,
15
+ validateMutationCaseIds,
16
+ } from "../../datarc-semantic-core/scripts/shared.mjs";
17
+ import {
18
+ bridgeLanguage,
19
+ knowledgeKind,
20
+ KNOWLEDGE_SLOT,
21
+ promptBody,
22
+ promptBridgeSource,
23
+ promptCollectionPath,
24
+ revalidatePairedKnowledge,
25
+ semanticPrompt,
26
+ } from "../../datarc-semantic-knowledge/scripts/knowledge-plan.mjs";
27
+
28
+ const PLAN_VERSION = 1; // must match interventions PLAN_VERSION
29
+ export function buildPromptPlan(knowledgePlan, workspaceId) {
30
+ assertEnvelopeHash(
31
+ knowledgePlan,
32
+ "planHash",
33
+ `APPLY:${knowledgePlan?.planHash}`,
34
+ "APPLY",
35
+ );
36
+ if (
37
+ knowledgePlan.workspaceId !== workspaceId ||
38
+ !Array.isArray(knowledgePlan.promptChanges)
39
+ )
40
+ fail(
41
+ "INVALID_PROMPT_BRIDGE_PLAN",
42
+ "Knowledge计划与工作区不匹配,请重新读取同一工作区的完整计划。",
43
+ );
44
+ const caseIds = new Set(
45
+ knowledgePlan.promptChanges.flatMap((change) => change.caseIds),
46
+ );
47
+ const scenesByCase = new Map();
48
+ for (const change of knowledgePlan.promptChanges) {
49
+ const scene = change.pairedKnowledge?.scene ?? change.after?.scene;
50
+ for (const caseId of change.caseIds) {
51
+ if (!scenesByCase.has(caseId)) scenesByCase.set(caseId, new Set());
52
+ scenesByCase.get(caseId).add(scene);
53
+ }
54
+ }
55
+ const authorities = knowledgePlan.authorities
56
+ .filter((authority) => caseIds.has(authority.caseId))
57
+ .map((authority) => ({
58
+ ...authority,
59
+ kind: "prompt_bridge",
60
+ target: {
61
+ scene: [...scenesByCase.get(authority.caseId)],
62
+ knowledgeTarget: structuredClone(authority.target),
63
+ },
64
+ }));
65
+ const steps = knowledgePlan.promptChanges.map((change) => ({
66
+ kind: "prompt_bridge",
67
+ caseIds: structuredClone(change.caseIds),
68
+ endpoint: change.endpoint,
69
+ operation: change.operation,
70
+ before: change.before,
71
+ after: change.after,
72
+ dictionarySyncRequired: false,
73
+ requiresContrast: knowledgePlan.steps.some(
74
+ (step) =>
75
+ step.requiresContrast === true &&
76
+ step.caseIds.some((caseId) => change.caseIds.includes(caseId)),
77
+ ),
78
+ pairedKnowledge: structuredClone({
79
+ ...change.pairedKnowledge,
80
+ knowledgeTarget: Object.fromEntries(
81
+ change.caseIds.map((caseId) => {
82
+ const authority = knowledgePlan.authorities.find(
83
+ (a) => a.caseId === caseId,
84
+ );
85
+ return [
86
+ caseId,
87
+ authority ? structuredClone(authority.target) : undefined,
88
+ ];
89
+ }),
90
+ ),
91
+ }),
92
+ preconditions: { dryRuns: change.dryRuns, source: change.source },
93
+ }));
94
+ const plan = {
95
+ version: PLAN_VERSION,
96
+ workspaceId,
97
+ dependsOn: knowledgePlan.planHash,
98
+ authorities,
99
+ steps,
100
+ summaries: steps.map((step) => ({
101
+ kind: "prompt_bridge",
102
+ status: "planned",
103
+ scene: step.after?.scene,
104
+ caseIds: structuredClone(step.caseIds),
105
+ })),
106
+ warnings: [],
107
+ impact: [],
108
+ };
109
+ bindSummaryAuthorityTargets(plan);
110
+ return withHash(plan, "planHash");
111
+ }
112
+
113
+ export async function revalidatePromptBridgeStep(
114
+ client,
115
+ workspaceId,
116
+ step,
117
+ authorities,
118
+ ) {
119
+ const { dryRuns, source } = validatePromptBridgeStepStructure(
120
+ step,
121
+ workspaceId,
122
+ );
123
+ await revalidatePairedKnowledge(client, workspaceId, step, authorities);
124
+ const collection = promptCollectionPath(workspaceId);
125
+ if (source.kind === "default") {
126
+ const defaults = await client.request("GET", `${collection}default/`, {
127
+ query: { scene: step.after.scene },
128
+ });
129
+ if (
130
+ !isRecord(defaults) ||
131
+ canonicalJson(promptBridgeSource("default", defaults)) !==
132
+ canonicalJson(source) ||
133
+ bridgeLanguage(defaults.prompt, step.after.scene, "prompt") !==
134
+ step.after.prompt ||
135
+ bridgeLanguage(defaults.promptEn, step.after.scene, "promptEn") !==
136
+ step.after.promptEn
137
+ )
138
+ fail(
139
+ "PROMPT_SOURCE_DRIFT",
140
+ "default Prompt changed after the bridge was planned",
141
+ );
142
+ }
143
+ for (const evidence of dryRuns) {
144
+ const response = await client.request("POST", `${collection}dry-run/`, {
145
+ body: {
146
+ scene: step.after.scene,
147
+ prompt: step.after[evidence.field],
148
+ language: evidence.language,
149
+ },
150
+ });
151
+ if (!isRecord(response) || typeof response.prompt !== "string")
152
+ fail("PROMPT_DRY_RUN_FAILED", "Prompt dry-run response is invalid");
153
+ }
154
+ }
155
+
156
+ export function validatePromptBridgeStepStructure(step, workspaceId) {
157
+ const allowed = new Set([
158
+ "after",
159
+ "before",
160
+ "caseIds",
161
+ "dictionarySyncRequired",
162
+ "endpoint",
163
+ "kind",
164
+ "operation",
165
+ "pairedKnowledge",
166
+ "preconditions",
167
+ ]);
168
+ if (
169
+ Object.keys(step).some(
170
+ (field) => !allowed.has(field) && field !== "requiresContrast",
171
+ ) ||
172
+ [...allowed].some((field) => !Object.hasOwn(step, field)) ||
173
+ (Object.hasOwn(step, "requiresContrast") &&
174
+ typeof step.requiresContrast !== "boolean") ||
175
+ step.kind !== "prompt_bridge" ||
176
+ step.dictionarySyncRequired !== false
177
+ )
178
+ fail("INVALID_PROMPT_BRIDGE_PLAN", "Prompt bridge step fields are invalid");
179
+ const collection = promptCollectionPath(workspaceId);
180
+ const after = validatePromptSnapshot(
181
+ step.after,
182
+ "after",
183
+ step.operation === "PATCH",
184
+ );
185
+ let before = null;
186
+ if (step.operation === "POST") {
187
+ if (
188
+ step.before !== null ||
189
+ after.id !== undefined ||
190
+ step.endpoint !== collection
191
+ )
192
+ fail(
193
+ "INVALID_PROMPT_BRIDGE_PLAN",
194
+ "Prompt bridge POST must create from the collection",
195
+ );
196
+ } else if (step.operation === "PATCH") {
197
+ before = validatePromptSnapshot(step.before, "before", true);
198
+ const beforeId = canonicalPlanResourceId(
199
+ before.id,
200
+ "INVALID_PROMPT_BRIDGE_PLAN",
201
+ );
202
+ const afterId = canonicalPlanResourceId(
203
+ after.id,
204
+ "INVALID_PROMPT_BRIDGE_PLAN",
205
+ );
206
+ if (
207
+ beforeId !== afterId ||
208
+ before.scene !== after.scene ||
209
+ step.endpoint !== `${collection}${beforeId}/` ||
210
+ statesEqual(before, after)
211
+ )
212
+ fail(
213
+ "INVALID_PROMPT_BRIDGE_PLAN",
214
+ "Prompt bridge PATCH identity or desired state is invalid",
215
+ );
216
+ } else
217
+ fail("INVALID_PROMPT_BRIDGE_PLAN", "Prompt bridge operation is invalid");
218
+
219
+ const caseIds = validateMutationCaseIds(
220
+ step.caseIds,
221
+ "INVALID_PROMPT_BRIDGE_PLAN",
222
+ );
223
+ if (
224
+ !isRecord(step.pairedKnowledge) ||
225
+ !["caseIds", "scene"].every((field) =>
226
+ Object.hasOwn(step.pairedKnowledge, field),
227
+ ) ||
228
+ Object.keys(step.pairedKnowledge).some(
229
+ (field) => !["caseIds", "scene", "knowledgeTarget"].includes(field),
230
+ ) ||
231
+ step.pairedKnowledge.scene !== after.scene ||
232
+ canonicalJson(step.pairedKnowledge.caseIds) !== canonicalJson(caseIds)
233
+ )
234
+ fail(
235
+ "INVALID_PROMPT_BRIDGE_PLAN",
236
+ "Prompt bridge is not bound to its Knowledge authorities",
237
+ );
238
+ const { dryRuns, source } = validatePromptBridgePreconditions(
239
+ step.preconditions,
240
+ before,
241
+ after,
242
+ );
243
+ return { after, before, caseIds, dryRuns, source };
244
+ }
245
+
246
+ export function validatePromptSnapshot(value, label, requireId) {
247
+ if (!isRecord(value))
248
+ fail(
249
+ "INVALID_PROMPT_BRIDGE_PLAN",
250
+ `Prompt bridge ${label} must be an object`,
251
+ );
252
+ const allowed = new Set([
253
+ ...(requireId ? ["id"] : []),
254
+ "prompt",
255
+ "promptEn",
256
+ "scene",
257
+ ]);
258
+ if (
259
+ Object.keys(value).some((field) => !allowed.has(field)) ||
260
+ [...allowed].some((field) => !Object.hasOwn(value, field)) ||
261
+ !Number.isSafeInteger(value.scene) ||
262
+ value.scene <= 0 ||
263
+ typeof value.prompt !== "string" ||
264
+ typeof value.promptEn !== "string" ||
265
+ (!value.prompt.trim() && !value.promptEn.trim())
266
+ )
267
+ fail(
268
+ "INVALID_PROMPT_BRIDGE_PLAN",
269
+ `Prompt bridge ${label} snapshot is invalid`,
270
+ );
271
+ if (requireId)
272
+ canonicalPlanResourceId(value.id, "INVALID_PROMPT_BRIDGE_PLAN");
273
+ for (const field of ["prompt", "promptEn"]) {
274
+ const count = value[field].split(KNOWLEDGE_SLOT).length - 1;
275
+ if (count > 1 || (label === "after" && value[field].trim() && count !== 1))
276
+ fail(
277
+ "INVALID_PROMPT_BRIDGE_PLAN",
278
+ `Prompt bridge ${label} slot count is invalid`,
279
+ );
280
+ }
281
+ return value;
282
+ }
283
+
284
+ export function validatePromptBridgePreconditions(
285
+ preconditions,
286
+ before,
287
+ after,
288
+ ) {
289
+ if (
290
+ !isRecord(preconditions) ||
291
+ canonicalJson(Object.keys(preconditions).sort()) !==
292
+ canonicalJson(["dryRuns", "source"]) ||
293
+ !Array.isArray(preconditions.dryRuns) ||
294
+ !isRecord(preconditions.source)
295
+ )
296
+ fail(
297
+ "INVALID_PROMPT_BRIDGE_PLAN",
298
+ "Prompt bridge preconditions are invalid",
299
+ );
300
+ const source = preconditions.source;
301
+ if (
302
+ canonicalJson(Object.keys(source).sort()) !==
303
+ canonicalJson(["kind", "promptEnHash", "promptHash"]) ||
304
+ !new Set(["default", "workspace_override"]).has(source.kind) ||
305
+ !/^[0-9a-f]{64}$/u.test(source.promptHash) ||
306
+ !/^[0-9a-f]{64}$/u.test(source.promptEnHash) ||
307
+ (source.kind === "default") !== (before === null) ||
308
+ (before !== null &&
309
+ canonicalJson(source) !==
310
+ canonicalJson(promptBridgeSource("workspace_override", before))) ||
311
+ (before !== null &&
312
+ (bridgeLanguage(before.prompt, after.scene, "prompt") !== after.prompt ||
313
+ bridgeLanguage(before.promptEn, after.scene, "promptEn") !==
314
+ after.promptEn))
315
+ )
316
+ fail(
317
+ "INVALID_PROMPT_BRIDGE_PLAN",
318
+ "Prompt bridge source evidence is invalid",
319
+ );
320
+ const expectedFields = ["prompt", "promptEn"].filter(
321
+ (field) =>
322
+ after[field].trim() &&
323
+ (before === null || after[field] !== before[field]),
324
+ );
325
+ const seen = new Set();
326
+ for (const evidence of preconditions.dryRuns) {
327
+ if (
328
+ !isRecord(evidence) ||
329
+ canonicalJson(Object.keys(evidence).sort()) !==
330
+ canonicalJson(["field", "language", "promptHash", "status"]) ||
331
+ !expectedFields.includes(evidence.field) ||
332
+ seen.has(evidence.field) ||
333
+ evidence.language !== (evidence.field === "prompt" ? "zh-CN" : "en-US") ||
334
+ evidence.promptHash !== hashValue(after[evidence.field]) ||
335
+ evidence.status !== "SUCCESS"
336
+ )
337
+ fail(
338
+ "INVALID_PROMPT_BRIDGE_PLAN",
339
+ "Prompt bridge dry-run evidence is invalid",
340
+ );
341
+ seen.add(evidence.field);
342
+ }
343
+ if (
344
+ seen.size !== expectedFields.length ||
345
+ expectedFields.some((field) => !seen.has(field))
346
+ )
347
+ fail(
348
+ "INVALID_PROMPT_BRIDGE_PLAN",
349
+ "every changed Prompt language requires one dry-run",
350
+ );
351
+ return { dryRuns: preconditions.dryRuns, source };
352
+ }
353
+
354
+ function promptWriteDesired(client, step) {
355
+ return client.request(step.operation, step.endpoint, {
356
+ body: promptBody(step.after, step.operation === "POST"),
357
+ });
358
+ }
359
+
360
+ function promptWriteBefore(client, step) {
361
+ return client.request("PATCH", step.endpoint, {
362
+ body: promptBody(step.before, false),
363
+ });
364
+ }
365
+
366
+ async function promptReadState(client, workspaceId, step) {
367
+ const id = step.after?.id ?? step.before?.id;
368
+ if (id !== undefined)
369
+ return semanticPrompt(
370
+ await client.request("GET", `${promptCollectionPath(workspaceId)}${id}/`),
371
+ );
372
+ const rows = requireArrayResponse(
373
+ await client.request("GET", promptCollectionPath(workspaceId)),
374
+ "INVALID_PROMPT_STATE",
375
+ "workspace Prompt list must be an array",
376
+ );
377
+ const matches = rows.filter(
378
+ (item) =>
379
+ String(item.scene) === String(step.after?.scene ?? step.before?.scene),
380
+ );
381
+ if (matches.length > 1)
382
+ fail(
383
+ "PROMPT_IDENTITY_AMBIGUOUS",
384
+ "multiple workspace Prompts match one scene",
385
+ );
386
+ return matches[0] ? semanticPrompt(matches[0]) : null;
387
+ }
388
+
389
+ async function promptReadCreatedState(client, workspaceId, step) {
390
+ const id = step.after?.id;
391
+ const rows = requireArrayResponse(
392
+ await client.request("GET", promptCollectionPath(workspaceId)),
393
+ "INVALID_PROMPT_STATE",
394
+ "workspace Prompt list must be an array",
395
+ );
396
+ const row = rows.find((item) => String(item.id) === String(id));
397
+ return row ? semanticPrompt(row) : null;
398
+ }
399
+
400
+ async function promptExactCreatedCandidates(client, workspaceId, step) {
401
+ const scene = step.after?.scene;
402
+ const rows = requireArrayResponse(
403
+ await client.request("GET", promptCollectionPath(workspaceId)),
404
+ "INVALID_PROMPT_STATE",
405
+ "workspace Prompt list must be an array",
406
+ );
407
+ return rows
408
+ .filter((row) => String(row.scene) === String(scene))
409
+ .map(semanticPrompt);
410
+ }
411
+
412
+ function promptRevalidate(client, workspaceId, step, ctx) {
413
+ return revalidatePromptBridgeStep(client, workspaceId, step, ctx.authorities);
414
+ }
415
+
416
+ function validatePromptAuthorityTarget(target) {
417
+ const allowed = new Set(["scene", "knowledgeTarget"]);
418
+ if (
419
+ Object.keys(target).some((field) => !allowed.has(field)) ||
420
+ !Array.isArray(target.scene) ||
421
+ target.scene.length === 0 ||
422
+ target.scene.some((scene) => !Number.isSafeInteger(scene) || scene <= 0)
423
+ )
424
+ fail("INVALID_PLAN_STRUCTURE", "Prompt authority target is invalid");
425
+ if (Object.hasOwn(target, "knowledgeTarget")) {
426
+ if (!isRecord(target.knowledgeTarget))
427
+ fail(
428
+ "INVALID_PLAN_STRUCTURE",
429
+ "Prompt缺少配对Knowledge权威,请重新生成计划。",
430
+ );
431
+ knowledgeKind.validateAuthorityTarget(target.knowledgeTarget);
432
+ }
433
+ }
434
+
435
+ function validatePromptPlanStep(step, plan, authorities, plannedCaseIds) {
436
+ const { caseIds } = validatePromptBridgeStepStructure(step, plan.workspaceId);
437
+ for (const caseId of caseIds) {
438
+ const authority = authorities.get(caseId);
439
+ const matched =
440
+ authority?.kind === "knowledge"
441
+ ? authority.target.scenes.includes(step.after.scene)
442
+ : authority?.kind === "prompt_bridge"
443
+ ? authority.target.scene.includes(step.after.scene)
444
+ : false;
445
+ if (
446
+ !matched ||
447
+ (authority.target.knowledgeTarget !== undefined &&
448
+ canonicalJson(authority.target.knowledgeTarget) !==
449
+ canonicalJson(step.pairedKnowledge.knowledgeTarget?.[caseId]))
450
+ )
451
+ fail(
452
+ "INVALID_PROMPT_BRIDGE_PLAN",
453
+ "Prompt bridge caseIds must match exact Knowledge authorities",
454
+ );
455
+ plannedCaseIds.add(caseId);
456
+ }
457
+ }
458
+
459
+ function promptSummaryMatches(summary, authorityTargets) {
460
+ const targets = authorityTargets.map(({ target }) => target);
461
+ return targets.every((target) => summary.name === target.name);
462
+ }
463
+
464
+ function promptVerificationAuthority(authority, planSteps, receipt) {
465
+ if (
466
+ !receipt ||
467
+ !Array.isArray(receipt.completedSteps) ||
468
+ !Array.isArray(planSteps)
469
+ )
470
+ fail(
471
+ "PROMPT_VERIFICATION_AUTHORITY_REQUIRED",
472
+ "Prompt验证需要完整计划和已完成回执,请回读原始执行工件后重试。",
473
+ );
474
+ promptKind.validateAuthorityTarget(authority.target);
475
+ const promptTargets = [];
476
+ let knowledgeTarget;
477
+ for (const [index, planned] of planSteps.entries()) {
478
+ if (
479
+ planned.kind !== "prompt_bridge" ||
480
+ !planned.caseIds?.includes(authority.caseId)
481
+ )
482
+ continue;
483
+ validatePromptBridgeStepStructure(planned, receipt.workspaceId);
484
+ const completed = receipt.completedSteps.filter(
485
+ (step) => step.planStepIndex === index,
486
+ );
487
+ if (completed.length !== 1)
488
+ fail(
489
+ "PROMPT_VERIFICATION_AUTHORITY_REQUIRED",
490
+ "Prompt回执缺少唯一完成步骤,请核对原执行工件,不要重放写入。",
491
+ );
492
+ const [step] = completed;
493
+ validatePromptSnapshot(step.after, "after", true);
494
+ const expected = { ...planned.after, id: step.after.id };
495
+ if (
496
+ step.kind !== "prompt_bridge" ||
497
+ step.planStepHash !== hashValue(planned) ||
498
+ canonicalJson(step.after) !== canonicalJson(expected) ||
499
+ (planned.after.id !== undefined && planned.after.id !== step.after.id) ||
500
+ step.endpoint !==
501
+ `${promptCollectionPath(receipt.workspaceId)}${step.after.id}/` ||
502
+ canonicalJson(step.pairedKnowledge) !==
503
+ canonicalJson(planned.pairedKnowledge) ||
504
+ canonicalJson(step.caseIds) !== canonicalJson(planned.caseIds) ||
505
+ !authority.target.scene.includes(step.after.scene)
506
+ )
507
+ fail(
508
+ "PROMPT_VERIFICATION_AUTHORITY_MISMATCH",
509
+ "Prompt完成状态与计划权威不匹配,请回读原计划和回执重新核对。",
510
+ );
511
+ const target = planned.pairedKnowledge.knowledgeTarget?.[authority.caseId];
512
+ if (!target || typeof target !== "object" || Array.isArray(target))
513
+ fail(
514
+ "PROMPT_VERIFICATION_AUTHORITY_REQUIRED",
515
+ "Prompt计划缺少配对Knowledge快照,请重新生成并确认计划。",
516
+ );
517
+ knowledgeKind.validateAuthorityTarget(target);
518
+ if (
519
+ (authority.target.knowledgeTarget !== undefined &&
520
+ canonicalJson(target) !==
521
+ canonicalJson(authority.target.knowledgeTarget)) ||
522
+ !target.active ||
523
+ !target.scenes.includes(step.after.scene) ||
524
+ (knowledgeTarget &&
525
+ canonicalJson(knowledgeTarget) !== canonicalJson(target))
526
+ )
527
+ fail(
528
+ "PROMPT_VERIFICATION_AUTHORITY_MISMATCH",
529
+ "Prompt场景与配对Knowledge权威不一致,请重新核对已确认的范围。",
530
+ );
531
+ knowledgeTarget = structuredClone(target);
532
+ promptTargets.push({
533
+ endpoint: step.endpoint,
534
+ after: structuredClone(step.after),
535
+ });
536
+ }
537
+ const scenes = promptTargets.map((target) => target.after.scene);
538
+ if (
539
+ scenes.length !== new Set(scenes).size ||
540
+ canonicalJson([...scenes].sort((a, b) => a - b)) !==
541
+ canonicalJson([...authority.target.scene].sort((a, b) => a - b))
542
+ )
543
+ fail(
544
+ "PROMPT_VERIFICATION_AUTHORITY_MISMATCH",
545
+ "Prompt验证未精确覆盖权威场景,请核对计划与完成回执。",
546
+ );
547
+ if (!knowledgeTarget || !promptTargets.length)
548
+ fail(
549
+ "PROMPT_VERIFICATION_AUTHORITY_REQUIRED",
550
+ "Prompt验证缺少完成目标,请回读完整执行回执。",
551
+ );
552
+ return { knowledgeTarget, promptTargets };
553
+ }
554
+
555
+ async function verifyPromptTargets(client, workspaceId, targets) {
556
+ const collection = promptCollectionPath(workspaceId);
557
+ const rows = await listAllPages(client, collection);
558
+ for (const target of targets) {
559
+ const matches = rows.filter(
560
+ (row) => String(row.scene) === String(target.after.scene),
561
+ );
562
+ if (
563
+ matches.length !== 1 ||
564
+ String(matches[0].id) !== String(target.after.id)
565
+ )
566
+ fail(
567
+ "PROMPT_STATE_DRIFT",
568
+ "待验证Prompt的身份或场景已变化,请回读最新配置重新生成方案。",
569
+ );
570
+ const current = semanticPrompt(
571
+ await client.request("GET", target.endpoint),
572
+ );
573
+ if (canonicalJson(current) !== canonicalJson(target.after))
574
+ fail(
575
+ "PROMPT_STATE_DRIFT",
576
+ "待验证Prompt模板已变化,请回读最新配置重新生成方案。",
577
+ );
578
+ }
579
+ }
580
+
581
+ export const promptKind = {
582
+ name: "prompt_bridge",
583
+ verificationAuthority: promptVerificationAuthority,
584
+ verifyCurrent: verifyPromptTargets,
585
+ planable: false,
586
+ writeDesired: promptWriteDesired,
587
+ writeBefore: promptWriteBefore,
588
+ readState: promptReadState,
589
+ readCreatedState: promptReadCreatedState,
590
+ postApplyRead: promptRevalidate,
591
+ exactCreatedCandidates: promptExactCreatedCandidates,
592
+ collection: promptCollectionPath,
593
+ targetKey: (step) => `prompt:${step.after?.id ?? step.after?.scene}`,
594
+ validateAuthorityTarget: validatePromptAuthorityTarget,
595
+ validateStep: validatePromptPlanStep,
596
+ summaryField: ["scene"],
597
+ summaryMatches: promptSummaryMatches,
598
+ };