@agentrica/mcp 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,110 @@
1
+ /* Palette del sito (apps/site/src/app/globals.css), tema scuro; contrasti AA misurati lì sugli stessi fondi. */
2
+ :root {
3
+ --background: #0b1020;
4
+ --foreground: #e8ebf4;
5
+ --card: #121a2e;
6
+ --secondary: #18223b;
7
+ --muted-foreground: #a8b1c7;
8
+ --destructive: #ff7a6b;
9
+ --border: #26324f;
10
+ --ring: #ffffff;
11
+ --aibpd: #f5b544;
12
+ --aica: #ff7a6b;
13
+ --aipca: #b49cff;
14
+ --aisa: #38d6f0;
15
+ --aiwda: #4fe0a8;
16
+ --dept: var(--muted-foreground);
17
+ --radius: 12px;
18
+ color-scheme: dark;
19
+ }
20
+
21
+ [data-dept="AIBPD"] { --dept: var(--aibpd); }
22
+ [data-dept="AICA"] { --dept: var(--aica); }
23
+ [data-dept="AIPCA"] { --dept: var(--aipca); }
24
+ [data-dept="AISA"] { --dept: var(--aisa); }
25
+ [data-dept="AIWDA"] { --dept: var(--aiwda); }
26
+
27
+ * { box-sizing: border-box; }
28
+
29
+ body {
30
+ margin: 0;
31
+ background: var(--background);
32
+ color: var(--foreground);
33
+ font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
34
+ }
35
+
36
+ code, .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 0.92em; }
37
+ code { background: var(--secondary); border-radius: 4px; padding: 0 0.25em; }
38
+
39
+ :focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
40
+
41
+ .wrap { max-width: 1200px; margin: 0 auto; padding: 0 16px; }
42
+
43
+ .top { border-bottom: 1px solid var(--border); background: var(--card); }
44
+ .top-row { display: flex; flex-wrap: wrap; gap: 4px 24px; align-items: baseline; padding-block: 12px; }
45
+ .top p { margin: 0; }
46
+ .brand { font-size: 1rem; font-weight: 700; margin: 0; }
47
+ .meta, .link { color: var(--muted-foreground); }
48
+ .link { margin-left: auto; }
49
+ .link[data-state="ok"]::before { content: "● "; color: var(--aiwda); }
50
+ .link[data-state="off"] { color: var(--destructive); }
51
+
52
+ main { display: grid; gap: 16px; padding-block: 16px 48px; }
53
+ .live { display: grid; gap: 16px; }
54
+ @media (min-width: 960px) { .live { grid-template-columns: 3fr 2fr; align-items: start; } }
55
+
56
+ .card { background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px 20px; min-width: 0; }
57
+ h2 { font-size: 1.15rem; margin: 0 0 12px; }
58
+ h3 { font-size: 1rem; margin: 16px 0 8px; }
59
+ .empty, .hint { color: var(--muted-foreground); margin: 0; }
60
+ .problems { margin: 0; padding: 12px 16px; border: 1px solid var(--destructive); border-radius: var(--radius); white-space: pre-line; }
61
+
62
+ .question { border: 1px solid var(--border); border-radius: var(--radius); padding: 12px 16px; background: var(--secondary); }
63
+ .question + .question { margin-top: 12px; }
64
+ .question fieldset { border: 0; margin: 0; padding: 0; }
65
+ .question legend { font-weight: 600; padding: 0; margin-bottom: 8px; }
66
+ .tag { display: inline-block; font-size: 0.8rem; color: var(--muted-foreground); border: 1px solid var(--border); border-radius: 999px; padding: 0 8px; margin-bottom: 6px; }
67
+ .option { display: grid; grid-template-columns: auto 1fr; gap: 0 10px; padding: 8px; border-radius: 8px; cursor: pointer; }
68
+ .option:hover { background: var(--card); }
69
+ .option input { margin-top: 0.3em; accent-color: var(--aisa); width: 1.05rem; height: 1.05rem; }
70
+ .option strong { display: block; }
71
+ .option span { color: var(--muted-foreground); }
72
+ .recommended { color: var(--aiwda); font-size: 0.85rem; font-weight: 600; margin-left: 6px; }
73
+ label.note { display: block; margin-top: 8px; }
74
+ textarea { display: block; width: 100%; margin-top: 4px; min-height: 3.5em; resize: vertical; background: var(--background); color: var(--foreground); border: 1px solid var(--border); border-radius: 8px; padding: 8px; font: inherit; }
75
+ button { font: inherit; cursor: pointer; border-radius: 8px; }
76
+ .send { margin-top: 12px; background: var(--foreground); color: var(--background); border: 0; padding: 8px 16px; font-weight: 600; }
77
+ .error { color: var(--destructive); margin: 8px 0 0; }
78
+ .sent { margin: 0; }
79
+
80
+ ol.activity { list-style: none; margin: 0; padding: 0; }
81
+ ol.activity li { display: grid; grid-template-columns: 3.5em 1fr; gap: 0 8px; padding: 6px 0; border-top: 1px solid var(--border); }
82
+ ol.activity li:first-child { border-top: 0; }
83
+ .dot::before { content: "●"; color: var(--dept); margin-right: 6px; }
84
+ .task { grid-column: 2; color: var(--muted-foreground); overflow-wrap: anywhere; }
85
+
86
+ .scroll { overflow-x: auto; }
87
+ table { border-collapse: collapse; width: 100%; }
88
+ th, td { text-align: left; padding: 6px 10px 6px 0; border-top: 1px solid var(--border); vertical-align: top; }
89
+ thead th { border-top: 0; color: var(--muted-foreground); font-weight: 600; font-size: 0.9rem; }
90
+ tr.current td { color: var(--foreground); font-weight: 600; }
91
+ .status-done { color: var(--aiwda); }
92
+ .goal { margin: 0 0 8px; }
93
+ ul.criteria { margin: 0; padding-left: 1.2em; }
94
+
95
+ .filters { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 8px; }
96
+ .filters button { background: transparent; color: var(--foreground); border: 1px solid var(--border); padding: 4px 12px; }
97
+ .filters button[aria-pressed="true"] { background: var(--foreground); color: var(--background); border-color: var(--foreground); }
98
+ ul.findings { list-style: none; margin: 0; padding: 0; }
99
+ ul.findings li { padding: 8px 0; border-top: 1px solid var(--border); }
100
+ ul.findings li:first-child { border-top: 0; }
101
+ .finding-meta { display: block; color: var(--muted-foreground); font-size: 0.9rem; }
102
+ .prio { font-weight: 700; }
103
+ summary { cursor: pointer; padding: 6px 0; font-weight: 600; }
104
+ details + details { border-top: 1px solid var(--border); }
105
+ .hint { margin-top: 12px; font-size: 0.9rem; }
106
+ .prio-P0 { color: var(--destructive); }
107
+
108
+ .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
109
+
110
+ @media (prefers-reduced-motion: no-preference) { .option, .filters button { transition: background-color 120ms; } }
@@ -0,0 +1,220 @@
1
+ // Pannello locale: server HTTP nello stesso processo del server MCP, attivo solo con --panel.
2
+ // Chi raggiunge la pagina risponde alle domande dell'agente, quindi le difese sono strette: ascolto solo su 127.0.0.1
3
+ // con porta casuale; token casuale nell'URL aperto dal tool, scambiato con un cookie HttpOnly e SameSite=Strict;
4
+ // Host fisso contro il DNS rebinding; Origin fisso e JSON obbligatorio per le POST; CSP 'self' e nessuna risorsa
5
+ // esterna. Le rotte sono un elenco chiuso: nessun percorso dell'URL diventa un percorso di file.
6
+ import { spawn } from "node:child_process";
7
+ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
8
+ import { readFileSync } from "node:fs";
9
+ import { createServer } from "node:http";
10
+ import { join } from "node:path";
11
+ import { readProject } from "./project.js";
12
+ const MAX_BODY_BYTES = 16_000;
13
+ const MAX_NOTE = 2000;
14
+ const MAX_ACTIVITY = 20;
15
+ const KEEPALIVE_MS = 25_000;
16
+ const SECURITY_HEADERS = {
17
+ "Content-Security-Policy": "default-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
18
+ "X-Content-Type-Options": "nosniff",
19
+ "X-Frame-Options": "DENY",
20
+ "Referrer-Policy": "no-referrer",
21
+ "Cache-Control": "no-store",
22
+ "Cross-Origin-Resource-Policy": "same-origin",
23
+ };
24
+ const PAGE_FILES = {
25
+ "/": ["index.html", "text/html; charset=utf-8"],
26
+ "/app.js": ["app.js", "text/javascript; charset=utf-8"],
27
+ "/style.css": ["style.css", "text/css; charset=utf-8"],
28
+ };
29
+ function sameSecret(given, token) {
30
+ if (!given)
31
+ return false;
32
+ const a = Buffer.from(given);
33
+ const b = Buffer.from(token);
34
+ return a.length === b.length && timingSafeEqual(a, b);
35
+ }
36
+ function cookie(req, name) {
37
+ for (const part of (req.headers.cookie ?? "").split(";")) {
38
+ const [key, ...value] = part.trim().split("=");
39
+ if (key === name)
40
+ return value.join("=");
41
+ }
42
+ return undefined;
43
+ }
44
+ function send(res, status, body = "", type = "text/plain; charset=utf-8") {
45
+ res.writeHead(status, { ...SECURITY_HEADERS, "Content-Type": type });
46
+ res.end(body);
47
+ }
48
+ function readBody(req) {
49
+ return new Promise((resolve, reject) => {
50
+ let size = 0;
51
+ const chunks = [];
52
+ req.on("data", (chunk) => {
53
+ size += chunk.length;
54
+ if (size > MAX_BODY_BYTES) {
55
+ reject(new Error("corpo troppo grande"));
56
+ req.destroy();
57
+ }
58
+ else
59
+ chunks.push(chunk);
60
+ });
61
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
62
+ req.on("error", reject);
63
+ });
64
+ }
65
+ /** Controlla una risposta della pagina contro la domanda: etichette esistenti, una sola se la scelta è singola. */
66
+ export function parseAnswer(question, body) {
67
+ if (typeof body !== "object" || body === null)
68
+ return null;
69
+ const { choices, note = "" } = body;
70
+ if (!Array.isArray(choices) || typeof note !== "string" || note.length > MAX_NOTE)
71
+ return null;
72
+ const labels = new Set(question.options.map((o) => o.label));
73
+ const picked = [...new Set(choices)];
74
+ if (!picked.every((c) => typeof c === "string" && labels.has(c)))
75
+ return null;
76
+ if (picked.length === 0 && note.trim() === "")
77
+ return null;
78
+ if (!question.multiple && picked.length > 1)
79
+ return null;
80
+ return { choices: picked, note: note.trim() };
81
+ }
82
+ /** Apre l'URL nel browser predefinito; se non riesce (es. sessione remota) l'URL resta nella risposta del tool. */
83
+ export function openBrowser(url) {
84
+ const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
85
+ try {
86
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
87
+ child.on("error", () => { });
88
+ child.unref();
89
+ }
90
+ catch {
91
+ // Nessun browser: l'utente apre l'URL a mano.
92
+ }
93
+ }
94
+ export async function startPanel(root, pageDir = join(import.meta.dirname, "page")) {
95
+ const token = randomBytes(32).toString("hex");
96
+ const pages = Object.fromEntries(Object.entries(PAGE_FILES).map(([route, [file, type]]) => [route, { body: readFileSync(join(pageDir, file)), type }]));
97
+ const pending = new Map();
98
+ const activity = [];
99
+ const viewers = new Set();
100
+ const changed = () => {
101
+ for (const viewer of viewers)
102
+ viewer.write("event: change\ndata: {}\n\n");
103
+ };
104
+ const server = createServer((req, res) => {
105
+ // Un errore in una richiesta non deve fermare il processo, che è anche il server MCP della sessione.
106
+ handle(req, res).catch(() => {
107
+ if (!res.headersSent)
108
+ send(res, 500, "Errore del pannello.");
109
+ else
110
+ res.end();
111
+ });
112
+ });
113
+ async function handle(req, res) {
114
+ const port = server.address().port;
115
+ const origin = `http://127.0.0.1:${port}`;
116
+ if (req.headers.host !== `127.0.0.1:${port}`)
117
+ return send(res, 421, "Host non valido.");
118
+ const url = new URL(req.url ?? "/", origin);
119
+ const cookieName = `agentrica_panel_${port}`;
120
+ if (req.method === "GET" && url.pathname === "/" && url.searchParams.has("t")) {
121
+ if (!sameSecret(url.searchParams.get("t") ?? undefined, token))
122
+ return send(res, 403, "Token non valido.");
123
+ // Il token esce dalla barra degli indirizzi e dalla cronologia: da qui vale il cookie.
124
+ res.writeHead(303, { ...SECURITY_HEADERS, Location: "/", "Set-Cookie": `${cookieName}=${token}; HttpOnly; SameSite=Strict; Path=/` });
125
+ res.end();
126
+ return;
127
+ }
128
+ if (!sameSecret(cookie(req, cookieName), token)) {
129
+ return send(res, 403, "Apri il pannello dall'URL che dà il tool open_panel dell'agente.");
130
+ }
131
+ if (req.method === "GET" && url.pathname in pages) {
132
+ const page = pages[url.pathname];
133
+ return send(res, 200, page.body.toString("utf8"), page.type);
134
+ }
135
+ if (req.method === "GET" && url.pathname === "/api/state") {
136
+ const project = await readProject(root);
137
+ const questions = [...pending.values()].map((p) => p.question);
138
+ return send(res, 200, JSON.stringify({ project, questions, activity }), "application/json; charset=utf-8");
139
+ }
140
+ if (req.method === "GET" && url.pathname === "/api/events") {
141
+ res.writeHead(200, { ...SECURITY_HEADERS, "Content-Type": "text/event-stream; charset=utf-8", Connection: "keep-alive" });
142
+ res.write("retry: 3000\n\n");
143
+ viewers.add(res);
144
+ req.on("close", () => viewers.delete(res));
145
+ return;
146
+ }
147
+ if (req.method === "POST" && url.pathname === "/api/answer") {
148
+ if (req.headers.origin !== origin)
149
+ return send(res, 403, "Origine non valida.");
150
+ if (!req.headers["content-type"]?.startsWith("application/json"))
151
+ return send(res, 415, "Serve JSON.");
152
+ let body;
153
+ try {
154
+ body = JSON.parse(await readBody(req));
155
+ }
156
+ catch {
157
+ return send(res, 400, "Richiesta non valida.");
158
+ }
159
+ const entry = typeof body?.id === "string" ? pending.get(body.id) : undefined;
160
+ if (!entry)
161
+ return send(res, 404, "La domanda non è più in attesa.");
162
+ const answer = parseAnswer(entry.question, body);
163
+ if (!answer)
164
+ return send(res, 400, "Risposta non valida.");
165
+ entry.resolve(answer);
166
+ res.writeHead(204, SECURITY_HEADERS);
167
+ res.end();
168
+ return;
169
+ }
170
+ return send(res, 404, "Non trovato.");
171
+ }
172
+ await new Promise((resolve, reject) => {
173
+ server.once("error", reject);
174
+ server.listen(0, "127.0.0.1", resolve);
175
+ });
176
+ const port = server.address().port;
177
+ const keepalive = setInterval(() => viewers.forEach((viewer) => viewer.write(": ping\n\n")), KEEPALIVE_MS);
178
+ keepalive.unref();
179
+ server.unref();
180
+ return {
181
+ url: `http://127.0.0.1:${port}/?t=${token}`,
182
+ ask(input, signal) {
183
+ return new Promise((resolve, reject) => {
184
+ const id = randomUUID();
185
+ const done = () => {
186
+ pending.delete(id);
187
+ signal.removeEventListener("abort", abort);
188
+ changed();
189
+ };
190
+ const abort = () => {
191
+ done();
192
+ reject(signal.reason);
193
+ };
194
+ if (signal.aborted)
195
+ return reject(signal.reason);
196
+ signal.addEventListener("abort", abort);
197
+ pending.set(id, {
198
+ question: { ...input, id, askedAt: new Date().toISOString() },
199
+ resolve: (answer) => {
200
+ done();
201
+ resolve(answer);
202
+ },
203
+ });
204
+ changed();
205
+ });
206
+ },
207
+ record(entry) {
208
+ activity.unshift({ ...entry, time: new Date().toISOString() });
209
+ activity.length = Math.min(activity.length, MAX_ACTIVITY);
210
+ changed();
211
+ },
212
+ hasViewers: () => viewers.size > 0,
213
+ close() {
214
+ clearInterval(keepalive);
215
+ for (const viewer of viewers)
216
+ viewer.end();
217
+ return new Promise((resolve) => server.close(() => resolve()));
218
+ },
219
+ };
220
+ }
@@ -0,0 +1,192 @@
1
+ // Lettura del progetto dell'utente per il pannello: fasi e backlog da plan/, rilievi da plan/ e audit/, stato di git.
2
+ // Il formato è quello di agentic-starter, descritto nel README del pacchetto. Si legge solo dentro plan/ e audit/
3
+ // della cartella del progetto: i link simbolici che escono sono rifiutati e ogni file ha un limite di dimensione.
4
+ // Un file mancante o fuori formato diventa un problema in `problems`, mai un errore che ferma il pannello.
5
+ import { execFile } from "node:child_process";
6
+ import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
7
+ import { basename, join, sep } from "node:path";
8
+ import { promisify } from "node:util";
9
+ const MAX_FILE_BYTES = 1_000_000;
10
+ const DEPARTMENT = /\b(AIBPD|AICA|AIPCA|AISA|AIWDA)\b/;
11
+ const PRIORITY = /\bP[0-3]\b/;
12
+ const CLOSED = new Set(["completata", "sospesa"]);
13
+ // Un rilievo è chiuso quando il testo (fasi) o lo stato (audit) dice «risolto» o «chiuso», in qualsiasi genere e
14
+ // numero, e non «non risolto»: la voce resta nel piano come storia ma il pannello non la mostra fra gli aperti.
15
+ const CLOSED_FINDING = /(?<!\bnon )\b(risolt|chius)[oaie]\b/i;
16
+ /** true se il testo dice che il rilievo è risolto o chiuso (README del pacchetto, «Formato»). */
17
+ export const isClosedFinding = (text) => CLOSED_FINDING.test(text);
18
+ /** Legge un file di testo sotto `root`, rifiutando link simbolici che escono e file troppo grandi. */
19
+ function readInside(root, path) {
20
+ const real = realpathSync(path);
21
+ if (!real.startsWith(root + sep))
22
+ throw new Error("fuori dalla cartella del progetto");
23
+ if (statSync(real).size > MAX_FILE_BYTES)
24
+ throw new Error("file troppo grande");
25
+ return readFileSync(real, "utf8");
26
+ }
27
+ /** Le righe di una sezione «## Titolo», fino alla sezione successiva dello stesso livello. */
28
+ export function section(markdown, heading) {
29
+ const lines = markdown.split("\n");
30
+ const start = lines.findIndex((line) => line.trim() === `## ${heading}`);
31
+ if (start === -1)
32
+ return null;
33
+ const end = lines.findIndex((line, i) => i > start && line.startsWith("## "));
34
+ return lines.slice(start + 1, end === -1 ? undefined : end);
35
+ }
36
+ /** Le righe di dati della prima tabella Markdown fra `lines`, senza intestazione e separatore. */
37
+ export function tableRows(lines) {
38
+ const rows = lines.filter((line) => line.trim().startsWith("|"));
39
+ return rows.slice(2).map((row) => row.trim().replace(/^\||\|$/g, "").split("|").map((cell) => cell.trim()));
40
+ }
41
+ /** Gli elementi di primo livello di un elenco puntato. */
42
+ export function bullets(lines) {
43
+ return lines.filter((line) => line.startsWith("- ")).map((line) => line.slice(2).trim());
44
+ }
45
+ const linkTarget = (cell) => /\]\(([^)]+)\)/.exec(cell)?.[1] ?? null;
46
+ const priorityOf = (text) => PRIORITY.exec(text)?.[0] ?? "";
47
+ function readPhases(root, plan, problems) {
48
+ let readme;
49
+ try {
50
+ readme = readInside(root, join(plan, "README.md"));
51
+ }
52
+ catch {
53
+ problems.push("Non trovo plan/README.md: il pannello legge il formato di agentic-starter (vedi il README del pacchetto).");
54
+ return [];
55
+ }
56
+ const fasi = section(readme, "Fasi");
57
+ const rows = fasi ? tableRows(fasi) : [];
58
+ if (rows.length === 0) {
59
+ problems.push("In plan/README.md manca la tabella «## Fasi» (Fase | File | Contenuto | Stato).");
60
+ return [];
61
+ }
62
+ return rows.map(([id = "", file = "", summary = "", status = ""]) => {
63
+ const target = linkTarget(file);
64
+ // Solo un nome di file dentro plan/: niente cartelle né percorsi che risalgono.
65
+ const safe = target && /^[\w.-]+\.md$/.test(target) && target !== "README.md" ? target : null;
66
+ return { id, file: safe, summary, status };
67
+ });
68
+ }
69
+ function readOpenPhase(root, plan, phase, problems) {
70
+ if (!phase.file)
71
+ return null;
72
+ let text;
73
+ try {
74
+ text = readInside(root, join(plan, phase.file));
75
+ }
76
+ catch {
77
+ problems.push(`Non trovo plan/${phase.file}, il file della fase ${phase.id}.`);
78
+ return null;
79
+ }
80
+ const title = /^# (.+)$/m.exec(text)?.[1] ?? phase.id;
81
+ const goal = /^\*\*Obiettivo\*\*:\s*(.+)$/m.exec(text)?.[1] ?? "";
82
+ const done = (section(text, "Fatto") ?? []).join("\n");
83
+ const backlog = section(text, "Backlog");
84
+ if (!backlog)
85
+ problems.push(`In plan/${phase.file} manca la sezione «## Backlog».`);
86
+ const tasks = tableRows(backlog ?? []).map(([id = "", task = "", priority = ""]) => ({
87
+ id,
88
+ task,
89
+ priority,
90
+ done: id !== "" && done.includes(`**${id}**`),
91
+ }));
92
+ return { id: phase.id, title, goal, status: phase.status, tasks, criteria: bullets(section(text, "Criteri di accettazione") ?? []) };
93
+ }
94
+ /** I «Rilievi aperti» dei file di fase, che sono l'elenco curato dei rilievi ancora da chiudere. */
95
+ function readPhaseFindings(root, plan, phases) {
96
+ return phases.flatMap((phase) => {
97
+ if (!phase.file)
98
+ return [];
99
+ let text;
100
+ try {
101
+ text = readInside(root, join(plan, phase.file));
102
+ }
103
+ catch {
104
+ return [];
105
+ }
106
+ return bullets(section(text, "Rilievi aperti") ?? [])
107
+ .filter((item) => !/^nessuno\b/i.test(item) && !isClosedFinding(item))
108
+ .map((item) => ({
109
+ id: "",
110
+ title: item,
111
+ priority: priorityOf(item),
112
+ department: DEPARTMENT.exec(item)?.[1] ?? null,
113
+ source: phase.id,
114
+ status: null,
115
+ }));
116
+ });
117
+ }
118
+ const asText = (value) => (typeof value === "string" ? value : "");
119
+ function readAuditFindings(root, problems) {
120
+ const audit = join(root, "audit");
121
+ let folders;
122
+ try {
123
+ folders = readdirSync(audit, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
124
+ }
125
+ catch {
126
+ return [];
127
+ }
128
+ return folders.flatMap((folder) => {
129
+ const files = readdirSync(join(audit, folder)).filter((name) => name.endsWith(".json")).sort();
130
+ return files.flatMap((file) => {
131
+ const source = `${folder}/${file}`;
132
+ let data;
133
+ try {
134
+ data = JSON.parse(readInside(root, join(audit, folder, file)));
135
+ }
136
+ catch {
137
+ problems.push(`audit/${source} non è un JSON leggibile: saltato.`);
138
+ return [];
139
+ }
140
+ const record = data;
141
+ if (!Array.isArray(record.rilievi)) {
142
+ problems.push(`audit/${source} non ha l'elenco «rilievi»: saltato.`);
143
+ return [];
144
+ }
145
+ const department = DEPARTMENT.exec(asText(record.agente))?.[1] ?? null;
146
+ const items = record.rilievi
147
+ .filter((item) => typeof item === "object" && item !== null)
148
+ .filter((item) => !isClosedFinding(asText(item.stato)));
149
+ return items.map((item) => ({
150
+ id: asText(item.id),
151
+ title: asText(item.titolo),
152
+ priority: priorityOf(asText(item.priorita)),
153
+ department,
154
+ source,
155
+ status: asText(item.stato) || null,
156
+ }));
157
+ });
158
+ });
159
+ }
160
+ const run = promisify(execFile);
161
+ /** Branch e numero di file modificati; null se la cartella non è un repository git o git non c'è. */
162
+ export async function readGit(root) {
163
+ try {
164
+ // Niente fsmonitor (un comando scelto dalla config del repository) e niente lock: il pannello legge e basta.
165
+ const args = ["--no-optional-locks", "-c", "core.fsmonitor=false", "status", "--porcelain=v1", "--branch"];
166
+ const { stdout } = await run("git", args, { cwd: root, timeout: 2000 });
167
+ const [head = "", ...rest] = stdout.split("\n").filter(Boolean);
168
+ const branch = head.replace(/^## /, "").replace(/^No commits yet on /, "").split("...")[0] ?? "";
169
+ const untracked = rest.filter((line) => line.startsWith("??")).length;
170
+ return { branch, changed: rest.length - untracked, untracked };
171
+ }
172
+ catch {
173
+ return null;
174
+ }
175
+ }
176
+ /** Legge plan/ e audit/ di `root` (la cartella del progetto, già risolta con realpath). */
177
+ export function readPlan(root) {
178
+ const problems = [];
179
+ const plan = join(root, "plan");
180
+ const phases = readPhases(root, plan, problems);
181
+ const open = phases.find((phase) => !CLOSED.has(phase.status.toLowerCase()));
182
+ return {
183
+ name: basename(root),
184
+ phases,
185
+ openPhase: open ? readOpenPhase(root, plan, open, problems) : null,
186
+ findings: [...readPhaseFindings(root, plan, phases), ...readAuditFindings(root, problems)],
187
+ problems,
188
+ };
189
+ }
190
+ export async function readProject(root) {
191
+ return { ...readPlan(root), git: await readGit(root) };
192
+ }
@@ -1,5 +1,5 @@
1
1
  /** Versione del server, uguale a quella di package.json (lo controlla prompt.test.ts). */
2
- export const VERSION = "0.2.1";
2
+ export const VERSION = "0.3.1";
3
3
  /** Cerca un agente per id, senza distinguere maiuscole e minuscole («aisa-02» o «AISA-02»). */
4
4
  export function findAgent(catalog, id) {
5
5
  const wanted = id.toUpperCase();
@@ -26,7 +26,7 @@ export function agentSummary({ department, agent }) {
26
26
  */
27
27
  export function selectSquad(catalog, spec) {
28
28
  if (spec === undefined)
29
- return [...catalog];
29
+ return catalog.map(({ director: _, ...d }) => d);
30
30
  const names = spec.split(",").map((name) => name.trim()).filter((name) => name !== "");
31
31
  if (names.length === 0)
32
32
  throw new Error("--agents è vuoto: indica id di agenti o sigle di reparti, es. --agents aisa,aiwda-08");
@@ -47,7 +47,7 @@ export function selectSquad(catalog, spec) {
47
47
  if (unknown.length > 0)
48
48
  throw new Error(`agente o reparto sconosciuto in --agents: ${unknown.map((n) => JSON.stringify(n)).join(", ")}`);
49
49
  return catalog
50
- .map((d) => ({ ...d, agents: d.agents.filter((a) => wanted.has(a.id)) }))
50
+ .map(({ director: _, ...d }) => ({ ...d, agents: d.agents.filter((a) => wanted.has(a.id)) }))
51
51
  .filter((d) => d.agents.length > 0);
52
52
  }
53
53
  export function agentText({ department, agent }, task) {