#!/usr/bin/env node "use strict"; /** * Builds ModuleMap-Bench from agentkit's evaluation data and the project clones. * * AGENTKIT=~/mvp/agentkit PROJECTS=~/mvp/map-trial/set-usuario \ * HISTORY=~/mvp/map-trial/history node build/build.js [roles|history|all] * * roles data/roles/*, data/features/*, results/agentkit-roles.*, annotation/round-2/* * history data/history/*, results/history.json (slow: redraws the Maps of ~400 commits) * * Deterministic: the same inputs give the same files. */ const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const crypto = require("node:crypto"); const { spawnSync } = require("node:child_process"); const HOME = os.homedir(); const AK = process.env.AGENTKIT || path.join(HOME, "mvp/agentkit"); const PROJECTS = process.env.PROJECTS || path.join(HOME, "mvp/map-trial/set-usuario"); const HISTORY = process.env.HISTORY || path.join(HOME, "mvp/map-trial/history"); const OUT = path.join(__dirname, ".."); const D = path.join(AK, "dist/src/core"); const { planMaps, renderMap, MAP_LAYOUT, ALPHABETICAL_LAYOUT } = require(`${D}/map/index.js`); const { javaCommits } = require(`${D}/map/history.js`); const { loadEffective } = require(`${D}/config/layers.js`); const { evaluate } = require(`${D}/map/evaluate.js`); const LABELS = path.join(AK, "test/data/map-eval"); const REVISED = JSON.parse(fs.readFileSync(path.join(__dirname, "notes-revised.json"), "utf8")); /** The projects published; BookStoreApp-Distributed-Application is left out: its repository has no licence. */ const META = [ { name: "mall-swarm", dir: "mall-swarm", license: "Apache-2.0", heldOut: true }, { name: "JeecgBoot", dir: "JeecgBoot/jeecg-boot", license: "Apache-2.0", heldOut: false }, { name: "yudao-cloud", dir: "yudao-cloud", license: "MIT", heldOut: false }, { name: "ruoyi-vue-pro", dir: "ruoyi-vue-pro", license: "MIT", heldOut: false }, { name: "supOS-backend", dir: "supOS-backend", license: "MulanPSL-2.0", heldOut: false }, { name: "e-procure", dir: "e-procure", license: "MIT", heldOut: false }, { name: "beeatlas-fdm-bpm", dir: "beeatlas-fdm-bpm", license: "Apache-2.0", heldOut: false }, { name: "kiwi", dir: "kiwi", license: "MIT", heldOut: true }, ]; const git = (cwd, ...args) => { const r = spawnSync("git", args, { cwd, encoding: "utf8", maxBuffer: 1 << 26 }); if (r.status !== 0) throw new Error(`git ${args.join(" ")} in ${cwd}: ${r.stderr}`); return r.stdout.trim(); }; const sortKeys = (o) => Array.isArray(o) ? o.map(sortKeys) : o && typeof o === "object" ? Object.fromEntries(Object.keys(o).sort().map((k) => [k, sortKeys(o[k])])) : o; const jsonl = (file, rows) => fs.writeFileSync(file, rows.map((r) => JSON.stringify(r)).join("\n") + "\n"); const csvCell = (v) => { const s = v === null || v === undefined ? "" : Array.isArray(v) ? v.join(";") : String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; }; const csv = (file, cols, rows) => fs.writeFileSync( file, [cols.join(","), ...rows.map((r) => cols.map((c) => csvCell(r[c])).join(","))].join("\n") + "\n", ); const repoUrl = (root) => git(root, "remote", "get-url", "origin").replace(/\.git$/, "").replace(/^git@github\.com:/, "https://github.com/"); /** The reactor's folder inside its repository, "" at the top. */ const prefixOf = (root) => path.relative(fs.realpathSync(git(root, "rev-parse", "--show-toplevel")), fs.realpathSync(root)).split(path.sep).join("/"); const quiet = (cfg) => ({ ...cfg, map: { ...cfg.map, suggest: "off" } }); // ── roles ──────────────────────────────────────────────────────────────── function buildRoles() { const labels = []; const predictions = []; const projects = []; const features = []; const families = []; const evalRows = {}; for (const p of META) { const root = path.join(PROJECTS, p.dir); const set = JSON.parse(fs.readFileSync(path.join(LABELS, `${p.name}.labels.json`), "utf8")); const commit = git(root, "rev-parse", "HEAD"); if (!commit.startsWith(set.commit)) throw new Error(`${p.name}: clone at ${commit}, labels at ${set.commit}`); const url = repoUrl(root); const prefix = prefixOf(root); const cfg = quiet(loadEffective(root, { flags: {} }).config); const { maps } = planMaps(root, cfg); const types = maps.flatMap((m) => m.types); const byName = new Map(types.map((t) => [t.qualifiedName, t])); for (const l of set.labels) { const t = byName.get(l.type); if (!t) throw new Error(`${p.name}: ${l.type} not in the sources`); const id = `${p.name}/${l.type}`; const repoPath = prefix ? `${prefix}/${t.rel}` : t.rel; labels.push( sortKeys({ id, project: p.name, commit, module: t.module, path: repoPath, url: `${url}/blob/${commit}/${repoPath}`, qualified_name: l.type, name: t.name, kind: t.declaration.kind === "class" && t.declaration.modifiers.includes("abstract") ? "abstract class" : t.declaration.kind, role: l.role, note: REVISED[id] ?? l.note ?? null, structure: { public: t.declaration.modifiers.includes("public"), annotations: t.annotations, supertypes: t.supertypes, imported_by: t.importedBy, implementations: t.implementations, used_within_module: t.usedWithin, data_class: t.data, framework_implemented: t.framework !== null, derived_marks: t.marks, }, }), ); predictions.push(sortKeys({ id, role: t.role ?? "none", reason: t.reason || null, marks: t.marks })); } const e = evaluate(set, types); for (const [r, c] of Object.entries(e.roles)) { const a = (evalRows[r] ??= { tp: 0, fp: 0, fn: 0, labelled: 0 }); for (const k of Object.keys(a)) a[k] += c[k]; } const javaFiles = new Set(types.map((t) => t.rel)).size; projects.push({ project: p.name, repository: url, commit, committed: git(root, "log", "-1", "--format=%cs"), license: p.license, reactor_folder: prefix || ".", modules: maps.length, java_files: javaFiles, top_level_types: types.length, labelled: set.labels.length, suggester_held_out: p.heldOut, }); const f = JSON.parse(fs.readFileSync(path.join(LABELS, `${p.name}.features.json`), "utf8")); for (const r of f.features) features.push(sortKeys({ id: `${p.name}/${r.type}`, project: p.name, hidden: r.hide ?? [], features: r.features })); const fam = JSON.parse(fs.readFileSync(path.join(LABELS, `${p.name}.families.json`), "utf8")); for (const r of fam.families) families.push(sortKeys({ project: p.name, key: r.key, size: r.size, labelled_roles: r.roles, majority_role: r.expected, mean_features: r.features })); process.stderr.write(`roles: ${p.name} ${set.labels.length}\n`); } labels.sort((a, b) => (a.id < b.id ? -1 : 1)); predictions.sort((a, b) => (a.id < b.id ? -1 : 1)); jsonl(path.join(OUT, "data/roles/labels.jsonl"), labels); csv( path.join(OUT, "data/roles/labels.csv"), ["id", "project", "module", "path", "qualified_name", "kind", "role", "note", "url"], labels, ); csv( path.join(OUT, "data/projects.csv"), ["project", "repository", "commit", "committed", "license", "reactor_folder", "modules", "java_files", "top_level_types", "labelled", "suggester_held_out"], projects, ); jsonl(path.join(OUT, "data/features/features.jsonl"), features); jsonl(path.join(OUT, "data/features/families.jsonl"), families); jsonl(path.join(OUT, "results/agentkit-roles.predictions.jsonl"), predictions); const pct = (n, d) => (d ? Math.round((1000 * n) / d) / 10 : null); const summary = Object.fromEntries( Object.entries(evalRows).filter(([, c]) => c.labelled || c.fp).map(([r, c]) => [r, { labelled: c.labelled, precision: r === "none" ? null : pct(c.tp, c.tp + c.fp), recall: pct(c.tp, c.tp + c.fn) }]), ); const right = Object.values(evalRows).reduce((n, c) => n + c.tp, 0); fs.writeFileSync( path.join(OUT, "results/agentkit-roles.json"), JSON.stringify({ tool: "agentkit map", labels: labels.length, accuracy: pct(right, labels.length), per_role: summary }, null, 2) + "\n", ); buildAnnotationSample(labels); process.stderr.write(`roles: ${labels.length} labels, accuracy ${pct(right, labels.length)} %\n`); } /** A blinded, stratified sample for a second annotator: 150 labels, in proportion to each project, by hash order. */ function buildAnnotationSample(labels, size = 150) { const byProject = new Map(); for (const l of labels) byProject.set(l.project, [...(byProject.get(l.project) ?? []), l]); const hash = (s) => crypto.createHash("sha256").update(`modulemap-bench-round-2:${s}`).digest("hex"); const quotas = [...byProject].map(([p, ls]) => ({ p, ls, exact: (size * ls.length) / labels.length })); quotas.forEach((q) => (q.n = Math.floor(q.exact))); let left = size - quotas.reduce((n, q) => n + q.n, 0); for (const q of [...quotas].sort((a, b) => b.exact - b.n - (a.exact - a.n) || (a.p < b.p ? -1 : 1))) { if (left-- <= 0) break; q.n++; } const sample = quotas .flatMap((q) => [...q.ls].sort((a, b) => (hash(a.id) < hash(b.id) ? -1 : 1)).slice(0, q.n)) .sort((a, b) => (hash(a.id) < hash(b.id) ? -1 : 1)); csv( path.join(OUT, "annotation/round-2/sample.csv"), ["id", "project", "qualified_name", "url", "role", "note"], sample.map((l) => ({ id: l.id, project: l.project, qualified_name: l.qualified_name, url: l.url, role: "", note: "" })), ); } // ── history ────────────────────────────────────────────────────────────── function buildHistory(n = 50) { const rows = []; const summary = {}; for (const p of META) { const root = path.join(HISTORY, p.dir); const top = git(root, "rev-parse", "--show-toplevel"); const prefix = prefixOf(root); const url = repoUrl(root); const cfg = quiet(loadEffective(root, { flags: {} }).config); const commits = javaCommits(root, n); const tree = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "mmb-")), "t"); git(top, "worktree", "add", "--detach", "--force", tree, `${commits[commits.length - 1]}^`); const s = (summary[p.name] = { repository: url, head: git(root, "rev-parse", "HEAD"), commits: 0, modified: 0, shown: { agentkit: 0, alphabetical: 0 } }); try { for (const c of commits) { git(tree, "checkout", "--detach", "--force", "--quiet", `${c}^`); const at = prefix ? path.join(tree, prefix) : tree; const files = new Set( git(top, "diff-tree", "--no-commit-id", "-r", "--diff-filter=M", "--name-only", `${c}^`, c) .split("\n") .filter((f) => f.endsWith(".java") && f.includes("src/main/java/")) .filter((f) => !prefix || f.startsWith(`${prefix}/`)) .map((f) => (prefix ? f.slice(prefix.length + 1) : f)), ); const { maps } = planMaps(at, cfg); const modified = []; const shown = { agentkit: [], alphabetical: [] }; for (const m of maps) { const changed = m.types.filter((t) => files.has(t.rel)); if (!changed.length) continue; for (const t of changed) modified.push({ qualified_name: t.qualifiedName, module: m.name, path: prefix ? `${prefix}/${t.rel}` : t.rel, agentkit_role: t.role ?? "none" }); for (const [k, layout] of [["agentkit", MAP_LAYOUT], ["alphabetical", ALPHABETICAL_LAYOUT]]) { const { inMap } = renderMap(at, m, m.links, m.types, () => true, m.processes, layout); shown[k].push(...changed.filter((t) => inMap.has(t)).map((t) => t.qualifiedName)); } } // A qualified name two modules declare counts once, as the labels do. const once = [...new Map(modified.map((x) => [x.qualified_name, x])).values()]; modified.length = 0; modified.push(...once.sort((a, b) => (a.qualified_name < b.qualified_name ? -1 : 1))); shown.agentkit = [...new Set(shown.agentkit)].sort(); shown.alphabetical = [...new Set(shown.alphabetical)].sort(); rows.push({ project: p.name, commit: c, parent: git(root, "rev-parse", `${c}^`), committed: git(root, "show", "-s", "--format=%cs", c), url: `${url}/commit/${c}`, modified, shown_before: shown, }); s.commits++; s.modified += modified.length; s.shown.agentkit += shown.agentkit.length; s.shown.alphabetical += shown.alphabetical.length; } } finally { spawnSync("git", ["worktree", "remove", "--force", tree], { cwd: top }); } process.stderr.write(`history: ${p.name} ${s.commits} commits, ${s.modified} modified\n`); } finishHistory(rows, summary, n); } /** The fewest measurable commits a project needs to be in the history benchmark. */ const MIN_COMMITS = 10; /** Drop projects with too short a history, and write the commits and their summary. */ function finishHistory(rows, summary, n) { for (const [name, s] of Object.entries(summary)) { if (s.commits >= MIN_COMMITS) continue; delete summary[name]; rows = rows.filter((r) => r.project !== name); process.stderr.write(`history: ${name} left out, ${s.commits} commit(s) < ${MIN_COMMITS}\n`); } jsonl(path.join(OUT, "data/history/commits.jsonl"), rows); const tot = Object.values(summary).reduce((a, s) => ({ commits: a.commits + s.commits, modified: a.modified + s.modified, agentkit: a.agentkit + s.shown.agentkit, alphabetical: a.alphabetical + s.shown.alphabetical }), { commits: 0, modified: 0, agentkit: 0, alphabetical: 0 }); const pct = (a, b) => Math.round((1000 * a) / b) / 10; fs.writeFileSync( path.join(OUT, "results/history.json"), JSON.stringify({ commits_per_project: n, min_commits: MIN_COMMITS, total: { ...tot, recall: { agentkit: pct(tot.agentkit, tot.modified), alphabetical: pct(tot.alphabetical, tot.modified) } }, projects: summary }, null, 2) + "\n", ); } const what = process.argv[2] ?? "all"; if (what === "roles" || what === "all") buildRoles(); if (what === "history" || what === "all") buildHistory(); // Re-derive the history files from data/history/commits.jsonl (dedupe, minimum, summary) without redrawing. if (what === "history-finish") { const rows = fs.readFileSync(path.join(OUT, "data/history/commits.jsonl"), "utf8").trim().split("\n").map((l) => JSON.parse(l)); const prev = JSON.parse(fs.readFileSync(path.join(OUT, "results/history.json"), "utf8")); const summary = {}; for (const r of rows) { r.modified = [...new Map(r.modified.map((x) => [x.qualified_name, x])).values()]; for (const k of Object.keys(r.shown_before)) r.shown_before[k] = [...new Set(r.shown_before[k])].sort(); const s = (summary[r.project] ??= { repository: prev.projects[r.project].repository, head: prev.projects[r.project].head, commits: 0, modified: 0, shown: { agentkit: 0, alphabetical: 0 } }); s.commits++; s.modified += r.modified.length; s.shown.agentkit += r.shown_before.agentkit.length; s.shown.alphabetical += r.shown_before.alphabetical.length; } finishHistory(rows, summary, prev.commits_per_project); }