claude-code-voc-intelligence-suite.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. #!/usr/bin/env node
  2. const fs = require('fs');
  3. const path = require('path');
  4. const os = require('os');
  5. const { spawnSync } = require('child_process');
  6. const qiniu = require('qiniu');
  7. const PROJECT_ROOT = path.resolve(__dirname, '..', '..');
  8. const SUITE_DIR = path.join(PROJECT_ROOT, 'claude-code', 'claude-code-voc-intelligence');
  9. const MANIFEST_PATH = path.join(SUITE_DIR, 'skill-package-manifest.json');
  10. const DIST_DIR = path.join(PROJECT_ROOT, 'dist');
  11. const PACKAGE_ID = 'claude-code-voc-intelligence';
  12. const NPM_PACKAGE_NAME = '@vocmarket/voc-skill';
  13. const PACKAGE_ZIP = path.join(DIST_DIR, `${PACKAGE_ID}.zip`);
  14. const DIST_MANIFEST = path.join(DIST_DIR, `${PACKAGE_ID}-suite-manifest.json`);
  15. const TEMP_ROOT = path.join(os.tmpdir(), 'claude-code-voc-pkg', PACKAGE_ID);
  16. const TEST_ROOT = path.join(os.tmpdir(), 'claude-code-voc-pkg-test', PACKAGE_ID);
  17. const CDN_PREFIX = 'x/claude-code-skills/packages';
  18. const CDN_KEY = `${CDN_PREFIX}/${PACKAGE_ID}.zip`;
  19. const CDN_DOMAIN = 'https://repos.fmode.cn';
  20. const BUCKET = 'nova-repos';
  21. const REQUIRED_FILES = [
  22. '.claude-plugin/plugin.json',
  23. '.mcp.json',
  24. 'bin/claude-voc.js',
  25. 'install.js',
  26. 'README.md',
  27. 'docs/customer-quickstart.md',
  28. 'docs/demo-runbook.md',
  29. 'docs/npm-packaging-notes.md',
  30. 'package.json',
  31. 'package-lock.json',
  32. 'skill-package-manifest.json',
  33. 'memory-templates/xiaohongshu-trend-profile.json',
  34. 'mcp/src/server.js',
  35. 'mcp/src/core/credentials.js',
  36. 'mcp/src/core/memory-store.js',
  37. 'mcp/src/core/result-envelope.js',
  38. 'mcp/src/features/xiaohongshu-trend/live-collector.js',
  39. 'mcp/src/features/xiaohongshu-trend/preference-memory.js',
  40. 'mcp/src/features/xiaohongshu-trend/report.js',
  41. 'mcp/src/features/xiaohongshu-trend/sample-data.js',
  42. 'mcp/src/features/douyin-trend/live-collector.js',
  43. 'mcp/src/features/douyin-trend/preference-memory.js',
  44. 'mcp/src/features/douyin-trend/report.js',
  45. 'mcp/src/features/douyin-trend/sample-data.js',
  46. 'mcp/src/features/voc-problem-deep-dive/deep-dive.js',
  47. 'mcp/src/providers/xiaohongshu-api.js',
  48. 'mcp/src/providers/douyin-api.js',
  49. 'mcp/src/tools/xiaohongshu-preference-update.js',
  50. 'mcp/src/tools/xiaohongshu-trend-run.js',
  51. 'mcp/src/tools/douyin-preference-update.js',
  52. 'mcp/src/tools/douyin-trend-run.js',
  53. 'mcp/src/tools/voc-problem-deep-dive-run.js',
  54. 'scripts/smoke-mcp.js',
  55. 'scripts/smoke-package.js',
  56. 'skills/xiaohongshu-trend-intelligence/SKILL.md',
  57. 'skills/douyin-trend-intelligence/SKILL.md',
  58. 'skills/voc-problem-deep-dive/SKILL.md',
  59. 'skills/xiaohongshu-trend-intelligence/references/user-workflow.md',
  60. 'skills/xiaohongshu-trend-intelligence/references/output-format.md',
  61. 'skills/xiaohongshu-trend-intelligence/references/live-mode.md'
  62. ];
  63. const EXCLUDED_DIRS = new Set([
  64. 'node_modules',
  65. 'memory',
  66. 'outputs',
  67. '.npm-cache-acceptance',
  68. '.tmp',
  69. '.git',
  70. '.claude'
  71. ]);
  72. const EXCLUDED_FILES = new Set([
  73. '.env',
  74. '.env.local',
  75. '.npmrc'
  76. ]);
  77. function parseArgs(argv) {
  78. const opts = {
  79. validate: false,
  80. build: false,
  81. testPackage: false,
  82. upload: false,
  83. help: false
  84. };
  85. for (const token of argv) {
  86. if (token === '--validate') opts.validate = true;
  87. else if (token === '--build') opts.build = true;
  88. else if (token === '--test-package') opts.testPackage = true;
  89. else if (token === '--upload') opts.upload = true;
  90. else if (token === '--all') {
  91. opts.validate = true;
  92. opts.build = true;
  93. opts.testPackage = true;
  94. } else if (token === '--help' || token === '-h') {
  95. opts.help = true;
  96. }
  97. }
  98. if (!opts.validate && !opts.build && !opts.testPackage && !opts.upload && !opts.help) {
  99. opts.validate = true;
  100. opts.build = true;
  101. opts.testPackage = true;
  102. }
  103. return opts;
  104. }
  105. function usage() {
  106. return [
  107. 'Usage:',
  108. ' node scripts/deploy/claude-code-voc-intelligence-suite.js',
  109. ' node scripts/deploy/claude-code-voc-intelligence-suite.js --validate',
  110. ' node scripts/deploy/claude-code-voc-intelligence-suite.js --build --test-package',
  111. ' node scripts/deploy/claude-code-voc-intelligence-suite.js --build --upload',
  112. '',
  113. 'Default mode is --validate --build --test-package without upload.',
  114. 'Upload requires QINIU_AK and QINIU_SK environment variables.'
  115. ].join('\n');
  116. }
  117. function ensureDir(dirPath) {
  118. fs.mkdirSync(dirPath, { recursive: true });
  119. }
  120. function readJson(filePath) {
  121. return JSON.parse(fs.readFileSync(filePath, 'utf8'));
  122. }
  123. function copyDirRecursive(srcDir, destDir) {
  124. ensureDir(destDir);
  125. let count = 0;
  126. for (const entry of fs.readdirSync(srcDir, { withFileTypes: true })) {
  127. if (entry.isDirectory() && EXCLUDED_DIRS.has(entry.name)) continue;
  128. if (entry.isFile() && EXCLUDED_FILES.has(entry.name)) continue;
  129. const src = path.join(srcDir, entry.name);
  130. const dest = path.join(destDir, entry.name);
  131. if (entry.isDirectory()) {
  132. count += copyDirRecursive(src, dest);
  133. } else if (entry.isFile()) {
  134. ensureDir(path.dirname(dest));
  135. fs.copyFileSync(src, dest);
  136. count++;
  137. }
  138. }
  139. return count;
  140. }
  141. function run(command, args, cwd) {
  142. const useCmd = process.platform === 'win32' && command === 'npm';
  143. const executable = useCmd ? 'cmd.exe' : command;
  144. const finalArgs = useCmd ? ['/d', '/s', '/c', 'npm', ...args] : args;
  145. const child = spawnSync(executable, finalArgs, {
  146. cwd,
  147. encoding: 'utf8',
  148. maxBuffer: 1024 * 1024 * 100
  149. });
  150. if (child.stdout) process.stdout.write(child.stdout);
  151. if (child.stderr) process.stderr.write(child.stderr);
  152. if (child.status !== 0) {
  153. const detail = child.error ? `: ${child.error.message}` : '';
  154. throw new Error(`${command} ${args.join(' ')} failed with exit ${child.status}${detail}`);
  155. }
  156. return child;
  157. }
  158. function createZip(sourceDir, destinationPath) {
  159. if (process.platform === 'win32') {
  160. run('tar.exe', ['-a', '-c', '-f', destinationPath, '-C', sourceDir, '.'], PROJECT_ROOT);
  161. return;
  162. }
  163. run('zip', ['-q', '-r', destinationPath, '.'], sourceDir);
  164. }
  165. function listZipEntries(zipPath) {
  166. const result = process.platform === 'win32'
  167. ? run('tar.exe', ['-t', '-f', zipPath], PROJECT_ROOT)
  168. : run('unzip', ['-Z1', zipPath], PROJECT_ROOT);
  169. return result.stdout
  170. .split(/\r?\n/)
  171. .map(entry => entry.replace(/^\.\//, '').replace(/\\/g, '/'))
  172. .filter(Boolean);
  173. }
  174. function extractZip(zipPath, destinationDir) {
  175. if (process.platform === 'win32') {
  176. run('tar.exe', ['-x', '-f', zipPath, '-C', destinationDir], PROJECT_ROOT);
  177. return;
  178. }
  179. run('unzip', ['-q', zipPath, '-d', destinationDir], PROJECT_ROOT);
  180. }
  181. function validateSuite() {
  182. console.log('[validate] claude-code-voc-intelligence suite');
  183. const missing = [];
  184. for (const rel of REQUIRED_FILES) {
  185. if (!fs.existsSync(path.join(SUITE_DIR, rel))) missing.push(rel);
  186. }
  187. const packageJson = readJson(path.join(SUITE_DIR, 'package.json'));
  188. const pluginJson = readJson(path.join(SUITE_DIR, '.claude-plugin', 'plugin.json'));
  189. const manifest = readJson(MANIFEST_PATH);
  190. const mcpJson = readJson(path.join(SUITE_DIR, '.mcp.json'));
  191. if (packageJson.name !== NPM_PACKAGE_NAME) missing.push('package.json:name mismatch');
  192. if (pluginJson.name !== 'voc-intelligence') missing.push('.claude-plugin/plugin.json:name mismatch');
  193. if (!manifest.skills.includes('xiaohongshu-trend-intelligence')) missing.push('manifest missing xiaohongshu-trend-intelligence');
  194. if (!mcpJson.mcpServers || !(mcpJson.mcpServers.voc || mcpJson.mcpServers['voc-intelligence'])) {
  195. missing.push('.mcp.json missing VOC MCP server');
  196. }
  197. if (missing.length) {
  198. throw new Error(`Suite validation failed:\n${missing.map(item => ` - ${item}`).join('\n')}`);
  199. }
  200. console.log(` ok: ${manifest.skills.length} skill, ${manifest.mcpTools.length} MCP tools`);
  201. }
  202. function buildSuite() {
  203. console.log('[build] dist/claude-code-voc-intelligence.zip');
  204. ensureDir(DIST_DIR);
  205. if (fs.existsSync(TEMP_ROOT)) fs.rmSync(TEMP_ROOT, { recursive: true, force: true });
  206. ensureDir(TEMP_ROOT);
  207. const copied = copyDirRecursive(SUITE_DIR, TEMP_ROOT);
  208. if (fs.existsSync(PACKAGE_ZIP)) fs.unlinkSync(PACKAGE_ZIP);
  209. createZip(TEMP_ROOT, PACKAGE_ZIP);
  210. const entries = new Set(listZipEntries(PACKAGE_ZIP));
  211. for (const required of ['install.js', '.claude-plugin/plugin.json']) {
  212. if (!entries.has(required)) {
  213. throw new Error(`Built zip is incomplete: missing ${required}`);
  214. }
  215. }
  216. writeDistManifest({ uploaded: false, copiedFiles: copied });
  217. const size = fs.statSync(PACKAGE_ZIP).size;
  218. console.log(` ok: ${PACKAGE_ZIP} (${(size / 1024).toFixed(0)} KB, ${copied} files)`);
  219. }
  220. function testPackage() {
  221. console.log('[test-package] unzip + install.js smoke');
  222. if (!fs.existsSync(PACKAGE_ZIP)) throw new Error(`Package zip not found: ${PACKAGE_ZIP}`);
  223. if (fs.existsSync(TEST_ROOT)) fs.rmSync(TEST_ROOT, { recursive: true, force: true });
  224. ensureDir(TEST_ROOT);
  225. extractZip(PACKAGE_ZIP, TEST_ROOT);
  226. run(process.execPath, ['install.js', '--smoke'], TEST_ROOT);
  227. console.log(' ok: extracted package can run install.js and sample/preference/MCP smoke');
  228. }
  229. function uploadFile(localFile, cdnKey) {
  230. return new Promise((resolve, reject) => {
  231. const accessKey = process.env.QINIU_AK;
  232. const secretKey = process.env.QINIU_SK;
  233. if (!accessKey || !secretKey) {
  234. return reject(new Error('Missing QINIU_AK or QINIU_SK environment variable'));
  235. }
  236. const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
  237. const putPolicy = new qiniu.rs.PutPolicy({ scope: `${BUCKET}:${cdnKey}`, expires: 3600 });
  238. const token = putPolicy.uploadToken(mac);
  239. const config = new qiniu.conf.Config({ zone: qiniu.zone.Zone_z2 });
  240. const formUploader = new qiniu.form_up.FormUploader(config);
  241. const putExtra = new qiniu.form_up.PutExtra();
  242. formUploader.putFile(token, cdnKey, localFile, putExtra, (err, body, info) => {
  243. if (err) return reject(err);
  244. if (info.statusCode === 200) return resolve({ key: body.key, url: `${CDN_DOMAIN}/${body.key}` });
  245. reject(new Error(`Upload failed: ${info.statusCode} ${JSON.stringify(body)}`));
  246. });
  247. });
  248. }
  249. async function uploadSuite() {
  250. console.log('[upload] qiniu nova-repos');
  251. if (!fs.existsSync(PACKAGE_ZIP)) throw new Error(`Package zip not found: ${PACKAGE_ZIP}`);
  252. const result = await uploadFile(PACKAGE_ZIP, CDN_KEY);
  253. writeDistManifest({ uploaded: true, downloadUrl: result.url });
  254. const urlsPath = path.join(DIST_DIR, 'download-urls.json');
  255. const urls = fs.existsSync(urlsPath) ? readJson(urlsPath) : {};
  256. urls[PACKAGE_ID] = result.url;
  257. fs.writeFileSync(urlsPath, `${JSON.stringify(urls, null, 2)}\n`, 'utf8');
  258. console.log(` ok: ${result.url}`);
  259. }
  260. function writeDistManifest(extra = {}) {
  261. const manifest = readJson(MANIFEST_PATH);
  262. const stat = fs.existsSync(PACKAGE_ZIP) ? fs.statSync(PACKAGE_ZIP) : undefined;
  263. const output = {
  264. name: PACKAGE_ID,
  265. version: manifest.version,
  266. generatedAt: new Date().toISOString(),
  267. packageZip: fs.existsSync(PACKAGE_ZIP) ? path.relative(PROJECT_ROOT, PACKAGE_ZIP).replace(/\\/g, '/') : '',
  268. packageZipBytes: stat ? stat.size : 0,
  269. plugin: manifest.plugin,
  270. skills: manifest.skills,
  271. mcpTools: manifest.mcpTools,
  272. installHint: manifest.installHint,
  273. installCommand: manifest.installCommand,
  274. npmInstallCommand: manifest.npmInstallCommand,
  275. npxInstallCommand: manifest.npxInstallCommand,
  276. workspaceInstallCommand: manifest.workspaceInstallCommand,
  277. workspaceInstallTarget: manifest.workspaceInstallTarget,
  278. buildCommand: 'node scripts/deploy/claude-code-voc-intelligence-suite.js --validate --build --test-package',
  279. uploadCommand: 'node scripts/deploy/claude-code-voc-intelligence-suite.js --validate --build --test-package --upload',
  280. ...extra
  281. };
  282. fs.writeFileSync(DIST_MANIFEST, `${JSON.stringify(output, null, 2)}\n`, 'utf8');
  283. console.log(`[manifest] ${path.relative(PROJECT_ROOT, DIST_MANIFEST)}`);
  284. }
  285. async function main() {
  286. const opts = parseArgs(process.argv.slice(2));
  287. if (opts.help) {
  288. console.log(usage());
  289. return;
  290. }
  291. if (opts.validate) validateSuite();
  292. if (opts.build) buildSuite();
  293. if (opts.testPackage) testPackage();
  294. if (opts.upload) await uploadSuite();
  295. if (!opts.build) writeDistManifest({ uploaded: false });
  296. console.log('[done] claude-code-voc-intelligence suite is ready');
  297. }
  298. main().catch(error => {
  299. console.error(`[error] ${error.message}`);
  300. process.exit(1);
  301. });