@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
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env node
2
+ import { EventEmitter } from "node:events";
3
+ import { mkdirSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { getPackageDir, RpcClient } from "@earendil-works/pi-coding-agent";
6
+ import { HOST, PORT } from "./config.js";
7
+ import { CronService } from "./cron.js";
8
+ import { setConversationStatus } from "./conversations.js";
9
+ import { seedDefaultAgents } from "./default-agent.js";
10
+ import { openDb } from "./db.js";
11
+ import { getPaths } from "./paths.js";
12
+ import { PiPool } from "./pool.js";
13
+ import { createApp } from "./server.js";
14
+ import { makeSpawner } from "./spawner.js";
15
+ const paths = getPaths();
16
+ mkdirSync(paths.home, { recursive: true });
17
+ const { db, version } = openDb(paths.db);
18
+ /** Cadences du service (bornes nommées : un chiffre nu ici est une décision, pas un détail). */
19
+ const SWEEP_INTERVAL_MS = 60_000;
20
+ const CRON_TICK_MS = 30_000;
21
+ // Seed des agents par défaut : Majordome (opérateur) + Chef de Projet (PM)
22
+ {
23
+ const seeded = seedDefaultAgents(db, paths);
24
+ if (seeded.majordome)
25
+ console.log("[cogitator] agent par défaut créé : Majordome");
26
+ if (seeded.chef)
27
+ console.log("[cogitator] agent créé : Chef de Projet");
28
+ if (seeded.architecte)
29
+ console.log("[cogitator] agent créé : Architecte de Skills");
30
+ }
31
+ // I3 : tout spawn passe par ce pool (factory RpcClient officiel, cli.js du pi résolu)
32
+ const factory = (opts) => new RpcClient({ cliPath: join(getPackageDir(), "dist/cli.js"), cwd: opts.cwd, args: opts.args, env: opts.env });
33
+ const pool = new PiPool({
34
+ factory,
35
+ callbacks: { onStatus: (convId, status) => setConversationStatus(db, convId, status) },
36
+ });
37
+ const events = new EventEmitter();
38
+ const spawner = makeSpawner({ db, pool, paths });
39
+ const cron = new CronService({
40
+ db, pool, spawner,
41
+ notify: (event) => events.emit("event", event),
42
+ });
43
+ const server = createApp({ db, dbPath: paths.db, dbVersion: version, paths, pool, cron, events });
44
+ server.listen(PORT, HOST, () => {
45
+ console.log(`[cogitator] http://${HOST}:${PORT}`);
46
+ console.log(`[cogitator] data: ${paths.home}`);
47
+ console.log(`[cogitator] pi agents: ${paths.piAgentsDir}`);
48
+ });
49
+ server.on("error", (err) => {
50
+ if (err.code === "EADDRINUSE") {
51
+ console.error(`[cogitator] port ${PORT} déjà utilisé — Cogitator tourne déjà ? (COGITATOR_PORT pour changer)`);
52
+ process.exit(1);
53
+ }
54
+ throw err;
55
+ });
56
+ // Recyclage idle toutes les minutes
57
+ const sweeper = setInterval(() => {
58
+ pool.sweep().catch(() => undefined);
59
+ }, SWEEP_INTERVAL_MS);
60
+ cron.start(CRON_TICK_MS);
61
+ async function shutdown() {
62
+ clearInterval(sweeper);
63
+ cron.stop();
64
+ await pool.dispose();
65
+ server.close();
66
+ db.close();
67
+ process.exit(0);
68
+ }
69
+ for (const sig of ["SIGINT", "SIGTERM"]) {
70
+ process.on(sig, () => void shutdown());
71
+ }
@@ -0,0 +1,7 @@
1
+ /** Config partagée par les trois points d'entrée (serveur, extension pi, serveur MCP). */
2
+ export const HOST = "127.0.0.1";
3
+ const DEFAULT_PORT = 5320;
4
+ /** Port d'écoute du serveur HTTP (COGITATOR_PORT pour changer). */
5
+ export const PORT = Number(process.env.COGITATOR_PORT ?? DEFAULT_PORT);
6
+ /** URL de base du serveur local — COGITATOR_URL l'emporte (ex. autre port/hôte). */
7
+ export const BASE_URL = process.env.COGITATOR_URL ?? `http://${HOST}:${PORT}`;
@@ -0,0 +1,41 @@
1
+ import { randomUUID } from "node:crypto";
2
+ /** Longueur max du titre dérivé d'un message (contrainte d'affichage de l'UI). */
3
+ const TITLE_MAX = 80;
4
+ export function listConversations(db, workspaceId) {
5
+ const sql = `
6
+ SELECT c.*, w.dir AS workspace_dir FROM conversation c
7
+ LEFT JOIN workspace w ON w.id = c.workspace_id
8
+ ${workspaceId ? "WHERE c.workspace_id = ?" : ""}
9
+ ORDER BY c.updated_at DESC`;
10
+ return (workspaceId
11
+ ? db.prepare(sql).all(workspaceId)
12
+ : db.prepare(sql).all());
13
+ }
14
+ export function getConversation(db, id) {
15
+ const row = db
16
+ .prepare(`SELECT c.*, w.dir AS workspace_dir FROM conversation c
17
+ LEFT JOIN workspace w ON w.id = c.workspace_id WHERE c.id = ?`)
18
+ .get(id);
19
+ return row ?? null;
20
+ }
21
+ export function createConversation(db, input) {
22
+ const id = randomUUID();
23
+ db.prepare(`INSERT INTO conversation (id, workspace_id, agent_id, provider, model, thinking, spawn_args, status)
24
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'idle')`).run(id, input.workspaceId ?? null, input.agentId ?? null, input.spawn.provider, input.spawn.model, input.spawn.thinking ?? null, JSON.stringify(input.spawn));
25
+ return getConversation(db, id);
26
+ }
27
+ export function setConversationStatus(db, id, status) {
28
+ db.prepare("UPDATE conversation SET status = ?, updated_at = datetime('now') WHERE id = ?").run(status, id);
29
+ }
30
+ export function setConversationSession(db, id, sessionFile) {
31
+ db.prepare("UPDATE conversation SET session_file = ?, updated_at = datetime('now') WHERE id = ?").run(sessionFile, id);
32
+ }
33
+ export function setConversationTitle(db, id, title) {
34
+ db.prepare("UPDATE conversation SET title = CASE WHEN title = '' THEN ? ELSE title END, updated_at = datetime('now') WHERE id = ?").run(title.slice(0, TITLE_MAX), id);
35
+ }
36
+ export function setConversationModel(db, id, provider, model, spawn) {
37
+ db.prepare("UPDATE conversation SET provider = ?, model = ?, spawn_args = ?, updated_at = datetime('now') WHERE id = ?").run(provider, model, JSON.stringify(spawn), id);
38
+ }
39
+ export function deleteConversation(db, id) {
40
+ return db.prepare("DELETE FROM conversation WHERE id = ?").run(id).changes > 0;
41
+ }
@@ -0,0 +1,227 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { CronExpressionParser } from "cron-parser";
3
+ import { getAgent } from "./agents.js";
4
+ import { createConversation, getConversation } from "./conversations.js";
5
+ import { spawnConfigFromPreset } from "./spawn.js";
6
+ /** Bornes du service (surchargeables par les options pour les tests). */
7
+ const DEFAULT_RUN_TIMEOUT_MS = 15 * 60_000;
8
+ const DEFAULT_TICK_MS = 30_000;
9
+ /** busy_policy=queue : on attend la fin du run actif, avec garde-fou. */
10
+ const QUEUE_POLL_MS = 2_000;
11
+ const QUEUE_WAIT_MAX_MS = 10 * 60_000;
12
+ // ---------- DB ops ----------
13
+ export function listTasks(db) {
14
+ const rows = db.prepare("SELECT * FROM cron_task ORDER BY name").all();
15
+ return rows.map((t) => ({ ...t, next_run_at: nextAfter(t)?.toISOString() ?? null }));
16
+ }
17
+ export function getTask(db, id) {
18
+ return db.prepare("SELECT * FROM cron_task WHERE id = ?").get(id) ?? null;
19
+ }
20
+ export function validateCronExpr(expr) {
21
+ try {
22
+ CronExpressionParser.parse(expr);
23
+ return true;
24
+ }
25
+ catch {
26
+ return false;
27
+ }
28
+ }
29
+ export function nextAfter(task, from = new Date()) {
30
+ try {
31
+ const base = task.last_run_at ? new Date(task.last_run_at) : new Date(task.created_at);
32
+ if (Number.isNaN(base.getTime()))
33
+ return null;
34
+ // itérateur positionné sur la dernière exécution ; next() donne l'occurrence suivante
35
+ const it = CronExpressionParser.parse(task.cron_expr, { currentDate: base > from ? from : base });
36
+ return it.next().toDate();
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ export function createTask(db, input) {
43
+ if (!input.name?.trim())
44
+ return { error: "name requis" };
45
+ if (!validateCronExpr(input.cron_expr))
46
+ return { error: `expression cron invalide: ${input.cron_expr}` };
47
+ if (!input.prompt?.trim())
48
+ return { error: "prompt requis" };
49
+ if (!db.prepare("SELECT 1 FROM agent_preset WHERE id = ?").get(input.agent_id))
50
+ return { error: "agent introuvable" };
51
+ if (!db.prepare("SELECT 1 FROM workspace WHERE id = ?").get(input.workspace_id))
52
+ return { error: "workspace introuvable" };
53
+ const id = randomUUID();
54
+ db.prepare(`INSERT INTO cron_task (id, name, cron_expr, prompt, agent_id, workspace_id, output_policy, busy_policy, catchup)
55
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, input.name.trim(), input.cron_expr, input.prompt, input.agent_id, input.workspace_id, input.output_policy ?? "append_session", input.busy_policy ?? "skip", input.catchup ? 1 : 0);
56
+ return { task: getTask(db, id) };
57
+ }
58
+ export function updateTask(db, id, input) {
59
+ const t = getTask(db, id);
60
+ if (!t)
61
+ return null;
62
+ if (input.cron_expr !== undefined && !validateCronExpr(input.cron_expr))
63
+ return null;
64
+ db.prepare(`UPDATE cron_task SET name = ?, cron_expr = ?, prompt = ?, output_policy = ?, busy_policy = ?,
65
+ catchup = ?, enabled = ?, last_run_at = ? WHERE id = ?`).run(input.name ?? t.name, input.cron_expr ?? t.cron_expr, input.prompt ?? t.prompt, input.output_policy ?? t.output_policy, input.busy_policy ?? t.busy_policy, input.catchup === undefined ? t.catchup : input.catchup ? 1 : 0, input.enabled === undefined ? t.enabled : input.enabled ? 1 : 0, input.cron_expr !== undefined || input.enabled !== undefined ? null : t.last_run_at, // reclock si expr change
66
+ id);
67
+ return getTask(db, id);
68
+ }
69
+ export function deleteTask(db, id) {
70
+ return db.prepare("DELETE FROM cron_task WHERE id = ?").run(id).changes > 0; // runs en CASCADE (suppression = purge de l'historique de la tâche)
71
+ }
72
+ export function listRuns(db, taskId, limit = 50) {
73
+ return db
74
+ .prepare("SELECT * FROM cron_run WHERE task_id = ? ORDER BY started_at DESC LIMIT ?")
75
+ .all(taskId, limit);
76
+ }
77
+ function runningRunFor(db, taskId) {
78
+ return db.prepare("SELECT * FROM cron_run WHERE task_id = ? AND status = 'running' ORDER BY started_at DESC LIMIT 1").get(taskId) ?? null;
79
+ }
80
+ function createRun(db, taskId) {
81
+ const id = randomUUID();
82
+ db.prepare("INSERT INTO cron_run (id, task_id) VALUES (?, ?)").run(id, taskId);
83
+ return id;
84
+ }
85
+ function finishRun(db, runId, status, sessionFile, error) {
86
+ db.prepare(`UPDATE cron_run SET finished_at = datetime('now'), status = ?, session_file = COALESCE(?, session_file), error = ?
87
+ WHERE id = ? AND status = 'running'`).run(status, sessionFile ?? null, error ?? null, runId);
88
+ }
89
+ function sleep(ms) {
90
+ return new Promise((r) => setTimeout(r, ms));
91
+ }
92
+ /** busy_policy : un run 'running' déjà en base (crash, autre instance) bloque le nouveau.
93
+ * Renvoie false quand le run courant a été tracé comme `skipped` (il ne doit pas s'exécuter). */
94
+ async function applyBusyPolicy(db, task, runId) {
95
+ const stale = runningRunFor(db, task.id);
96
+ if (!stale || stale.id === runId)
97
+ return true;
98
+ if (task.busy_policy === "skip") {
99
+ finishRun(db, runId, "skipped", null, `run ${stale.id} encore actif (policy skip)`);
100
+ return false;
101
+ }
102
+ if (task.busy_policy === "kill") {
103
+ finishRun(db, stale.id, "killed", null, "supplanté par un nouveau run");
104
+ }
105
+ // queue : attendre la fin du run actif (garde-fou : QUEUE_WAIT_MAX_MS)
106
+ const deadline = Date.now() + QUEUE_WAIT_MAX_MS;
107
+ while (runningRunFor(db, task.id) && Date.now() < deadline)
108
+ await sleep(QUEUE_POLL_MS);
109
+ return true;
110
+ }
111
+ /** Dernière session connue de la tâche (output_policy=append_session la reprend). */
112
+ function lastSessionFile(db, taskId) {
113
+ const last = db
114
+ .prepare(`SELECT session_file FROM cron_run
115
+ WHERE task_id = ? AND session_file IS NOT NULL
116
+ ORDER BY started_at DESC LIMIT 1`)
117
+ .get(taskId);
118
+ return last?.session_file ?? null;
119
+ }
120
+ // ---------- Service ----------
121
+ export class CronService {
122
+ opts;
123
+ timer = null;
124
+ firing = new Set(); // garde anti-recouvrement dans un tick
125
+ constructor(opts) {
126
+ this.opts = opts;
127
+ }
128
+ /** Boucle de tick ; appelée par le timer et testable directement. */
129
+ async tick(now = new Date()) {
130
+ const { db } = this.opts;
131
+ const tasks = db.prepare("SELECT * FROM cron_task WHERE enabled = 1").all();
132
+ for (const task of tasks) {
133
+ if (this.firing.has(task.id))
134
+ continue;
135
+ const next = nextAfter(task, now);
136
+ if (!next || next > now)
137
+ continue;
138
+ if (!task.catchup) {
139
+ // rattrapage désactivé : on avance au prochain créneau sans exécuter
140
+ db.prepare("UPDATE cron_task SET last_run_at = ? WHERE id = ?").run(now.toISOString(), task.id);
141
+ continue;
142
+ }
143
+ void this.fireNow(task.id).catch(() => undefined);
144
+ }
145
+ }
146
+ start(intervalMs = DEFAULT_TICK_MS) {
147
+ if (this.timer)
148
+ return;
149
+ this.timer = setInterval(() => this.tick().catch(() => undefined), intervalMs);
150
+ }
151
+ stop() {
152
+ if (this.timer)
153
+ clearInterval(this.timer);
154
+ this.timer = null;
155
+ }
156
+ /** Tire une exécution (manuelle ou planifiée). Crée toujours un CronRun (O3). */
157
+ async fireNow(taskId) {
158
+ const { db, spawner, pool } = this.opts;
159
+ const task = getTask(db, taskId);
160
+ if (!task)
161
+ return null;
162
+ if (this.firing.has(taskId)) {
163
+ // déjà en cours dans ce process : skip tracé
164
+ const runId = createRun(db, taskId);
165
+ finishRun(db, runId, "skipped", null, "tâche déjà en cours dans ce process");
166
+ return this.getRun(runId);
167
+ }
168
+ this.firing.add(taskId);
169
+ const runId = createRun(db, taskId);
170
+ db.prepare("UPDATE cron_task SET last_run_at = ? WHERE id = ?").run(new Date().toISOString(), taskId);
171
+ this.opts.notify?.({ type: "cron_run_started", taskId, runId, name: task.name });
172
+ let convId = null;
173
+ try {
174
+ if (!(await applyBusyPolicy(db, task, runId)))
175
+ return this.getRun(runId);
176
+ const preset = task.agent_id ? getAgent(db, task.agent_id) : null;
177
+ if (!preset) {
178
+ finishRun(db, runId, "error", null, "agent introuvable (supprimé ?)");
179
+ return this.getRun(runId);
180
+ }
181
+ const conv = this.createRunConversation(task, preset);
182
+ convId = conv.id;
183
+ await spawner.ensure(conv);
184
+ // s'abonner AVANT de prompt : un LLM rapide peut settled avant l'abonnement sinon
185
+ const settled = pool.waitForSettled(conv.id, this.opts.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS);
186
+ await pool.prompt(conv.id, task.prompt);
187
+ await settled;
188
+ const finalConv = db.prepare("SELECT session_file FROM conversation WHERE id = ?").get(conv.id);
189
+ finishRun(db, runId, "ok", finalConv.session_file);
190
+ this.opts.notify?.({ type: "cron_run_finished", taskId, runId, name: task.name, status: "ok", sessionFile: finalConv.session_file });
191
+ return this.getRun(runId);
192
+ }
193
+ catch (err) {
194
+ const message = err instanceof Error ? err.message : String(err);
195
+ const status = message.includes("timeout") ? "timeout" : "error";
196
+ finishRun(db, runId, status, null, message);
197
+ this.opts.notify?.({ type: "cron_run_finished", taskId, runId, name: task.name, status, error: message });
198
+ return this.getRun(runId);
199
+ }
200
+ finally {
201
+ // la conversation cron est éphémère : row supprimée (le .jsonl reste, I5),
202
+ // ce qui libère aussi session_file UNIQUE pour la reprise append_session du prochain run
203
+ if (convId) {
204
+ await pool.evict(convId).catch(() => undefined);
205
+ db.prepare("DELETE FROM conversation WHERE id = ?").run(convId);
206
+ }
207
+ this.firing.delete(taskId);
208
+ }
209
+ }
210
+ /** Conversation éphémère du run, dans le workspace de la tâche (session reprise si append_session). */
211
+ createRunConversation(task, preset) {
212
+ const { db } = this.opts;
213
+ const conv = createConversation(db, {
214
+ workspaceId: task.workspace_id,
215
+ agentId: preset.id,
216
+ spawn: spawnConfigFromPreset(preset),
217
+ });
218
+ const resumeFile = task.output_policy === "append_session" ? lastSessionFile(db, task.id) : null;
219
+ if (resumeFile)
220
+ db.prepare("UPDATE conversation SET session_file = ? WHERE id = ?").run(resumeFile, conv.id);
221
+ db.prepare("UPDATE conversation SET title = ? WHERE id = ?").run(`[cron] ${task.name}`, conv.id);
222
+ return getConversation(db, conv.id);
223
+ }
224
+ getRun(runId) {
225
+ return this.opts.db.prepare("SELECT * FROM cron_run WHERE id = ?").get(runId);
226
+ }
227
+ }
package/dist/src/db.js ADDED
@@ -0,0 +1,128 @@
1
+ import Database from "better-sqlite3";
2
+ // Schéma courant (v2) — conversation.session_file devient nullable et un snapshot
3
+ // spawn_args (JSON du SpawnConfig figé, O6) est ajouté.
4
+ const SCHEMA_V2 = `
5
+ CREATE TABLE IF NOT EXISTS agent_preset (
6
+ id TEXT PRIMARY KEY,
7
+ slug TEXT NOT NULL UNIQUE,
8
+ name TEXT NOT NULL,
9
+ description TEXT NOT NULL DEFAULT '',
10
+ provider TEXT NOT NULL,
11
+ model TEXT NOT NULL,
12
+ thinking TEXT,
13
+ system_prompt TEXT NOT NULL DEFAULT '',
14
+ skills TEXT NOT NULL DEFAULT '[]',
15
+ tools_allowlist TEXT,
16
+ mcp_servers TEXT NOT NULL DEFAULT '[]',
17
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
18
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
19
+ );
20
+
21
+ CREATE TABLE IF NOT EXISTS subagent_setup (
22
+ id TEXT PRIMARY KEY,
23
+ agent_id TEXT NOT NULL REFERENCES agent_preset(id) ON DELETE CASCADE,
24
+ name TEXT NOT NULL,
25
+ description TEXT NOT NULL DEFAULT '',
26
+ provider TEXT NOT NULL,
27
+ model TEXT NOT NULL,
28
+ thinking TEXT,
29
+ system_prompt TEXT NOT NULL DEFAULT '',
30
+ skills TEXT NOT NULL DEFAULT '[]',
31
+ mcp_servers TEXT NOT NULL DEFAULT '[]',
32
+ UNIQUE (agent_id, name)
33
+ );
34
+
35
+ CREATE TABLE IF NOT EXISTS workspace (
36
+ id TEXT PRIMARY KEY,
37
+ dir TEXT NOT NULL UNIQUE,
38
+ name TEXT NOT NULL,
39
+ default_agent_id TEXT REFERENCES agent_preset(id) ON DELETE SET NULL
40
+ );
41
+
42
+ CREATE TABLE IF NOT EXISTS conversation (
43
+ id TEXT PRIMARY KEY,
44
+ workspace_id TEXT REFERENCES workspace(id) ON DELETE SET NULL,
45
+ agent_id TEXT REFERENCES agent_preset(id) ON DELETE SET NULL,
46
+ provider TEXT NOT NULL,
47
+ model TEXT NOT NULL,
48
+ thinking TEXT,
49
+ session_file TEXT UNIQUE,
50
+ spawn_args TEXT NOT NULL DEFAULT '{}',
51
+ title TEXT NOT NULL DEFAULT '',
52
+ status TEXT NOT NULL DEFAULT 'idle',
53
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
54
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
55
+ );
56
+
57
+ CREATE TABLE IF NOT EXISTS cron_task (
58
+ id TEXT PRIMARY KEY,
59
+ name TEXT NOT NULL,
60
+ cron_expr TEXT NOT NULL,
61
+ prompt TEXT NOT NULL,
62
+ agent_id TEXT REFERENCES agent_preset(id) ON DELETE SET NULL,
63
+ workspace_id TEXT NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
64
+ output_policy TEXT NOT NULL DEFAULT 'append_session',
65
+ busy_policy TEXT NOT NULL DEFAULT 'skip',
66
+ catchup INTEGER NOT NULL DEFAULT 0,
67
+ enabled INTEGER NOT NULL DEFAULT 1,
68
+ last_run_at TEXT,
69
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
70
+ );
71
+
72
+ CREATE TABLE IF NOT EXISTS cron_run (
73
+ id TEXT PRIMARY KEY,
74
+ task_id TEXT NOT NULL REFERENCES cron_task(id) ON DELETE CASCADE,
75
+ started_at TEXT NOT NULL DEFAULT (datetime('now')),
76
+ finished_at TEXT,
77
+ status TEXT NOT NULL DEFAULT 'running',
78
+ session_file TEXT,
79
+ error TEXT
80
+ );
81
+ `;
82
+ // v1 → v2 : rebuild de conversation (SQLite ne permet pas de lever un NOT NULL)
83
+ const MIGRATE_V1_TO_V2 = `
84
+ CREATE TABLE conversation_v2 (
85
+ id TEXT PRIMARY KEY,
86
+ workspace_id TEXT REFERENCES workspace(id) ON DELETE SET NULL,
87
+ agent_id TEXT REFERENCES agent_preset(id) ON DELETE SET NULL,
88
+ provider TEXT NOT NULL,
89
+ model TEXT NOT NULL,
90
+ thinking TEXT,
91
+ session_file TEXT UNIQUE,
92
+ spawn_args TEXT NOT NULL DEFAULT '{}',
93
+ title TEXT NOT NULL DEFAULT '',
94
+ status TEXT NOT NULL DEFAULT 'idle',
95
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
96
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
97
+ );
98
+ INSERT INTO conversation_v2 (id, workspace_id, agent_id, provider, model, thinking, session_file, title, status, created_at, updated_at)
99
+ SELECT id, workspace_id, agent_id, provider, model, thinking, session_file, title, status, created_at, updated_at FROM conversation;
100
+ DROP TABLE conversation;
101
+ ALTER TABLE conversation_v2 RENAME TO conversation;
102
+ `;
103
+ // v2 → v3 : agent par défaut global (le "Majordome")
104
+ const MIGRATE_V2_TO_V3 = `ALTER TABLE agent_preset ADD COLUMN is_default INTEGER NOT NULL DEFAULT 0;`;
105
+ export function openDb(dbPath) {
106
+ const db = new Database(dbPath);
107
+ db.pragma("journal_mode = WAL");
108
+ db.pragma("foreign_keys = ON");
109
+ const version = db.pragma("user_version", { simple: true });
110
+ if (version < 1) {
111
+ db.exec(SCHEMA_V2);
112
+ db.exec(MIGRATE_V2_TO_V3);
113
+ db.pragma("user_version = 3");
114
+ return { db, version: 3 };
115
+ }
116
+ if (version < 2) {
117
+ // FK OFF pendant la migration (pratique SQLite standard ; les parents peuvent être créés plus tard)
118
+ db.pragma("foreign_keys = OFF");
119
+ db.exec(MIGRATE_V1_TO_V2);
120
+ db.pragma("foreign_keys = ON");
121
+ db.pragma("user_version = 2");
122
+ }
123
+ if (version < 3) {
124
+ db.exec(MIGRATE_V2_TO_V3);
125
+ db.pragma("user_version = 3");
126
+ }
127
+ return { db, version: 3 };
128
+ }
@@ -0,0 +1,154 @@
1
+ import { existsSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { createAgent } from "./agents.js";
5
+ import { readJson } from "./json-files.js";
6
+ export const PATH_LOOKUP_DEPTH = 6;
7
+ /** Remonte depuis le module jusqu'à la racine du paquet @ignitionai/cogitator. */
8
+ export function findPackageRoot(from = dirname(fileURLToPath(import.meta.url))) {
9
+ let dir = from;
10
+ for (let i = 0; i < PATH_LOOKUP_DEPTH; i++) {
11
+ const pkg = join(dir, "package.json");
12
+ if (existsSync(pkg) && readJson(pkg, {}).name === PACKAGE_NAME)
13
+ return dir;
14
+ const parent = dirname(dir);
15
+ if (parent === dir)
16
+ break;
17
+ dir = parent;
18
+ }
19
+ return null;
20
+ }
21
+ const PACKAGE_NAME = "@ignitionai/cogitator";
22
+ /** Provider/modèle par défaut de pi (settings.json), utilisés pour seeder les agents fournis. */
23
+ function readPiDefaults(paths) {
24
+ const settings = readJson(join(paths.piAgentDir, "settings.json"), {});
25
+ return { provider: settings.defaultProvider ?? "openai", model: settings.defaultModel ?? "gpt-5.4" };
26
+ }
27
+ /** Serveur MCP embarqué de Cogitator, exposé aux agents seedés (vide si le build manque). */
28
+ function cogitatorMcpServers() {
29
+ const root = findPackageRoot();
30
+ const script = root ? join(root, "dist", "src", "mcp-server.js") : null;
31
+ if (!script || !existsSync(script))
32
+ return [];
33
+ return [{ name: "cogitator", command: "node", args: [script] }];
34
+ }
35
+ export const MAJORDOME_PROMPT = `Tu es le Majordome de Cogitator — l'agent opérateur du panneau de contrôle pi.
36
+
37
+ Tu manipules Cogitator via tes outils MCP (préfixe cogitator_) :
38
+ - CRUD des agents (presets), validation, définition de l'agent par défaut
39
+ - CRUD des tâches cron (planification, fire manuel, historique des runs)
40
+ - CRUD des workspaces (dossiers de projet)
41
+ - Création/liste des conversations, liste des providers et skills
42
+
43
+ Workflow de SETUP de projet (quand on te demande d'initialiser/configurer ce workspace) :
44
+ A. ANALYSER le repo : structure, stack (package.json et consorts), README, scripts, état git (branches, remote GitHub), existence de AGENTS.md / .agents/rules / hooks.
45
+ B. PROPOSER (en liste courte, attends le feu vert) :
46
+ 1. Conventions — fichier AGENTS.md ou .agents/rules/ avec les règles du projet (utilise le skill rules-manager si disponible) : stack, commandes, conventions de code, ce que les agents ne doivent JAMAIS faire.
47
+ 2. Protection git — hooks qui bloquent les commandes destructrices (push --force, reset --hard, clean) via le skill hooks-manager/git-guardrails si disponible.
48
+ 3. Board initial — crée les cartes GitHub du backlog évident (cogitator_board_create_card) : dette visible, TODO du README, bugs connus, prochaines étapes.
49
+ 4. Agents — propose les presets utiles pour ce projet (via cogitator_list_agents puis cogitator_create_agent si manquant, discipline check-first).
50
+ C. EXÉCUTER après validation, et terminer par un bilan : ce qui a été créé, où, et comment le maintenir.
51
+
52
+ Règles de conduite :
53
+ 1. Avant toute action destructive (suppression), confirme explicitement avec l'utilisateur.
54
+ 2. Quand tu crées un agent, propose de le valider (cogitator_validate_agent) après création.
55
+ 3. Pour les expressions cron, propose du clair ("tous les jours à 9h" → "0 9 * * *").
56
+ 4. Réponds en français, court et structuré.
57
+ 5. Si un outil renvoie une erreur, explique-la et propose une correction.`;
58
+ export const CHEF_DE_PROJET_PROMPT = `Tu es le Chef de Projet de ce workspace. Le board kanban est la réplique des GitHub Issues du repo : chaque carte = une issue (source de vérité GitHub). Colonnes = labels status:backlog|todo|in_progress|canceled (clos → done) ; priorités = labels priority:urgent|high|medium|low. Tu peux aussi utiliser directement gh (gh issue list/create/edit/comment) dans ce dossier, ou les outils MCP cogitator_board_*.
59
+
60
+ Tes responsabilités :
61
+ 1. LIRE le board avant de répondre sur l'état du projet (cogitator_board_list, ou gh issue list).
62
+ 2. Créer, déplacer, mettre à jour et commenter les cartes (outils MCP cogitator_board_*).
63
+ 3. Relier les cartes aux conversations de travail (conversation_ids) pour que l'activité fichiers se cumule sur la carte.
64
+ 4. Repérer les cartes stagnantes (in_progress sans activité récente) et les blocages (blocked_by non résolus).
65
+ 4bis. Lancer les agents sur leurs tickets : assigne la carte (assignee_agent_id) puis cogitator_board_start_work — la conversation spawnée est automatiquement liée (activité cumulée).
66
+ 4ter. Créer les moyens manquants — TOUJOURS VÉRIFIER L'EXISTANT D'ABORD, jamais de doublon :
67
+ - Agent : d'abord cogitator_list_agents — un preset existant couvre-t-il la tâche ? Si oui, réutilise-le (cogitator_update_agent si besoin). Si non, cogitator_create_agent (provider, modèle, thinking, prompt de scope, skills, MCP), puis cogitator_validate_agent.
68
+ - Skill : d'abord cogitator_list_skills — un skill existant couvre-t-il le besoin ? SI ET SEULEMENT SI aucun ne convient : déléguer à l'Architecte de Skills, OU importer via cogitator_import_skills (GitHub/npx).
69
+ 5. Proposer des priorités — ne jamais décider seul d'annuler une carte sans confirmation explicite.
70
+ 6. Fournir des bilans : "où on en est", "qu'est-ce qui bloque", "prochaines étapes" — courts et factuels.
71
+
72
+ === MÉTHODES OBLIGATOIRES (skills AI Blueprint) ===
73
+
74
+ Certaines méthodes de ton écosystème ont leur SKILL.md à invocation désactivée : tu ne peux pas t'y charger par toi-même, mais tu as l'outil read — LIS le fichier et applique la méthode quand le contexte correspond :
75
+ - ~/.agents/skills/to-tickets/SKILL.md → DÉCOUPAGE D'UN CHANTIER. Méthode "tracer-bullet" : chaque carte est une slice verticale livrable (pas une couche technique), et chaque carte déclare ses dépendances via blocks/blocked_by (natifs du board — c'est exactement ce que ce skill appelle "blocking edges on a real tracker"). Applique cette discipline À CHAQUE découpage.
76
+ - ~/.agents/skills/use-delegate/SKILL.md → ÉCONOMIE DE DÉLÉGATION. Tu es l'hôte : tu planifies, découpes, relis et bilan. Les exécutants font le travail lourd — crée-les sur des modèles ÉCONOMES (deepseek/deepseek-flash, kimi-for-coding) sauf si la tâche exige un modèle fort ; réserve ton modèle à l'orchestration. Vérifie le résultat des exécutants avant de marquer une carte Terminé.
77
+ - ~/.agents/skills/use-goal/SKILL.md → OBJECTIF PERSISTANT. Quand un chantier dépasse une session, structure-le comme un goal : un objectif unique avec critères de complétion vérifiables, écrits dans la carte (description) ou en commentaire.
78
+ - ~/.agents/skills/loop-me/SKILL.md → WORKFLOWS RÉCURRENTS. Si l'utilisateur décrit un pattern récurrent (veille, audit, release), lis ce skill et propose de le spécifier (cron Cogitator + carte récurrente).
79
+
80
+ Si l'utilisateur tape /skill:<nom> dans le chat, pi injecte le skill — applique-le alors directement.
81
+
82
+ Règles : réponds en français, structure en listes courtes. Une carte = une unité de travail livrable. Le board est la source de vérité : si la réalité diverge du board, mets le board à jour (ou propose de le faire).`;
83
+ /** Seed du Chef de Projet (agent de gestion de projet, par workspace via son cwd). */
84
+ function seedChefDeProjet(db, paths) {
85
+ const existing = db.prepare("SELECT id FROM agent_preset WHERE slug = 'chef-de-projet'").get();
86
+ if (existing)
87
+ return { created: false };
88
+ const defaults = readPiDefaults(paths);
89
+ const agent = createAgent(db, {
90
+ name: "Chef de Projet",
91
+ description: "Agent de gestion de projet : pilote le board kanban du workspace (cogitator.board.json), suit les cartes, détecte les blocages, relie conversations et activité. Skills complets.",
92
+ provider: defaults.provider,
93
+ model: defaults.model,
94
+ system_prompt: CHEF_DE_PROJET_PROMPT,
95
+ skills: [],
96
+ mcp_servers: cogitatorMcpServers(),
97
+ });
98
+ return { created: true, agentId: agent.id };
99
+ }
100
+ /**
101
+ * Seed du Majordome : si aucun agent n'existe, crée l'agent opérateur par défaut.
102
+ * Provider/modèle repris des defaults pi (settings.json) ; MCP = serveur Cogitator embarqué.
103
+ */
104
+ export function seedDefaultAgent(db, paths) {
105
+ const count = db.prepare("SELECT COUNT(*) AS n FROM agent_preset").get();
106
+ if (count.n > 0)
107
+ return { created: false };
108
+ const defaults = readPiDefaults(paths);
109
+ const agent = createAgent(db, {
110
+ name: "Majordome",
111
+ description: "Agent opérateur Cogitator : crée des agents, des crons, gère workspaces et conversations via les outils MCP cogitator_.",
112
+ provider: defaults.provider,
113
+ model: defaults.model,
114
+ system_prompt: MAJORDOME_PROMPT,
115
+ skills: [],
116
+ mcp_servers: cogitatorMcpServers(),
117
+ });
118
+ db.prepare("UPDATE agent_preset SET is_default = 1 WHERE id = ?").run(agent.id);
119
+ return { created: true, agentId: agent.id };
120
+ }
121
+ export const ARCHITECTE_SKILLS_PROMPT = `Tu es l'Architecte de Skills — expert en création de skills pour agents (specification Agent Skills / SKILL.md, compatible pi, Claude Code, Codex).
122
+
123
+ Ton travail, quand on te demande un skill :
124
+ 1. COMPRENDRE le besoin réel : ce que le skill doit faire, QUAND il doit se déclencher (mots-clés, situations), pour quel outil. Pose UNE question si le besoin est flou, puis propose un plan.
125
+ 2. CONCEVOIR : name (kebab-case, ≤64), description (≤1024 caractères — jamais au-delà, pi refuse), corps structuré : ce que le skill produit, ses règles, ses limites, ses étapes. Références progressives (references/ pour le détail) si le skill est gros.
126
+ 3. ÉCRIRE dans ~/.agents/skills/<name>/SKILL.md (frontmatter YAML + corps markdown). Crée references/ ou scripts/ si nécessaire. Jamais de secrets ni d'appels réseau cachés dans un skill.
127
+ 4. VALIDER : vérifie via cogitator_list_skills (ou relis le fichier) que le skill est découvert, que la description fait moins de 1024 caractères, que le frontmatter a name + description. Corrige immédiatement si non.
128
+ 5. RENDRE COMPTE : chemin du skill, description choisie, ce qui la déclenche, comment le tester (/skill:<name>).
129
+
130
+ Règles : réponds en français. Un skill = une responsabilité. La description doit dire CE QUE fait le skill ET QUAND l'utiliser (c'est elle qui route le modèle vers le skill). Ne surcharge jamais : si un skill existant fait déjà le job, dis-le et améliore-le plutôt.`;
131
+ /** Seed de l'Architecte de Skills (expert création de SKILL.md). */
132
+ function seedArchitecteSkills(db, paths) {
133
+ const existing = db.prepare("SELECT id FROM agent_preset WHERE slug = 'architecte-de-skills'").get();
134
+ if (existing)
135
+ return { created: false };
136
+ const defaults = readPiDefaults(paths);
137
+ const agent = createAgent(db, {
138
+ name: "Architecte de Skills",
139
+ description: "Expert création de skills (SKILL.md, spec Agent Skills) : conçoit, écrit dans ~/.agents/skills, valide la découverte et la qualité du frontmatter.",
140
+ provider: defaults.provider,
141
+ model: defaults.model,
142
+ system_prompt: ARCHITECTE_SKILLS_PROMPT,
143
+ skills: [],
144
+ mcp_servers: cogitatorMcpServers(),
145
+ });
146
+ return { created: true, agentId: agent.id };
147
+ }
148
+ /** Seed des agents par défaut : Majordome (si aucun) + Chef de Projet + Architecte de Skills. */
149
+ export function seedDefaultAgents(db, paths) {
150
+ const m = seedDefaultAgent(db, paths);
151
+ const c = seedChefDeProjet(db, paths);
152
+ const a = seedArchitecteSkills(db, paths);
153
+ return { majordome: m.created, chef: c.created, architecte: a.created };
154
+ }