@ignitionai/cogitator 0.1.0

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.
Files changed (75) hide show
  1. package/README.md +44 -0
  2. package/dist/extensions/index.js +63 -0
  3. package/dist/src/agents.js +238 -0
  4. package/dist/src/board.js +277 -0
  5. package/dist/src/cli.js +71 -0
  6. package/dist/src/config.js +7 -0
  7. package/dist/src/conversations.js +41 -0
  8. package/dist/src/cron.js +227 -0
  9. package/dist/src/db.js +128 -0
  10. package/dist/src/default-agent.js +154 -0
  11. package/dist/src/file-changes.js +113 -0
  12. package/dist/src/history.js +88 -0
  13. package/dist/src/json-files.js +18 -0
  14. package/dist/src/mcp-env.js +29 -0
  15. package/dist/src/mcp-server.js +167 -0
  16. package/dist/src/paths.js +22 -0
  17. package/dist/src/pi.js +23 -0
  18. package/dist/src/pool.js +183 -0
  19. package/dist/src/registry.js +171 -0
  20. package/dist/src/schemas.js +134 -0
  21. package/dist/src/server.js +829 -0
  22. package/dist/src/session-lines.js +27 -0
  23. package/dist/src/skills-import.js +167 -0
  24. package/dist/src/spawn.js +39 -0
  25. package/dist/src/spawner.js +28 -0
  26. package/dist/src/workspace-files.js +93 -0
  27. package/dist/src/workspaces.js +81 -0
  28. package/package.json +60 -0
  29. package/web/dist/assets/index-BoKe95MT.js +12 -0
  30. package/web/dist/assets/index-SltX54ZZ.css +1 -0
  31. package/web/dist/assets/inter-cyrillic-400-normal-HOLc17fK.woff +0 -0
  32. package/web/dist/assets/inter-cyrillic-400-normal-obahsSVq.woff2 +0 -0
  33. package/web/dist/assets/inter-cyrillic-500-normal-BasfLYem.woff2 +0 -0
  34. package/web/dist/assets/inter-cyrillic-500-normal-CxZf_p3X.woff +0 -0
  35. package/web/dist/assets/inter-cyrillic-600-normal-4D_pXhcN.woff +0 -0
  36. package/web/dist/assets/inter-cyrillic-600-normal-CWCymEST.woff2 +0 -0
  37. package/web/dist/assets/inter-cyrillic-ext-400-normal-BQZuk6qB.woff2 +0 -0
  38. package/web/dist/assets/inter-cyrillic-ext-400-normal-DQukG94-.woff +0 -0
  39. package/web/dist/assets/inter-cyrillic-ext-500-normal-B0yAr1jD.woff2 +0 -0
  40. package/web/dist/assets/inter-cyrillic-ext-500-normal-BmqWE9Dz.woff +0 -0
  41. package/web/dist/assets/inter-cyrillic-ext-600-normal-Bcila6Z-.woff +0 -0
  42. package/web/dist/assets/inter-cyrillic-ext-600-normal-Dfes3d0z.woff2 +0 -0
  43. package/web/dist/assets/inter-greek-400-normal-B4URO6DV.woff2 +0 -0
  44. package/web/dist/assets/inter-greek-400-normal-q2sYcFCs.woff +0 -0
  45. package/web/dist/assets/inter-greek-500-normal-BIZE56-Y.woff2 +0 -0
  46. package/web/dist/assets/inter-greek-500-normal-Xzm54t5V.woff +0 -0
  47. package/web/dist/assets/inter-greek-600-normal-BZpKdvQh.woff +0 -0
  48. package/web/dist/assets/inter-greek-600-normal-plRanbMR.woff2 +0 -0
  49. package/web/dist/assets/inter-greek-ext-400-normal-DGGRlc-M.woff2 +0 -0
  50. package/web/dist/assets/inter-greek-ext-400-normal-KugGGMne.woff +0 -0
  51. package/web/dist/assets/inter-greek-ext-500-normal-2j5mBUwD.woff +0 -0
  52. package/web/dist/assets/inter-greek-ext-500-normal-C4iEst2y.woff2 +0 -0
  53. package/web/dist/assets/inter-greek-ext-600-normal-B8X0CLgF.woff +0 -0
  54. package/web/dist/assets/inter-greek-ext-600-normal-DRtmH8MT.woff2 +0 -0
  55. package/web/dist/assets/inter-latin-400-normal-C38fXH4l.woff2 +0 -0
  56. package/web/dist/assets/inter-latin-400-normal-CyCys3Eg.woff +0 -0
  57. package/web/dist/assets/inter-latin-500-normal-BL9OpVg8.woff +0 -0
  58. package/web/dist/assets/inter-latin-500-normal-Cerq10X2.woff2 +0 -0
  59. package/web/dist/assets/inter-latin-600-normal-CiBQ2DWP.woff +0 -0
  60. package/web/dist/assets/inter-latin-600-normal-LgqL8muc.woff2 +0 -0
  61. package/web/dist/assets/inter-latin-ext-400-normal-77YHD8bZ.woff +0 -0
  62. package/web/dist/assets/inter-latin-ext-400-normal-C1nco2VV.woff2 +0 -0
  63. package/web/dist/assets/inter-latin-ext-500-normal-BxGbmqWO.woff +0 -0
  64. package/web/dist/assets/inter-latin-ext-500-normal-CV4jyFjo.woff2 +0 -0
  65. package/web/dist/assets/inter-latin-ext-600-normal-CIVaiw4L.woff +0 -0
  66. package/web/dist/assets/inter-latin-ext-600-normal-D2bJ5OIk.woff2 +0 -0
  67. package/web/dist/assets/inter-vietnamese-400-normal-Bbgyi5SW.woff +0 -0
  68. package/web/dist/assets/inter-vietnamese-400-normal-DMkecbls.woff2 +0 -0
  69. package/web/dist/assets/inter-vietnamese-500-normal-DOriooB6.woff2 +0 -0
  70. package/web/dist/assets/inter-vietnamese-500-normal-mJboJaSs.woff +0 -0
  71. package/web/dist/assets/inter-vietnamese-600-normal-BuLX-rYi.woff +0 -0
  72. package/web/dist/assets/inter-vietnamese-600-normal-Cc8MFFhd.woff2 +0 -0
  73. package/web/dist/favicon.png +0 -0
  74. package/web/dist/icon.png +0 -0
  75. package/web/dist/index.html +16 -0
package/README.md ADDED
@@ -0,0 +1,44 @@
1
+ # Cogitator
2
+
3
+ **Panneau de contrôle web pour [pi](https://pi.dev)** — l'agent de coding en CLI.
4
+
5
+ Cogitator orchestre tes processus pi comme l'Adeptus Mechanicus pilote ses cogitateurs : des agents composables, des workspaces, des conversations libres et un cron — le tout configurable depuis un navigateur, sans quitter l'écosystème pi.
6
+
7
+ ## Ce que Cogitator fait
8
+
9
+ - **Agents composables** : un agent = `provider + modèle + thinking + skills + MCP + prompt de scope + subagents`. Chaque conversation pi est spawnée avec les flags natifs (`--model id:thinking`, `--no-skills --skill …`, `--append-system-prompt`, allowlist d'outils).
10
+ - **Workspaces** : un dossier sur disque = un workspace (aligné sur le modèle cwd-bound de pi), avec agent par défaut.
11
+ - **Conversations libres** : aucun workspace, provider/modèle ou agent choisi à la volée.
12
+ - **Cron** : tâches planifiées qui tirent un prompt contre un agent, résultat append dans une session dédiée, busy-guard anti-chevauchement.
13
+ - **Config pi complète** : providers (codex, claude, kimi…) lus/écrits via `models.json` / `auth.json`, skills scannés depuis les emplacements natifs, MCP user-level (`~/.pi/agent/mcp.json`).
14
+
15
+ ## Installation
16
+
17
+ ```sh
18
+ pi install npm:@ignitionai/cogitator
19
+ # puis dans pi :
20
+ /cogitator # démarre le serveur détaché et ouvre http://127.0.0.1:5320
21
+ ```
22
+
23
+ Ou standalone : `npx @ignitionai/cogitator`
24
+
25
+ ## État du projet
26
+
27
+ ✅ **MVP M0→M6 terminé** — serveur + extension + UI web. Voir [`docs/context/plans/active/0001-mvp.md`](docs/context/plans/active/0001-mvp.md) et [`docs/context/current-state.md`](docs/context/current-state.md).
28
+
29
+ ## UI web
30
+
31
+ 6 écrans : **Conversations** (chat streaming SSE, historique, stop, switch modèle), **Workspaces** (file-picker, agent par défaut), **Agents** (éditeur de presets complet + Apply herdr), **Providers** (read model pi + clés), **Cron** (tâches, runs, fire manuel), **Settings** (santé, MCP user-level).
32
+
33
+ Dev UI : `npm run dev:web` (vite sur 5321, proxy API → 5320).
34
+
35
+ ## Documentation
36
+
37
+ | Document | Contenu |
38
+ |---|---|
39
+ | [Domain Model](docs/architecture/domain-model.md) | Bounded contexts, entités, invariants, diagramme ER |
40
+ | [Blueprint](docs/architecture/blueprint.md) | Composants, process pool, spawn flags, cron, apply |
41
+ | [API Contract](docs/architecture/api-contract.md) | Endpoints REST + SSE |
42
+ | [Décisions (ADRs)](docs/context/decisions/) | Pourquoi ce design (7 ADRs + stack decision record) |
43
+ | [Plan MVP](docs/context/plans/active/0001-mvp.md) | Jalons M0 → M6 |
44
+ | [Context Index](docs/context/README.md) | Index durable du projet |
@@ -0,0 +1,63 @@
1
+ import { spawn } from "node:child_process";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { BASE_URL } from "../src/config.js";
5
+ import { decodeMcpEnv, MCP_ENV_VAR } from "../src/mcp-env.js";
6
+ // I4 : l'entry de l'extension ne démarre RIEN au load — uniquement la commande et
7
+ // l'enregistrement MCP (qui ne fait que déclarer des serveurs, le builtin connecte).
8
+ /** Attente du démarrage du serveur détaché : ~5 s au total. */
9
+ const STARTUP_ATTEMPTS = 50;
10
+ const STARTUP_POLL_MS = 100;
11
+ async function isUp() {
12
+ try {
13
+ const res = await fetch(`${BASE_URL}/api/health`);
14
+ return res.ok;
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ }
20
+ function openBrowser(url) {
21
+ const platform = process.platform;
22
+ const [cmd, args] = platform === "darwin"
23
+ ? ["open", [url]]
24
+ : platform === "win32"
25
+ ? ["cmd", ["/c", "start", url]]
26
+ : ["xdg-open", [url]];
27
+ spawn(cmd, args, { detached: true, stdio: "ignore" }).unref();
28
+ }
29
+ export default function (pi) {
30
+ // ADR-002 : les serveurs MCP du preset voyagent via env (COGITATOR_MCP) et sont
31
+ // enregistrés ici ; le support MCP builtin de pi les connecte au démarrage de session.
32
+ pi.on("session_start", () => {
33
+ const registrations = decodeMcpEnv(process.env[MCP_ENV_VAR]);
34
+ if (!registrations)
35
+ return;
36
+ for (const { name, config } of registrations) {
37
+ try {
38
+ // shape mcpServers validée à l'encodage ; le type exact de pi est plus étroit
39
+ pi.registerMcpServer(name, config);
40
+ }
41
+ catch (err) {
42
+ console.warn(`[cogitator] registerMcpServer ${name}:`, err instanceof Error ? err.message : err);
43
+ }
44
+ }
45
+ });
46
+ pi.registerCommand("cogitator", {
47
+ description: "Ouvrir le panneau de contrôle Cogitator (démarre le serveur si besoin)",
48
+ handler: async (_args, ctx) => {
49
+ if (!(await isUp())) {
50
+ const here = dirname(fileURLToPath(import.meta.url)); // dist/extensions
51
+ const entry = join(here, "..", "src", "cli.js");
52
+ spawn(process.execPath, [entry], { detached: true, stdio: "ignore" }).unref();
53
+ for (let i = 0; i < STARTUP_ATTEMPTS; i++) {
54
+ if (await isUp())
55
+ break;
56
+ await new Promise((resolve) => setTimeout(resolve, STARTUP_POLL_MS));
57
+ }
58
+ }
59
+ openBrowser(BASE_URL);
60
+ ctx.ui.notify(`Cogitator — ${BASE_URL}`, "info");
61
+ },
62
+ });
63
+ }
@@ -0,0 +1,238 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { SUBAGENT_NAME, THINKING_LEVELS } from "./schemas.js";
5
+ import { readCatalog } from "./registry.js";
6
+ // ---------- Slugs ----------
7
+ export function slugify(text) {
8
+ return (text
9
+ .normalize("NFD")
10
+ .replace(/[\u0300-\u036f]/g, "")
11
+ .toLowerCase()
12
+ .replace(/[^a-z0-9]+/g, "-")
13
+ .replace(/^-+|-+$/g, "")
14
+ .replace(/-{2,}/g, "-")
15
+ .slice(0, 64) || "agent");
16
+ }
17
+ const THINKING_SET = new Set(THINKING_LEVELS);
18
+ /** Narrowing à la frontière DB : valeur invalide → null (la validation métier est dans validateAgent). */
19
+ function parseThinking(value) {
20
+ return value !== null && THINKING_SET.has(value) ? value : null;
21
+ }
22
+ /** Colonnes JSON des lignes SQLite : toute valeur illisible retombe sur un défaut sûr. */
23
+ function parseJsonArray(raw, fallback) {
24
+ if (!raw)
25
+ return fallback;
26
+ try {
27
+ const parsed = JSON.parse(raw);
28
+ return Array.isArray(parsed) ? parsed : fallback;
29
+ }
30
+ catch {
31
+ return fallback;
32
+ }
33
+ }
34
+ function rowToPreset(row, subs) {
35
+ return {
36
+ id: row.id,
37
+ slug: row.slug,
38
+ name: row.name,
39
+ description: row.description,
40
+ provider: row.provider,
41
+ model: row.model,
42
+ thinking: parseThinking(row.thinking),
43
+ system_prompt: row.system_prompt,
44
+ skills: parseJsonArray(row.skills, []),
45
+ tools_allowlist: row.tools_allowlist ? parseJsonArray(row.tools_allowlist, []) : null,
46
+ mcp_servers: parseJsonArray(row.mcp_servers, []),
47
+ created_at: row.created_at,
48
+ updated_at: row.updated_at,
49
+ is_default: row.is_default,
50
+ subagents: subs.map((s) => ({
51
+ id: s.id,
52
+ name: s.name,
53
+ description: s.description,
54
+ provider: s.provider,
55
+ model: s.model,
56
+ thinking: parseThinking(s.thinking),
57
+ system_prompt: s.system_prompt,
58
+ skills: parseJsonArray(s.skills, []),
59
+ mcp_servers: parseJsonArray(s.mcp_servers, []),
60
+ })),
61
+ };
62
+ }
63
+ // ---------- CRUD ----------
64
+ /** Presets complets, subagents inclus : l'UI édite ces objets tels quels (un preset tronqué
65
+ * écraserait le prompt de scope et les subagents au save). */
66
+ export function listAgents(db) {
67
+ const rows = db.prepare("SELECT * FROM agent_preset ORDER BY is_default DESC, name").all();
68
+ const subsFor = db.prepare("SELECT * FROM subagent_setup WHERE agent_id = ? ORDER BY name");
69
+ return rows.map((r) => rowToPreset(r, subsFor.all(r.id)));
70
+ }
71
+ export function getDefaultAgentId(db) {
72
+ const row = db.prepare("SELECT id FROM agent_preset WHERE is_default = 1 LIMIT 1").get();
73
+ return row?.id ?? null;
74
+ }
75
+ /** Définit l'agent par défaut global (un seul — transaction). */
76
+ export function setDefaultAgent(db, id) {
77
+ const existing = getAgent(db, id);
78
+ if (!existing)
79
+ return false;
80
+ db.transaction(() => {
81
+ db.prepare("UPDATE agent_preset SET is_default = 0").run();
82
+ db.prepare("UPDATE agent_preset SET is_default = 1 WHERE id = ?").run(id);
83
+ })();
84
+ return true;
85
+ }
86
+ export function getAgent(db, id) {
87
+ const row = db.prepare("SELECT * FROM agent_preset WHERE id = ?").get(id);
88
+ if (!row)
89
+ return null;
90
+ const subs = db.prepare("SELECT * FROM subagent_setup WHERE agent_id = ? ORDER BY name").all(id);
91
+ return rowToPreset(row, subs);
92
+ }
93
+ function uniqueSlug(db, name, excludeId) {
94
+ const base = slugify(name);
95
+ let slug = base;
96
+ let n = 2;
97
+ while (db.prepare("SELECT 1 FROM agent_preset WHERE slug = ? AND id != ?").get(slug, excludeId ?? "")) {
98
+ slug = `${base}-${n++}`;
99
+ }
100
+ return slug;
101
+ }
102
+ export function createAgent(db, input) {
103
+ const id = randomUUID();
104
+ const slug = uniqueSlug(db, input.name);
105
+ const now = new Date().toISOString();
106
+ db.prepare(`INSERT INTO agent_preset (id, slug, name, description, provider, model, thinking, system_prompt, skills, tools_allowlist, mcp_servers, created_at, updated_at)
107
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, slug, input.name, input.description ?? "", input.provider, input.model, input.thinking ?? null, input.system_prompt ?? "", JSON.stringify(input.skills ?? []), input.tools_allowlist ? JSON.stringify(input.tools_allowlist) : null, JSON.stringify(input.mcp_servers ?? []), now, now);
108
+ replaceSubagents(db, id, input.subagents ?? []);
109
+ return getAgent(db, id);
110
+ }
111
+ export function updateAgent(db, id, input) {
112
+ const existing = getAgent(db, id);
113
+ if (!existing)
114
+ return null;
115
+ db.prepare(`UPDATE agent_preset SET slug = ?, name = ?, description = ?, provider = ?, model = ?, thinking = ?,
116
+ system_prompt = ?, skills = ?, tools_allowlist = ?, mcp_servers = ?, updated_at = ?
117
+ WHERE id = ?`).run(uniqueSlug(db, input.name, id), input.name, input.description ?? "", input.provider, input.model, input.thinking ?? null, input.system_prompt ?? "", JSON.stringify(input.skills ?? []), input.tools_allowlist ? JSON.stringify(input.tools_allowlist) : null, JSON.stringify(input.mcp_servers ?? []), new Date().toISOString(), id);
118
+ replaceSubagents(db, id, input.subagents ?? []);
119
+ return getAgent(db, id);
120
+ }
121
+ export function deleteAgent(db, id) {
122
+ const res = db.prepare("DELETE FROM agent_preset WHERE id = ?").run(id);
123
+ return res.changes > 0;
124
+ }
125
+ function replaceSubagents(db, agentId, subs) {
126
+ db.prepare("DELETE FROM subagent_setup WHERE agent_id = ?").run(agentId);
127
+ const insert = db.prepare(`INSERT INTO subagent_setup (id, agent_id, name, description, provider, model, thinking, system_prompt, skills, mcp_servers)
128
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
129
+ for (const s of subs) {
130
+ insert.run(randomUUID(), agentId, s.name, s.description ?? "", s.provider, s.model, s.thinking ?? null, s.system_prompt ?? "", JSON.stringify(s.skills ?? []), JSON.stringify(s.mcp_servers ?? []));
131
+ }
132
+ }
133
+ export async function validateAgent(paths, preset, checkAuth) {
134
+ const errors = [];
135
+ const warnings = [];
136
+ const catalog = readCatalog(paths);
137
+ const checkModel = (where, provider, model) => {
138
+ const models = catalog.get(provider);
139
+ if (!models) {
140
+ errors.push(`${where}: provider inconnu dans le catalogue pi: ${provider}`);
141
+ }
142
+ else if (!models.some((m) => m.id === model)) {
143
+ errors.push(`${where}: modèle ${model} inconnu pour ${provider}`);
144
+ }
145
+ };
146
+ if (!preset.name.trim())
147
+ errors.push("name requis");
148
+ checkModel("agent", preset.provider, preset.model);
149
+ if (preset.thinking && !THINKING_SET.has(preset.thinking))
150
+ errors.push(`thinking invalide: ${preset.thinking}`);
151
+ for (const skill of preset.skills ?? []) {
152
+ const p = skill.startsWith("~") ? join(process.env.HOME ?? "~", skill.slice(1)) : skill;
153
+ if (!existsSync(p))
154
+ errors.push(`skill introuvable: ${skill}`);
155
+ }
156
+ for (const m of preset.mcp_servers ?? []) {
157
+ if (!/^[A-Za-z0-9_-]+$/.test(m.name))
158
+ errors.push(`MCP: nom invalide ${m.name}`);
159
+ if (!m.command && !m.url)
160
+ errors.push(`MCP ${m.name}: command ou url requis`);
161
+ }
162
+ const ready = await checkAuth(preset.provider);
163
+ if (ready === false)
164
+ warnings.push(`provider ${preset.provider}: auth non prête (pi auth check)`);
165
+ if (ready === null)
166
+ warnings.push(`provider ${preset.provider}: statut auth indéterminé`);
167
+ const seen = new Set();
168
+ for (const sub of preset.subagents ?? []) {
169
+ if (!SUBAGENT_NAME.test(sub.name))
170
+ errors.push(`subagent: nom invalide ${sub.name} (minuscules, chiffres, -, _)`);
171
+ if (seen.has(sub.name))
172
+ errors.push(`subagent: nom dupliqué ${sub.name}`);
173
+ seen.add(sub.name);
174
+ checkModel(`subagent ${sub.name}`, sub.provider, sub.model);
175
+ }
176
+ return { errors, warnings };
177
+ }
178
+ // ---------- Apply → registre herdr (O1/O2 du contrat) ----------
179
+ function subagentFileName(agentSlug, subName) {
180
+ return `noo-${agentSlug}-${subName}.md`;
181
+ }
182
+ function renderSubagent(sub, agentSlug) {
183
+ const lines = [
184
+ "---",
185
+ `name: noo-${agentSlug}-${sub.name}`,
186
+ `description: ${(sub.description ?? "").replace(/\n/g, " ")}`,
187
+ "kind: pi",
188
+ `model: ${sub.provider}/${sub.model}`,
189
+ ];
190
+ if (sub.thinking)
191
+ lines.push(`thinking: ${sub.thinking}`);
192
+ if (sub.skills?.length)
193
+ lines.push(`skills: ${JSON.stringify(sub.skills)}`);
194
+ lines.push("---", "", sub.system_prompt ?? "");
195
+ return { file: subagentFileName(agentSlug, sub.name), content: lines.join("\n") + "\n" };
196
+ }
197
+ export function applyAgent(paths, preset) {
198
+ mkdirSync(paths.piAgentsDir, { recursive: true });
199
+ const prefix = `noo-${preset.slug}-`;
200
+ const desired = new Map();
201
+ for (const sub of preset.subagents) {
202
+ const { file, content } = renderSubagent(sub, preset.slug);
203
+ desired.set(file, content);
204
+ }
205
+ const written = [];
206
+ const deleted = [];
207
+ for (const [file, content] of desired) {
208
+ const path = join(paths.piAgentsDir, file);
209
+ const existing = existsSync(path) ? readFileSync(path, "utf8") : null;
210
+ if (existing !== content) {
211
+ writeFileSync(path, content);
212
+ written.push(file);
213
+ }
214
+ }
215
+ for (const entry of readdirSync(paths.piAgentsDir)) {
216
+ if (!entry.startsWith(prefix) || !entry.endsWith(".md"))
217
+ continue; // O2 : on ne touche qu'à nos fichiers
218
+ if (!desired.has(entry)) {
219
+ rmSync(join(paths.piAgentsDir, entry));
220
+ deleted.push(entry);
221
+ }
222
+ }
223
+ return { written, deleted };
224
+ }
225
+ /** Supprime les définitions herdr d'un preset supprimé (uniquement ses fichiers noo-<slug>-*). */
226
+ export function unapplyAgent(paths, slug) {
227
+ if (!existsSync(paths.piAgentsDir))
228
+ return [];
229
+ const prefix = `noo-${slug}-`;
230
+ const deleted = [];
231
+ for (const entry of readdirSync(paths.piAgentsDir)) {
232
+ if (entry.startsWith(prefix) && entry.endsWith(".md")) {
233
+ rmSync(join(paths.piAgentsDir, entry));
234
+ deleted.push(entry);
235
+ }
236
+ }
237
+ return deleted;
238
+ }
@@ -0,0 +1,277 @@
1
+ import { execFile } from "node:child_process";
2
+ import { join } from "node:path";
3
+ import { readJson, atomicWriteJson } from "./json-files.js";
4
+ import { CARD_PRIORITIES, CARD_STATUSES } from "./schemas.js";
5
+ const STATUSES = CARD_STATUSES;
6
+ const PRIORITIES = CARD_PRIORITIES;
7
+ /** Statuts/priorités viennent des schémas zod : les predicats gardent le narrowing côté TS. */
8
+ function isStatus(value) {
9
+ return STATUSES.includes(value);
10
+ }
11
+ function isPriority(value) {
12
+ return PRIORITIES.includes(value);
13
+ }
14
+ export function boardPath(wsDir) {
15
+ return join(wsDir, "cogitator.board.json");
16
+ }
17
+ // ---------- gh ----------
18
+ const GH_TIMEOUT_MS = 20_000;
19
+ const GH_QUICK_TIMEOUT_MS = 10_000;
20
+ const GH_MAX_BUFFER = 8 * 1024 * 1024;
21
+ const GH_ERROR_MAX = 300;
22
+ const GH_ISSUE_LIMIT = 200;
23
+ function gh(wsDir, args, timeoutMs = GH_TIMEOUT_MS) {
24
+ return new Promise((resolve) => {
25
+ execFile("gh", args, { cwd: wsDir, timeout: timeoutMs, maxBuffer: GH_MAX_BUFFER }, (err, stdout, stderr) => {
26
+ resolve({ ok: !err, stdout: String(stdout), stderr: String(stderr).trim() });
27
+ });
28
+ });
29
+ }
30
+ /** Erreur gh homogène et tronquée (les sorties gh peuvent être longues). */
31
+ function ghError(action, r) {
32
+ return { error: `${action}: ${r.stderr || r.stdout}`.slice(0, GH_ERROR_MAX) };
33
+ }
34
+ async function listIssues(wsDir) {
35
+ const r = await gh(wsDir, [
36
+ "issue", "list", "--state", "all", "--limit", String(GH_ISSUE_LIMIT),
37
+ "--json", "number,title,body,state,labels,url,createdAt,updatedAt",
38
+ ]);
39
+ if (!r.ok)
40
+ return { error: `gh inaccessible ou repo sans remote : ${r.stderr || r.stdout}`.slice(0, GH_ERROR_MAX) };
41
+ try {
42
+ return { issues: JSON.parse(r.stdout) };
43
+ }
44
+ catch {
45
+ return { error: "sortie gh inattendue (issue list)" };
46
+ }
47
+ }
48
+ // ---------- mapping ----------
49
+ export function statusFromIssue(issue) {
50
+ if (issue.state === "CLOSED") {
51
+ return issue.labels.some((l) => l.name === "status:canceled") ? "canceled" : "done";
52
+ }
53
+ const found = issue.labels.find((l) => l.name.startsWith("status:"))?.name.slice("status:".length);
54
+ return found && isStatus(found) ? found : "todo";
55
+ }
56
+ export function priorityFromIssue(issue) {
57
+ const found = issue.labels.find((l) => l.name.startsWith("priority:"))?.name.slice("priority:".length);
58
+ return found && isPriority(found) ? found : "medium";
59
+ }
60
+ const USER_LABELS_MAX = 8;
61
+ function userLabels(issue) {
62
+ return issue.labels
63
+ .map((l) => l.name)
64
+ .filter((n) => !n.startsWith("status:") && !n.startsWith("priority:"))
65
+ .slice(0, USER_LABELS_MAX);
66
+ }
67
+ function mergeCard(issue, extras) {
68
+ return {
69
+ id: String(issue.number),
70
+ number: issue.number,
71
+ url: issue.url,
72
+ title: issue.title,
73
+ description: issue.body ?? "",
74
+ status: statusFromIssue(issue),
75
+ priority: priorityFromIssue(issue),
76
+ labels: userLabels(issue),
77
+ assignee_agent_id: extras?.assignee_agent_id ?? null,
78
+ conversation_ids: extras?.conversation_ids ?? [],
79
+ blocks: extras?.blocks ?? [],
80
+ blocked_by: extras?.blocked_by ?? [],
81
+ github_issue: issue.number,
82
+ comments: extras?.comments ?? [],
83
+ created_at: issue.createdAt,
84
+ updated_at: issue.updatedAt,
85
+ };
86
+ }
87
+ // ---------- sidecar ----------
88
+ function readSidecar(wsDir) {
89
+ const raw = readJson(boardPath(wsDir), { version: 2, extras: {} });
90
+ if (raw.version === 2 && typeof raw.extras === "object")
91
+ return raw;
92
+ return { version: 2, extras: {} }; // v1 ou invalide : on repart sur un sidecar vide (migration gérée par GitHub)
93
+ }
94
+ function saveSidecar(wsDir, sidecar) {
95
+ atomicWriteJson(boardPath(wsDir), sidecar);
96
+ }
97
+ /** Extras Cogitator d'une carte (clé = numéro d'issue). */
98
+ function readExtras(wsDir, number) {
99
+ return readSidecar(wsDir).extras[String(number)];
100
+ }
101
+ // ---------- API publique ----------
102
+ /** Liste les cartes = issues GitHub + extras sidecar. */
103
+ export async function listCards(wsDir) {
104
+ const listed = await listIssues(wsDir);
105
+ if ("error" in listed)
106
+ return { error: listed.error };
107
+ const sidecar = readSidecar(wsDir);
108
+ const cards = listed.issues.map((i) => mergeCard(i, sidecar.extras[String(i.number)]));
109
+ cards.sort((a, b) => b.updated_at.localeCompare(a.updated_at));
110
+ return { cards };
111
+ }
112
+ function targetLabels(write) {
113
+ const status = write.status ?? "backlog";
114
+ const priority = write.priority ?? "medium";
115
+ return [`status:${status}`, `priority:${priority}`, ...(write.labels ?? [])];
116
+ }
117
+ async function ensureOpenState(wsDir, number, status) {
118
+ if (status === "done" || status === "canceled") {
119
+ await gh(wsDir, ["issue", "close", String(number)]);
120
+ }
121
+ else {
122
+ await gh(wsDir, ["issue", "reopen", String(number)]);
123
+ }
124
+ }
125
+ const LABEL_COLOR_SYSTEM = "5e6ad2";
126
+ const LABEL_COLOR_USER = "8a8f98";
127
+ const LABELS_ENSURED = new Set();
128
+ /** Crée les labels manquants sur le repo (idempotent). Les labels système ne sont recréés
129
+ * qu'une fois par workspace et par process ; les labels carte sont assurés à chaque écriture. */
130
+ async function ensureLabels(wsDir, cardLabels = []) {
131
+ if (!LABELS_ENSURED.has(wsDir)) {
132
+ const system = [
133
+ ...STATUSES.map((s) => `status:${s}`),
134
+ ...PRIORITIES.map((p) => `priority:${p}`),
135
+ ];
136
+ for (const name of system) {
137
+ await gh(wsDir, ["label", "create", name, "--force", "--color", LABEL_COLOR_SYSTEM], GH_QUICK_TIMEOUT_MS);
138
+ }
139
+ LABELS_ENSURED.add(wsDir);
140
+ }
141
+ for (const name of cardLabels) {
142
+ await gh(wsDir, ["label", "create", name, "--force", "--color", LABEL_COLOR_USER], GH_QUICK_TIMEOUT_MS);
143
+ }
144
+ }
145
+ export async function createCardGh(wsDir, write) {
146
+ // gh issue create n'a pas --json : l'URL de la nouvelle issue est imprimée sur stdout
147
+ await ensureLabels(wsDir, write.labels ?? []);
148
+ const r = await gh(wsDir, [
149
+ "issue", "create", "--title", write.title,
150
+ "--body", write.description ?? "",
151
+ ...targetLabels(write).flatMap((l) => ["--label", l]),
152
+ ]);
153
+ if (!r.ok)
154
+ return ghError("gh issue create a échoué", r);
155
+ const urlMatch = r.stdout.trim().match(/\/issues\/(\d+)/);
156
+ if (!urlMatch)
157
+ return { error: `URL d'issue introuvable dans la sortie gh : ${r.stdout.slice(0, GH_ERROR_MAX)}` };
158
+ const number = Number(urlMatch[1]);
159
+ const now = new Date().toISOString();
160
+ const issue = {
161
+ number,
162
+ title: write.title,
163
+ body: write.description ?? "",
164
+ state: "OPEN",
165
+ labels: targetLabels(write).map((name) => ({ name })),
166
+ url: r.stdout.trim().split("\n").pop(),
167
+ createdAt: now,
168
+ updatedAt: now,
169
+ };
170
+ const sidecar = readSidecar(wsDir);
171
+ sidecar.extras[String(issue.number)] = {
172
+ assignee_agent_id: write.assignee_agent_id ?? null,
173
+ conversation_ids: write.conversation_ids ?? [],
174
+ blocks: write.blocks ?? [],
175
+ blocked_by: write.blocked_by ?? [],
176
+ comments: [],
177
+ };
178
+ saveSidecar(wsDir, sidecar);
179
+ return { card: mergeCard(issue, sidecar.extras[String(issue.number)]) };
180
+ }
181
+ export async function updateCardGh(wsDir, number, write) {
182
+ const listed = await listIssues(wsDir);
183
+ if ("error" in listed)
184
+ return { error: listed.error };
185
+ const issue = listed.issues.find((i) => i.number === number);
186
+ if (!issue)
187
+ return { error: `issue #${number} introuvable` };
188
+ const current = mergeCard(issue, readExtras(wsDir, number));
189
+ const next = {
190
+ title: write.title ?? current.title,
191
+ description: write.description ?? current.description,
192
+ status: write.status ?? current.status,
193
+ priority: write.priority ?? current.priority,
194
+ labels: write.labels ?? current.labels,
195
+ };
196
+ // labels : différence add/remove
197
+ const wanted = new Set(targetLabels(next));
198
+ const have = new Set(issue.labels.map((l) => l.name));
199
+ const add = [...wanted].filter((l) => !have.has(l));
200
+ const remove = [...have].filter((l) => l.startsWith("status:") || l.startsWith("priority:")).filter((l) => !wanted.has(l));
201
+ const args = ["issue", "edit", String(number), "--title", next.title, "--body", next.description];
202
+ for (const l of add)
203
+ args.push("--add-label", l);
204
+ for (const l of remove)
205
+ args.push("--remove-label", l);
206
+ await ensureLabels(wsDir, next.labels);
207
+ const r = await gh(wsDir, args);
208
+ if (!r.ok)
209
+ return ghError("gh issue edit a échoué", r);
210
+ await ensureOpenState(wsDir, number, next.status);
211
+ // extras sidecar
212
+ const sidecar = readSidecar(wsDir);
213
+ const extras = sidecar.extras[String(number)] ?? { comments: [] };
214
+ if (write.assignee_agent_id !== undefined)
215
+ extras.assignee_agent_id = write.assignee_agent_id;
216
+ if (write.conversation_ids !== undefined)
217
+ extras.conversation_ids = write.conversation_ids;
218
+ if (write.blocks !== undefined)
219
+ extras.blocks = write.blocks.filter((id) => id !== String(number));
220
+ if (write.blocked_by !== undefined)
221
+ extras.blocked_by = write.blocked_by.filter((id) => id !== String(number));
222
+ sidecar.extras[String(number)] = extras;
223
+ saveSidecar(wsDir, sidecar);
224
+ const relisted = await listIssues(wsDir);
225
+ if ("error" in relisted)
226
+ return { error: relisted.error };
227
+ const updated = relisted.issues.find((i) => i.number === number);
228
+ if (!updated)
229
+ return { error: `issue #${number} introuvable` };
230
+ return { card: mergeCard(updated, sidecar.extras[String(number)]) };
231
+ }
232
+ export async function moveCardGh(wsDir, number, status) {
233
+ if (!isStatus(status))
234
+ return { error: `statut invalide: ${status}` };
235
+ const listed = await listIssues(wsDir);
236
+ if ("error" in listed)
237
+ return { error: listed.error };
238
+ const issue = listed.issues.find((i) => i.number === number);
239
+ if (!issue)
240
+ return { error: `issue #${number} introuvable` };
241
+ const current = mergeCard(issue, readExtras(wsDir, number));
242
+ return updateCardGh(wsDir, number, { status, priority: current.priority, labels: current.labels });
243
+ }
244
+ const COMMENTS_MAX = 100;
245
+ export async function addCommentGh(wsDir, number, text, author = "user") {
246
+ // commentaire GitHub (visible par tous) + copie locale dans le sidecar pour l'UI
247
+ const r = await gh(wsDir, ["issue", "comment", String(number), "--body", `_${author}_ (via Cogitator) :\n${text}`]);
248
+ if (!r.ok)
249
+ return ghError("gh issue comment a échoué", r);
250
+ const sidecar = readSidecar(wsDir);
251
+ const extras = sidecar.extras[String(number)] ?? {};
252
+ const comment = { id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, author, text, at: new Date().toISOString() };
253
+ extras.comments = [...(extras.comments ?? []), comment].slice(-COMMENTS_MAX);
254
+ sidecar.extras[String(number)] = extras;
255
+ saveSidecar(wsDir, sidecar);
256
+ const listed = await listIssues(wsDir);
257
+ if ("error" in listed)
258
+ return { error: listed.error };
259
+ const issue = listed.issues.find((i) => i.number === number);
260
+ if (!issue)
261
+ return { error: `issue #${number} introuvable` };
262
+ return { card: mergeCard(issue, extras) };
263
+ }
264
+ /** "Suppression" = fermeture de l'issue (GitHub ne supprime pas) + nettoyage du sidecar et des relations. */
265
+ export async function closeCardGh(wsDir, number) {
266
+ const r = await gh(wsDir, ["issue", "close", String(number), "--comment", "Fermé via Cogitator"]);
267
+ if (!r.ok)
268
+ return ghError("gh issue close a échoué", r);
269
+ const sidecar = readSidecar(wsDir);
270
+ delete sidecar.extras[String(number)];
271
+ for (const extras of Object.values(sidecar.extras)) {
272
+ extras.blocks = (extras.blocks ?? []).filter((id) => id !== String(number));
273
+ extras.blocked_by = (extras.blocked_by ?? []).filter((id) => id !== String(number));
274
+ }
275
+ saveSidecar(wsDir, sidecar);
276
+ return { ok: true };
277
+ }