9ffe734275
Deploy / deploy (push) Successful in 7m40s
- /api/articles[/slug]: GET/PUT/POST/DELETE, article JSON stored in PostgreSQL (schema analysis) - /api/tool-taxonomy: categories (tree), per-paper tools, each tool in one or more categories - /contents/tools-of-agents: category table with roll-up and links to the papers; removed "By kind of contribution" and "Recent papers" - content moves out of the repo: removed content/articles, load-articles.js, agent-tools.ts Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FbMbJPadPzVwvt9rU9GBNo
175 lines
10 KiB
TypeScript
175 lines
10 KiB
TypeScript
import { query, tx } from './db';
|
|
import { ensureAnalysisSchema } from './analysis-schema';
|
|
import { HttpError } from './api';
|
|
|
|
const bad = (msg: string): never => { throw new HttpError(400, msg); };
|
|
const SLUG = /^[a-z0-9][a-z0-9-]*$/;
|
|
|
|
export interface CategoryInput { slug: string; title: string; parent?: string | null; descr?: string | null; position?: number }
|
|
export interface ToolInput { name: string; does?: string | null; builtOn?: string | null; where?: string | null; categories: string[] }
|
|
|
|
/** Create or update categories (a list; parents may appear in the same list or already exist). */
|
|
export async function saveCategories(body: any) {
|
|
const list: CategoryInput[] = Array.isArray(body) ? body : body?.categories;
|
|
if (!Array.isArray(list) || !list.length) bad('send {"categories":[{"slug","title","parent"?,"descr"?,"position"?}, ...]}');
|
|
const seen = new Set<string>();
|
|
for (const c of list) {
|
|
if (!c || typeof c.slug !== 'string' || !SLUG.test(c.slug)) bad(`bad category slug ${JSON.stringify(c?.slug)} (lowercase letters, digits, dashes)`);
|
|
if (typeof c.title !== 'string' || !c.title.trim()) bad(`category ${c.slug}: missing title`);
|
|
if (seen.has(c.slug)) bad(`duplicate category ${c.slug}`);
|
|
seen.add(c.slug);
|
|
}
|
|
await ensureAnalysisSchema();
|
|
return tx(async (q) => {
|
|
const existing = new Set((await q<{ slug: string }>('SELECT slug FROM analysis.tool_category')).map((r) => r.slug));
|
|
for (const c of list) if (c.parent && !seen.has(c.parent) && !existing.has(c.parent)) bad(`category ${c.slug}: unknown parent ${c.parent}`);
|
|
for (const c of list) {
|
|
const pos = Number.isInteger(c.position) ? c.position! : null;
|
|
await q(
|
|
`INSERT INTO analysis.tool_category(slug, title, parent_slug, descr, position)
|
|
VALUES (?, ?, ?, ?, COALESCE(?::int, (SELECT COALESCE(MAX(position), -1) + 1 FROM analysis.tool_category)))
|
|
ON CONFLICT (slug) DO UPDATE SET title = EXCLUDED.title, parent_slug = EXCLUDED.parent_slug, descr = EXCLUDED.descr,
|
|
position = CASE WHEN ?::int IS NULL THEN analysis.tool_category.position ELSE EXCLUDED.position END`,
|
|
[c.slug, c.title, c.parent ?? null, c.descr ?? null, pos, pos]);
|
|
}
|
|
// no cycles
|
|
const all = await q<{ slug: string; parent_slug: string | null }>('SELECT slug, parent_slug FROM analysis.tool_category');
|
|
const parent = new Map(all.map((r) => [r.slug, r.parent_slug]));
|
|
for (const c of list) {
|
|
const path = new Set<string>();
|
|
for (let s: string | null | undefined = c.slug; s; s = parent.get(s)) {
|
|
if (path.has(s)) bad(`category ${c.slug} would be its own ancestor`);
|
|
path.add(s);
|
|
}
|
|
}
|
|
return { saved: list.length, total: all.length };
|
|
});
|
|
}
|
|
|
|
export async function deleteCategory(slug: string) {
|
|
await ensureAnalysisSchema();
|
|
const kids = await query<{ slug: string }>('SELECT slug FROM analysis.tool_category WHERE parent_slug = ?', [slug]);
|
|
if (kids.length) throw new HttpError(409, `category ${slug} still has children: ${kids.map((k) => k.slug).join(', ')}`);
|
|
const r = await query('DELETE FROM analysis.tool_category WHERE slug = ? RETURNING slug', [slug]);
|
|
if (!r.length) throw new HttpError(404, `no category ${slug}`);
|
|
return { deleted: slug };
|
|
}
|
|
|
|
/** Replace the tools one paper designed (the paper is the stable key conf + ext_id). */
|
|
export async function savePaperTools(conf: string, extId: string, body: any) {
|
|
const tools: ToolInput[] = body?.tools;
|
|
if (!Array.isArray(tools)) bad('send {"tools":[{"name","does"?,"builtOn"?,"where"?,"categories":[slug,...]}, ...]}');
|
|
const names = new Set<string>();
|
|
for (const t of tools) {
|
|
if (!t || typeof t.name !== 'string' || !t.name.trim()) bad('every tool needs a name');
|
|
if (names.has(t.name)) bad(`duplicate tool ${t.name}`);
|
|
names.add(t.name);
|
|
if (!Array.isArray(t.categories)) bad(`tool ${t.name}: categories must be a list of category slugs`);
|
|
}
|
|
await ensureAnalysisSchema();
|
|
const out = await tx(async (q) => {
|
|
const known = new Set((await q<{ slug: string }>('SELECT slug FROM analysis.tool_category')).map((r) => r.slug));
|
|
for (const t of tools) {
|
|
const unknown = t.categories.filter((c) => !known.has(c));
|
|
if (unknown.length) bad(`tool ${t.name}: unknown categories ${unknown.join(', ')} (create them first with PUT /api/tool-taxonomy/categories)`);
|
|
}
|
|
await q('DELETE FROM analysis.paper_tool WHERE conf = ? AND ext_id = ?', [conf, extId]);
|
|
for (let i = 0; i < tools.length; i++) {
|
|
const t = tools[i];
|
|
const id = (await q<{ id: number }>(
|
|
'INSERT INTO analysis.paper_tool(conf, ext_id, tool, descr, built_on, ref, position) VALUES (?,?,?,?,?,?,?) RETURNING id',
|
|
[conf, extId, t.name, t.does ?? null, t.builtOn ?? null, t.where ?? null, i]))[0].id;
|
|
for (const c of new Set(t.categories)) await q('INSERT INTO analysis.paper_tool_category(tool_id, category_slug) VALUES (?,?)', [id, c]);
|
|
}
|
|
return { conf, ext_id: extId, tools: tools.length };
|
|
});
|
|
const [paper] = await query<{ id: number; title: string }>('SELECT id, title FROM papers WHERE conf = ? AND ext_id = ?', [conf, extId]);
|
|
return { ...out, paper: paper ? { id: paper.id, title: paper.title, url: `/papers/${paper.id}` } : null };
|
|
}
|
|
|
|
export async function deletePaperTools(conf: string, extId: string) {
|
|
await ensureAnalysisSchema();
|
|
const r = await query('DELETE FROM analysis.paper_tool WHERE conf = ? AND ext_id = ? RETURNING id', [conf, extId]);
|
|
return { conf, ext_id: extId, deleted: r.length };
|
|
}
|
|
|
|
interface ToolRow { id: number; conf: string; ext_id: string; tool: string; descr: string | null; built_on: string | null; ref: string | null; paper_id: number | null; title: string | null }
|
|
|
|
async function loadAll() {
|
|
await ensureAnalysisSchema();
|
|
const [cats, tools, maps] = await Promise.all([
|
|
query<{ slug: string; title: string; parent_slug: string | null; descr: string | null; position: number }>(
|
|
'SELECT slug, title, parent_slug, descr, position FROM analysis.tool_category ORDER BY position, slug'),
|
|
query<ToolRow>(
|
|
`SELECT t.id, t.conf, t.ext_id, t.tool, t.descr, t.built_on, t.ref, p.id AS paper_id, p.title
|
|
FROM analysis.paper_tool t LEFT JOIN papers p ON p.conf = t.conf AND p.ext_id = t.ext_id
|
|
ORDER BY t.conf, t.ext_id, t.position, t.id`),
|
|
query<{ tool_id: number; category_slug: string }>('SELECT tool_id, category_slug FROM analysis.paper_tool_category'),
|
|
]);
|
|
const catsOf = new Map<number, string[]>();
|
|
for (const m of maps) (catsOf.get(m.tool_id) ?? catsOf.set(m.tool_id, []).get(m.tool_id)!).push(m.category_slug);
|
|
return { cats, tools: tools.map((t) => ({ ...t, categories: catsOf.get(t.id) ?? [] })) };
|
|
}
|
|
|
|
/** Everything, for the GET endpoint: categories, and per paper its tools. */
|
|
export async function exportTaxonomy() {
|
|
const { cats, tools } = await loadAll();
|
|
const papers = new Map<string, any>();
|
|
for (const t of tools) {
|
|
const k = `${t.conf}/${t.ext_id}`;
|
|
if (!papers.has(k)) papers.set(k, { conf: t.conf, ext_id: t.ext_id, paper: t.paper_id ? { id: t.paper_id, title: t.title } : null, tools: [] });
|
|
papers.get(k).tools.push({ name: t.tool, does: t.descr, builtOn: t.built_on, where: t.ref, categories: t.categories });
|
|
}
|
|
return {
|
|
categories: cats.map((c) => ({ slug: c.slug, title: c.title, parent: c.parent_slug, descr: c.descr, position: c.position })),
|
|
papers: [...papers.values()],
|
|
};
|
|
}
|
|
|
|
export async function exportPaperTools(conf: string, extId: string) {
|
|
const all = await exportTaxonomy();
|
|
return all.papers.find((p) => p.conf === conf && p.ext_id === extId) ?? { conf, ext_id: extId, paper: null, tools: [] };
|
|
}
|
|
|
|
// ---- the table shown on /contents/tools-of-agents ----
|
|
|
|
export interface TaxonomyEntry { tool: string; descr: string | null; paperId: number | null; paperLabel: string; via: string | null }
|
|
export interface TaxonomyRow { slug: string; title: string; path: string[]; depth: number; descr: string | null; papers: number; entries: TaxonomyEntry[] }
|
|
export interface ToolTable { rows: TaxonomyRow[]; uncategorised: TaxonomyEntry[]; tools: number; papers: number }
|
|
|
|
const label = (t: { title: string | null; ext_id: string }) => (t.title ? t.title.split(':')[0].trim() : t.ext_id);
|
|
|
|
/** One row per category, in tree order. A category lists every tool filed under it or under any category below it. */
|
|
export async function getToolTable(): Promise<ToolTable> {
|
|
let data: Awaited<ReturnType<typeof loadAll>>;
|
|
try { data = await loadAll(); } catch { return { rows: [], uncategorised: [], tools: 0, papers: 0 }; }
|
|
const { cats, tools } = data;
|
|
const kids = new Map<string | null, typeof cats>();
|
|
for (const c of cats) {
|
|
const p = c.parent_slug && cats.some((x) => x.slug === c.parent_slug) ? c.parent_slug : null;
|
|
(kids.get(p) ?? kids.set(p, []).get(p)!).push(c);
|
|
}
|
|
const rows: TaxonomyRow[] = [];
|
|
const walk = (parent: string | null, path: string[]) => {
|
|
for (const c of kids.get(parent) ?? []) {
|
|
const here = [...path, c.title];
|
|
const sub: { slug: string; title: string }[] = []; // strict descendants
|
|
const collect = (s: string) => { for (const k of kids.get(s) ?? []) { sub.push(k); collect(k.slug); } };
|
|
collect(c.slug);
|
|
const entries: TaxonomyEntry[] = [];
|
|
const keys = new Set<string>();
|
|
for (const t of tools) {
|
|
const via = t.categories.includes(c.slug) ? null : sub.find((s) => t.categories.includes(s.slug))?.title;
|
|
if (via === undefined) continue; // not filed here or below
|
|
entries.push({ tool: t.tool, descr: t.descr, paperId: t.paper_id, paperLabel: label(t), via });
|
|
keys.add(`${t.conf}/${t.ext_id}`);
|
|
}
|
|
rows.push({ slug: c.slug, title: c.title, path: here, depth: here.length - 1, descr: c.descr, papers: keys.size, entries });
|
|
walk(c.slug, here);
|
|
}
|
|
};
|
|
walk(null, []);
|
|
const uncategorised = tools.filter((t) => !t.categories.length).map((t) => ({ tool: t.tool, descr: t.descr, paperId: t.paper_id, paperLabel: label(t), via: null }));
|
|
return { rows, uncategorised, tools: tools.length, papers: new Set(tools.map((t) => `${t.conf}/${t.ext_id}`)).size };
|
|
}
|