@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.
- package/README.md +20 -2
- package/cordis.patch.yml +4 -0
- package/icon.svg +4 -0
- package/index.js +35 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +37 -4
- package/skills/datarc-access-permissions/SKILL.md +30 -0
- package/skills/datarc-access-permissions/references/api.md +31 -0
- package/skills/datarc-access-permissions/references/write-order.md +16 -0
- package/skills/datarc-analysis-report/SKILL.md +125 -0
- package/skills/datarc-analysis-report/agents/openai.yaml +6 -0
- package/skills/datarc-analysis-report/references/analyst-frameworks.md +215 -0
- package/skills/datarc-analysis-report/references/api-contracts.md +478 -0
- package/skills/datarc-analysis-report/references/direct-card-fallback-design.md +66 -0
- package/skills/datarc-analysis-report/references/human-in-the-loop.md +142 -0
- package/skills/datarc-analysis-report/references/loop-personalization-policy.md +138 -0
- package/skills/datarc-analysis-report/references/manifest-example.json +779 -0
- package/skills/datarc-analysis-report/references/narrative-schema.md +160 -0
- package/skills/datarc-analysis-report/references/question-syntax.md +151 -0
- package/skills/datarc-analysis-report/scripts/run_analysis_report.py +2225 -0
- package/skills/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -0
- package/skills/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -0
- package/skills/datarc-data-search/SKILL.md +243 -0
- package/skills/datarc-data-search/scripts/calculate.py +116 -0
- package/skills/datarc-data-search/scripts/data-search.mjs +628 -0
- package/skills/datarc-data-search/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-data-search/scripts/search-result.mjs +211 -0
- package/skills/datarc-dataseek-batch-evaluation/SKILL.md +59 -0
- package/skills/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -0
- package/skills/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -0
- package/skills/datarc-dataseek-batch-evaluation/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -0
- package/skills/datarc-dataseek-search/SKILL.md +96 -0
- package/skills/datarc-dataseek-search/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -0
- package/skills/datarc-dataseek-semantic-debugging/SKILL.md +44 -0
- package/skills/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -0
- package/skills/datarc-dataseek-semantic-debugging/evals/evals.json +165 -0
- package/skills/datarc-dataseek-semantic-debugging/references/dataset.md +77 -0
- package/skills/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -0
- package/skills/datarc-dataseek-semantic-debugging/references/interventions.md +64 -0
- package/skills/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -0
- package/skills/datarc-dataseek-semantic-debugging/references/rollback.md +11 -0
- package/skills/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -0
- package/skills/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -0
- package/skills/datarc-dataseek-testset-generation/SKILL.md +47 -0
- package/skills/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -0
- package/skills/datarc-datasource/SKILL.md +97 -0
- package/skills/datarc-oauth/SKILL.md +47 -0
- package/skills/datarc-oauth/scripts/auth.mjs +130 -0
- package/skills/datarc-oauth/scripts/credentials.mjs +237 -0
- package/skills/datarc-report-add-card/SKILL.md +90 -0
- package/skills/datarc-report-add-card/agents/openai.yaml +4 -0
- package/skills/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
- package/skills/datarc-report-add-card/scripts/report-card.mjs +439 -0
- package/skills/datarc-semantic-alias/SKILL.md +20 -0
- package/skills/datarc-semantic-alias/scripts/alias-plan.mjs +422 -0
- package/skills/datarc-semantic-alias/scripts/alias.mjs +11 -0
- package/skills/datarc-semantic-calibration/SKILL.md +20 -0
- package/skills/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -0
- package/skills/datarc-semantic-calibration/scripts/calibration.mjs +11 -0
- package/skills/datarc-semantic-core/SKILL.md +12 -0
- package/skills/datarc-semantic-core/scripts/artifact-journal.mjs +830 -0
- package/skills/datarc-semantic-core/scripts/canonical.mjs +48 -0
- package/skills/datarc-semantic-core/scripts/case-model.mjs +608 -0
- package/skills/datarc-semantic-core/scripts/cli.mjs +180 -0
- package/skills/datarc-semantic-core/scripts/datarc-client.mjs +180 -0
- package/skills/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -0
- package/skills/datarc-semantic-core/scripts/interventions.mjs +693 -0
- package/skills/datarc-semantic-core/scripts/live-resolution.mjs +305 -0
- package/skills/datarc-semantic-core/scripts/model-scope.mjs +49 -0
- package/skills/datarc-semantic-core/scripts/reproduction.mjs +330 -0
- package/skills/datarc-semantic-core/scripts/semantic-cli.mjs +740 -0
- package/skills/datarc-semantic-core/scripts/shared.mjs +312 -0
- package/skills/datarc-semantic-core/scripts/verification.mjs +1014 -0
- package/skills/datarc-semantic-dataset/SKILL.md +20 -0
- package/skills/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -0
- package/skills/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -0
- package/skills/datarc-semantic-dataset/scripts/dataset.mjs +11 -0
- package/skills/datarc-semantic-knowledge/SKILL.md +38 -0
- package/skills/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -0
- package/skills/datarc-semantic-knowledge/references/knowledge-generation.json +16 -0
- package/skills/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -0
- package/skills/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -0
- package/skills/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -0
- package/skills/datarc-semantic-prompt/SKILL.md +20 -0
- package/skills/datarc-semantic-prompt/scripts/prompt-plan.mjs +447 -0
- package/skills/datarc-semantic-prompt/scripts/prompt.mjs +15 -0
- package/skills/datarc-semantic-synonym/SKILL.md +20 -0
- package/skills/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -0
- package/skills/datarc-semantic-synonym/scripts/synonym.mjs +11 -0
- package/skills/datarc-viz-analysis-report/SKILL.md +108 -0
- package/skills/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -0
- package/skills/datarc-viz-analysis-report/assets/echarts.min.js +45 -0
- package/skills/datarc-viz-analysis-report/references/api-contracts.md +163 -0
- package/skills/datarc-viz-analysis-report/references/derivation-log.md +157 -0
- package/skills/datarc-viz-analysis-report/references/evidence-framework.md +76 -0
- package/skills/datarc-viz-analysis-report/references/html-template.md +92 -0
- package/skills/datarc-viz-analysis-report/references/provenance-format.md +56 -0
- package/skills/datarc-viz-analysis-report/references/question-syntax.md +151 -0
- package/skills/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -0
- package/skills/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -0
- package/skills/datarc-workspace-configuration/SKILL.md +59 -0
- package/skills/datarc-workspace-configuration/references/artifacts.md +75 -0
- package/skills/datarc-workspace-configuration/references/verification.md +20 -0
- package/skills/datarc-workspace-configuration/scripts/configuration.mjs +662 -0
- package/skills/datarc-workspace-context/SKILL.md +43 -0
- package/skills/datarc-workspace-context/agents/openai.yaml +4 -0
- package/skills/datarc-workspace-context/scripts/datarc-client.mjs +31 -0
- package/skills/datarc-workspace-context/scripts/query-display.mjs +114 -0
- package/skills/datarc-workspace-context/scripts/workspace-context.mjs +58 -0
- package/skills/datarc-workspace-custom-tables/SKILL.md +89 -0
- package/skills/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -0
- package/skills/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -0
- package/skills/datarc-workspace-keywords/SKILL.md +197 -0
- package/skills/datarc-workspace-keywords/agents/openai.yaml +4 -0
- package/skills/datarc-workspace-keywords/references/api-fields.md +79 -0
- package/skills/datarc-workspace-keywords/references/derived-measures.md +177 -0
- package/skills/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -0
- package/skills/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -0
- package/skills/datarc-workspace-membership/SKILL.md +29 -0
- package/skills/datarc-workspace-membership/references/api.md +19 -0
- package/skills/datarc-workspace-modeling/SKILL.md +209 -0
- package/skills/datarc-workspace-modeling/agents/openai.yaml +4 -0
- package/skills/datarc-workspace-modeling/references/join-preview.md +38 -0
- package/skills/datarc-workspace-modeling/references/model-plan.md +300 -0
- package/skills/datarc-workspace-modeling/references/model-tags.md +95 -0
- package/skills/datarc-workspace-modeling/references/modeling-contract.json +29 -0
- package/skills/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -0
- package/skills/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -0
- package/skills/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -0
- package/skills/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -0
- package/skills-index.json +194 -0
|
@@ -0,0 +1,1020 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
appendFile,
|
|
4
|
+
mkdir,
|
|
5
|
+
readFile,
|
|
6
|
+
rename,
|
|
7
|
+
writeFile,
|
|
8
|
+
} from "node:fs/promises";
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { dirname, isAbsolute, relative, resolve } from "node:path";
|
|
11
|
+
import { pathToFileURL } from "node:url";
|
|
12
|
+
import {
|
|
13
|
+
createClient,
|
|
14
|
+
isGlobalError,
|
|
15
|
+
parseArgs,
|
|
16
|
+
required,
|
|
17
|
+
runCli,
|
|
18
|
+
} from "./datarc-client.mjs";
|
|
19
|
+
|
|
20
|
+
const OUTPUT_COLUMNS = [
|
|
21
|
+
"测试_实际理解JSON",
|
|
22
|
+
"测试_实际问题Token",
|
|
23
|
+
"测试_实际问题TokenWord",
|
|
24
|
+
"测试_执行状态",
|
|
25
|
+
"测试_是否正确",
|
|
26
|
+
"测试_差异阶段",
|
|
27
|
+
"测试_差异简述",
|
|
28
|
+
"测试_报错信息",
|
|
29
|
+
];
|
|
30
|
+
const COMPARISON_VERSION = 3;
|
|
31
|
+
|
|
32
|
+
export function parseCsv(text) {
|
|
33
|
+
const rows = [];
|
|
34
|
+
let row = [];
|
|
35
|
+
let field = "";
|
|
36
|
+
let quoted = false;
|
|
37
|
+
const source = String(text).replace(/^\uFEFF/, "");
|
|
38
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
39
|
+
const character = source[index];
|
|
40
|
+
if (quoted) {
|
|
41
|
+
if (character === '"' && source[index + 1] === '"') {
|
|
42
|
+
field += '"';
|
|
43
|
+
index += 1;
|
|
44
|
+
} else if (character === '"') quoted = false;
|
|
45
|
+
else field += character;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (character === '"' && field === "") quoted = true;
|
|
49
|
+
else if (character === ",") {
|
|
50
|
+
row.push(field);
|
|
51
|
+
field = "";
|
|
52
|
+
} else if (character === "\n" || character === "\r") {
|
|
53
|
+
if (character === "\r" && source[index + 1] === "\n") index += 1;
|
|
54
|
+
row.push(field);
|
|
55
|
+
rows.push(row);
|
|
56
|
+
row = [];
|
|
57
|
+
field = "";
|
|
58
|
+
} else field += character;
|
|
59
|
+
}
|
|
60
|
+
if (quoted) throw new Error("CSV 存在未闭合的引号");
|
|
61
|
+
if (field !== "" || row.length) {
|
|
62
|
+
row.push(field);
|
|
63
|
+
rows.push(row);
|
|
64
|
+
}
|
|
65
|
+
return rows.filter((item, index) => index === 0 || item.some(Boolean));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function stringifyCsv(rows) {
|
|
69
|
+
return `${rows.map((row) => row.map(csvField).join(",")).join("\r\n")}\r\n`;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function extractFinalTokens(actions) {
|
|
73
|
+
const candidates = [];
|
|
74
|
+
visit(actions, (value) => {
|
|
75
|
+
if (value?.type !== "answer") return;
|
|
76
|
+
if (Array.isArray(value.data?.tokens)) candidates.push(value.data.tokens);
|
|
77
|
+
});
|
|
78
|
+
return candidates.at(-1) ?? null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function tokensToWords(tokens) {
|
|
82
|
+
const words = [];
|
|
83
|
+
visit(tokens, (value) => {
|
|
84
|
+
if (typeof value?.word === "string" && value.word.trim())
|
|
85
|
+
words.push(value.word.trim());
|
|
86
|
+
});
|
|
87
|
+
return words.join(" ");
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function unsupportedQueryType(actions) {
|
|
91
|
+
let result = null;
|
|
92
|
+
visit(actions, (value) => {
|
|
93
|
+
if (!result && ["parallel", "chained"].includes(value?.type))
|
|
94
|
+
result = value.type;
|
|
95
|
+
});
|
|
96
|
+
return result;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function extractUnderstanding(message) {
|
|
100
|
+
const step = [...(message.history ?? [])].reverse().find(
|
|
101
|
+
(item) =>
|
|
102
|
+
item?.name === "理解问题" || item?.name === "Understand the problem",
|
|
103
|
+
);
|
|
104
|
+
if (!step) throw new Error("DataSeek 消息历史中缺少理解问题步骤");
|
|
105
|
+
const candidates = [
|
|
106
|
+
step.reasoning_content ?? step.reasoningContent,
|
|
107
|
+
Array.isArray(step.reasoning_content)
|
|
108
|
+
? step.reasoning_content.join("")
|
|
109
|
+
: undefined,
|
|
110
|
+
Array.isArray(step.reasoningContent)
|
|
111
|
+
? step.reasoningContent.join("")
|
|
112
|
+
: undefined,
|
|
113
|
+
step.result,
|
|
114
|
+
step.content,
|
|
115
|
+
Array.isArray(step.content) ? step.content.join("") : undefined,
|
|
116
|
+
];
|
|
117
|
+
for (const candidate of candidates) {
|
|
118
|
+
const understanding = findUnderstanding(candidate);
|
|
119
|
+
if (understanding) return understanding;
|
|
120
|
+
}
|
|
121
|
+
throw new Error("DataSeek 理解问题步骤没有可解析的结构化 JSON");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function structurallyEqual(left, right) {
|
|
125
|
+
return canonicalJson(left) === canonicalJson(right);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function tokensEquivalent(left, right) {
|
|
129
|
+
return equivalentTokenValue(left, right);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export async function collect(args, options = {}) {
|
|
133
|
+
const inputPath = resolveExistingPath(required(args, "input"));
|
|
134
|
+
const outputDirectory = safeOutputDirectory(required(args, "output-dir"));
|
|
135
|
+
const workspaceId = required(args, "workspace-id");
|
|
136
|
+
const columns = {
|
|
137
|
+
question: required(args, "question-column"),
|
|
138
|
+
expectedUnderstanding: required(args, "expected-understanding-column"),
|
|
139
|
+
expectedTokens: required(args, "expected-tokens-column"),
|
|
140
|
+
expectedTokenWords: args["expected-token-words-column"] ?? null,
|
|
141
|
+
};
|
|
142
|
+
const intervalMs = positiveInteger(
|
|
143
|
+
args["poll-interval-ms"] ?? 2000,
|
|
144
|
+
"poll-interval-ms",
|
|
145
|
+
true,
|
|
146
|
+
);
|
|
147
|
+
const maxWaitMs = positiveInteger(
|
|
148
|
+
args["max-wait-ms"] ?? 600000,
|
|
149
|
+
"max-wait-ms",
|
|
150
|
+
);
|
|
151
|
+
const concurrency = positiveInteger(args.concurrency ?? 1, "concurrency");
|
|
152
|
+
const inputText = await readFile(inputPath, "utf8");
|
|
153
|
+
const rows = parseCsv(inputText);
|
|
154
|
+
if (!rows.length)
|
|
155
|
+
throw new Error("CSV 为空;请确认输入文件路径、内容和 UTF-8 编码后重试");
|
|
156
|
+
const header = rows[0];
|
|
157
|
+
validateColumns(header, columns);
|
|
158
|
+
validateOutputColumns(header);
|
|
159
|
+
await mkdir(outputDirectory, { recursive: true });
|
|
160
|
+
const checkpointPath = resolve(outputDirectory, "checkpoint.jsonl");
|
|
161
|
+
const reviewPath = resolve(outputDirectory, "review.jsonl");
|
|
162
|
+
const manifestPath = resolve(outputDirectory, "manifest.json");
|
|
163
|
+
const previous = await readJsonLines(checkpointPath, true);
|
|
164
|
+
const latest = latestByRow(previous);
|
|
165
|
+
const retryErrors = args["retry-errors"] === true;
|
|
166
|
+
const cases = rows
|
|
167
|
+
.slice(1)
|
|
168
|
+
.map((values, index) => ({
|
|
169
|
+
rowNumber: index + 2,
|
|
170
|
+
values: padRow(values, header.length),
|
|
171
|
+
}))
|
|
172
|
+
.map((item) => ({
|
|
173
|
+
...item,
|
|
174
|
+
caseKey: digestJson({
|
|
175
|
+
workspaceId: String(workspaceId),
|
|
176
|
+
columns,
|
|
177
|
+
values: item.values,
|
|
178
|
+
}),
|
|
179
|
+
}));
|
|
180
|
+
const pending = cases.filter((currentCase) => {
|
|
181
|
+
const item = latest.get(currentCase.rowNumber);
|
|
182
|
+
return (
|
|
183
|
+
!item ||
|
|
184
|
+
item.caseKey !== currentCase.caseKey ||
|
|
185
|
+
(item.collectionStatus === "success" &&
|
|
186
|
+
item.comparisonVersion !== COMPARISON_VERSION) ||
|
|
187
|
+
(retryErrors && item.collectionStatus === "error")
|
|
188
|
+
);
|
|
189
|
+
});
|
|
190
|
+
const client = options.client ?? createClient(options);
|
|
191
|
+
const tokenMetadataCache = new Map();
|
|
192
|
+
let cursor = 0;
|
|
193
|
+
let fatalError;
|
|
194
|
+
const workers = Array.from(
|
|
195
|
+
{ length: Math.min(concurrency, pending.length) },
|
|
196
|
+
async () => {
|
|
197
|
+
while (!fatalError) {
|
|
198
|
+
const current = pending[cursor];
|
|
199
|
+
cursor += 1;
|
|
200
|
+
if (!current) return;
|
|
201
|
+
const record = await collectRow(
|
|
202
|
+
client,
|
|
203
|
+
workspaceId,
|
|
204
|
+
header,
|
|
205
|
+
current,
|
|
206
|
+
columns,
|
|
207
|
+
{
|
|
208
|
+
intervalMs,
|
|
209
|
+
maxWaitMs,
|
|
210
|
+
tokenMetadataCache,
|
|
211
|
+
},
|
|
212
|
+
);
|
|
213
|
+
await appendFile(checkpointPath, `${JSON.stringify(record)}\n`, "utf8");
|
|
214
|
+
latest.set(record.rowNumber, record);
|
|
215
|
+
if (record.fatal)
|
|
216
|
+
fatalError = Object.assign(
|
|
217
|
+
new Error(record.error.message),
|
|
218
|
+
record.error,
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
);
|
|
223
|
+
await Promise.all(workers);
|
|
224
|
+
if (fatalError) throw fatalError;
|
|
225
|
+
const records = cases
|
|
226
|
+
.map((item) => latest.get(item.rowNumber))
|
|
227
|
+
.filter((record, index) => record?.caseKey === cases[index].caseKey);
|
|
228
|
+
const review = records.filter(needsReview).map(toReviewCase);
|
|
229
|
+
await atomicWrite(
|
|
230
|
+
reviewPath,
|
|
231
|
+
review.map((item) => JSON.stringify(item)).join("\n") +
|
|
232
|
+
(review.length ? "\n" : ""),
|
|
233
|
+
);
|
|
234
|
+
const manifest = {
|
|
235
|
+
schemaVersion: 1,
|
|
236
|
+
workspaceId: String(workspaceId),
|
|
237
|
+
input: inputPath,
|
|
238
|
+
inputDigest: digestText(inputText),
|
|
239
|
+
outputDirectory,
|
|
240
|
+
columns,
|
|
241
|
+
rowCount: rows.length - 1,
|
|
242
|
+
checkpoint: checkpointPath,
|
|
243
|
+
review: reviewPath,
|
|
244
|
+
collectedAt: new Date().toISOString(),
|
|
245
|
+
};
|
|
246
|
+
await atomicWrite(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
247
|
+
return {
|
|
248
|
+
manifest: manifestPath,
|
|
249
|
+
checkpoint: checkpointPath,
|
|
250
|
+
review: reviewPath,
|
|
251
|
+
total: manifest.rowCount,
|
|
252
|
+
collected: records.length,
|
|
253
|
+
automaticPass: records.filter(isAutomaticPass).length,
|
|
254
|
+
needsReview: review.length,
|
|
255
|
+
errors: records.filter((item) => item.collectionStatus === "error").length,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export async function finalize(args) {
|
|
260
|
+
const manifestPath = resolveExistingPath(required(args, "manifest"));
|
|
261
|
+
const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
|
|
262
|
+
const inputText = await readFile(manifest.input, "utf8");
|
|
263
|
+
if (digestText(inputText) !== manifest.inputDigest)
|
|
264
|
+
throw new Error("原始 CSV 在采集后发生变化,请重新运行 collect");
|
|
265
|
+
const rows = parseCsv(inputText);
|
|
266
|
+
const records = latestByRow(await readJsonLines(manifest.checkpoint));
|
|
267
|
+
const decisions = latestByRow(
|
|
268
|
+
args.decisions
|
|
269
|
+
? await readJsonLines(resolveExistingPath(args.decisions))
|
|
270
|
+
: [],
|
|
271
|
+
);
|
|
272
|
+
const outputPath = safeOutputFile(required(args, "output"));
|
|
273
|
+
const summaryPath = `${outputPath}.summary.json`;
|
|
274
|
+
const protectedPaths = [
|
|
275
|
+
manifestPath,
|
|
276
|
+
manifest.input,
|
|
277
|
+
manifest.checkpoint,
|
|
278
|
+
manifest.review,
|
|
279
|
+
...(args.decisions ? [resolveExistingPath(args.decisions)] : []),
|
|
280
|
+
].map((path) => resolve(path).toLowerCase());
|
|
281
|
+
if (
|
|
282
|
+
[outputPath, summaryPath].some((path) =>
|
|
283
|
+
protectedPaths.includes(path.toLowerCase()),
|
|
284
|
+
)
|
|
285
|
+
)
|
|
286
|
+
throw new Error(
|
|
287
|
+
"--output 及其 .summary.json 不得覆盖输入 CSV、manifest、checkpoint、review 或 decisions;请指定其他输出路径后重试",
|
|
288
|
+
);
|
|
289
|
+
const outputRows = [[...rows[0], ...OUTPUT_COLUMNS]];
|
|
290
|
+
const summary = { pass: 0, fail: 0, review: 0, error: 0 };
|
|
291
|
+
for (let index = 1; index < rows.length; index += 1) {
|
|
292
|
+
const rowNumber = index + 1;
|
|
293
|
+
const record = records.get(rowNumber);
|
|
294
|
+
const result = finalResult(record, decisions.get(rowNumber));
|
|
295
|
+
summary[result.verdict] += 1;
|
|
296
|
+
outputRows.push([
|
|
297
|
+
...padRow(rows[index], rows[0].length),
|
|
298
|
+
jsonCell(record?.actualUnderstanding),
|
|
299
|
+
jsonCell(record?.actualTokens),
|
|
300
|
+
record?.actualTokenWords ?? "",
|
|
301
|
+
result.executionStatus,
|
|
302
|
+
correctnessLabel(result.verdict),
|
|
303
|
+
result.mismatchStage,
|
|
304
|
+
result.summary,
|
|
305
|
+
result.errorMessage,
|
|
306
|
+
]);
|
|
307
|
+
}
|
|
308
|
+
await mkdir(dirname(outputPath), { recursive: true });
|
|
309
|
+
await atomicWrite(outputPath, stringifyCsv(outputRows));
|
|
310
|
+
await atomicWrite(
|
|
311
|
+
summaryPath,
|
|
312
|
+
`${JSON.stringify({ total: rows.length - 1, ...summary }, null, 2)}\n`,
|
|
313
|
+
);
|
|
314
|
+
return {
|
|
315
|
+
output: outputPath,
|
|
316
|
+
summary: summaryPath,
|
|
317
|
+
total: rows.length - 1,
|
|
318
|
+
...summary,
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export async function execute(argv, options = {}) {
|
|
323
|
+
const args = parseArgs(argv);
|
|
324
|
+
if (args.help === true || args._[0] === "help" || !args._[0]) return help();
|
|
325
|
+
if (args._[0] === "collect") return collect(args, options);
|
|
326
|
+
if (args._[0] === "finalize") return finalize(args);
|
|
327
|
+
throw new Error("命令应为 collect 或 finalize");
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
async function collectRow(
|
|
331
|
+
client,
|
|
332
|
+
workspaceId,
|
|
333
|
+
header,
|
|
334
|
+
item,
|
|
335
|
+
columns,
|
|
336
|
+
pollOptions,
|
|
337
|
+
) {
|
|
338
|
+
const source = Object.fromEntries(
|
|
339
|
+
header.map((name, index) => [name, item.values[index] ?? ""]),
|
|
340
|
+
);
|
|
341
|
+
const base = {
|
|
342
|
+
rowNumber: item.rowNumber,
|
|
343
|
+
caseKey: item.caseKey,
|
|
344
|
+
comparisonVersion: COMPARISON_VERSION,
|
|
345
|
+
source,
|
|
346
|
+
question: source[columns.question],
|
|
347
|
+
};
|
|
348
|
+
let expectedUnderstanding;
|
|
349
|
+
let expectedTokens;
|
|
350
|
+
let expectedTokenWords;
|
|
351
|
+
try {
|
|
352
|
+
if (!base.question.trim()) throw new Error("原始问题为空");
|
|
353
|
+
expectedUnderstanding = parseJsonCell(
|
|
354
|
+
source[columns.expectedUnderstanding],
|
|
355
|
+
"期望理解 JSON",
|
|
356
|
+
);
|
|
357
|
+
expectedTokens = parseJsonCell(
|
|
358
|
+
source[columns.expectedTokens],
|
|
359
|
+
"期望问题 Token",
|
|
360
|
+
);
|
|
361
|
+
expectedTokenWords = columns.expectedTokenWords
|
|
362
|
+
? normalizeWords(source[columns.expectedTokenWords])
|
|
363
|
+
: tokensToWords(expectedTokens);
|
|
364
|
+
if (!expectedTokenWords) throw new Error("期望问题 Token Word 为空");
|
|
365
|
+
} catch (error) {
|
|
366
|
+
return {
|
|
367
|
+
...base,
|
|
368
|
+
collectionStatus: "error",
|
|
369
|
+
fatal: false,
|
|
370
|
+
error: { code: "INVALID_CASE", message: error.message },
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
try {
|
|
374
|
+
const thread = await client.request(
|
|
375
|
+
"POST",
|
|
376
|
+
`/api/v3/account-projects/${workspaceId}/threads/`,
|
|
377
|
+
{ body: {} },
|
|
378
|
+
);
|
|
379
|
+
const message = await client.request(
|
|
380
|
+
"POST",
|
|
381
|
+
`/api/v3/account-projects/${workspaceId}/threads/${thread.uid}/messages/`,
|
|
382
|
+
{
|
|
383
|
+
body: { message: base.question },
|
|
384
|
+
},
|
|
385
|
+
);
|
|
386
|
+
const completedMessage = await waitForMessage(
|
|
387
|
+
client,
|
|
388
|
+
workspaceId,
|
|
389
|
+
thread.uid,
|
|
390
|
+
message.id,
|
|
391
|
+
pollOptions,
|
|
392
|
+
);
|
|
393
|
+
const unsupportedType = unsupportedQueryType(
|
|
394
|
+
completedMessage.current?.result,
|
|
395
|
+
);
|
|
396
|
+
if (unsupportedType) {
|
|
397
|
+
const error = new Error(
|
|
398
|
+
`当前批量评测仅支持直接单 query,不支持 ${unsupportedType}`,
|
|
399
|
+
);
|
|
400
|
+
error.code = "UNSUPPORTED_QUERY_TYPE";
|
|
401
|
+
throw error;
|
|
402
|
+
}
|
|
403
|
+
const actualUnderstanding = extractUnderstanding(completedMessage);
|
|
404
|
+
const actualTokens = extractFinalTokens(completedMessage.current?.result);
|
|
405
|
+
if (!actualTokens) throw new Error("DataSeek 最终 answer 缺少问题 Token");
|
|
406
|
+
const actualTokenWords = tokensToWords(actualTokens);
|
|
407
|
+
if (!actualTokenWords) throw new Error("DataSeek 最终问题 Token 缺少 word");
|
|
408
|
+
const exactUnderstanding = structurallyEqual(
|
|
409
|
+
expectedUnderstanding,
|
|
410
|
+
actualUnderstanding,
|
|
411
|
+
);
|
|
412
|
+
let expectedComparableTokens = expectedTokens;
|
|
413
|
+
let actualComparableTokens = actualTokens;
|
|
414
|
+
const metadataStatus = { attempted: false, complete: true };
|
|
415
|
+
let equivalentTokens = tokensEquivalent(expectedTokens, actualTokens);
|
|
416
|
+
if (
|
|
417
|
+
(!equivalentTokens || !exactUnderstanding) &&
|
|
418
|
+
tokensShareStructure(expectedTokens, actualTokens)
|
|
419
|
+
) {
|
|
420
|
+
[expectedComparableTokens, actualComparableTokens] = await Promise.all([
|
|
421
|
+
enrichTokenNames(
|
|
422
|
+
client,
|
|
423
|
+
workspaceId,
|
|
424
|
+
expectedTokens,
|
|
425
|
+
pollOptions.tokenMetadataCache,
|
|
426
|
+
metadataStatus,
|
|
427
|
+
),
|
|
428
|
+
enrichTokenNames(
|
|
429
|
+
client,
|
|
430
|
+
workspaceId,
|
|
431
|
+
actualTokens,
|
|
432
|
+
pollOptions.tokenMetadataCache,
|
|
433
|
+
metadataStatus,
|
|
434
|
+
),
|
|
435
|
+
]);
|
|
436
|
+
equivalentTokens = tokensEquivalent(
|
|
437
|
+
expectedComparableTokens,
|
|
438
|
+
actualComparableTokens,
|
|
439
|
+
);
|
|
440
|
+
}
|
|
441
|
+
const equivalentUnderstanding =
|
|
442
|
+
equivalentTokens &&
|
|
443
|
+
understandingEquivalent(
|
|
444
|
+
expectedUnderstanding,
|
|
445
|
+
actualUnderstanding,
|
|
446
|
+
tokenNamePairs(expectedComparableTokens, actualComparableTokens),
|
|
447
|
+
);
|
|
448
|
+
const equivalentTokenWords = tokenWordsEquivalent(
|
|
449
|
+
expectedTokenWords,
|
|
450
|
+
actualTokenWords,
|
|
451
|
+
expectedTokens,
|
|
452
|
+
actualTokens,
|
|
453
|
+
expectedComparableTokens,
|
|
454
|
+
actualComparableTokens,
|
|
455
|
+
);
|
|
456
|
+
return {
|
|
457
|
+
...base,
|
|
458
|
+
comparisonVersion:
|
|
459
|
+
!metadataStatus.attempted || metadataStatus.complete
|
|
460
|
+
? COMPARISON_VERSION
|
|
461
|
+
: null,
|
|
462
|
+
collectionStatus: "success",
|
|
463
|
+
expectedUnderstanding,
|
|
464
|
+
expectedTokens,
|
|
465
|
+
expectedTokenWords,
|
|
466
|
+
actualUnderstanding,
|
|
467
|
+
actualTokens,
|
|
468
|
+
actualTokenWords,
|
|
469
|
+
stages: [{ name: "understanding", payload: actualUnderstanding }],
|
|
470
|
+
exact: {
|
|
471
|
+
understanding: exactUnderstanding,
|
|
472
|
+
tokens: structurallyEqual(expectedTokens, actualTokens),
|
|
473
|
+
tokenWords:
|
|
474
|
+
normalizeWords(expectedTokenWords) === normalizeWords(actualTokenWords),
|
|
475
|
+
},
|
|
476
|
+
equivalent: {
|
|
477
|
+
understanding: equivalentUnderstanding,
|
|
478
|
+
tokens: equivalentTokens,
|
|
479
|
+
tokenWords: equivalentTokenWords,
|
|
480
|
+
},
|
|
481
|
+
};
|
|
482
|
+
} catch (error) {
|
|
483
|
+
return {
|
|
484
|
+
...base,
|
|
485
|
+
collectionStatus: "error",
|
|
486
|
+
fatal: isGlobalError(error),
|
|
487
|
+
expectedUnderstanding,
|
|
488
|
+
expectedTokens,
|
|
489
|
+
expectedTokenWords,
|
|
490
|
+
error: {
|
|
491
|
+
code: error.code ?? "UNEXPECTED_ERROR",
|
|
492
|
+
message: error.message ?? String(error),
|
|
493
|
+
},
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
async function waitForMessage(
|
|
499
|
+
client,
|
|
500
|
+
workspaceId,
|
|
501
|
+
threadUid,
|
|
502
|
+
messageId,
|
|
503
|
+
options,
|
|
504
|
+
) {
|
|
505
|
+
const started = Date.now();
|
|
506
|
+
while (Date.now() - started <= options.maxWaitMs) {
|
|
507
|
+
const message = await client.request(
|
|
508
|
+
"GET",
|
|
509
|
+
`/api/v3/account-projects/${workspaceId}/threads/${threadUid}/messages/${messageId}/`,
|
|
510
|
+
);
|
|
511
|
+
if (message.current?.error) throw new Error(String(message.current.error));
|
|
512
|
+
if (Array.isArray(message.current?.result) && message.current.result.length)
|
|
513
|
+
return message;
|
|
514
|
+
await client.sleep(options.intervalMs);
|
|
515
|
+
}
|
|
516
|
+
const error = new Error(
|
|
517
|
+
"DataSeek 消息轮询超时;请调大 --max-wait-ms 后重试",
|
|
518
|
+
);
|
|
519
|
+
error.code = "TASK_TIMEOUT";
|
|
520
|
+
throw error;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function finalResult(record, decision) {
|
|
524
|
+
if (!record)
|
|
525
|
+
return {
|
|
526
|
+
verdict: "error",
|
|
527
|
+
executionStatus: "missing",
|
|
528
|
+
mismatchStage: "unknown",
|
|
529
|
+
summary: "",
|
|
530
|
+
errorMessage: "缺少采集记录",
|
|
531
|
+
};
|
|
532
|
+
if (record.collectionStatus === "error")
|
|
533
|
+
return {
|
|
534
|
+
verdict: "error",
|
|
535
|
+
executionStatus: "error",
|
|
536
|
+
mismatchStage: "unknown",
|
|
537
|
+
summary: "",
|
|
538
|
+
errorMessage: record.error?.message ?? "DataSeek 调用失败",
|
|
539
|
+
};
|
|
540
|
+
if (isAutomaticPass(record))
|
|
541
|
+
return {
|
|
542
|
+
verdict: "pass",
|
|
543
|
+
executionStatus: "success",
|
|
544
|
+
mismatchStage: "",
|
|
545
|
+
summary: "",
|
|
546
|
+
errorMessage: "",
|
|
547
|
+
};
|
|
548
|
+
if (!decision)
|
|
549
|
+
return {
|
|
550
|
+
verdict: "review",
|
|
551
|
+
executionStatus: "success",
|
|
552
|
+
mismatchStage: "unknown",
|
|
553
|
+
summary: "尚未进行逻辑等价复核",
|
|
554
|
+
errorMessage: "",
|
|
555
|
+
};
|
|
556
|
+
if (decision.caseKey !== record.caseKey)
|
|
557
|
+
return {
|
|
558
|
+
verdict: "review",
|
|
559
|
+
executionStatus: "success",
|
|
560
|
+
mismatchStage: "unknown",
|
|
561
|
+
summary: "判定不属于当前案例,需重新复核",
|
|
562
|
+
errorMessage: "",
|
|
563
|
+
};
|
|
564
|
+
validateDecision(decision, record.rowNumber);
|
|
565
|
+
return {
|
|
566
|
+
verdict: decision.verdict,
|
|
567
|
+
executionStatus: "success",
|
|
568
|
+
mismatchStage: decision.mismatchStage,
|
|
569
|
+
summary:
|
|
570
|
+
decision.verdict === "pass"
|
|
571
|
+
? ""
|
|
572
|
+
: singleLine(decision.summary).slice(0, 300),
|
|
573
|
+
errorMessage: "",
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
function validateDecision(decision, rowNumber) {
|
|
578
|
+
if (!["pass", "fail", "review"].includes(decision.verdict))
|
|
579
|
+
throw new Error(`第 ${rowNumber} 行 verdict 无效`);
|
|
580
|
+
if (
|
|
581
|
+
!["understanding", "tokens", "both", "unknown"].includes(
|
|
582
|
+
decision.mismatchStage,
|
|
583
|
+
)
|
|
584
|
+
)
|
|
585
|
+
throw new Error(`第 ${rowNumber} 行 mismatchStage 无效`);
|
|
586
|
+
if (!singleLine(decision.summary))
|
|
587
|
+
throw new Error(`第 ${rowNumber} 行 summary 为空`);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
function needsReview(record) {
|
|
591
|
+
return record.collectionStatus === "success" && !isAutomaticPass(record);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function isAutomaticPass(record) {
|
|
595
|
+
return (
|
|
596
|
+
record.collectionStatus === "success" &&
|
|
597
|
+
(record.exact?.understanding === true ||
|
|
598
|
+
record.equivalent?.understanding === true) &&
|
|
599
|
+
(record.exact?.tokens === true || record.equivalent?.tokens === true) &&
|
|
600
|
+
(record.exact?.tokenWords === true ||
|
|
601
|
+
record.equivalent?.tokenWords === true)
|
|
602
|
+
);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function toReviewCase(record) {
|
|
606
|
+
return {
|
|
607
|
+
rowNumber: record.rowNumber,
|
|
608
|
+
caseKey: record.caseKey,
|
|
609
|
+
question: record.question,
|
|
610
|
+
expected: {
|
|
611
|
+
understanding: record.expectedUnderstanding,
|
|
612
|
+
tokens: record.expectedTokens,
|
|
613
|
+
tokenWords: record.expectedTokenWords,
|
|
614
|
+
},
|
|
615
|
+
actual: {
|
|
616
|
+
understanding: record.actualUnderstanding,
|
|
617
|
+
tokens: record.actualTokens,
|
|
618
|
+
tokenWords: record.actualTokenWords,
|
|
619
|
+
},
|
|
620
|
+
exact: record.exact,
|
|
621
|
+
equivalent: record.equivalent,
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function equivalentTokenValue(left, right) {
|
|
626
|
+
if (Array.isArray(left) || Array.isArray(right))
|
|
627
|
+
return (
|
|
628
|
+
Array.isArray(left) &&
|
|
629
|
+
Array.isArray(right) &&
|
|
630
|
+
left.length === right.length &&
|
|
631
|
+
left.every((value, index) => equivalentTokenValue(value, right[index]))
|
|
632
|
+
);
|
|
633
|
+
if (!left || !right || typeof left !== "object" || typeof right !== "object")
|
|
634
|
+
return Object.is(left, right);
|
|
635
|
+
if (isNamedToken(left) || isNamedToken(right)) {
|
|
636
|
+
if (!isNamedToken(left) || !isNamedToken(right) || left.prop !== right.prop)
|
|
637
|
+
return false;
|
|
638
|
+
if (!tokenNamesOverlap(left, right)) return false;
|
|
639
|
+
return structurallyEqual(tokenWithoutNames(left), tokenWithoutNames(right));
|
|
640
|
+
}
|
|
641
|
+
return structurallyEqual(left, right);
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function tokensShareStructure(left, right) {
|
|
645
|
+
if (Array.isArray(left) || Array.isArray(right))
|
|
646
|
+
return (
|
|
647
|
+
Array.isArray(left) &&
|
|
648
|
+
Array.isArray(right) &&
|
|
649
|
+
left.length === right.length &&
|
|
650
|
+
left.every((value, index) => tokensShareStructure(value, right[index]))
|
|
651
|
+
);
|
|
652
|
+
if (!left || !right || typeof left !== "object" || typeof right !== "object")
|
|
653
|
+
return Object.is(left, right);
|
|
654
|
+
if (isNamedToken(left) || isNamedToken(right))
|
|
655
|
+
return (
|
|
656
|
+
isNamedToken(left) &&
|
|
657
|
+
isNamedToken(right) &&
|
|
658
|
+
left.prop === right.prop &&
|
|
659
|
+
structurallyEqual(tokenWithoutNames(left), tokenWithoutNames(right))
|
|
660
|
+
);
|
|
661
|
+
return structurallyEqual(left, right);
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
async function enrichTokenNames(client, workspaceId, value, cache, status) {
|
|
665
|
+
if (Array.isArray(value))
|
|
666
|
+
return Promise.all(
|
|
667
|
+
value.map((item) =>
|
|
668
|
+
enrichTokenNames(client, workspaceId, item, cache, status),
|
|
669
|
+
),
|
|
670
|
+
);
|
|
671
|
+
if (!isNamedToken(value)) return value;
|
|
672
|
+
status.attempted = true;
|
|
673
|
+
const key = `${value.prop}\u0000${value.word}`;
|
|
674
|
+
if (!cache.has(key))
|
|
675
|
+
cache.set(
|
|
676
|
+
key,
|
|
677
|
+
client
|
|
678
|
+
.request("POST", `/api/v2/account-projects/${workspaceId}/tokens/`, {
|
|
679
|
+
body: { word: value.word, prop: value.prop, siriType: 2 },
|
|
680
|
+
})
|
|
681
|
+
.catch(() => null),
|
|
682
|
+
);
|
|
683
|
+
const metadata = await cache.get(key);
|
|
684
|
+
if (!metadata || typeof metadata !== "object") {
|
|
685
|
+
status.complete = false;
|
|
686
|
+
return value;
|
|
687
|
+
}
|
|
688
|
+
return {
|
|
689
|
+
...value,
|
|
690
|
+
synonyms: uniqueTokenNames(value.synonyms, metadata.synonyms),
|
|
691
|
+
aliases: uniqueTokenNames(
|
|
692
|
+
value.aliases,
|
|
693
|
+
metadata.aliases,
|
|
694
|
+
metadata.originalName ? [metadata.originalName] : [],
|
|
695
|
+
),
|
|
696
|
+
};
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
function tokenWordsEquivalent(
|
|
700
|
+
expectedWords,
|
|
701
|
+
actualWords,
|
|
702
|
+
expectedTokens,
|
|
703
|
+
actualTokens,
|
|
704
|
+
expectedComparableTokens,
|
|
705
|
+
actualComparableTokens,
|
|
706
|
+
) {
|
|
707
|
+
if (normalizeWords(expectedWords) === normalizeWords(actualWords)) return true;
|
|
708
|
+
return (
|
|
709
|
+
normalizeWords(expectedWords) ===
|
|
710
|
+
normalizeWords(tokensToWords(expectedTokens)) &&
|
|
711
|
+
normalizeWords(actualWords) ===
|
|
712
|
+
normalizeWords(tokensToWords(actualTokens)) &&
|
|
713
|
+
tokensEquivalent(expectedComparableTokens, actualComparableTokens)
|
|
714
|
+
);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
function understandingEquivalent(left, right, namePairs) {
|
|
718
|
+
if (Array.isArray(left) || Array.isArray(right))
|
|
719
|
+
return (
|
|
720
|
+
Array.isArray(left) &&
|
|
721
|
+
Array.isArray(right) &&
|
|
722
|
+
left.length === right.length &&
|
|
723
|
+
left.every((value, index) =>
|
|
724
|
+
understandingEquivalent(value, right[index], namePairs),
|
|
725
|
+
)
|
|
726
|
+
);
|
|
727
|
+
if (left && right && typeof left === "object" && typeof right === "object") {
|
|
728
|
+
const leftKeys = Object.keys(left).sort();
|
|
729
|
+
const rightKeys = Object.keys(right).sort();
|
|
730
|
+
return (
|
|
731
|
+
structurallyEqual(leftKeys, rightKeys) &&
|
|
732
|
+
leftKeys.every((key) =>
|
|
733
|
+
understandingEquivalent(left[key], right[key], namePairs),
|
|
734
|
+
)
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
if (Object.is(left, right)) return true;
|
|
738
|
+
if (typeof left !== "string" || typeof right !== "string") return false;
|
|
739
|
+
const leftName = normalizeTokenName(left);
|
|
740
|
+
const rightName = normalizeTokenName(right);
|
|
741
|
+
return namePairs.some(
|
|
742
|
+
(pair) => pair.left.has(leftName) && pair.right.has(rightName),
|
|
743
|
+
);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
function tokenNamePairs(left, right) {
|
|
747
|
+
if (Array.isArray(left) && Array.isArray(right))
|
|
748
|
+
return left.flatMap((value, index) =>
|
|
749
|
+
tokenNamePairs(value, right[index]),
|
|
750
|
+
);
|
|
751
|
+
if (!isNamedToken(left) || !isNamedToken(right) || left.prop !== right.prop)
|
|
752
|
+
return [];
|
|
753
|
+
if (!tokenNamesOverlap(left, right)) return [];
|
|
754
|
+
return [{ left: tokenNames(left), right: tokenNames(right) }];
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
function uniqueTokenNames(...groups) {
|
|
758
|
+
return [
|
|
759
|
+
...new Set(
|
|
760
|
+
groups
|
|
761
|
+
.flatMap(validTokenNameArray)
|
|
762
|
+
.map((value) => value.trim())
|
|
763
|
+
.filter(Boolean),
|
|
764
|
+
),
|
|
765
|
+
];
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
function isNamedToken(value) {
|
|
769
|
+
return typeof value?.prop === "string" && typeof value?.word === "string";
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
function tokenNamesOverlap(left, right) {
|
|
773
|
+
const leftNames = tokenNames(left);
|
|
774
|
+
return [...tokenNames(right)].some((name) => leftNames.has(name));
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
function tokenNames(token) {
|
|
778
|
+
return new Set(
|
|
779
|
+
[
|
|
780
|
+
token.word,
|
|
781
|
+
...validTokenNameArray(token.synonyms),
|
|
782
|
+
...validTokenNameArray(token.aliases),
|
|
783
|
+
]
|
|
784
|
+
.map(normalizeTokenName)
|
|
785
|
+
.filter(Boolean),
|
|
786
|
+
);
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
function validTokenNameArray(value) {
|
|
790
|
+
return Array.isArray(value) &&
|
|
791
|
+
value.every((item) => typeof item === "string")
|
|
792
|
+
? value
|
|
793
|
+
: [];
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
function normalizeTokenName(value) {
|
|
797
|
+
return String(value ?? "").trim().toLowerCase();
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
function tokenWithoutNames(token) {
|
|
801
|
+
const { word: _word, synonyms: _synonyms, aliases: _aliases, ...rest } =
|
|
802
|
+
token;
|
|
803
|
+
return rest;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
function visit(value, callback, seen = new Set()) {
|
|
807
|
+
if (!value || typeof value !== "object" || seen.has(value)) return;
|
|
808
|
+
seen.add(value);
|
|
809
|
+
callback(value);
|
|
810
|
+
for (const child of Array.isArray(value) ? value : Object.values(value))
|
|
811
|
+
visit(child, callback, seen);
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
function findUnderstanding(value) {
|
|
815
|
+
if (value === null || value === undefined) return null;
|
|
816
|
+
if (Array.isArray(value)) {
|
|
817
|
+
for (const item of [...value].reverse()) {
|
|
818
|
+
const result = findUnderstanding(item);
|
|
819
|
+
if (result) return result;
|
|
820
|
+
}
|
|
821
|
+
return null;
|
|
822
|
+
}
|
|
823
|
+
if (typeof value === "object") {
|
|
824
|
+
if (
|
|
825
|
+
Object.hasOwn(value, "dimensions") &&
|
|
826
|
+
Object.hasOwn(value, "metrics") &&
|
|
827
|
+
Object.hasOwn(value, "time_range")
|
|
828
|
+
)
|
|
829
|
+
return value;
|
|
830
|
+
for (const item of Object.values(value)) {
|
|
831
|
+
const result = findUnderstanding(item);
|
|
832
|
+
if (result) return result;
|
|
833
|
+
}
|
|
834
|
+
return null;
|
|
835
|
+
}
|
|
836
|
+
const text = String(value).trim();
|
|
837
|
+
const objectStart = text.indexOf("{");
|
|
838
|
+
const objectEnd = text.lastIndexOf("}");
|
|
839
|
+
const candidates = [
|
|
840
|
+
text,
|
|
841
|
+
text.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, ""),
|
|
842
|
+
objectStart >= 0 && objectEnd > objectStart
|
|
843
|
+
? text.slice(objectStart, objectEnd + 1)
|
|
844
|
+
: "",
|
|
845
|
+
];
|
|
846
|
+
for (const candidate of candidates) {
|
|
847
|
+
if (!candidate) continue;
|
|
848
|
+
try {
|
|
849
|
+
const result = findUnderstanding(JSON.parse(candidate));
|
|
850
|
+
if (result) return result;
|
|
851
|
+
} catch {
|
|
852
|
+
// 尝试同一文本的下一种 JSON 包装形式。
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
return null;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
function canonicalJson(value) {
|
|
859
|
+
return JSON.stringify(canonicalValue(value));
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
function digestJson(value) {
|
|
863
|
+
return digestText(canonicalJson(value));
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
function digestText(value) {
|
|
867
|
+
return createHash("sha256").update(value, "utf8").digest("hex");
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
function canonicalValue(value) {
|
|
871
|
+
if (Array.isArray(value)) return value.map(canonicalValue);
|
|
872
|
+
if (value && typeof value === "object")
|
|
873
|
+
return Object.fromEntries(
|
|
874
|
+
Object.keys(value)
|
|
875
|
+
.sort()
|
|
876
|
+
.map((key) => [key, canonicalValue(value[key])]),
|
|
877
|
+
);
|
|
878
|
+
return value;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
function parseJsonCell(value, label) {
|
|
882
|
+
const text = String(value ?? "").trim();
|
|
883
|
+
if (!text) throw new Error(`${label}为空`);
|
|
884
|
+
try {
|
|
885
|
+
return JSON.parse(text);
|
|
886
|
+
} catch {
|
|
887
|
+
throw new Error(`${label}不是有效 JSON`);
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
function validateColumns(header, columns) {
|
|
892
|
+
if (new Set(header).size !== header.length)
|
|
893
|
+
throw new Error("CSV 表头存在重复列名");
|
|
894
|
+
for (const [kind, name] of Object.entries(columns)) {
|
|
895
|
+
if (name !== null && !header.includes(name))
|
|
896
|
+
throw new Error(`CSV 缺少 ${kind} 列:${name}`);
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
function validateOutputColumns(header) {
|
|
901
|
+
const conflict = OUTPUT_COLUMNS.find((name) => header.includes(name));
|
|
902
|
+
if (conflict) throw new Error(`原始 CSV 已包含保留输出列:${conflict}`);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
function positiveInteger(value, name, allowZero = false) {
|
|
906
|
+
const number = Number(value);
|
|
907
|
+
if (!Number.isInteger(number) || number < (allowZero ? 0 : 1))
|
|
908
|
+
throw new Error(`--${name} 必须是${allowZero ? "非负" : "正"}整数`);
|
|
909
|
+
return number;
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
function safeOutputDirectory(value) {
|
|
913
|
+
if (typeof value !== "string" || !value || isAbsolute(value))
|
|
914
|
+
throw new Error("--output-dir 必须是当前目录下的相对路径");
|
|
915
|
+
const root = resolve(process.cwd());
|
|
916
|
+
const target = resolve(root, value);
|
|
917
|
+
if (relative(root, target).startsWith(".."))
|
|
918
|
+
throw new Error("--output-dir 不得超出当前目录");
|
|
919
|
+
return target;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
function safeOutputFile(value) {
|
|
923
|
+
if (typeof value !== "string" || !value || isAbsolute(value))
|
|
924
|
+
throw new Error("--output 必须是当前目录下的相对路径");
|
|
925
|
+
const root = resolve(process.cwd());
|
|
926
|
+
const target = resolve(root, value);
|
|
927
|
+
if (relative(root, target).startsWith(".."))
|
|
928
|
+
throw new Error("--output 不得超出当前目录");
|
|
929
|
+
return target;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
function resolveExistingPath(value) {
|
|
933
|
+
return resolve(process.cwd(), String(value));
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
async function readJsonLines(path, missingAllowed = false) {
|
|
937
|
+
let text;
|
|
938
|
+
try {
|
|
939
|
+
text = await readFile(path, "utf8");
|
|
940
|
+
} catch (error) {
|
|
941
|
+
if (missingAllowed && error.code === "ENOENT") return [];
|
|
942
|
+
throw error;
|
|
943
|
+
}
|
|
944
|
+
return text
|
|
945
|
+
.split(/\r?\n/)
|
|
946
|
+
.filter(Boolean)
|
|
947
|
+
.map((line, index) => {
|
|
948
|
+
try {
|
|
949
|
+
return JSON.parse(line);
|
|
950
|
+
} catch {
|
|
951
|
+
throw new Error(`${path} 第 ${index + 1} 行不是有效 JSON`);
|
|
952
|
+
}
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
function latestByRow(records) {
|
|
957
|
+
const result = new Map();
|
|
958
|
+
for (const record of records) {
|
|
959
|
+
if (!Number.isInteger(record?.rowNumber) || record.rowNumber < 2)
|
|
960
|
+
throw new Error("artifact 包含无效 rowNumber");
|
|
961
|
+
result.set(record.rowNumber, record);
|
|
962
|
+
}
|
|
963
|
+
return result;
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
async function atomicWrite(path, content) {
|
|
967
|
+
await mkdir(dirname(path), { recursive: true });
|
|
968
|
+
const temporary = `${path}.tmp-${process.pid}`;
|
|
969
|
+
await writeFile(temporary, content, "utf8");
|
|
970
|
+
await rename(temporary, path);
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
function padRow(row, length) {
|
|
974
|
+
return Array.from({ length }, (_, index) => row[index] ?? "");
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
function csvField(value) {
|
|
978
|
+
const text = String(value ?? "");
|
|
979
|
+
return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
function jsonCell(value) {
|
|
983
|
+
return value === undefined ? "" : JSON.stringify(value);
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
function singleLine(value) {
|
|
987
|
+
return String(value ?? "")
|
|
988
|
+
.replace(/[\r\n]+/g, " ")
|
|
989
|
+
.trim();
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
function normalizeWords(value) {
|
|
993
|
+
return singleLine(value).replace(/\s+/g, " ");
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
function correctnessLabel(verdict) {
|
|
997
|
+
return { pass: "是", fail: "否", review: "待复核", error: "执行错误" }[
|
|
998
|
+
verdict
|
|
999
|
+
];
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
function help() {
|
|
1003
|
+
return {
|
|
1004
|
+
usage: [
|
|
1005
|
+
"collect --workspace-id <id> --input <csv> --output-dir <relative-dir> --question-column <name> --expected-understanding-column <name> --expected-tokens-column <name> [--expected-token-words-column <name>]",
|
|
1006
|
+
"finalize --manifest <json> [--decisions <jsonl>] --output <relative-csv>",
|
|
1007
|
+
],
|
|
1008
|
+
options: {
|
|
1009
|
+
collect: [
|
|
1010
|
+
"--concurrency <n>",
|
|
1011
|
+
"--poll-interval-ms <n>",
|
|
1012
|
+
"--max-wait-ms <n>",
|
|
1013
|
+
"--retry-errors",
|
|
1014
|
+
],
|
|
1015
|
+
},
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
|
|
1020
|
+
await runCli(() => execute(process.argv.slice(2)));
|