@imenam/mcp-organizer 1.0.17 → 1.0.19

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,127 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { requireAdmin } from "./admin.js";
5
+ import { OrganizerError } from "./errors.js";
6
+ /**
7
+ * Connexion de Claude pour le runner : un token d'abonnement créé par
8
+ * `claude setup-token`, collé par un administrateur dans la page
9
+ * Administration, vérifié par une requête minimale, puis gardé en base chiffré
10
+ * en AES-256-GCM. La clé est un fichier du répertoire de données, hors de la
11
+ * base, lisible par le seul compte du site, créé au premier enregistrement.
12
+ * L'API ne rend jamais le token, seulement ses 4 derniers caractères.
13
+ */
14
+ /** Fichier de la clé de chiffrement du token, dans le répertoire de données. */
15
+ export const CLAUDE_KEY_FILE = "claude-token.key";
16
+ /** Durée de validité d'un token créé par `claude setup-token`. */
17
+ const TOKEN_VALIDITY_MS = 365 * 24 * 3600_000;
18
+ const KEY_BYTES = 32;
19
+ const IV_BYTES = 12;
20
+ const CIPHER_VERSION = "v1";
21
+ export function claudeKeyPath(dataDir) {
22
+ return path.join(dataDir, CLAUDE_KEY_FILE);
23
+ }
24
+ function parseKey(file, raw) {
25
+ const key = Buffer.from(raw.trim(), "base64");
26
+ if (key.length !== KEY_BYTES)
27
+ throw new OrganizerError(`${file} n'est pas une clé de chiffrement valide : reconnectez Claude dans la page Administration.`);
28
+ return key;
29
+ }
30
+ /** Clé de chiffrement existante ; erreur si le fichier manque. */
31
+ function readKey(dataDir) {
32
+ const file = claudeKeyPath(dataDir);
33
+ let raw;
34
+ try {
35
+ raw = fs.readFileSync(file, "utf8");
36
+ }
37
+ catch (err) {
38
+ if (err?.code === "ENOENT")
39
+ throw new OrganizerError(`La clé de chiffrement du token Claude (${file}) est absente : reconnectez Claude dans la page Administration.`);
40
+ throw err;
41
+ }
42
+ return parseKey(file, raw);
43
+ }
44
+ /** Clé de chiffrement, créée au premier appel en 0600. */
45
+ function ensureKey(dataDir) {
46
+ const file = claudeKeyPath(dataDir);
47
+ try {
48
+ fs.writeFileSync(file, crypto.randomBytes(KEY_BYTES).toString("base64"), { encoding: "utf8", mode: 0o600, flag: "wx" });
49
+ }
50
+ catch (err) {
51
+ if (err?.code !== "EEXIST")
52
+ throw err;
53
+ }
54
+ return readKey(dataDir);
55
+ }
56
+ /** Chiffre `token` : `v1.<iv>.<tag>.<données>`, en base64url. */
57
+ export function encryptToken(key, token) {
58
+ const iv = crypto.randomBytes(IV_BYTES);
59
+ const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
60
+ const data = Buffer.concat([cipher.update(token, "utf8"), cipher.final()]);
61
+ return [CIPHER_VERSION, iv.toString("base64url"), cipher.getAuthTag().toString("base64url"), data.toString("base64url")].join(".");
62
+ }
63
+ /** Déchiffre un token chiffré par `encryptToken` ; erreur si la clé ne correspond pas ou si le chiffré a été altéré. */
64
+ export function decryptToken(key, blob) {
65
+ const [version, iv, tag, data] = blob.split(".");
66
+ if (version !== CIPHER_VERSION || iv === undefined || tag === undefined || data === undefined)
67
+ throw new OrganizerError("Token Claude chiffré illisible : reconnectez Claude dans la page Administration.");
68
+ try {
69
+ const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(iv, "base64url"));
70
+ decipher.setAuthTag(Buffer.from(tag, "base64url"));
71
+ return Buffer.concat([decipher.update(Buffer.from(data, "base64url")), decipher.final()]).toString("utf8");
72
+ }
73
+ catch {
74
+ throw new OrganizerError("Le token Claude ne se déchiffre pas avec la clé du répertoire de données : reconnectez Claude dans la page Administration.");
75
+ }
76
+ }
77
+ /** État de la connexion, sans le token. */
78
+ export function claudeConnectionView(store) {
79
+ const connection = store.findClaudeConnection();
80
+ if (!connection)
81
+ return { tokenHint: null, savedAt: null, expiresAt: null, refusedAt: null, refusedReason: null };
82
+ return {
83
+ tokenHint: connection.tokenHint,
84
+ savedAt: connection.savedAt,
85
+ expiresAt: new Date(Date.parse(connection.savedAt) + TOKEN_VALIDITY_MS).toISOString(),
86
+ refusedAt: connection.refusedAt,
87
+ refusedReason: connection.refusedReason,
88
+ };
89
+ }
90
+ /** État de la connexion, pour un administrateur. */
91
+ export function getClaudeConnection(store, userId) {
92
+ requireAdmin(store, userId);
93
+ return claudeConnectionView(store);
94
+ }
95
+ /** Chiffre et enregistre `token` au nom de `userId`, sans le vérifier. */
96
+ export function storeClaudeToken(store, dataDir, userId, token) {
97
+ const key = ensureKey(dataDir);
98
+ store.mutate({ type: "user", userId }, (tx) => tx.setClaudeConnection(encryptToken(key, token), token.slice(-4)));
99
+ return claudeConnectionView(store);
100
+ }
101
+ /** Vérifie `token` avec `check` (requête minimale à Claude), puis l'enregistre chiffré ; un token refusé n'est pas enregistré. */
102
+ export async function saveClaudeToken(store, dataDir, userId, token, check) {
103
+ requireAdmin(store, userId);
104
+ await check(token);
105
+ return storeClaudeToken(store, dataDir, userId, token);
106
+ }
107
+ /** Token enregistré, déchiffré ; erreur si la clé manque ou ne correspond pas. */
108
+ export function readClaudeToken(store, dataDir) {
109
+ const connection = store.findClaudeConnection();
110
+ return connection ? decryptToken(readKey(dataDir), connection.tokenCipher) : null;
111
+ }
112
+ /** État du runner quand sa commande est configurée : désactivé sans token, ou avec un token refusé par Claude. */
113
+ export function claudeRunnerStatus(store) {
114
+ const connection = store.findClaudeConnection();
115
+ if (!connection)
116
+ return { enabled: false, disabledReason: "Claude n'est pas connecté : collez un token dans la page Administration, section « Connexion de Claude »." };
117
+ if (connection.refusedAt !== null) {
118
+ return { enabled: false, disabledReason: "Claude a refusé le token (expiré ou révoqué) : reconnectez Claude dans la page Administration." };
119
+ }
120
+ return { enabled: true, disabledReason: null };
121
+ }
122
+ /** Messages de Claude Code qui signalent un token absent, expiré, révoqué ou invalide. */
123
+ const AUTH_FAILURE = /authentication_error|invalid bearer token|oauth token has expired|oauth token (?:was |has been )?revoked|invalid authentication credentials|invalid api key|not logged in|login expired|please run \/login/i;
124
+ /** Vrai si `text`, écrit par Claude Code, dit que le token n'est pas accepté. */
125
+ export function isAuthFailure(text) {
126
+ return text !== null && AUTH_FAILURE.test(text);
127
+ }
@@ -42,8 +42,25 @@ function viewSettings(view) {
42
42
  const { name, layout, groupBy, thenBy, showEmptyGroups, statuses, priorities, assigneeIds, unassigned, tagIds } = view;
43
43
  return { name, layout, groupBy, thenBy, showEmptyGroups, statuses, priorities, assigneeIds, unassigned, tagIds };
44
44
  }
45
- function sameState(entityType, a, b) {
46
- return JSON.stringify(comparable(entityType, a)) === JSON.stringify(comparable(entityType, b));
45
+ /** Rang d'un élément de checklist ou d'un point de vérification ; null pour les autres entités. */
46
+ function listPosition(entityType, snapshot) {
47
+ if (snapshot === null)
48
+ return null;
49
+ if (entityType === "checklist_item")
50
+ return ChecklistItemSchema.parse(snapshot).position;
51
+ if (entityType === "test_checkpoint")
52
+ return TestCheckpointSchema.parse(snapshot).position;
53
+ return null;
54
+ }
55
+ /**
56
+ * Vrai si l'état courant `current` est celui que l'action a laissé (`after`) ;
57
+ * le rang d'un élément de liste n'est comparé que si l'action l'a déplacé.
58
+ */
59
+ function sameState(entityType, current, after, before) {
60
+ if (JSON.stringify(comparable(entityType, current)) !== JSON.stringify(comparable(entityType, after)))
61
+ return false;
62
+ const moved = listPosition(entityType, before) !== listPosition(entityType, after);
63
+ return !moved || listPosition(entityType, current) === listPosition(entityType, after);
47
64
  }
48
65
  /** Désignation d'une entité dans les messages, avec l'accord du participe. */
49
66
  function describe(store, entityType, snapshot) {
@@ -112,7 +129,7 @@ export function undoAgentAction(tx, action) {
112
129
  if (current === null) {
113
130
  throw new InvariantError(`${label} a été supprimé${agreement} depuis par ${lastModifier(store, entityType, action.entityId, action)} : annulation impossible.`);
114
131
  }
115
- if (!sameState(entityType, current, action.after)) {
132
+ if (!sameState(entityType, current, action.after, action.before)) {
116
133
  throw new InvariantError(`${label} a été modifié${agreement} depuis par ${lastModifier(store, entityType, action.entityId, action)} : l'annulation écraserait cette modification.`);
117
134
  }
118
135
  if (action.before === null)
@@ -233,15 +250,21 @@ function restore(tx, entityType, entityId, before) {
233
250
  return;
234
251
  case "checklist_item": {
235
252
  const item = ChecklistItemSchema.parse(before);
253
+ if (item.position !== tx.store.getChecklistItem(entityId).position)
254
+ tx.restoreChecklistItemPosition(entityId, item.position);
236
255
  tx.updateChecklistItem(entityId, { text: item.text, done: item.done });
237
256
  return;
238
257
  }
239
258
  case "task_question":
240
259
  tx.replaceQuestion(QuestionSnapshotSchema.parse(before));
241
260
  return;
242
- case "test_checkpoint":
243
- tx.updateCheckpoint(entityId, TestCheckpointSchema.parse(before).text);
261
+ case "test_checkpoint": {
262
+ const checkpoint = TestCheckpointSchema.parse(before);
263
+ if (checkpoint.position !== tx.store.getCheckpoint(entityId).position)
264
+ tx.restoreCheckpointPosition(entityId, checkpoint.position);
265
+ tx.updateCheckpoint(entityId, checkpoint.text);
244
266
  return;
267
+ }
245
268
  case "idea": {
246
269
  const idea = IdeaSchema.parse(before);
247
270
  if (idea.promotedTaskId !== null && !tx.store.findTask(idea.promotedTaskId)) {
@@ -601,6 +601,18 @@ export const MIGRATIONS = [
601
601
  position REAL NOT NULL
602
602
  );
603
603
  CREATE INDEX question_options_question ON question_options(question_id, position);
604
+ `,
605
+ // Connexion de Claude pour le runner (une seule ligne) : token d'abonnement chiffré, son indice, et son refus par Claude.
606
+ `
607
+ CREATE TABLE claude_connection (
608
+ id INTEGER PRIMARY KEY CHECK (id = 1),
609
+ token_cipher TEXT NOT NULL CHECK (token_cipher <> ''),
610
+ token_hint TEXT NOT NULL,
611
+ saved_at TEXT NOT NULL,
612
+ saved_by TEXT REFERENCES users(id) ON DELETE SET NULL,
613
+ refused_at TEXT,
614
+ refused_reason TEXT
615
+ );
604
616
  `,
605
617
  ];
606
618
  /** Version du schéma attendue par ce code. */
@@ -2,7 +2,7 @@ import type Database from "better-sqlite3";
2
2
  import { WatcherRegistry } from "./watchers.js";
3
3
  import { type BoardGrouping, type BoardLayout, type EntityType, type MemberRole, type RequestKind, type RequestStatus, type SpaceKind, type TaskPriority, type TaskStatus, type TaskType, type TestResultValue, type AccessLinkPurpose, type AgentOperation, type UserStatus, type VersionedEntityType } from "../../shared/schemas/enums.schema.js";
4
4
  import { type AccessLink, type AgentAction, type AgentInstructions, type AgentRequest, type AgentToken, type Attachment, type BoardView, type Change, type ChecklistItem, type Comment, type QuestionOption, type QuestionSnapshot, type TaskQuestion, type EntityVersion, type FollowUp, type Idea, type Invitation, type Membership, type Notification, type Session, type Space, type Tag, type Task, type TaskSnapshot, type TestCheckpoint, type TestResult, type TestReview, type User, type UserSettings, type NotificationPreferences, type SpaceNotificationSettings } from "../../shared/schemas/entities.schema.js";
5
- import { type RunnerSessionRecord, type RunnerSettings } from "../../shared/schemas/admin-api.schema.js";
5
+ import { type ClaudeConnection, type RunnerSessionRecord, type RunnerSettings } from "../../shared/schemas/admin-api.schema.js";
6
6
  /**
7
7
  * Auteur d'une mutation : un utilisateur de la GUI, ou un agent qui agit avec
8
8
  * son jeton, avec les droits du propriétaire du jeton, pour une demande que ce
@@ -46,6 +46,8 @@ export declare class Store {
46
46
  findSpaceNotificationSettings(userId: string, spaceId: string): SpaceNotificationSettings | null;
47
47
  /** Limites d'une session du runner. */
48
48
  getRunnerSettings(): RunnerSettings;
49
+ /** Connexion de Claude enregistrée, ou null tant qu'aucun token ne l'est. */
50
+ findClaudeConnection(): ClaudeConnection | null;
49
51
  /** Sessions du runner commencées depuis `since`, de la plus récente à la plus ancienne. */
50
52
  listRunnerSessionsSince(since: string): RunnerSessionRecord[];
51
53
  /** Instructions de l'agent propres à un espace, ou celles du site quand `spaceId` est null ; null s'il n'y en a pas. */
@@ -141,6 +143,11 @@ export declare class Store {
141
143
  id: string;
142
144
  taskId: string;
143
145
  }[];
146
+ /** État des éléments de checklist des tâches d'un espace. */
147
+ listChecklistInSpace(spaceId: string): {
148
+ taskId: string;
149
+ done: boolean;
150
+ }[];
144
151
  /** Résultats saisis sur les points des tâches d'un espace. */
145
152
  listTestResultsInSpace(spaceId: string): {
146
153
  taskId: string;
@@ -544,8 +551,11 @@ export declare class Mutation {
544
551
  /** Un choix unique a pour réponse une seule proposition ou la réponse libre. */
545
552
  private requireSingleAnswer;
546
553
  private touchQuestion;
547
- /** Ajoute un élément en fin de checklist d'une tâche standard. */
548
- addChecklistItem(taskId: string, text: string): ChecklistItem;
554
+ /**
555
+ * Ajoute un élément à la checklist d'une tâche standard : juste après
556
+ * `afterId` (null : en tête), en fin de liste sans `afterId`.
557
+ */
558
+ addChecklistItem(taskId: string, text: string, afterId?: string | null): ChecklistItem;
549
559
  updateChecklistItem(id: string, patch: {
550
560
  text?: string;
551
561
  done?: boolean;
@@ -555,6 +565,8 @@ export declare class Mutation {
555
565
  restoreChecklistItem(snapshot: ChecklistItem): ChecklistItem;
556
566
  /** Place un élément de checklist juste après `afterId` (null : en tête), en renumérotant la liste si besoin. */
557
567
  moveChecklistItem(id: string, afterId: string | null): ChecklistItem;
568
+ /** Ramène un élément de checklist au rang `position`, refusé si un autre élément l'occupe. */
569
+ restoreChecklistItemPosition(id: string, position: number): ChecklistItem;
558
570
  private updateChecklistItemPosition;
559
571
  /**
560
572
  * Rang d'un élément inséré juste après `afterId` (null : en tête) dans
@@ -566,8 +578,11 @@ export declare class Mutation {
566
578
  private testTask;
567
579
  /** Tâche de test dont l'utilisateur acteur est testeur (assigné). */
568
580
  private testedTask;
569
- /** Ajoute un point de vérification en fin de liste d'une tâche de test. */
570
- addCheckpoint(taskId: string, text: string): TestCheckpoint;
581
+ /**
582
+ * Ajoute un point de vérification à une tâche de test : juste après
583
+ * `afterId` (null : en tête), en fin de liste sans `afterId`.
584
+ */
585
+ addCheckpoint(taskId: string, text: string, afterId?: string | null): TestCheckpoint;
571
586
  updateCheckpoint(id: string, text: string): TestCheckpoint;
572
587
  /** Supprime un point de vérification et les résultats saisis dessus. */
573
588
  deleteCheckpoint(id: string): void;
@@ -575,6 +590,8 @@ export declare class Mutation {
575
590
  restoreCheckpoint(snapshot: TestCheckpoint, results: readonly TestResult[]): TestCheckpoint;
576
591
  /** Place un point de vérification juste après `afterId` (null : en tête), en renumérotant la liste si besoin. */
577
592
  moveCheckpoint(id: string, afterId: string | null): TestCheckpoint;
593
+ /** Ramène un point de vérification au rang `position`, refusé si un autre point l'occupe. */
594
+ restoreCheckpointPosition(id: string, position: number): TestCheckpoint;
578
595
  /**
579
596
  * Enregistre le résultat de l'utilisateur acteur sur un point : valeur,
580
597
  * commentaire, ou les deux. Seul un testeur de la tâche saisit ses propres
@@ -729,6 +746,10 @@ export declare class Mutation {
729
746
  setAgentInstructions(spaceId: string | null, text: string): AgentInstructions | null;
730
747
  /** Fixe les limites d'une session du runner. */
731
748
  setRunnerSettings(settings: RunnerSettings): RunnerSettings;
749
+ /** Enregistre le token chiffré de Claude, à la place du précédent ; un refus antérieur est effacé. */
750
+ setClaudeConnection(tokenCipher: string, tokenHint: string): ClaudeConnection;
751
+ /** Marque le token de Claude comme refusé par Claude, avec le message de Claude Code. */
752
+ markClaudeTokenRefused(reason: string): void;
732
753
  /** Enregistre le relevé d'une session du runner terminée. */
733
754
  recordRunnerSession(record: RunnerSessionRecord): void;
734
755
  /** Vérifie les invariants sur l'état final, puis écrit les versions et le journal. */
@@ -5,7 +5,7 @@ import { newId } from "./ids.js";
5
5
  import { WatcherRegistry } from "./watchers.js";
6
6
  import { MAX_TASK_DEPTH, TASK_PRIORITIES, TASK_STATUSES, } from "../../shared/schemas/enums.schema.js";
7
7
  import { AccessLinkSchema, AgentActionSchema, AgentInstructionsSchema, AgentTokenSchema, AgentRequestSchema, AttachmentSchema, BoardViewSchema, ChangeSchema, ChecklistItemSchema, CommentSchema, MAX_QUESTION_OPTIONS, QuestionOptionSchema, TaskQuestionSchema, EntityVersionSchema, FollowUpSchema, IdeaSchema, IdeaSnapshotSchema, InvitationSchema, MembershipSchema, NotificationSchema, SessionSchema, SpaceSchema, TagSchema, TaskSchema, TaskSnapshotSchema, TestCheckpointSchema, TestResultSchema, TestReviewSchema, UserSchema, UserSettingsSchema, SpaceNotificationSettingsSchema, } from "../../shared/schemas/entities.schema.js";
8
- import { RunnerSessionRecordSchema, RunnerSettingsSchema } from "../../shared/schemas/admin-api.schema.js";
8
+ import { ClaudeConnectionSchema, RunnerSessionRecordSchema, RunnerSettingsSchema, } from "../../shared/schemas/admin-api.schema.js";
9
9
  /** Valide `value` avec `schema` ; une donnée invalide est une erreur métier qui liste les champs fautifs. */
10
10
  function validate(schema, value, what) {
11
11
  const parsed = schema.safeParse(value);
@@ -434,6 +434,20 @@ export class Store {
434
434
  const row = this.db.prepare("SELECT * FROM runner_settings WHERE id = 1").get();
435
435
  return RunnerSettingsSchema.parse({ maxTurns: row.max_turns, maxMinutes: row.max_minutes, maxBudgetUsd: row.max_budget_usd });
436
436
  }
437
+ /** Connexion de Claude enregistrée, ou null tant qu'aucun token ne l'est. */
438
+ findClaudeConnection() {
439
+ const row = this.db.prepare("SELECT * FROM claude_connection WHERE id = 1").get();
440
+ if (!row)
441
+ return null;
442
+ return ClaudeConnectionSchema.parse({
443
+ tokenCipher: row.token_cipher,
444
+ tokenHint: row.token_hint,
445
+ savedAt: row.saved_at,
446
+ savedBy: row.saved_by,
447
+ refusedAt: row.refused_at,
448
+ refusedReason: row.refused_reason,
449
+ });
450
+ }
437
451
  /** Sessions du runner commencées depuis `since`, de la plus récente à la plus ancienne. */
438
452
  listRunnerSessionsSince(since) {
439
453
  return this.db.prepare("SELECT * FROM runner_sessions WHERE started_at >= ? ORDER BY started_at DESC, id").all(since).map(runnerSessionFromRow);
@@ -741,6 +755,11 @@ export class Store {
741
755
  .all(spaceId);
742
756
  return rows.map((row) => ({ id: row.id, taskId: row.task_id }));
743
757
  }
758
+ /** État des éléments de checklist des tâches d'un espace. */
759
+ listChecklistInSpace(spaceId) {
760
+ const rows = this.db.prepare("SELECT c.task_id, c.done FROM checklist_items c JOIN tasks t ON t.id = c.task_id WHERE t.space_id = ?").all(spaceId);
761
+ return rows.map((row) => ({ taskId: row.task_id, done: bool(row.done) }));
762
+ }
744
763
  /** Résultats saisis sur les points des tâches d'un espace. */
745
764
  listTestResultsInSpace(spaceId) {
746
765
  const rows = this.db
@@ -1783,14 +1802,24 @@ export class Mutation {
1783
1802
  this.touch("task_question", question.id, this.store.getTask(question.taskId).spaceId, null, question.taskId);
1784
1803
  }
1785
1804
  // --- Checklist ---
1786
- /** Ajoute un élément en fin de checklist d'une tâche standard. */
1787
- addChecklistItem(taskId, text) {
1805
+ /**
1806
+ * Ajoute un élément à la checklist d'une tâche standard : juste après
1807
+ * `afterId` (null : en tête), en fin de liste sans `afterId`.
1808
+ */
1809
+ addChecklistItem(taskId, text, afterId) {
1788
1810
  const task = this.store.getTask(taskId);
1789
1811
  if (task.type !== "standard") {
1790
1812
  throw new InvariantError(`Task ${taskLabel(this.db, task)} is a test: it has checkpoints, not a checklist.`);
1791
1813
  }
1792
1814
  const items = this.store.listChecklist(taskId);
1793
- const item = validate(ChecklistItemSchema, { id: newId(), taskId, text, done: false, position: positionBetween(items.at(-1)?.position ?? null, null) }, "checklist item");
1815
+ const position = this.slotAfter(items, afterId === undefined ? (items.at(-1)?.id ?? null) : afterId, `Checklist item ${afterId} is not in this checklist`, (ids) => {
1816
+ const update = this.db.prepare("UPDATE checklist_items SET position = ? WHERE id = ?");
1817
+ ids.forEach((itemId, index) => {
1818
+ update.run(index + 1, itemId);
1819
+ this.touch("checklist_item", itemId, task.spaceId, null, taskId);
1820
+ });
1821
+ });
1822
+ const item = validate(ChecklistItemSchema, { id: newId(), taskId, text, done: false, position }, "checklist item");
1794
1823
  this.db
1795
1824
  .prepare("INSERT INTO checklist_items (id, task_id, text, done, position) VALUES (?, ?, ?, ?, ?)")
1796
1825
  .run(item.id, item.taskId, item.text, item.done ? 1 : 0, item.position);
@@ -1835,6 +1864,14 @@ export class Mutation {
1835
1864
  });
1836
1865
  return this.updateChecklistItemPosition(item, position, spaceId);
1837
1866
  }
1867
+ /** Ramène un élément de checklist au rang `position`, refusé si un autre élément l'occupe. */
1868
+ restoreChecklistItemPosition(id, position) {
1869
+ const item = this.store.getChecklistItem(id);
1870
+ if (this.store.listChecklist(item.taskId).some((other) => other.id !== id && other.position === position)) {
1871
+ throw new InvariantError("La position d'alors est désormais occupée par un autre élément de la checklist : restauration impossible.");
1872
+ }
1873
+ return this.updateChecklistItemPosition(item, position, this.store.getTask(item.taskId).spaceId);
1874
+ }
1838
1875
  updateChecklistItemPosition(item, position, spaceId) {
1839
1876
  this.db.prepare("UPDATE checklist_items SET position = ? WHERE id = ?").run(position, item.id);
1840
1877
  this.touch("checklist_item", item.id, spaceId, null, item.taskId);
@@ -1876,11 +1913,21 @@ export class Mutation {
1876
1913
  }
1877
1914
  return task;
1878
1915
  }
1879
- /** Ajoute un point de vérification en fin de liste d'une tâche de test. */
1880
- addCheckpoint(taskId, text) {
1916
+ /**
1917
+ * Ajoute un point de vérification à une tâche de test : juste après
1918
+ * `afterId` (null : en tête), en fin de liste sans `afterId`.
1919
+ */
1920
+ addCheckpoint(taskId, text, afterId) {
1881
1921
  const task = this.testTask(taskId);
1882
1922
  const checkpoints = this.store.listCheckpoints(taskId);
1883
- const checkpoint = validate(TestCheckpointSchema, { id: newId(), taskId, text, position: positionBetween(checkpoints.at(-1)?.position ?? null, null) }, "checkpoint");
1923
+ const position = this.slotAfter(checkpoints, afterId === undefined ? (checkpoints.at(-1)?.id ?? null) : afterId, `Checkpoint ${afterId} is not in this test`, (ids) => {
1924
+ const update = this.db.prepare("UPDATE test_checkpoints SET position = ? WHERE id = ?");
1925
+ ids.forEach((checkpointId, index) => {
1926
+ update.run(index + 1, checkpointId);
1927
+ this.touch("test_checkpoint", checkpointId, task.spaceId, null, taskId);
1928
+ });
1929
+ });
1930
+ const checkpoint = validate(TestCheckpointSchema, { id: newId(), taskId, text, position }, "checkpoint");
1884
1931
  this.db
1885
1932
  .prepare("INSERT INTO test_checkpoints (id, task_id, text, position) VALUES (?, ?, ?, ?)")
1886
1933
  .run(checkpoint.id, checkpoint.taskId, checkpoint.text, checkpoint.position);
@@ -1934,6 +1981,16 @@ export class Mutation {
1934
1981
  this.touch("test_checkpoint", id, spaceId, null, checkpoint.taskId);
1935
1982
  return { ...checkpoint, position };
1936
1983
  }
1984
+ /** Ramène un point de vérification au rang `position`, refusé si un autre point l'occupe. */
1985
+ restoreCheckpointPosition(id, position) {
1986
+ const checkpoint = this.store.getCheckpoint(id);
1987
+ if (this.store.listCheckpoints(checkpoint.taskId).some((other) => other.id !== id && other.position === position)) {
1988
+ throw new InvariantError("La position d'alors est désormais occupée par un autre point de vérification : restauration impossible.");
1989
+ }
1990
+ this.db.prepare("UPDATE test_checkpoints SET position = ? WHERE id = ?").run(position, id);
1991
+ this.touch("test_checkpoint", id, this.store.getTask(checkpoint.taskId).spaceId, null, checkpoint.taskId);
1992
+ return { ...checkpoint, position };
1993
+ }
1937
1994
  /**
1938
1995
  * Enregistre le résultat de l'utilisateur acteur sur un point : valeur,
1939
1996
  * commentaire, ou les deux. Seul un testeur de la tâche saisit ses propres
@@ -2656,6 +2713,20 @@ export class Mutation {
2656
2713
  .run(valid.maxTurns, valid.maxMinutes, valid.maxBudgetUsd, this.now, this.actor.userId);
2657
2714
  return valid;
2658
2715
  }
2716
+ /** Enregistre le token chiffré de Claude, à la place du précédent ; un refus antérieur est effacé. */
2717
+ setClaudeConnection(tokenCipher, tokenHint) {
2718
+ if (this.actor.type !== "user")
2719
+ throw new InvariantError("Only a user can connect Claude.");
2720
+ const connection = validate(ClaudeConnectionSchema, { tokenCipher, tokenHint, savedAt: this.now, savedBy: this.actor.userId, refusedAt: null, refusedReason: null }, "Claude connection");
2721
+ this.db
2722
+ .prepare("INSERT OR REPLACE INTO claude_connection (id, token_cipher, token_hint, saved_at, saved_by, refused_at, refused_reason) VALUES (1, ?, ?, ?, ?, NULL, NULL)")
2723
+ .run(connection.tokenCipher, connection.tokenHint, connection.savedAt, connection.savedBy);
2724
+ return connection;
2725
+ }
2726
+ /** Marque le token de Claude comme refusé par Claude, avec le message de Claude Code. */
2727
+ markClaudeTokenRefused(reason) {
2728
+ this.db.prepare("UPDATE claude_connection SET refused_at = ?, refused_reason = ? WHERE id = 1").run(this.now, reason);
2729
+ }
2659
2730
  /** Enregistre le relevé d'une session du runner terminée. */
2660
2731
  recordRunnerSession(record) {
2661
2732
  const valid = validate(RunnerSessionRecordSchema, record, "runner session");
@@ -76,6 +76,14 @@ function buildForest(store, space) {
76
76
  const checkpoints = new Map();
77
77
  for (const { id, taskId } of store.listCheckpointsInSpace(space.id))
78
78
  checkpoints.set(taskId, [...(checkpoints.get(taskId) ?? []), id]);
79
+ const checklists = new Map();
80
+ for (const { taskId, done } of store.listChecklistInSpace(space.id)) {
81
+ const progress = checklists.get(taskId) ?? { done: 0, total: 0 };
82
+ progress.total += 1;
83
+ if (done)
84
+ progress.done += 1;
85
+ checklists.set(taskId, progress);
86
+ }
79
87
  const results = new Map();
80
88
  for (const result of store.listTestResultsInSpace(space.id))
81
89
  results.set(result.taskId, [...(results.get(result.taskId) ?? []), result]);
@@ -95,6 +103,7 @@ function buildForest(store, space) {
95
103
  assigneeIds: assignees.get(task.id) ?? [],
96
104
  tagIds: tags.get(task.id) ?? [],
97
105
  subtasks: { done: 0, total: 0 },
106
+ checklist: checklists.get(task.id) ?? { done: 0, total: 0 },
98
107
  test: task.type === "test" ? summarizeTest(checkpoints.get(task.id) ?? [], results.get(task.id) ?? [], assignees.get(task.id) ?? []) : null,
99
108
  children: [],
100
109
  });
@@ -52,7 +52,7 @@ const COMMENTS = {
52
52
  ORGANIZER_PUBLIC_URL: "# URL ouverte par les utilisateurs, derrière nginx.",
53
53
  PORT: "# Écoute du site ; nginx le joint à cette adresse.",
54
54
  MCP_ORGANIZER_DATA_DIR: "# Base SQLite, pièces jointes et journaux.",
55
- ORGANIZER_RUNNER_CLAUDE: "# Claude Code du runner, connecté pour le compte du site.",
55
+ ORGANIZER_RUNNER_CLAUDE: "# Claude Code du runner ; Claude se connecte dans la page Administration.",
56
56
  GROQ_API_KEY: "# Dictée vocale (Groq).",
57
57
  SMTP_URL: "# Envoi des e-mails (invitations, notifications).",
58
58
  };
@@ -30,8 +30,13 @@ export interface GuiApiContext {
30
30
  transcriber: Transcriber;
31
31
  /** Runner du site : son état, et le lancement d'une session ponctuelle (null quand il est désactivé). */
32
32
  runner: {
33
- status: RunnerStatus;
33
+ /** État du runner : sa commande, puis la connexion de Claude. */
34
+ status: () => RunnerStatus;
34
35
  runNow: ((spaceId: string) => void) | null;
36
+ /** Vérifie un token Claude par une requête minimale (null quand la commande du runner n'est pas configurée). */
37
+ checkClaudeToken: ((token: string) => Promise<void>) | null;
38
+ /** Reprend les espaces autorisés qui ont des demandes en attente. */
39
+ resume: () => void;
35
40
  /** Dernière session du runner dans un espace, quand elle a échoué. */
36
41
  lastFailure: (spaceId: string) => RunnerFailure | null;
37
42
  /** Session du runner en cours dans un espace. */
@@ -43,6 +48,8 @@ export interface GuiApiContext {
43
48
  /** Arrêt d'urgence : tue tous les processus Claude Code de la machine du site. */
44
49
  killAll: (userId: string) => Promise<KillAllResponse>;
45
50
  };
51
+ /** Répertoire de données du site, qui porte la clé de chiffrement du token Claude. */
52
+ dataDir: string;
46
53
  /** Horloge, imposée par les tests. */
47
54
  now?: () => Date;
48
55
  }
@@ -17,8 +17,9 @@ import { createIdea, delegatePromotion, listIdeas, promoteIdea, setIdeaArchived
17
17
  import { CreateIdeaRequestSchema, PromoteIdeaRequestSchema, UpdateIdeaRequestSchema } from "../shared/schemas/ideas-api.schema.js";
18
18
  import { createAgentToken, listAgentTokens, revokeAgentToken } from "./core/agent-tokens.js";
19
19
  import { CreateTokenRequestSchema } from "../shared/schemas/tokens-api.schema.js";
20
+ import { getClaudeConnection, saveClaudeToken } from "./core/claude-connection.js";
20
21
  import { getRunnerSettings, listAdminSpaces, processQueueNow, requireAdmin, runnerUsage, setRunnerAllowed, setRunnerSettings } from "./core/admin.js";
21
- import { RunnerSettingsSchema, RunnerUsageQuerySchema, SetRunnerAllowedRequestSchema } from "../shared/schemas/admin-api.schema.js";
22
+ import { RunnerSettingsSchema, RunnerUsageQuerySchema, SaveClaudeTokenRequestSchema, SetRunnerAllowedRequestSchema } from "../shared/schemas/admin-api.schema.js";
22
23
  import { getSiteInstructions, getSpaceInstructions, setSiteInstructions, setSpaceInstructions } from "./core/agent-instructions.js";
23
24
  import { SetAgentInstructionsRequestSchema } from "../shared/schemas/instructions-api.schema.js";
24
25
  import { TranscriptionError } from "./core/transcription.js";
@@ -312,7 +313,7 @@ route("POST", "/ideas/:ideaId/promote", (ctx, { user, request, params }) => ({
312
313
  }));
313
314
  route("POST", "/ideas/:ideaId/delegate", (ctx, { user, params }) => ({ body: delegatePromotion(ctx.store, user.id, params.ideaId) }));
314
315
  // --- File de l'agent et historique -------------------------------------------------
315
- route("GET", "/spaces/:spaceId/requests", (ctx, { user, params }) => ({ body: listRequests(ctx.store, user.id, params.spaceId, { disabledReason: ctx.runner.status.disabledReason, failure: ctx.runner.lastFailure(params.spaceId), session: ctx.runner.currentSession(params.spaceId) }, now(ctx)) }));
316
+ route("GET", "/spaces/:spaceId/requests", (ctx, { user, params }) => ({ body: listRequests(ctx.store, user.id, params.spaceId, { disabledReason: ctx.runner.status().disabledReason, failure: ctx.runner.lastFailure(params.spaceId), session: ctx.runner.currentSession(params.spaceId) }, now(ctx)) }));
316
317
  route("POST", "/spaces/:spaceId/requests", (ctx, { user, request, params }) => ({
317
318
  body: createRequest(ctx.store, user.id, params.spaceId, parseBody(CreateRequestSchema, request.body)),
318
319
  }));
@@ -374,24 +375,36 @@ route("POST", "/tokens", (ctx, { user, request }) => {
374
375
  });
375
376
  route("POST", "/tokens/:tokenId/revoke", (ctx, { user, params }) => ({ body: revokeAgentToken(ctx.store, user.id, params.tokenId, now(ctx)) }));
376
377
  // --- Administration ----------------------------------------------------------------
377
- route("GET", "/admin/spaces", (ctx, { user }) => ({ body: listAdminSpaces(ctx.store, user.id, ctx.runner.status) }));
378
+ route("GET", "/admin/spaces", (ctx, { user }) => ({ body: listAdminSpaces(ctx.store, user.id, ctx.runner.status()) }));
378
379
  route("POST", "/spaces/:spaceId/runner/run", (ctx, { user, params }) => {
379
380
  requireAdmin(ctx.store, user.id);
380
381
  const runNow = ctx.runner.runNow;
381
- if (!runNow)
382
- throw new ApiError("unavailable", `Runner désactivé : ${ctx.runner.status.disabledReason}`);
382
+ const status = ctx.runner.status();
383
+ if (!runNow || !status.enabled)
384
+ throw new ApiError("unavailable", `Runner désactivé : ${status.disabledReason}`);
383
385
  return { body: processQueueNow(ctx.store, user.id, params.spaceId, runNow) };
384
386
  });
385
387
  route("POST", "/spaces/:spaceId/runner/stop", (ctx, { user, params }) => {
386
388
  requireAdmin(ctx.store, user.id);
387
389
  const stopSession = ctx.runner.stopSession;
388
390
  if (!stopSession)
389
- throw new ApiError("unavailable", `Runner désactivé : ${ctx.runner.status.disabledReason}`);
391
+ throw new ApiError("unavailable", `Runner désactivé : ${ctx.runner.status().disabledReason}`);
390
392
  const abortedRequests = stopSession(params.spaceId, user.id);
391
393
  if (abortedRequests === null)
392
394
  throw new InvariantError("Aucune session du runner ne tourne dans cet espace.");
393
395
  return { body: { abortedRequests } };
394
396
  });
397
+ route("GET", "/admin/claude", (ctx, { user }) => ({ body: getClaudeConnection(ctx.store, user.id) }));
398
+ route("PUT", "/admin/claude", async (ctx, { user, request }) => {
399
+ requireAdmin(ctx.store, user.id);
400
+ const check = ctx.runner.checkClaudeToken;
401
+ if (!check)
402
+ throw new ApiError("unavailable", `Runner désactivé : ${ctx.runner.status().disabledReason}`);
403
+ const { token } = parseBody(SaveClaudeTokenRequestSchema, request.body);
404
+ const view = await saveClaudeToken(ctx.store, ctx.dataDir, user.id, token, check);
405
+ ctx.runner.resume();
406
+ return { body: view };
407
+ });
395
408
  route("GET", "/admin/runner/settings", (ctx, { user }) => ({ body: getRunnerSettings(ctx.store, user.id) }));
396
409
  route("PUT", "/admin/runner/settings", (ctx, { user, request }) => ({
397
410
  body: setRunnerSettings(ctx.store, user.id, parseBody(RunnerSettingsSchema, request.body)),
@@ -211,7 +211,7 @@ export const AGENT_TOOLS = [
211
211
  path: "tasks/{task}/checklist",
212
212
  definition: {
213
213
  name: "edit_checklist",
214
- description: "Edit the checklist of a standard task (add, rename, check or uncheck, delete items) or the checkpoints of a test task (add, rename, delete; testers record the results themselves). Operations apply in order, all or nothing. Item ids come from get_task.",
214
+ description: "Edit the checklist of a standard task (add, rename, check or uncheck, move, delete items) or the checkpoints of a test task (add, rename, move, delete; testers record the results themselves). An item is added at the end, or right after after_item_id (null: first); move places an item right after after_item_id (null: first). Operations apply in order, all or nothing. Item ids come from get_task.",
215
215
  inputSchema: {
216
216
  type: "object",
217
217
  properties: {
@@ -224,9 +224,13 @@ export const AGENT_TOOLS = [
224
224
  items: {
225
225
  type: "object",
226
226
  properties: {
227
- action: { type: "string", enum: ["add", "update", "delete"] },
228
- text: { type: "string", maxLength: MAX_CHECKLIST_ITEM_LENGTH, description: "add: text of the new item; update: new text." },
229
- item_id: { type: "string", description: "update / delete: id of the checklist item or checkpoint." },
227
+ action: { type: "string", enum: ["add", "update", "move", "delete"] },
228
+ text: { type: "string", maxLength: MAX_CHECKLIST_ITEM_LENGTH, description: "add: text of the new item (markdown); update: new text." },
229
+ item_id: { type: "string", description: "update / move / delete: id of the checklist item or checkpoint." },
230
+ after_item_id: {
231
+ type: ["string", "null"],
232
+ description: "add (optional) / move (required): id of the item to place it right after; null places it first. Omitted on add: at the end.",
233
+ },
230
234
  done: { type: "boolean", description: "update, standard task only: check (true) or uncheck (false) the item." },
231
235
  },
232
236
  required: ["action"],
@@ -15,6 +15,8 @@ export interface RunnerConfig {
15
15
  claudeDir: string;
16
16
  /** Dossier des sessions : configurations MCP éphémères, dossier courant de Claude Code. */
17
17
  workDir: string;
18
+ /** Répertoire de données du site, qui porte la clé de chiffrement du token Claude. */
19
+ dataDir: string;
18
20
  }
19
21
  /** Vrai si une session du runner peut joindre le site écoutant sur `host`, en http sur la machine. */
20
22
  export declare function isRunnerHost(host: string): boolean;
@@ -78,6 +80,14 @@ export declare class SiteRunner {
78
80
  /** Planifie une session pour l'espace ; un espace en cours de session est repris après elle. */
79
81
  schedule(spaceId: string): void;
80
82
  private drain;
83
+ /** Planifie les espaces autorisés qui ont des demandes en attente. */
84
+ resume(): void;
85
+ /**
86
+ * Vérifie un token Claude par une requête minimale (modèle Haiku, un tour,
87
+ * aucun outil ni serveur MCP), dans les conditions des sessions ; erreur avec
88
+ * la réponse de Claude Code s'il est refusé.
89
+ */
90
+ checkToken(claudeToken: string): Promise<void>;
81
91
  private runSession;
82
92
  /** Enregistre le relevé de la session : issue, modèle, tours, tokens et coût annoncé par Claude Code. */
83
93
  private record;