ai-contribution-analytics.mjs 18.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
#!/usr/bin/env node

/**
 * AI Contribution Analytics
 *
 * 从三个数据源采集 AI 贡献数据,生成 HTML 可视化报告:
 * 1. 文件头 @ai-co-author 注释扫描
 * 2. Git log 历史解析
 * 3. .ai-attribution.json 归因清单
 *
 * 用法:
 *   pnpm run ai:analytics
 *   pnpm run ai:analytics -- --output reports/
 *   pnpm run ai:analytics -- --since "30 days ago"
 *   pnpm run ai:analytics -- --scan-dir apps/web --scan-dir packages
 */

import childProcess from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";

import { requireWorkspaceRoot } from "./workspace-root.mjs";

const repoRoot = requireWorkspaceRoot();

// ── CLI ──

function parseCliArgs() {
	const args = process.argv.slice(2);
	const parsed = { outputDir: "", since: "", scanDirs: [] };

	for (let i = 0; i < args.length; i++) {
		const arg = args[i];
		const next = args[i + 1];
		if (arg === "--output" && next) {
			parsed.outputDir = next;
			i++;
		} else if (arg === "--since" && next) {
			parsed.since = next;
			i++;
		} else if (arg === "--scan-dir" && next) {
			parsed.scanDirs.push(next);
			i++;
		}
	}

	return parsed;
}

// ── Data Collection: File Headers ──

const SCANNABLE_EXTENSIONS = new Set([
	".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
	".vue", ".uvue", ".svelte",
	".uts", ".css", ".scss",
]);

const CO_AUTHOR_REGEX = /@ai-co-author\s+(\S+)\s*\|\s*(\S+)\s*\|\s*(\S+)/;

function scanFileHeaders(baseDir, scanDirs) {
	const results = [];
	const dirs = scanDirs.length > 0
		? scanDirs.map((d) => path.resolve(baseDir, d))
		: [baseDir];

	for (const dir of dirs) {
		walkDir(dir, baseDir, results);
	}
	return results;
}

function walkDir(dir, baseDir, results) {
	if (!fs.existsSync(dir)) return;

	let entries;
	try {
		entries = fs.readdirSync(dir, { withFileTypes: true });
	} catch {
		return;
	}

	for (const entry of entries) {
		const fullPath = path.join(dir, entry.name);

		if (entry.isDirectory()) {
			if (shouldSkipDir(entry.name)) continue;
			walkDir(fullPath, baseDir, results);
			continue;
		}

		if (!entry.isFile()) continue;
		const ext = path.extname(entry.name).toLowerCase();
		if (!SCANNABLE_EXTENSIONS.has(ext)) continue;

		const info = readCoAuthorHeader(fullPath);
		if (info) {
			results.push({
				filePath: normalizePath(path.relative(baseDir, fullPath)),
				extension: ext,
				lineCount: countLines(fullPath),
				...info,
			});
		}
	}
}

function shouldSkipDir(name) {
	return (
		name === "node_modules" ||
		name === ".git" ||
		name === "dist" ||
		name === ".output" ||
		name === ".nuxt" ||
		name === ".turbo" ||
		name === "uni_modules"
	);
}

function readCoAuthorHeader(filePath) {
	try {
		const fd = fs.openSync(filePath, "r");
		const buf = Buffer.alloc(1024);
		const bytesRead = fs.readSync(fd, buf, 0, 1024, 0);
		fs.closeSync(fd);

		const head = buf.toString("utf8", 0, bytesRead);
		const lines = head.split(/\r?\n/).slice(0, 10);

		for (const line of lines) {
			const match = line.match(CO_AUTHOR_REGEX);
			if (match) {
				return {
					tool: match[1],
					provider: match[2].split("/")[0] || "unknown",
					model: match[2].split("/").slice(1).join("/") || "unknown",
					timestamp: match[3],
					source: "file-header",
				};
			}
		}
	} catch { /* skip unreadable */ }
	return null;
}

function countLines(filePath) {
	try {
		const content = fs.readFileSync(filePath, "utf8");
		return content.split(/\r?\n/).length;
	} catch {
		return 0;
	}
}

// ── Data Collection: Git Log ──

function parseGitLog(since) {
	const sinceArg = since ? `--since="${since}"` : "";
	const format = "%H|%ai|%s";
	const cmd = `git log --all ${sinceArg} --format="${format}" --diff-filter=A -- "*.ts" "*.tsx" "*.vue" "*.js" "*.mjs" "*.uvue" "*.uts"`;

	const result = childProcess.spawnSync(cmd, {
		cwd: repoRoot,
		shell: true,
		encoding: "utf8",
	});

	if (result.status !== 0 || !result.stdout) return [];

	const commits = [];
	for (const line of result.stdout.trim().split(/\r?\n/)) {
		if (!line) continue;
		const parts = line.split("|");
		if (parts.length < 3) continue;

		commits.push({
			hash: parts[0],
			date: parts[1].trim(),
			message: parts.slice(2).join("|").trim(),
		});
	}

	const gitRecords = [];
	for (const commit of commits) {
		const filesResult = childProcess.spawnSync(
			`git diff-tree --no-commit-id -r --name-only --diff-filter=A ${commit.hash}`,
			{ cwd: repoRoot, shell: true, encoding: "utf8" },
		);

		if (filesResult.status !== 0 || !filesResult.stdout) continue;

		const files = filesResult.stdout.trim().split(/\r?\n/).filter(Boolean);
		for (const file of files) {
			const showResult = childProcess.spawnSync(
				`git show ${commit.hash}:${file}`,
				{ cwd: repoRoot, shell: true, encoding: "utf8", maxBuffer: 1024 },
			);

			if (showResult.status !== 0 || !showResult.stdout) continue;

			const headLines = showResult.stdout.split(/\r?\n/).slice(0, 10);
			for (const line of headLines) {
				const match = line.match(CO_AUTHOR_REGEX);
				if (match) {
					gitRecords.push({
						filePath: normalizePath(file),
						tool: match[1],
						provider: match[2].split("/")[0] || "unknown",
						model: match[2].split("/").slice(1).join("/") || "unknown",
						timestamp: match[3],
						commitHash: commit.hash.slice(0, 8),
						commitDate: commit.date,
						commitMessage: commit.message,
						source: "git-log",
					});
					break;
				}
			}
		}
	}

	return gitRecords;
}

// ── Data Collection: Attribution Manifests ──

function scanAttributionManifests(baseDir) {
	const results = [];
	walkForManifests(baseDir, baseDir, results);
	return results;
}

function walkForManifests(dir, baseDir, results) {
	if (!fs.existsSync(dir)) return;

	let entries;
	try {
		entries = fs.readdirSync(dir, { withFileTypes: true });
	} catch {
		return;
	}

	for (const entry of entries) {
		const fullPath = path.join(dir, entry.name);

		if (entry.isDirectory()) {
			if (shouldSkipDir(entry.name)) continue;
			walkForManifests(fullPath, baseDir, results);
			continue;
		}

		if (entry.name === ".ai-attribution.json") {
			try {
				const data = JSON.parse(fs.readFileSync(fullPath, "utf8"));
				const relDir = normalizePath(path.relative(baseDir, path.dirname(fullPath)));

				for (const file of Array.isArray(data.files) ? data.files : []) {
					results.push({
						filePath: `${relDir}/${file.path || "unknown"}`,
						provider: data.provider || file.provider || "unknown",
						model: data.model || file.model || "unknown",
						timestamp: data.generatedAt || "unknown",
						language: file.language || "",
						purpose: file.purpose || "",
						source: "attribution-manifest",
					});
				}
			} catch { /* skip malformed */ }
		}
	}
}

// ── Merge & Dedup ──

function mergeRecords(fileHeaders, gitRecords, manifests) {
	const byFile = new Map();
	const priority = { "file-header": 0, "attribution-manifest": 1, "git-log": 2 };

	const all = [...fileHeaders, ...manifests, ...gitRecords];
	for (const record of all) {
		const existing = byFile.get(record.filePath);
		if (!existing || (priority[record.source] ?? 9) < (priority[existing.source] ?? 9)) {
			byFile.set(record.filePath, record);
		}
	}

	return [...byFile.values()];
}

// ── Aggregation ──

function aggregate(records) {
	const stats = {
		totalFiles: records.length,
		totalLines: 0,
		byProvider: {},
		byModel: {},
		byExtension: {},
		byDirectory: {},
		byMonth: {},
		bySource: {},
		timeline: [],
	};

	for (const r of records) {
		stats.totalLines += r.lineCount || 0;

		increment(stats.byProvider, r.provider || "unknown");
		increment(stats.byModel, `${r.provider}/${r.model}`);
		increment(stats.byExtension, r.extension || "unknown");
		increment(stats.bySource, r.source || "unknown");

		const dir = getTopDirs(r.filePath);
		increment(stats.byDirectory, dir);

		const month = parseMonth(r.timestamp || r.commitDate);
		if (month) {
			increment(stats.byMonth, month);
		}

		if (r.timestamp || r.commitDate) {
			stats.timeline.push({
				date: r.timestamp || r.commitDate,
				file: r.filePath,
				provider: r.provider,
				model: r.model,
			});
		}
	}

	stats.timeline.sort((a, b) => new Date(a.date) - new Date(b.date));

	return stats;
}

function increment(obj, key) {
	if (!obj[key]) obj[key] = 0;
	obj[key]++;
}

function getTopDirs(filePath) {
	const parts = normalizePath(filePath).split("/");
	if (parts.length >= 3) return `${parts[0]}/${parts[1]}/${parts[2]}`;
	if (parts.length >= 2) return `${parts[0]}/${parts[1]}`;
	return parts[0] || "root";
}

function parseMonth(dateStr) {
	if (!dateStr || dateStr === "unknown") return null;
	try {
		const d = new Date(dateStr);
		if (Number.isNaN(d.getTime())) return null;
		return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
	} catch {
		return null;
	}
}

// ── HTML Report ──

function generateHtmlReport(stats, records) {
	const generatedAt = new Date().toISOString();

	const providerEntries = Object.entries(stats.byProvider).sort((a, b) => b[1] - a[1]);
	const modelEntries = Object.entries(stats.byModel).sort((a, b) => b[1] - a[1]);
	const extEntries = Object.entries(stats.byExtension).sort((a, b) => b[1] - a[1]);
	const dirEntries = Object.entries(stats.byDirectory).sort((a, b) => b[1] - a[1]);
	const monthEntries = Object.entries(stats.byMonth).sort((a, b) => a[0].localeCompare(b[0]));

	const recentFiles = records
		.filter((r) => r.timestamp && r.timestamp !== "unknown")
		.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
		.slice(0, 50);

	return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Venus AI Contribution Analytics</title>
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0f172a; color: #e2e8f0; padding: 2rem; }
  h1 { font-size: 1.75rem; margin-bottom: 0.5rem; color: #f8fafc; }
  .subtitle { color: #94a3b8; margin-bottom: 2rem; font-size: 0.875rem; }
  .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1.5rem; margin-bottom: 2rem; }
  .card { background: #1e293b; border-radius: 12px; padding: 1.5rem; border: 1px solid #334155; }
  .card h2 { font-size: 0.875rem; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 1rem; }
  .stat-value { font-size: 2.5rem; font-weight: 700; color: #38bdf8; }
  .bar-chart { width: 100%; }
  .bar-row { display: flex; align-items: center; margin-bottom: 0.5rem; gap: 0.75rem; }
  .bar-label { flex: 0 0 180px; font-size: 0.8rem; color: #cbd5e1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .bar-track { flex: 1; background: #334155; border-radius: 4px; height: 24px; position: relative; overflow: hidden; }
  .bar-fill { height: 100%; border-radius: 4px; background: linear-gradient(90deg, #3b82f6, #38bdf8); display: flex; align-items: center; padding-left: 8px; }
  .bar-count { font-size: 0.75rem; color: #f8fafc; font-weight: 600; white-space: nowrap; }
  .full-width { grid-column: 1 / -1; }
  table { width: 100%; border-collapse: collapse; font-size: 0.8rem; }
  th { text-align: left; padding: 0.75rem; border-bottom: 2px solid #334155; color: #94a3b8; font-weight: 600; }
  td { padding: 0.6rem 0.75rem; border-bottom: 1px solid #1e293b; color: #cbd5e1; }
  tr:hover td { background: #1e293b; }
  .tag { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; }
  .tag-provider { background: #1e3a5f; color: #38bdf8; }
  .tag-model { background: #1e3a3f; color: #2dd4bf; }
  .tag-ext { background: #3b1e5f; color: #a78bfa; }
  .timeline-bar { display: flex; align-items: flex-end; gap: 2px; height: 120px; padding-top: 1rem; }
  .timeline-col { flex: 1; background: linear-gradient(180deg, #3b82f6, #1d4ed8); border-radius: 3px 3px 0 0; min-width: 8px; }
  .timeline-labels { display: flex; gap: 2px; margin-top: 0.5rem; }
  .timeline-label { flex: 1; font-size: 0.6rem; color: #64748b; text-align: center; min-width: 8px; }
  .summary-pills { display: flex; flex-wrap: wrap; gap: 0.5rem; margin-bottom: 1.5rem; }
  .pill { background: #1e293b; border: 1px solid #334155; border-radius: 8px; padding: 0.5rem 1rem; font-size: 0.8rem; color: #94a3b8; }
  .pill strong { color: #f8fafc; }
</style>
</head>
<body>

<h1>Venus AI Contribution Analytics</h1>
<p class="subtitle">Generated at ${generatedAt} | Data sources: file-headers, git-log, attribution-manifests</p>

<div class="summary-pills">
  <div class="pill"><strong>${stats.totalFiles}</strong> AI-generated files</div>
  <div class="pill"><strong>${stats.totalLines.toLocaleString()}</strong> total lines</div>
  <div class="pill"><strong>${providerEntries.length}</strong> providers</div>
  <div class="pill"><strong>${modelEntries.length}</strong> models</div>
</div>

<div class="grid">
  <div class="card">
    <h2>Provider Distribution</h2>
    <div class="bar-chart">
      ${providerEntries.map(([name, count]) => `<div class="bar-row"><span class="bar-label">${name}</span><div class="bar-track"><div class="bar-fill" style="width: ${(count / Math.max(...providerEntries.map((p) => p[1]), 1) * 100).toFixed(1)}%"><span class="bar-count">${count}</span></div></div></div>`).join("")}
    </div>
  </div>
  <div class="card">
    <h2>Model Distribution</h2>
    <div class="bar-chart">
      ${modelEntries.slice(0, 10).map(([name, count]) => `<div class="bar-row"><span class="bar-label" title="${name}">${name}</span><div class="bar-track"><div class="bar-fill" style="width: ${(count / Math.max(...modelEntries.map((m) => m[1]), 1) * 100).toFixed(1)}%; background: linear-gradient(90deg, #10b981, #2dd4bf);"><span class="bar-count">${count}</span></div></div></div>`).join("")}
    </div>
  </div>
  <div class="card">
    <h2>File Type</h2>
    <div class="bar-chart">
      ${extEntries.map(([name, count]) => `<div class="bar-row"><span class="bar-label">${name}</span><div class="bar-track"><div class="bar-fill" style="width: ${(count / Math.max(...extEntries.map((e) => e[1]), 1) * 100).toFixed(1)}%; background: linear-gradient(90deg, #8b5cf6, #a78bfa);"><span class="bar-count">${count}</span></div></div></div>`).join("")}
    </div>
  </div>
  <div class="card">
    <h2>Directory</h2>
    <div class="bar-chart">
      ${dirEntries.slice(0, 10).map(([name, count]) => `<div class="bar-row"><span class="bar-label" title="${name}">${name}</span><div class="bar-track"><div class="bar-fill" style="width: ${(count / Math.max(...dirEntries.map((d) => d[1]), 1) * 100).toFixed(1)}%; background: linear-gradient(90deg, #f59e0b, #fbbf24);"><span class="bar-count">${count}</span></div></div></div>`).join("")}
    </div>
  </div>
  <div class="card full-width">
    <h2>Monthly Trend</h2>
    ${monthEntries.length > 0 ? `<div class="timeline-bar">${monthEntries.map(([, count]) => `<div class="timeline-col" style="height: ${(count / Math.max(...monthEntries.map((m) => m[1]), 1) * 100).toFixed(1)}%;" title="${count} files"></div>`).join("")}</div><div class="timeline-labels">${monthEntries.map(([month]) => `<div class="timeline-label">${month}</div>`).join("")}</div>` : "<p style='color:#64748b'>No timeline data yet.</p>"}
  </div>
  <div class="card full-width">
    <h2>Recent AI-Generated Files (Top 50)</h2>
    ${recentFiles.length > 0 ? `<table><thead><tr><th>File</th><th>Provider</th><th>Model</th><th>Lines</th><th>Source</th><th>Time</th></tr></thead><tbody>${recentFiles.map((r) => `<tr><td>${r.filePath}</td><td><span class="tag tag-provider">${r.provider}</span></td><td><span class="tag tag-model">${r.model}</span></td><td>${r.lineCount || "-"}</td><td><span class="tag tag-ext">${r.source}</span></td><td>${formatDate(r.timestamp)}</td></tr>`).join("")}</tbody></table>` : "<p style='color:#64748b'>No data yet.</p>"}
  </div>
</div>
</body>
</html>`;
}

function formatDate(dateStr) {
	if (!dateStr || dateStr === "unknown") return "-";
	try {
		const d = new Date(dateStr);
		if (Number.isNaN(d.getTime())) return dateStr;
		return d.toISOString().slice(0, 10);
	} catch {
		return dateStr;
	}
}

// ── Helpers ──

function normalizePath(p) {
	return p.replaceAll("\\", "/");
}

// ── Main ──

function main() {
	const args = parseCliArgs();
	const outputDir = args.outputDir || path.join(repoRoot, "docs");
	const since = args.since || "";
	const scanDirs = args.scanDirs;

	console.log("[ai-analytics] Collecting data...");

	console.log("[ai-analytics] Source 1: Scanning file headers...");
	const fileHeaders = scanFileHeaders(repoRoot, scanDirs);
	console.log(`[ai-analytics]   Found ${fileHeaders.length} files with @ai-co-author headers`);

	console.log("[ai-analytics] Source 2: Parsing git log...");
	const gitRecords = parseGitLog(since);
	console.log(`[ai-analytics]   Found ${gitRecords.length} records from git history`);

	console.log("[ai-analytics] Source 3: Scanning attribution manifests...");
	const manifests = scanAttributionManifests(repoRoot);
	console.log(`[ai-analytics]   Found ${manifests.length} records from manifests`);

	const merged = mergeRecords(fileHeaders, gitRecords, manifests);
	console.log(`[ai-analytics] Merged: ${merged.length} unique files`);

	const stats = aggregate(merged);

	const html = generateHtmlReport(stats, merged);
	const outputDirResolved = path.resolve(outputDir);
	if (!fs.existsSync(outputDirResolved)) {
		fs.mkdirSync(outputDirResolved, { recursive: true });
	}

	const outputFile = path.join(outputDirResolved, "ai-contribution-report.html");
	fs.writeFileSync(outputFile, html, "utf8");
	console.log(`[ai-analytics] Report generated: ${normalizePath(path.relative(repoRoot, outputFile))}`);

	const jsonFile = path.join(outputDirResolved, "ai-contribution-data.json");
	const jsonData = {
		generatedAt: new Date().toISOString(),
		stats: {
			totalFiles: stats.totalFiles,
			totalLines: stats.totalLines,
			byProvider: stats.byProvider,
			byModel: stats.byModel,
			byExtension: stats.byExtension,
			byDirectory: stats.byDirectory,
			byMonth: stats.byMonth,
			bySource: stats.bySource,
		},
		records: merged.map((r) => ({
			file: r.filePath,
			provider: r.provider,
			model: r.model,
			extension: r.extension,
			lines: r.lineCount,
			source: r.source,
			timestamp: r.timestamp,
		})),
	};
	fs.writeFileSync(jsonFile, `${JSON.stringify(jsonData, null, 2)}\n`, "utf8");
	console.log(`[ai-analytics] Data exported: ${normalizePath(path.relative(repoRoot, jsonFile))}`);
}

main();