case-intake.mjs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. #!/usr/bin/env node
  2. // Copyright (c) 未来飞马
  3. //
  4. // This Source Code Form is subject to the terms of the Mozilla Public
  5. // License, v. 2.0. If a copy of the MPL was not distributed with this
  6. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
  7. //
  8. // Trademark Notice:
  9. // The MPL-2.0 license grants copyright permissions for source code only.
  10. // It does NOT grant any rights to use trademarks including "未来飞马",
  11. // "Harness Loop", "RSI", and associated slogan "让AI进化提前发生,让AI落地快人一步".
  12. // Any use of these trademarks requires separate written permission.
  13. /**
  14. * skill-case-get —— 案例采集 / 拆解 / 归档 主入口
  15. *
  16. * 管线:
  17. * ① 输入识别:连续多图 / .docx / .pptx / 图文混合 / 裸图 / 视频
  18. * ② 拆解提取:图片→skill-vision(OCR+语义);docx/pptx→python3 标准库解包;视频→抽帧+skill-listen 转写
  19. * ③ 分组与顺序:尺寸/时间/内容相似度判同组;九宫格按左上→右下给显式 order
  20. * ④ 案例信息 vs 素材 分离
  21. * ⑤ 合规判断:能否入库?客诉/负面?→ riskFlags / privacyFindings
  22. * ⑥ 打标:静态属性 + 跟进状态七段 + 亮点/场景/异议 + 学校别名归一
  23. * ⑦ 入库:caseSubmit 写待审清单(reviewStatus=pending, readyForUse=false),带幂等键
  24. * ⑧ 字典自进化:新标签追加进 references/tag-dictionary.json
  25. *
  26. * 子命令:
  27. * plan 只识别 + 提取 + 分组(不调任何模型,纯本机)
  28. * ingest plan + 图片理解 + 分类打标 → 产出 case-package.json(默认不提交)
  29. * submit 读取 case-package.json(可先 reorder)→ 调云函数 caseSubmit
  30. * reorder 调整 materialAssets 顺序(支持数组 + 顺序调整)
  31. * dictionary 查看 / 追加标签字典
  32. * selftest 本机自检(office 解包 + 分组 + 打标 + 合规)
  33. *
  34. * 安全:绝不打印 token/PII;生成的产物默认落在 <cwd>/case-get-outputs/。
  35. */
  36. import fs from 'node:fs';
  37. import path from 'node:path';
  38. import zlib from 'node:zlib';
  39. import { spawnSync } from 'node:child_process';
  40. import { parseArgs } from 'node:util';
  41. import {
  42. TENANT_DEFAULT, SKILL_ROOT, buildIdempotencyKey, deriveAssetUrl, ensureDir, firstText, imageUrlsFrom,
  43. learnAliases, learnTags, loadDictionary, newRunId, normalizeMaterialAsset, outputsDir,
  44. readJson, reorderAssets, resolvePython, saveDictionary, sortAssets, truncate, uniq, writeJson,
  45. } from './lib.mjs';
  46. import { readImageInfo, IMAGE_EXTENSIONS, VIDEO_EXTENSIONS, DOC_EXTENSIONS, DECK_EXTENSIONS, TEXT_EXTENSIONS } from './image-size.mjs';
  47. import { applyGroupOverrides, groupMaterials, DEFAULT_ORDERING_RULE } from './grouping.mjs';
  48. import { classifyCase } from './classify.mjs';
  49. import { processVideo } from './listen-bridge.mjs';
  50. import { analyzeImages } from './vision-bridge.mjs';
  51. import { CloudError, submitCase } from './cloud-client.mjs';
  52. // ---------------------------------------------------------------------------
  53. // 输入识别
  54. // ---------------------------------------------------------------------------
  55. export function detectSourceType({ images = 0, documents = 0, decks = 0, videos = 0, texts = 0 }) {
  56. const kinds = [images > 0, documents > 0, decks > 0, videos > 0, texts > 0].filter(Boolean).length;
  57. if (kinds > 1) return 'mixed';
  58. if (images > 1) return 'image_group';
  59. if (images === 1 && videos === 0) return 'single_image';
  60. if (videos > 0) return 'image_group'; // 视频素材组,按 group 处理
  61. if (decks > 0) return 'presentation';
  62. if (documents > 0) return 'document';
  63. return 'mixed';
  64. }
  65. export function classifyInput(filePath) {
  66. const ext = path.extname(filePath).toLowerCase();
  67. if (IMAGE_EXTENSIONS.has(ext)) return 'image';
  68. if (VIDEO_EXTENSIONS.has(ext)) return 'video';
  69. if (DOC_EXTENSIONS.has(ext)) return 'docx';
  70. if (DECK_EXTENSIONS.has(ext)) return 'pptx';
  71. if (TEXT_EXTENSIONS.has(ext)) return 'text';
  72. return 'unknown';
  73. }
  74. /** 展开目录(只展开一层里的文件,不递归太深,避免误扫)。 */
  75. export function expandInputs(inputs, maxDepth = 2) {
  76. const out = [];
  77. const walk = (target, depth) => {
  78. let stat;
  79. try {
  80. stat = fs.statSync(target);
  81. } catch {
  82. out.push({ path: target, exists: false });
  83. return;
  84. }
  85. if (stat.isDirectory()) {
  86. if (depth > maxDepth) return;
  87. for (const entry of fs.readdirSync(target).sort()) {
  88. if (entry.startsWith('.')) continue;
  89. walk(path.join(target, entry), depth + 1);
  90. }
  91. return;
  92. }
  93. out.push({ path: target, exists: true, size: stat.size, mtimeMs: stat.mtimeMs });
  94. };
  95. for (const input of inputs) walk(input, 0);
  96. return out;
  97. }
  98. // ---------------------------------------------------------------------------
  99. // ② 拆解提取
  100. // ---------------------------------------------------------------------------
  101. function runOfficeExtract(files, mediaOut) {
  102. if (!files.length) return { available: true, results: [], error: null };
  103. const script = path.join(SKILL_ROOT, 'scripts', 'office_extract.py');
  104. if (!fs.existsSync(script)) return { available: false, results: [], error: `缺少 ${script}` };
  105. const python = resolvePython();
  106. const args = [script, '--media-out', mediaOut];
  107. for (const file of files) args.push('--input', file);
  108. const run = spawnSync(python, args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
  109. if (run.error) {
  110. return { available: false, results: [], error: `${python} 启动失败:${run.error.message}(.docx/.pptx 解包需要 python3 标准库)` };
  111. }
  112. let parsed = null;
  113. try {
  114. parsed = JSON.parse(run.stdout || '{}');
  115. } catch {
  116. return { available: true, results: [], error: `office_extract 输出不是 JSON:${truncate(run.stderr || run.stdout, 300)}` };
  117. }
  118. return {
  119. available: true,
  120. results: parsed.results || [],
  121. error: parsed.ok ? null : `部分文档解包失败:${(parsed.results || []).filter((r) => !r.ok).map((r) => r.error).join(', ')}`,
  122. };
  123. }
  124. function sleep(ms) {
  125. return new Promise((resolve) => { setTimeout(resolve, ms); });
  126. }
  127. // ---------------------------------------------------------------------------
  128. // plan:识别 + 提取 + 分组
  129. // ---------------------------------------------------------------------------
  130. export async function runPlan(options = {}) {
  131. const outDir = ensureDir(options.outDir);
  132. const mediaDir = ensureDir(path.join(outDir, 'media'));
  133. const entries = expandInputs(options.inputs || []);
  134. const missing = entries.filter((e) => !e.exists).map((e) => e.path);
  135. const buckets = { image: [], video: [], docx: [], pptx: [], text: [], unknown: [] };
  136. for (const entry of entries) {
  137. if (!entry.exists) continue;
  138. buckets[classifyInput(entry.path)].push(entry.path);
  139. }
  140. const warnings = [];
  141. for (const file of missing) warnings.push(`输入不存在:${file}`);
  142. if (buckets.unknown.length) warnings.push(`忽略无法识别的文件:${buckets.unknown.join(', ')}`);
  143. // ---- docx / pptx 解包
  144. const docxResults = runOfficeExtract(buckets.docx, path.join(mediaDir, 'docx'));
  145. const pptxResults = runOfficeExtract(buckets.pptx, path.join(mediaDir, 'pptx'));
  146. if (docxResults.error) warnings.push(docxResults.error);
  147. if (pptxResults.error) warnings.push(pptxResults.error);
  148. const textBundle = { paragraphs: [], notes: [], titles: [], transcript: '' };
  149. const mediaFromDocs = [];
  150. for (const result of [...docxResults.results, ...pptxResults.results]) {
  151. if (!result.ok) {
  152. warnings.push(`${result.fileName || result.input} 解包失败:${result.error}`);
  153. continue;
  154. }
  155. for (const p of result.paragraphs || []) if (p.text) textBundle.paragraphs.push(p.text);
  156. for (const h of result.headings || []) if (h) textBundle.titles.push(h);
  157. for (const note of result.notes || []) {
  158. if (typeof note === 'string') textBundle.notes.push(note);
  159. else if (note && note.text) textBundle.notes.push(note.text);
  160. }
  161. for (const slide of result.slides || []) if (slide.title) textBundle.titles.push(slide.title);
  162. for (const media of result.media || []) {
  163. if (media.kind === 'image' && media.localPath) mediaFromDocs.push({ ...media, sourceDoc: result.fileName || result.input });
  164. }
  165. }
  166. // ---- 纯文本输入(.md/.txt):并入说明语料
  167. for (const file of buckets.text) {
  168. try {
  169. const text = fs.readFileSync(file, 'utf8');
  170. textBundle.paragraphs.push(...text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean));
  171. } catch (error) {
  172. warnings.push(`文本读取失败 ${file}:${error.message}`);
  173. }
  174. }
  175. // ---- 图片:读尺寸/时间
  176. const imageItems = [];
  177. for (const file of buckets.image) {
  178. const info = readImageInfo(file);
  179. if (!info.ok) warnings.push(`图片信息读取失败 ${path.basename(file)}:${info.error}`);
  180. imageItems.push({
  181. kind: 'image',
  182. localPath: path.resolve(file),
  183. width: info.width || null,
  184. height: info.height || null,
  185. mtimeMs: info.mtimeMs || fs.statSync(file).mtimeMs,
  186. ocrText: '',
  187. description: '',
  188. label: path.basename(file),
  189. origin: 'direct',
  190. });
  191. }
  192. // 文档内嵌图片也参与分组(图文混合)。sourceKey 钉住来源文档,
  193. // 避免两份不同文档的配图因为同比例、同落盘时间被误并成一组。
  194. for (const media of mediaFromDocs) {
  195. const info = readImageInfo(media.localPath);
  196. imageItems.push({
  197. kind: 'image',
  198. localPath: media.localPath,
  199. width: info.width || null,
  200. height: info.height || null,
  201. mtimeMs: info.mtimeMs || null,
  202. ocrText: '',
  203. description: media.nearbyText || '',
  204. label: `${media.sourceDoc || '文档'} 内嵌图`,
  205. origin: 'document-media',
  206. sourceKey: media.sourceDoc || '',
  207. slide: media.slide,
  208. });
  209. }
  210. // ---- 视频:抽帧 + 转写
  211. const videoReports = [];
  212. for (const file of buckets.video) {
  213. if (options.skipVideo) {
  214. warnings.push(`跳过视频(--skip-video):${path.basename(file)}`);
  215. continue;
  216. }
  217. const report = await processVideo(file, {
  218. workDir: path.join(mediaDir, 'video', path.basename(file, path.extname(file))),
  219. frameCount: options.frameCount || 6,
  220. diarize: Boolean(options.diarize),
  221. });
  222. videoReports.push(report);
  223. for (const warning of report.warnings) warnings.push(`${path.basename(file)}:${warning}`);
  224. if (report.transcription && report.transcription.text) {
  225. textBundle.transcript = [textBundle.transcript, report.transcription.text].filter(Boolean).join('\n');
  226. }
  227. for (const frame of report.frames || []) {
  228. imageItems.push({
  229. kind: 'image',
  230. localPath: frame.localPath,
  231. width: null,
  232. height: null,
  233. mtimeMs: null,
  234. ocrText: '',
  235. description: `视频抽帧 @${frame.atMs != null ? `${Math.round(frame.atMs / 1000)}s` : '开头'}`,
  236. label: `${path.basename(file)} 抽帧`,
  237. origin: 'video-frame',
  238. atMs: frame.atMs,
  239. videoPath: path.resolve(file),
  240. });
  241. }
  242. }
  243. // ---- 分组(尺寸 / 时间 / 内容)
  244. let groups = groupMaterials(imageItems, options.grouping || {});
  245. groups = applyGroupOverrides(groups, options.groupOverrides);
  246. const sourceType = options.sourceType || detectSourceType({
  247. images: buckets.image.length,
  248. documents: buckets.docx.length + buckets.text.length,
  249. decks: buckets.pptx.length,
  250. videos: buckets.video.length,
  251. });
  252. const plan = {
  253. runId: options.runId || newRunId(),
  254. generatedAt: new Date().toISOString(),
  255. tenantId: options.tenantId || TENANT_DEFAULT,
  256. sourceType,
  257. sourceRef: options.sourceRef || '',
  258. authorizationStatus: String(options.authorizationStatus || '').toLowerCase(),
  259. inputs: {
  260. images: buckets.image.map((p) => path.resolve(p)),
  261. documents: buckets.docx.map((p) => path.resolve(p)),
  262. decks: buckets.pptx.map((p) => path.resolve(p)),
  263. videos: buckets.video.map((p) => path.resolve(p)),
  264. texts: buckets.text.map((p) => path.resolve(p)),
  265. },
  266. counts: {
  267. imageCount: imageItems.length,
  268. documentCount: buckets.docx.length,
  269. deckCount: buckets.pptx.length,
  270. videoCount: buckets.video.length,
  271. groupCount: groups.length,
  272. },
  273. textBundle,
  274. groups,
  275. videoReports,
  276. warnings,
  277. // 生成物绝对路径(后续 vision / submit 直接引用)
  278. artifacts: {
  279. extracted: path.join(outDir, 'extracted.json'),
  280. groupPlan: path.join(outDir, 'group-plan.json'),
  281. },
  282. };
  283. if (!groups.length) plan.warnings.push('没有识别到任何可用素材(没有任何图片/视频/文档内嵌图)');
  284. writeJson(plan.artifacts.extracted, { textBundle, mediaFromDocs, videoReports });
  285. writeJson(plan.artifacts.groupPlan, { sourceType, groups });
  286. return plan;
  287. }
  288. // ---------------------------------------------------------------------------
  289. // ingest:plan + 图片理解 + 分类打标 → 案例包
  290. // ---------------------------------------------------------------------------
  291. export async function runIngest(options = {}) {
  292. const plan = await runPlan(options);
  293. const outDir = options.outDir;
  294. const warnings = [...plan.warnings];
  295. // 图片理解(OCR + 语义)——没有图片时跳过
  296. const allImages = plan.groups.flatMap((g) => g.items.filter((i) => i.kind === 'image'));
  297. let vision = { available: true, results: [], error: null, needsHostRead: false };
  298. if (options.skipVision) {
  299. warnings.push('跳过图片理解(--skip-vision):素材只有文件名,ocrText/description 为空');
  300. } else if (allImages.length) {
  301. const batchHint = [
  302. plan.textBundle.titles.slice(0, 3).join(' / '),
  303. plan.textBundle.paragraphs.slice(0, 3).join(' / '),
  304. ].filter(Boolean).join(' | ');
  305. vision = await analyzeImages(
  306. allImages.map((item) => ({ localPath: item.localPath, url: item.url, label: item.label })),
  307. { model: options.visionModel, batchHint },
  308. );
  309. if (!vision.available) {
  310. warnings.push(vision.error);
  311. } else if (vision.needsHostRead) {
  312. warnings.push('宿主多模态模式:vision 返回了读图指令(instruction),请宿主 Agent 用 Read 工具读图后把 JSON 结果写入 vision-host.json,再执行 submit。');
  313. } else if (vision.error) {
  314. warnings.push(vision.error);
  315. }
  316. }
  317. // 把 vision 结果并回素材
  318. const visionByFile = new Map();
  319. for (const result of vision.results || []) {
  320. if (result.file) visionByFile.set(path.resolve(result.file), result);
  321. }
  322. const enrichedGroups = plan.groups.map((group) => ({
  323. ...group,
  324. items: group.items.map((item) => {
  325. const enriched = { ...item };
  326. if (item.kind === 'image' && item.localPath) {
  327. const found = visionByFile.get(path.resolve(item.localPath));
  328. if (found) {
  329. enriched.ocrText = found.ocrText || enriched.ocrText || '';
  330. enriched.description = found.description || enriched.description || '';
  331. enriched.usageSuggestion = found.usageSuggestion || '';
  332. enriched.label = found.label || enriched.label || '';
  333. // 分析未产出结论(宿主读图待补 / 分析失败)时保持默认 role='material',
  334. // 不能凭空把素材降级成说明配图。
  335. enriched.role = found.role || 'material';
  336. enriched.piiHints = found.piiHints || [];
  337. enriched.visionPending = Boolean(found.needsHostRead);
  338. } else {
  339. enriched.role = enriched.role || 'material';
  340. }
  341. }
  342. return enriched;
  343. }),
  344. }));
  345. // 案例信息 vs 素材:分离后分类打标
  346. const dict = loadDictionary(options.dictPath);
  347. const visionResults = (vision.results || []).map((r) => ({ ...r }));
  348. const classification = classifyCase({
  349. dict,
  350. groups: enrichedGroups,
  351. visionResults,
  352. textBundle: plan.textBundle,
  353. authorizationStatus: plan.authorizationStatus,
  354. hints: options.hints || {},
  355. });
  356. // ⑧ 字典自进化
  357. const learn = learnTags(dict, classification.learned.tags);
  358. const aliasLearn = learnAliases(dict, classification.learned.aliases);
  359. const dictionaryChanges = { tags: learn.added, aliases: aliasLearn.added, skipped: learn.skipped };
  360. const dictionaryFile = options.dictPath ? path.resolve(options.dictPath) : undefined;
  361. if ((learn.added.length || aliasLearn.added.length) && !options.noLearn) {
  362. saveDictionary(dict);
  363. } else if (options.noLearn && (learn.added.length || aliasLearn.added.length)) {
  364. warnings.push('字典自进化被 --no-learn 关闭:本次新增标签未落盘');
  365. dictionaryChanges.tags = [];
  366. dictionaryChanges.aliases = [];
  367. }
  368. if (dictionaryFile) writeJson(dictionaryFile, readJson(dictionaryFile, {}));
  369. // ---- 组装 materialAssets[](逐字对齐 SHARED-CONTRACT.md)
  370. const materialAssets = [];
  371. const groupInfoList = [];
  372. const assetProblems = [];
  373. let missingUrlCount = 0;
  374. for (const group of enrichedGroups) {
  375. groupInfoList.push({
  376. groupId: group.groupId,
  377. layout: group.layout,
  378. count: group.count,
  379. orderingRule: group.orderingRule,
  380. });
  381. for (const item of sortAssets(group.items)) {
  382. // 本地文件没有公网 URL 时,按 --asset-base-url 派生;没给基础地址则留空并警告
  383. const derivedUrl = item.url || deriveAssetUrl(item.localPath, options.assetBaseUrl);
  384. if (!derivedUrl && item.localPath) missingUrlCount += 1;
  385. const { asset, problems } = normalizeMaterialAsset({
  386. order: item.order,
  387. groupId: group.groupId,
  388. kind: item.kind,
  389. url: derivedUrl,
  390. localPath: item.localPath || '',
  391. label: item.label || '',
  392. ocrText: item.ocrText || '',
  393. description: item.description || '',
  394. usageSuggestion: item.usageSuggestion || '',
  395. role: item.role || 'material',
  396. }, materialAssets.length);
  397. assetProblems.push(...problems);
  398. materialAssets.push(asset);
  399. }
  400. }
  401. for (const problem of assetProblems) warnings.push(problem);
  402. if (missingUrlCount) {
  403. warnings.push(`${missingUrlCount} 个素材只有本地路径、没有 URL:用 --asset-base-url <CDN前缀> 派生,或由归档方补齐 url 后再 submit(检索侧只看 url)。`);
  404. }
  405. // 全局重编号:materialAssets 已按「分组顺序 → 组内 order」构建,
  406. // 这里只顺次改写 order。**不能**再按 order 全局排序——各组的 order 都从 1 起,
  407. // 直接排会把四组的第一张图并到最前面。
  408. const orderedAssets = materialAssets.map((asset, index) => ({ ...asset, order: index + 1 }));
  409. const imageUrls = imageUrlsFrom(orderedAssets);
  410. // ---- 组装案例包(幂等键:tenantId + 内容指纹)
  411. const title = firstText(options.title, classification.caseFields.title);
  412. const idempotencyKey = buildIdempotencyKey({
  413. tenantId: plan.tenantId,
  414. sourceType: plan.sourceType,
  415. sourceRef: plan.sourceRef,
  416. title,
  417. materialAssets: orderedAssets,
  418. explicit: options.idempotencyKey,
  419. });
  420. const primaryGroup = groupInfoList[0] || { groupId: 'g1', layout: '1x1', count: 0, orderingRule: DEFAULT_ORDERING_RULE };
  421. const casePackage = {
  422. schemaVersion: '1.0.0',
  423. generatedAt: new Date().toISOString(),
  424. runId: plan.runId,
  425. contract: 'SHARED-CONTRACT.md',
  426. // ---- 云函数 caseSubmit 入参(逐字对齐)
  427. sourceType: plan.sourceType,
  428. sourceRef: plan.sourceRef,
  429. idempotencyKey,
  430. title,
  431. summary: firstText(options.summary, classification.caseFields.summary),
  432. materialAssets: orderedAssets,
  433. groupInfo: primaryGroup,
  434. groupInfoList,
  435. schoolCanonical: (classification.tags.schoolCanonical || [])[0] || '',
  436. tags: uniq([
  437. ...(classification.tags.country || []),
  438. ...(classification.tags.schoolCanonical || []),
  439. ...(classification.tags.major || []),
  440. ...(classification.tags.stage || []),
  441. ...(classification.tags.subject || []),
  442. ...(classification.tags.highlightTypes || []),
  443. ...(classification.tags.scenarioTags || []),
  444. ...(classification.tags.objectionTags || []),
  445. ...(classification.fit.fitStatus || []),
  446. ...(classification.tags.productLine || []),
  447. ]),
  448. highlightTypes: classification.tags.highlightTypes || [],
  449. scenarioTags: classification.tags.scenarioTags || [],
  450. objectionTags: classification.tags.objectionTags || [],
  451. riskFlags: classification.compliance.riskFlags || [],
  452. authorizationStatus: plan.authorizationStatus || '',
  453. // ---- 案例字段(案例说明,与素材分开)
  454. targetCustomer: firstText(options.targetCustomer, classification.caseFields.targetCustomer),
  455. usageSuggestion: firstText(options.usageSuggestion, classification.caseFields.usageSuggestion),
  456. resultEvidence: classification.caseFields.resultEvidence,
  457. outcome: classification.caseFields.outcome,
  458. country: (classification.tags.country || [])[0] || '',
  459. major: (classification.tags.major || [])[0] || '',
  460. stage: (classification.tags.stage || [])[0] || '',
  461. subject: (classification.tags.subject || [])[0] || '',
  462. fitStatus: classification.fit.fitStatus || [],
  463. schoolAliases: classification.tags.schoolAliases || [],
  464. imageUrls,
  465. hasImage: imageUrls.length > 0,
  466. imageText: truncate(orderedAssets.map((a) => a.ocrText).filter(Boolean).join(' '), 400),
  467. privacyFindings: classification.compliance.privacyFindings || [],
  468. complianceBlockers: classification.compliance.complianceBlockers || [],
  469. reviewHint: classification.compliance.reviewHint,
  470. summaryLine: casePackageSummaryLine(classification, orderedAssets.length),
  471. submittedBy: options.submittedBy || '',
  472. // ---- 落库后由服务端决定的字段(此处只声明预期值,供 dry-run 展示)
  473. expected: { reviewStatus: 'pending', readyForUse: false },
  474. };
  475. // ---- 产出物
  476. const artifacts = {
  477. extracted: plan.artifacts.extracted,
  478. groupPlan: plan.artifacts.groupPlan,
  479. vision: path.join(outDir, 'vision.json'),
  480. materialAssets: path.join(outDir, 'material-assets.json'),
  481. casePackage: path.join(outDir, 'case-package.json'),
  482. report: path.join(outDir, 'report.md'),
  483. };
  484. writeJson(artifacts.vision, vision);
  485. writeJson(artifacts.materialAssets, { groupInfoList, materialAssets: orderedAssets });
  486. writeJson(artifacts.casePackage, casePackage);
  487. fs.writeFileSync(artifacts.report, renderReport({ plan, casePackage, vision, dictionaryChanges, warnings }), 'utf8');
  488. const blockers = casePackage.complianceBlockers || [];
  489. const canSubmit = plan.authorizationStatus === 'authorized' && blockers.length === 0 && orderedAssets.length > 0;
  490. return { plan, casePackage, vision, dictionaryChanges, warnings, artifacts, canSubmit };
  491. }
  492. function casePackageSummaryLine(classification, assetCount) {
  493. const fits = (classification.fit.fitStatus || []).join('/') || '未命中';
  494. const risks = (classification.compliance.riskFlags || []).join('/') || '无';
  495. return `${assetCount} 个素材;适用跟进状态:${fits};风险:${risks}`;
  496. }
  497. // ---------------------------------------------------------------------------
  498. // 报告
  499. // ---------------------------------------------------------------------------
  500. export function renderReport({ plan, casePackage, vision, dictionaryChanges, warnings }) {
  501. const lines = [];
  502. lines.push(`# 案例采集报告 · ${casePackage.runId}`);
  503. lines.push('');
  504. lines.push(`- 生成时间:${casePackage.generatedAt}`);
  505. lines.push(`- 来源类型:\`${casePackage.sourceType}\``);
  506. lines.push(`- 授权状态:\`${casePackage.authorizationStatus || '缺失'}\``);
  507. lines.push(`- 幂等键:\`${casePackage.idempotencyKey}\``);
  508. lines.push(`- 素材数:${casePackage.materialAssets.length}(分组 ${casePackage.groupInfoList.length} 组)`);
  509. lines.push(`- 图片理解:${vision.available ? `已启用(${vision.source}${vision.needsHostRead ? ',待宿主读图' : ''})` : '不可用'}`);
  510. lines.push('');
  511. lines.push('## 素材顺序(materialAssets)');
  512. lines.push('');
  513. lines.push('| order | groupId | kind | role | 标签 | 说明 |');
  514. lines.push('| --- | --- | --- | --- | --- | --- |');
  515. for (const asset of casePackage.materialAssets) {
  516. lines.push(`| ${asset.order} | ${asset.groupId} | ${asset.kind} | ${asset.role} | ${truncate(asset.label, 20)} | ${truncate(asset.description || asset.ocrText, 60)} |`);
  517. }
  518. lines.push('');
  519. lines.push('## 分组(九宫格阅读顺序:左上 → 右下)');
  520. lines.push('');
  521. for (const group of casePackage.groupInfoList) {
  522. lines.push(`- \`${group.groupId}\` ${group.layout} · ${group.count} 张 · \`${group.orderingRule}\``);
  523. }
  524. lines.push('');
  525. lines.push('## 标签');
  526. lines.push('');
  527. lines.push(`- 学校(归一):${casePackage.schoolCanonical || '未识别'}${casePackage.schoolAliases.length ? `(命中别名:${casePackage.schoolAliases.join('、')})` : ''}`);
  528. lines.push(`- 国家:${casePackage.country || '未识别'} · 专业:${casePackage.major || '未识别'} · 阶段:${casePackage.stage || '未识别'} · 科目:${casePackage.subject || '未识别'}`);
  529. lines.push(`- 亮点:${casePackage.highlightTypes.join('、') || '无'}`);
  530. lines.push(`- 场景:${casePackage.scenarioTags.join('、') || '无'}`);
  531. lines.push(`- 异议:${casePackage.objectionTags.join('、') || '无'}`);
  532. lines.push(`- 适用跟进状态:${(casePackage.fitStatus || []).join('、') || '未命中'}`);
  533. lines.push('');
  534. lines.push('## 合规判断');
  535. lines.push('');
  536. lines.push(`- riskFlags:${casePackage.riskFlags.join('、') || '无'}`);
  537. lines.push(`- privacyFindings:${casePackage.privacyFindings.length} 条(仅记录,本期不打码)`);
  538. for (const finding of casePackage.privacyFindings) {
  539. lines.push(` - ${finding.field} / ${finding.rule}:\`${finding.snippet}\``);
  540. }
  541. lines.push(`- 结论:${casePackage.complianceBlockers.length ? '不入库' : '可入库待审'}`);
  542. for (const blocker of casePackage.complianceBlockers) lines.push(` - ⛔ ${blocker}`);
  543. lines.push(`- 审核提示:${casePackage.reviewHint}`);
  544. lines.push('');
  545. lines.push('## 字典自进化');
  546. lines.push('');
  547. lines.push(`- 新增标签:${dictionaryChanges.tags.length ? dictionaryChanges.tags.map((t) => `${t.dimension}=${t.value}`).join('、') : '无'}`);
  548. lines.push(`- 新增别名:${dictionaryChanges.aliases.length ? dictionaryChanges.aliases.map((a) => `${a.aliasText}→${a.canonicalName}`).join('、') : '无'}`);
  549. lines.push('');
  550. if (warnings.length) {
  551. lines.push('## 警告');
  552. lines.push('');
  553. for (const warning of uniq(warnings)) lines.push(`- ⚠️ ${warning}`);
  554. lines.push('');
  555. }
  556. lines.push('## 下一步');
  557. lines.push('');
  558. lines.push('1. 打开 `material-assets.json` 核对顺序(九宫格从左到右、从上到下),需要调整用 `reorder`;');
  559. lines.push('2. 确认无误后执行 `submit --package case-package.json`,落到待审清单(reviewStatus=pending,不进公共素材库);');
  560. lines.push('3. 由负责人用 `caseApprove` 审核放行后才会 `readyForUse=true`、进检索结果。');
  561. return `${lines.join('\n')}\n`;
  562. }
  563. // ---------------------------------------------------------------------------
  564. // submit
  565. // ---------------------------------------------------------------------------
  566. export async function runSubmit(options = {}) {
  567. const packagePath = path.resolve(options.package);
  568. const casePackage = readJson(packagePath, null);
  569. if (!casePackage) throw new Error(`读不到案例包:${packagePath}`);
  570. const blockers = casePackage.complianceBlockers || [];
  571. if (String(casePackage.authorizationStatus || '').toLowerCase() !== 'authorized') {
  572. return {
  573. submitted: false,
  574. reason: `authorizationStatus=${casePackage.authorizationStatus || '缺失'},仅 authorized 才可入库(硬规则:无授权不入库)`,
  575. blockers: ['UNAUTHORIZED'],
  576. };
  577. }
  578. if (blockers.length) {
  579. return { submitted: false, reason: 'complianceBlockers 非空,禁止入库', blockers };
  580. }
  581. if (!casePackage.materialAssets || !casePackage.materialAssets.length) {
  582. return { submitted: false, reason: 'materialAssets 为空,无法构成案例', blockers: ['NO_MATERIAL'] };
  583. }
  584. try {
  585. const response = await submitCase(casePackage, { submittedBy: options.submittedBy, token: options.token });
  586. if (!response.ok) {
  587. return { submitted: false, reason: `caseSubmit 返回错误:${response.error.code} ${response.error.message}`, error: response.error };
  588. }
  589. return {
  590. submitted: true,
  591. objectId: response.result.objectId,
  592. reviewStatus: response.result.reviewStatus || 'pending',
  593. readyForUse: response.result.readyForUse === true,
  594. };
  595. } catch (error) {
  596. if (error instanceof CloudError) {
  597. return {
  598. submitted: false,
  599. reason: error.message,
  600. offline: true,
  601. hint: '未提交成功(网络不可达/未登录)。案例包已保存在本地,可直接重跑 submit;幂等键保证重复提交只产生一条。',
  602. };
  603. }
  604. throw error;
  605. }
  606. }
  607. // ---------------------------------------------------------------------------
  608. // reorder
  609. // ---------------------------------------------------------------------------
  610. export function runReorder(options = {}) {
  611. const assetsPath = path.resolve(options.materialAssets || options.package);
  612. const bundle = readJson(assetsPath, null);
  613. if (!bundle) throw new Error(`读不到素材文件:${assetsPath}`);
  614. const list = Array.isArray(bundle) ? bundle : bundle.materialAssets;
  615. if (!Array.isArray(list)) throw new Error('素材文件里没有 materialAssets 数组');
  616. let next;
  617. if (options.move) {
  618. const [from, to] = String(options.move).split(/[:>,-]/).map((v) => Number(v.trim()));
  619. if (!Number.isFinite(from) || !Number.isFinite(to)) throw new Error('--move 格式应为 from:to,如 3:1');
  620. next = reorderAssets(list, from, to);
  621. } else if (options.order) {
  622. // --order "3,1,2" 表示「新顺序 = 原来第 3 项、第 1 项、第 2 项」(按位置,不是按 order 值)
  623. const positions = String(options.order).split(/[,\s]+/).map((v) => Number(v.trim())).filter(Number.isFinite);
  624. if (positions.length !== list.length) throw new Error(`--order 需要 ${list.length} 个位置序号,收到 ${positions.length} 个`);
  625. const byPosition = sortAssets(list);
  626. next = positions.map((position, index) => {
  627. const picked = byPosition[position - 1];
  628. if (!picked) throw new Error(`--order 位置越界:${position}(共 ${byPosition.length} 项)`);
  629. return { ...picked, order: index + 1 };
  630. });
  631. } else {
  632. throw new Error('需要 --move "3:1" 或 --order "3,1,2"');
  633. }
  634. const out = Array.isArray(bundle)
  635. ? next
  636. : { ...bundle, materialAssets: next, reorderedAt: new Date().toISOString() };
  637. writeJson(assetsPath, out);
  638. return { file: assetsPath, materialAssets: next };
  639. }
  640. // ---------------------------------------------------------------------------
  641. // 字典
  642. // ---------------------------------------------------------------------------
  643. export function runDictionary(options = {}) {
  644. const dict = loadDictionary(options.dictPath);
  645. if (options.add) {
  646. const items = [];
  647. for (const raw of options.add) {
  648. const [dimension, value] = String(raw).split('=');
  649. items.push({ dimension: (dimension || '').trim(), value: (value || '').trim() });
  650. }
  651. const result = learnTags(dict, items);
  652. if (result.added.length) saveDictionary(dict);
  653. return { added: result.added, skipped: result.skipped, file: dict.__file };
  654. }
  655. if (options.alias) {
  656. const entries = [];
  657. for (const raw of options.alias) {
  658. const [aliasText, canonicalName, country] = String(raw).split('=');
  659. entries.push({ aliasText: (aliasText || '').trim(), canonicalName: (canonicalName || '').trim(), country: (country || '').trim() });
  660. }
  661. const result = learnAliases(dict, entries);
  662. if (result.added.length) saveDictionary(dict);
  663. return { added: result.added, file: dict.__file };
  664. }
  665. return {
  666. file: dict.__file,
  667. dimensions: Object.entries(dict.dimensions || {}).map(([key, dim]) => ({
  668. dimension: key,
  669. label: dim.label,
  670. count: Array.isArray(dim.values) ? dim.values.length : Array.isArray(dim.entries) ? dim.entries.length : 0,
  671. values: dim.values || undefined,
  672. })),
  673. learnedCount: (dict.__learned || []).length,
  674. };
  675. }
  676. // ---------------------------------------------------------------------------
  677. // selftest
  678. // ---------------------------------------------------------------------------
  679. export async function runSelftest(options = {}) {
  680. const results = [];
  681. const python = resolvePython();
  682. // ① office 解包(python 标准库)
  683. const officeScript = path.join(SKILL_ROOT, 'scripts', 'office_extract.py');
  684. const officeRun = spawnSync(python, [officeScript, '--selftest'], { encoding: 'utf8' });
  685. results.push({
  686. name: 'office_extract(docx/pptx 标准库解包)',
  687. ok: officeRun.status === 0,
  688. detail: truncate(officeRun.stdout || officeRun.stderr || '', 400),
  689. });
  690. // ② 分组 / 打标 / 合规:离线合成样例
  691. const tmpRoot = ensureDir(path.join(outputsDir(options.outDir), 'selftest', newRunId()));
  692. const pngPath = path.join(tmpRoot, 'grid-01.png');
  693. fs.writeFileSync(pngPath, makeTinyPng(400, 400));
  694. const gridItems = [0, 1, 2, 3, 4, 5, 6, 7, 8].map((i) => ({
  695. kind: 'image',
  696. localPath: path.join(tmpRoot, `grid-${String(i + 1).padStart(2, '0')}.png`),
  697. width: 400,
  698. height: 400,
  699. mtimeMs: 1_700_000_000_000 + i * 1000,
  700. ocrText: '帝国理工 计算机科学 考前冲刺 提分',
  701. description: '',
  702. label: `朋友圈素材 ${i + 1}`,
  703. }));
  704. const groups = groupMaterials(gridItems, {});
  705. const gridOk = groups.length === 1 && groups[0].count === 9 && groups[0].layout === '3x3'
  706. && groups[0].items.every((item, index) => item.order === index + 1);
  707. results.push({
  708. name: '九宫格分组与顺序(3x3,order 1..9)',
  709. ok: gridOk,
  710. detail: `分组数=${groups.length},布局=${groups[0] && groups[0].layout},顺序=${groups[0] && groups[0].items.map((i) => i.order).join(',')}`,
  711. });
  712. const separated = groupMaterials([
  713. { kind: 'image', localPath: path.join(tmpRoot, 'a1.png'), width: 400, height: 400, mtimeMs: 1, ocrText: '帝国理工 提分' },
  714. { kind: 'image', localPath: path.join(tmpRoot, 'a2.png'), width: 400, height: 400, mtimeMs: 2000, ocrText: '帝国理工 提分' },
  715. { kind: 'image', localPath: path.join(tmpRoot, 'b1.png'), width: 1600, height: 900, mtimeMs: 900_000_000, ocrText: '香港大学 申诉' },
  716. ], {});
  717. results.push({
  718. name: '跨批次不误并组(时间 + 尺寸 + 内容三重信号)',
  719. ok: separated.length === 2,
  720. detail: `分组数=${separated.length},各组成员=${separated.map((g) => g.count).join('+')}`,
  721. });
  722. const dict = loadDictionary(options.dictPath);
  723. const classified = classifyCase({
  724. dict,
  725. groups: [...groups, ...separated],
  726. visionResults: [],
  727. textBundle: { paragraphs: ['帝国理工 计算机科学 考前冲刺辅导案例,学生期末提分 18 分,家长很满意', '微信:student_demo 联系 13800000000'], notes: [], titles: [], transcript: '' },
  728. authorizationStatus: 'authorized',
  729. hints: {},
  730. });
  731. const classifyOk = classified.tags.schoolCanonical.includes('帝国理工')
  732. && classified.tags.highlightTypes.includes('提分')
  733. && classified.compliance.privacyFindings.length > 0
  734. && classified.compliance.authorizationOk === true;
  735. results.push({
  736. name: '打标 + 别名归一(IC→帝国理工)+ 隐私发现',
  737. ok: classifyOk,
  738. detail: `学校=${classified.tags.schoolCanonical.join('/')},亮点=${classified.tags.highlightTypes.join('/')},隐私=${classified.compliance.privacyFindings.map((f) => f.field).join('/')}`,
  739. });
  740. const complaint = classifyCase({
  741. dict,
  742. groups: [],
  743. visionResults: [],
  744. textBundle: { paragraphs: ['学生投诉退费纠纷,要求赔偿'], notes: [], titles: [], transcript: '' },
  745. authorizationStatus: 'pending',
  746. hints: {},
  747. });
  748. const riskOk = complaint.compliance.riskFlags.includes('COMPLAINT')
  749. && complaint.compliance.riskFlags.includes('UNAUTHORIZED')
  750. && complaint.compliance.complianceBlockers.length >= 2
  751. && complaint.compliance.authorizationOk === false;
  752. results.push({
  753. name: '合规判断(客诉/负面 → riskFlags;无授权 → 不入库)',
  754. ok: riskOk,
  755. detail: `riskFlags=${complaint.compliance.riskFlags.join('/')},blockers=${complaint.compliance.complianceBlockers.length}`,
  756. });
  757. const reorderOk = (() => {
  758. const moved = reorderAssets(sortAssets(groups[0].items).map((i) => ({ ...i, kind: 'image' })), 9, 1);
  759. return moved[0].order === 1 && moved.length === 9;
  760. })();
  761. results.push({ name: '素材顺序调整(reorder)', ok: reorderOk, detail: '把第 9 张移到第 1 位后重新编号 1..9' });
  762. const failed = results.filter((r) => !r.ok);
  763. return { ok: failed.length === 0, checked: results.length, failed: failed.length, results, workDir: tmpRoot };
  764. }
  765. /** 合成一个最小的合法 PNG(用于自检,不引用任何真实素材)。 */
  766. export function makeTinyPng(width = 1, height = 1) {
  767. const crcTable = (() => {
  768. const table = new Int32Array(256);
  769. for (let n = 0; n < 256; n++) {
  770. let c = n;
  771. for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
  772. table[n] = c;
  773. }
  774. return table;
  775. })();
  776. const crc32 = (buf) => {
  777. let c = -1;
  778. for (const byte of buf) c = crcTable[(c ^ byte) & 0xff] ^ (c >>> 8);
  779. return (c ^ -1) >>> 0;
  780. };
  781. const chunk = (type, data) => {
  782. const length = Buffer.alloc(4);
  783. length.writeUInt32BE(data.length, 0);
  784. const typeBuf = Buffer.from(type, 'ascii');
  785. const crc = Buffer.alloc(4);
  786. crc.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0);
  787. return Buffer.concat([length, typeBuf, data, crc]);
  788. };
  789. const ihdr = Buffer.alloc(13);
  790. ihdr.writeUInt32BE(width, 0);
  791. ihdr.writeUInt32BE(height, 4);
  792. ihdr[8] = 8; // bit depth
  793. ihdr[9] = 6; // RGBA
  794. const raw = Buffer.alloc((width * 4 + 1) * height);
  795. return Buffer.concat([
  796. Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
  797. chunk('IHDR', ihdr),
  798. chunk('IDAT', zlib.deflateSync(raw)),
  799. chunk('IEND', Buffer.alloc(0)),
  800. ]);
  801. }
  802. // ---------------------------------------------------------------------------
  803. // CLI
  804. // ---------------------------------------------------------------------------
  805. function parseCli(argv) {
  806. const command = argv[0] && !argv[0].startsWith('-') ? argv[0] : 'ingest';
  807. const rest = command === argv[0] ? argv.slice(1) : argv;
  808. const { values, positionals } = parseArgs({
  809. args: rest,
  810. options: {
  811. input: { type: 'string', multiple: true, default: [] },
  812. image: { type: 'string', multiple: true, default: [] },
  813. doc: { type: 'string', multiple: true, default: [] },
  814. deck: { type: 'string', multiple: true, default: [] },
  815. video: { type: 'string', multiple: true, default: [] },
  816. 'out-dir': { type: 'string' },
  817. 'source-type': { type: 'string' },
  818. 'source-ref': { type: 'string' },
  819. authorization: { type: 'string', default: 'pending' },
  820. title: { type: 'string' },
  821. summary: { type: 'string' },
  822. 'target-customer': { type: 'string' },
  823. 'usage-suggestion': { type: 'string' },
  824. 'school-canonical': { type: 'string' },
  825. 'product-line': { type: 'string' },
  826. major: { type: 'string' },
  827. stage: { type: 'string' },
  828. country: { type: 'string' },
  829. highlight: { type: 'string', multiple: true, default: [] },
  830. scenario: { type: 'string', multiple: true, default: [] },
  831. objection: { type: 'string', multiple: true, default: [] },
  832. 'idempotency-key': { type: 'string' },
  833. 'asset-base-url': { type: 'string' },
  834. 'submitted-by': { type: 'string' },
  835. 'vision-model': { type: 'string' },
  836. 'skip-vision': { type: 'boolean', default: false },
  837. 'skip-video': { type: 'boolean', default: false },
  838. 'frame-count': { type: 'string' },
  839. diarize: { type: 'boolean', default: false },
  840. 'no-learn': { type: 'boolean', default: false },
  841. 'dict-path': { type: 'string' },
  842. package: { type: 'string' },
  843. 'material-assets': { type: 'string' },
  844. move: { type: 'string' },
  845. order: { type: 'string' },
  846. add: { type: 'string', multiple: true, default: [] },
  847. alias: { type: 'string', multiple: true, default: [] },
  848. out: { type: 'string' },
  849. json: { type: 'boolean', default: false },
  850. help: { type: 'boolean', default: false, short: 'h' },
  851. },
  852. allowPositionals: true,
  853. });
  854. return { command, values, positionals };
  855. }
  856. function collectInputs(values, positionals) {
  857. return [
  858. ...values.input,
  859. ...values.image,
  860. ...values.doc,
  861. ...values.deck,
  862. ...values.video,
  863. ...positionals,
  864. ];
  865. }
  866. async function cliMain(argv) {
  867. const { command, values, positionals } = parseCli(argv);
  868. if (values.help) {
  869. process.stdout.write(HELP_TEXT);
  870. return 0;
  871. }
  872. if (command === 'selftest') {
  873. const report = await runSelftest({ dictPath: values['dict-path'], outDir: values['out-dir'] });
  874. process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
  875. return report.ok ? 0 : 1;
  876. }
  877. if (command === 'dictionary') {
  878. const report = runDictionary({ add: values.add, alias: values.alias, dictPath: values['dict-path'] });
  879. process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
  880. return 0;
  881. }
  882. if (command === 'reorder') {
  883. const report = runReorder({
  884. materialAssets: values['material-assets'] || values.package,
  885. move: values.move,
  886. order: values.order,
  887. });
  888. process.stdout.write(`${JSON.stringify({ ok: true, file: report.file, order: report.materialAssets.map((a) => a.order) }, null, 2)}\n`);
  889. return 0;
  890. }
  891. if (command === 'submit') {
  892. if (!values.package) {
  893. process.stderr.write('需要 --package <case-package.json>\n');
  894. return 2;
  895. }
  896. const report = await runSubmit({ package: values.package, submittedBy: values['submitted-by'] });
  897. process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
  898. return report.submitted ? 0 : 4;
  899. }
  900. // plan / ingest
  901. const outDir = values['out-dir']
  902. || path.join(outputsDir(), `${values['source-ref'] ? `${slug(values['source-ref'])}-` : ''}${newRunId()}`);
  903. const options = {
  904. inputs: collectInputs(values, positionals),
  905. outDir,
  906. sourceType: values['source-type'],
  907. sourceRef: values['source-ref'],
  908. authorizationStatus: values.authorization,
  909. title: values.title,
  910. summary: values.summary,
  911. targetCustomer: values['target-customer'],
  912. usageSuggestion: values['usage-suggestion'],
  913. idempotencyKey: values['idempotency-key'],
  914. assetBaseUrl: values['asset-base-url'] || process.env.CASE_ASSET_BASE_URL || '',
  915. submittedBy: values['submitted-by'],
  916. visionModel: values['vision-model'],
  917. skipVision: values['skip-vision'],
  918. skipVideo: values['skip-video'],
  919. frameCount: values['frame-count'] ? Number(values['frame-count']) : undefined,
  920. diarize: values.diarize,
  921. noLearn: values['no-learn'],
  922. dictPath: values['dict-path'],
  923. hints: {
  924. schoolCanonical: values['school-canonical'],
  925. productLine: values['product-line'],
  926. major: values.major,
  927. stage: values.stage,
  928. country: values.country,
  929. highlightTypes: values.highlight,
  930. scenarioTags: values.scenario,
  931. objectionTags: values.objection,
  932. },
  933. };
  934. if (!options.inputs.length) {
  935. process.stderr.write('至少需要一个输入(位置参数或 --input / --image / --doc / --deck / --video)\n');
  936. return 2;
  937. }
  938. if (command === 'plan') {
  939. const plan = await runPlan(options);
  940. process.stdout.write(`${JSON.stringify({
  941. ok: true,
  942. command: 'plan',
  943. runId: plan.runId,
  944. sourceType: plan.sourceType,
  945. counts: plan.counts,
  946. groups: plan.groups.map((g) => ({ groupId: g.groupId, layout: g.layout, count: g.count, orderingRule: g.orderingRule })),
  947. warnings: plan.warnings,
  948. outDir,
  949. }, null, 2)}\n`);
  950. return 0;
  951. }
  952. const report = await runIngest(options);
  953. const summary = {
  954. ok: true,
  955. command: 'ingest',
  956. runId: report.casePackage.runId,
  957. sourceType: report.casePackage.sourceType,
  958. idempotencyKey: report.casePackage.idempotencyKey,
  959. materialAssets: report.casePackage.materialAssets.length,
  960. groups: report.casePackage.groupInfoList,
  961. title: report.casePackage.title,
  962. tags: {
  963. schoolCanonical: report.casePackage.schoolCanonical,
  964. schoolAliases: report.casePackage.schoolAliases,
  965. country: report.casePackage.country,
  966. major: report.casePackage.major,
  967. stage: report.casePackage.stage,
  968. subject: report.casePackage.subject,
  969. highlightTypes: report.casePackage.highlightTypes,
  970. scenarioTags: report.casePackage.scenarioTags,
  971. objectionTags: report.casePackage.objectionTags,
  972. fitStatus: report.casePackage.fitStatus,
  973. },
  974. compliance: {
  975. riskFlags: report.casePackage.riskFlags,
  976. privacyFindings: report.casePackage.privacyFindings.length,
  977. blockers: report.casePackage.complianceBlockers,
  978. canSubmit: report.canSubmit,
  979. expected: report.casePackage.expected,
  980. },
  981. dictionaryChanges: report.dictionaryChanges,
  982. warnings: uniq(report.warnings),
  983. artifacts: report.artifacts,
  984. };
  985. process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`);
  986. return 0;
  987. }
  988. function slug(value) {
  989. return String(value).replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
  990. }
  991. const HELP_TEXT = `skill-case-get —— 案例采集 / 拆解 / 归档
  992. 用法:
  993. case-intake.mjs ingest [输入...] [选项] 拆解 + 打标,产出案例包(默认不提交)
  994. case-intake.mjs plan [输入...] 只识别 + 提取 + 分组(不调模型)
  995. case-intake.mjs submit --package <file> 提交到云函数 caseSubmit(待审清单)
  996. case-intake.mjs reorder --material-assets <file> --move "3:1"
  997. case-intake.mjs dictionary [--add highlightTypes=退费保障] [--alias "IC=帝国理工=英国"]
  998. case-intake.mjs selftest
  999. 输入(可混用,支持目录):
  1000. --image a.jpg --image b.jpg ... 连续多图 / 裸图 / 九宫格
  1001. --doc case.docx Word
  1002. --deck deck.pptx PPT
  1003. --video clip.mp4 视频(抽帧 + 转写)
  1004. --input <file|dir> 自动按扩展名分流
  1005. 采集选项:
  1006. --authorization authorized|pending|denied 授权状态(硬门:仅 authorized 可入库,默认 pending)
  1007. --source-ref <ref> 来源引用(不含 PII)
  1008. --source-type <t> image_group|document|presentation|mixed|single_image
  1009. --title / --summary / --target-customer / --usage-suggestion 覆盖自动抽取的案例字段
  1010. --school-canonical / --product-line / --major / --stage / --country
  1011. --highlight / --scenario / --objection 显式补标签(可重复)
  1012. --idempotency-key <key> 幂等键(默认按内容指纹生成)
  1013. --asset-base-url <base> 本地素材 URL 前缀(CDN / Parse Files),用于派生 materialAssets[].url
  1014. (也可用环境变量 CASE_ASSET_BASE_URL)
  1015. --out-dir <dir> 产物目录(默认 <cwd>/case-get-outputs/<runId>)
  1016. --skip-vision / --skip-video / --no-learn 关闭图片理解 / 视频处理 / 字典自进化
  1017. --submitted-by <userId> 提交人
  1018. 提交选项:
  1019. --package <case-package.json> ingest 产出的案例包
  1020. --submitted-by <userId>
  1021. 产物(--out-dir):
  1022. extracted.json 文档文本 + 内嵌媒体
  1023. group-plan.json 分组与九宫格顺序
  1024. vision.json 每张图的 OCR / 描述 / 使用建议
  1025. material-assets.json materialAssets[](可编辑顺序)
  1026. case-package.json 云函数 caseSubmit 入参(逐字对齐共享契约)
  1027. report.md 人类可读报告
  1028. `;
  1029. const invokedDirectly = process.argv[1] && path.resolve(process.argv[1]).endsWith(path.join('scripts', 'case-intake.mjs'));
  1030. if (invokedDirectly) {
  1031. cliMain(process.argv.slice(2))
  1032. .then((code) => process.exit(code))
  1033. .catch((error) => {
  1034. process.stderr.write(`skill-case-get 失败:${error.message}\n`);
  1035. process.exit(1);
  1036. });
  1037. }
  1038. export { cliMain };