@imenam/mcp-organizer 1.0.3 → 1.0.8

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 (64) hide show
  1. package/README.md +154 -26
  2. package/dist/shared/schemas/admin-api.schema.d.ts +193 -0
  3. package/dist/shared/schemas/admin-api.schema.js +84 -0
  4. package/dist/shared/schemas/agent-api.schema.d.ts +27 -0
  5. package/dist/shared/schemas/agent-api.schema.js +14 -0
  6. package/dist/shared/schemas/agent-tools.schema.d.ts +48 -0
  7. package/dist/shared/schemas/agent-tools.schema.js +14 -1
  8. package/dist/shared/schemas/api.schema.d.ts +2 -0
  9. package/dist/shared/schemas/api.schema.js +2 -0
  10. package/dist/shared/schemas/entities.schema.d.ts +88 -1
  11. package/dist/shared/schemas/entities.schema.js +65 -3
  12. package/dist/shared/schemas/enums.schema.d.ts +19 -1
  13. package/dist/shared/schemas/enums.schema.js +8 -0
  14. package/dist/shared/schemas/instructions-api.schema.d.ts +42 -0
  15. package/dist/shared/schemas/instructions-api.schema.js +25 -0
  16. package/dist/shared/schemas/notifications-api.schema.d.ts +31 -0
  17. package/dist/shared/schemas/notifications-api.schema.js +22 -1
  18. package/dist/shared/schemas/tasks-api.schema.d.ts +2 -0
  19. package/dist/shared/schemas/views-api.schema.d.ts +139 -0
  20. package/dist/shared/schemas/views-api.schema.js +33 -0
  21. package/dist/src/agent-api/requests.js +6 -3
  22. package/dist/src/cli/set-admin.d.ts +1 -0
  23. package/dist/src/cli/set-admin.js +45 -0
  24. package/dist/src/cli/setup.d.ts +9 -6
  25. package/dist/src/cli/setup.js +108 -35
  26. package/dist/src/core/accounts.js +2 -1
  27. package/dist/src/core/admin.d.ts +38 -0
  28. package/dist/src/core/admin.js +130 -0
  29. package/dist/src/core/agent-instructions.d.ts +6 -0
  30. package/dist/src/core/agent-instructions.js +43 -0
  31. package/dist/src/core/agent-tokens.d.ts +9 -1
  32. package/dist/src/core/agent-tokens.js +25 -2
  33. package/dist/src/core/agent.d.ts +7 -0
  34. package/dist/src/core/agent.js +38 -1
  35. package/dist/src/core/board-views.d.ts +12 -0
  36. package/dist/src/core/board-views.js +84 -0
  37. package/dist/src/core/migrations.js +435 -344
  38. package/dist/src/core/notifications.d.ts +7 -1
  39. package/dist/src/core/notifications.js +32 -1
  40. package/dist/src/core/requests.d.ts +8 -2
  41. package/dist/src/core/requests.js +6 -5
  42. package/dist/src/core/store.d.ts +77 -5
  43. package/dist/src/core/store.js +340 -46
  44. package/dist/src/deploy/env-render.d.ts +1 -1
  45. package/dist/src/deploy/env-render.js +2 -0
  46. package/dist/src/gui-api.d.ts +17 -0
  47. package/dist/src/gui-api.js +73 -4
  48. package/dist/src/index.js +8 -1
  49. package/dist/src/mcp/start.d.ts +1 -1
  50. package/dist/src/mcp/start.js +4 -4
  51. package/dist/src/mcp/tools.js +14 -4
  52. package/dist/src/server/claude-processes.d.ts +26 -0
  53. package/dist/src/server/claude-processes.js +72 -0
  54. package/dist/src/server/claude-stream.d.ts +39 -0
  55. package/dist/src/server/claude-stream.js +111 -0
  56. package/dist/src/server/runner.d.ts +91 -0
  57. package/dist/src/server/runner.js +355 -0
  58. package/dist/src/server/start.js +26 -0
  59. package/gui/dist/assets/index-BX6iBj41.js +70 -0
  60. package/gui/dist/assets/index-CXzkYy4P.css +1 -0
  61. package/gui/dist/index.html +2 -2
  62. package/package.json +3 -2
  63. package/gui/dist/assets/index-BVN0agCc.css +0 -1
  64. package/gui/dist/assets/index-DI1_kr81.js +0 -70
@@ -3,8 +3,9 @@ import { ForbiddenError, InvariantError, NotFoundError, OrganizerError } from ".
3
3
  import { positionBetween } from "../../shared/logic/positions.js";
4
4
  import { newId } from "./ids.js";
5
5
  import { WatcherRegistry } from "./watchers.js";
6
- import { MAX_TASK_DEPTH, } from "../../shared/schemas/enums.schema.js";
7
- import { AccessLinkSchema, AgentActionSchema, AgentTokenSchema, AgentRequestSchema, AttachmentSchema, ChangeSchema, ChecklistItemSchema, CommentSchema, EntityVersionSchema, IdeaSchema, IdeaSnapshotSchema, InvitationSchema, MembershipSchema, NotificationSchema, SessionSchema, SpaceSchema, TagSchema, TaskSchema, TaskSnapshotSchema, TestCheckpointSchema, TestResultSchema, TestReviewSchema, UserSchema, UserSettingsSchema, } from "../../shared/schemas/entities.schema.js";
6
+ import { MAX_TASK_DEPTH, TASK_PRIORITIES, TASK_STATUSES, } from "../../shared/schemas/enums.schema.js";
7
+ import { AccessLinkSchema, AgentActionSchema, AgentInstructionsSchema, AgentTokenSchema, AgentRequestSchema, AttachmentSchema, BoardViewSchema, ChangeSchema, ChecklistItemSchema, CommentSchema, EntityVersionSchema, 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
9
  /** Valide `value` avec `schema` ; une donnée invalide est une erreur métier qui liste les champs fautifs. */
9
10
  function validate(schema, value, what) {
10
11
  const parsed = schema.safeParse(value);
@@ -24,9 +25,45 @@ function userFromRow(row) {
24
25
  displayName: row.display_name,
25
26
  passwordHash: row.password_hash,
26
27
  status: row.status,
28
+ isAdmin: bool(row.is_admin),
27
29
  createdAt: row.created_at,
28
30
  });
29
31
  }
32
+ function spaceNotificationSettingsFromRow(row) {
33
+ return SpaceNotificationSettingsSchema.parse({
34
+ userId: row.user_id,
35
+ spaceId: row.space_id,
36
+ notifyAssignApp: bool(row.notify_assign_app),
37
+ notifyAssignEmail: bool(row.notify_assign_email),
38
+ notifyCommentApp: bool(row.notify_comment_app),
39
+ notifyCommentEmail: bool(row.notify_comment_email),
40
+ });
41
+ }
42
+ function agentInstructionsFromRow(row) {
43
+ return AgentInstructionsSchema.parse({ spaceId: row.space_id, text: row.text, updatedAt: row.updated_at, updatedBy: row.updated_by });
44
+ }
45
+ function runnerSessionFromRow(row) {
46
+ return RunnerSessionRecordSchema.parse({
47
+ id: row.id,
48
+ spaceId: row.space_id,
49
+ spaceName: row.space_name,
50
+ startedAt: row.started_at,
51
+ endedAt: row.ended_at,
52
+ outcome: row.outcome,
53
+ model: row.model,
54
+ turns: row.turns,
55
+ costUsd: row.cost_usd,
56
+ inputTokens: row.input_tokens,
57
+ outputTokens: row.output_tokens,
58
+ cacheReadTokens: row.cache_read_tokens,
59
+ cacheCreationTokens: row.cache_creation_tokens,
60
+ });
61
+ }
62
+ /** Les quatre préférences de notification d'un objet qui les porte. */
63
+ function preferencesOf(source) {
64
+ const { notifyAssignApp, notifyAssignEmail, notifyCommentApp, notifyCommentEmail } = source;
65
+ return { notifyAssignApp, notifyAssignEmail, notifyCommentApp, notifyCommentEmail };
66
+ }
30
67
  function settingsFromRow(row) {
31
68
  return UserSettingsSchema.parse({
32
69
  userId: row.user_id,
@@ -34,6 +71,7 @@ function settingsFromRow(row) {
34
71
  notifyAssignEmail: bool(row.notify_assign_email),
35
72
  notifyCommentApp: bool(row.notify_comment_app),
36
73
  notifyCommentEmail: bool(row.notify_comment_email),
74
+ assistantHistory: row.assistant_history,
37
75
  });
38
76
  }
39
77
  function sessionFromRow(row) {
@@ -63,6 +101,7 @@ function agentTokenFromRow(row) {
63
101
  lastUsedAt: row.last_used_at,
64
102
  expiresAt: row.expires_at,
65
103
  revokedAt: row.revoked_at,
104
+ isRunner: bool(row.is_runner),
66
105
  });
67
106
  }
68
107
  function invitationFromRow(row) {
@@ -86,6 +125,7 @@ function spaceFromRow(row) {
86
125
  ownerId: row.owner_id,
87
126
  keyPrefix: row.key_prefix,
88
127
  nextTaskNumber: row.next_task_number,
128
+ runnerAllowed: bool(row.runner_allowed),
89
129
  createdAt: row.created_at,
90
130
  });
91
131
  }
@@ -125,6 +165,23 @@ function ideaFromRow(row) {
125
165
  createdAt: row.created_at,
126
166
  });
127
167
  }
168
+ function boardViewFromRow(row) {
169
+ return BoardViewSchema.parse({
170
+ id: row.id,
171
+ spaceId: row.space_id,
172
+ userId: row.user_id,
173
+ name: row.name,
174
+ layout: row.layout,
175
+ groupBy: row.group_by,
176
+ thenBy: row.then_by,
177
+ showEmptyGroups: bool(row.show_empty_groups),
178
+ statuses: JSON.parse(row.statuses),
179
+ priorities: JSON.parse(row.priorities),
180
+ position: row.position,
181
+ createdAt: row.created_at,
182
+ updatedAt: row.updated_at,
183
+ });
184
+ }
128
185
  function requestFromRow(row) {
129
186
  return AgentRequestSchema.parse({
130
187
  id: row.id,
@@ -136,6 +193,7 @@ function requestFromRow(row) {
136
193
  text: row.text,
137
194
  status: row.status,
138
195
  reply: row.reply,
196
+ followUps: JSON.parse(row.follow_ups),
139
197
  failureReason: row.failure_reason,
140
198
  createdAt: row.created_at,
141
199
  updatedAt: row.updated_at,
@@ -278,6 +336,7 @@ export class Store {
278
336
  activeMutation = null;
279
337
  emailListener = null;
280
338
  pendingRequestListeners = new Set();
339
+ runnerAllowedListeners = new Set();
281
340
  /** Présence des veilleurs de notifications, par jeton d'agent. */
282
341
  watchers = new WatcherRegistry();
283
342
  constructor(db) {
@@ -308,6 +367,36 @@ export class Store {
308
367
  countUsers() {
309
368
  return this.db.prepare("SELECT COUNT(*) AS n FROM users").get().n;
310
369
  }
370
+ /** Tous les comptes, du plus ancien au plus récent. */
371
+ listUsers() {
372
+ return this.db.prepare("SELECT * FROM users ORDER BY created_at, id").all().map(userFromRow);
373
+ }
374
+ countAdmins() {
375
+ return this.db.prepare("SELECT COUNT(*) AS n FROM users WHERE is_admin = 1").get().n;
376
+ }
377
+ /** Préférences de notification propres à un espace, ou null si l'utilisateur y suit celles de son compte. */
378
+ findSpaceNotificationSettings(userId, spaceId) {
379
+ const row = this.db.prepare("SELECT * FROM space_notification_settings WHERE user_id = ? AND space_id = ?").get(userId, spaceId);
380
+ return row ? spaceNotificationSettingsFromRow(row) : null;
381
+ }
382
+ /** Limites d'une session du runner. */
383
+ getRunnerSettings() {
384
+ const row = this.db.prepare("SELECT * FROM runner_settings WHERE id = 1").get();
385
+ return RunnerSettingsSchema.parse({ maxTurns: row.max_turns, maxMinutes: row.max_minutes, maxBudgetUsd: row.max_budget_usd });
386
+ }
387
+ /** Sessions du runner commencées depuis `since`, de la plus récente à la plus ancienne. */
388
+ listRunnerSessionsSince(since) {
389
+ return this.db.prepare("SELECT * FROM runner_sessions WHERE started_at >= ? ORDER BY started_at DESC, id").all(since).map(runnerSessionFromRow);
390
+ }
391
+ /** Instructions de l'agent propres à un espace, ou celles du site quand `spaceId` est null ; null s'il n'y en a pas. */
392
+ findAgentInstructions(spaceId) {
393
+ const row = this.db.prepare("SELECT * FROM agent_instructions WHERE space_id IS ?").get(spaceId);
394
+ return row ? agentInstructionsFromRow(row) : null;
395
+ }
396
+ /** Préférences de notification qui s'appliquent à un utilisateur dans un espace : celles de l'espace, sinon celles du compte. */
397
+ notificationPreferences(userId, spaceId) {
398
+ return preferencesOf(this.findSpaceNotificationSettings(userId, spaceId) ?? this.getUserSettings(userId));
399
+ }
311
400
  getUserSettings(userId) {
312
401
  const row = this.db.prepare("SELECT * FROM user_settings WHERE user_id = ?").get(userId);
313
402
  if (!row)
@@ -338,6 +427,11 @@ export class Store {
338
427
  return row ? agentTokenFromRow(row) : null;
339
428
  }
340
429
  /** Jetons qui couvrent un espace, tous propriétaires confondus, du plus récemment utilisé au moins récemment. */
430
+ /** Jeton du runner de l'espace, s'il a déjà servi. */
431
+ findRunnerToken(spaceId) {
432
+ const row = this.db.prepare("SELECT * FROM agent_tokens WHERE space_id = ? AND is_runner = 1 AND revoked_at IS NULL").get(spaceId);
433
+ return row ? agentTokenFromRow(row) : null;
434
+ }
341
435
  listAgentTokensOfSpace(spaceId) {
342
436
  const rows = this.db
343
437
  .prepare("SELECT * FROM agent_tokens WHERE space_id = ? ORDER BY last_used_at IS NULL, last_used_at DESC, created_at DESC, id DESC")
@@ -392,11 +486,16 @@ export class Store {
392
486
  /** Espaces dont l'utilisateur est membre : son espace personnel d'abord, puis les espaces communs par nom. */
393
487
  listSpacesOf(userId) {
394
488
  const rows = this.db
395
- .prepare(`SELECT s.* FROM spaces s JOIN memberships m ON m.space_id = s.id
489
+ .prepare(`SELECT s.* FROM spaces s JOIN memberships m ON m.space_id = s.id
396
490
  WHERE m.user_id = ? ORDER BY s.kind = 'shared', s.name COLLATE NOCASE`)
397
491
  .all(userId);
398
492
  return rows.map(spaceFromRow);
399
493
  }
494
+ /** Tous les espaces : les espaces personnels d'abord, puis les espaces communs par nom. */
495
+ listAllSpaces() {
496
+ const rows = this.db.prepare("SELECT * FROM spaces ORDER BY kind = 'shared', name COLLATE NOCASE, id").all();
497
+ return rows.map(spaceFromRow);
498
+ }
400
499
  listMemberships(spaceId) {
401
500
  const rows = this.db.prepare("SELECT * FROM memberships WHERE space_id = ? ORDER BY joined_at, user_id").all(spaceId);
402
501
  return rows.map(membershipFromRow);
@@ -542,7 +641,7 @@ export class Store {
542
641
  /** Résultats saisis sur les points des tâches d'un espace. */
543
642
  listTestResultsInSpace(spaceId) {
544
643
  const rows = this.db
545
- .prepare(`SELECT c.task_id, r.checkpoint_id, r.tester_id, r.result FROM test_results r
644
+ .prepare(`SELECT c.task_id, r.checkpoint_id, r.tester_id, r.result FROM test_results r
546
645
  JOIN test_checkpoints c ON c.id = r.checkpoint_id JOIN tasks t ON t.id = c.task_id WHERE t.space_id = ?`)
547
646
  .all(spaceId);
548
647
  return rows.map((row) => ({
@@ -587,7 +686,7 @@ export class Store {
587
686
  /** Pièces jointes d'une tâche et de toutes ses sous-tâches. */
588
687
  listAttachmentsInSubtree(taskId) {
589
688
  const rows = this.db
590
- .prepare(`WITH RECURSIVE subtree(id) AS (SELECT ? UNION ALL SELECT t.id FROM tasks t JOIN subtree s ON t.parent_id = s.id)
689
+ .prepare(`WITH RECURSIVE subtree(id) AS (SELECT ? UNION ALL SELECT t.id FROM tasks t JOIN subtree s ON t.parent_id = s.id)
591
690
  SELECT a.* FROM attachments a JOIN subtree s ON a.task_id = s.id`)
592
691
  .all(taskId);
593
692
  return rows.map(attachmentFromRow);
@@ -617,11 +716,27 @@ export class Store {
617
716
  /** Demandes de promotion (`idea_promotion`) en attente ou en cours sur les idées d'un espace. */
618
717
  listOpenPromotionRequests(spaceId) {
619
718
  const rows = this.db
620
- .prepare(`SELECT r.* FROM agent_requests r JOIN ideas i ON i.id = r.context_idea_id
719
+ .prepare(`SELECT r.* FROM agent_requests r JOIN ideas i ON i.id = r.context_idea_id
621
720
  WHERE i.space_id = ? AND r.kind = 'idea_promotion' AND r.status IN ('pending', 'processing') ORDER BY r.created_at, r.id`)
622
721
  .all(spaceId);
623
722
  return rows.map(requestFromRow);
624
723
  }
724
+ // --- Vues du tableau de bord ---
725
+ findBoardView(id) {
726
+ const row = this.db.prepare("SELECT * FROM board_views WHERE id = ?").get(id);
727
+ return row ? boardViewFromRow(row) : null;
728
+ }
729
+ getBoardView(id) {
730
+ const view = this.findBoardView(id);
731
+ if (!view)
732
+ throw new NotFoundError(`Board view ${id} not found.`);
733
+ return view;
734
+ }
735
+ /** Vues d'un membre dans un espace, dans l'ordre des onglets. */
736
+ listBoardViews(spaceId, userId) {
737
+ const rows = this.db.prepare("SELECT * FROM board_views WHERE space_id = ? AND user_id = ? ORDER BY position, id").all(spaceId, userId);
738
+ return rows.map(boardViewFromRow);
739
+ }
625
740
  /** Tâches de test qui vérifient une tâche. */
626
741
  listTestsOf(taskId) {
627
742
  const rows = this.db.prepare("SELECT * FROM tasks WHERE tested_task_id = ? ORDER BY number").all(taskId);
@@ -650,6 +765,21 @@ export class Store {
650
765
  .all({ spaceId, status, limit });
651
766
  return rows.map(requestFromRow);
652
767
  }
768
+ /**
769
+ * Échanges clos (traités ou en échec) d'un auteur dans un espace, antérieurs à
770
+ * la demande `before`, du plus ancien au plus récent : les `limit` derniers.
771
+ */
772
+ listClosedRequestsOfAuthorBefore(spaceId, authorId, before, limit) {
773
+ if (limit === 0)
774
+ return [];
775
+ const rows = this.db
776
+ .prepare(`SELECT * FROM agent_requests
777
+ WHERE target_space_id = @spaceId AND author_id = @authorId AND status IN ('done', 'failed')
778
+ AND (created_at < @createdAt OR (created_at = @createdAt AND id < @id))
779
+ ORDER BY created_at DESC, id DESC LIMIT @limit`)
780
+ .all({ spaceId, authorId, createdAt: before.createdAt, id: before.id, limit });
781
+ return rows.map(requestFromRow).reverse();
782
+ }
653
783
  /** Demandes d'un espace, de la plus récente à la plus ancienne, au plus `limit`. */
654
784
  listAgentRequestsOfSpace(spaceId, limit) {
655
785
  const rows = this.db
@@ -712,9 +842,9 @@ export class Store {
712
842
  */
713
843
  listNotifications(userId, limit, offset) {
714
844
  const rows = this.db
715
- .prepare(`SELECT n.* FROM notifications n JOIN tasks t ON t.id = n.task_id
716
- JOIN memberships m ON m.space_id = t.space_id AND m.user_id = n.user_id
717
- WHERE n.user_id = ? AND n.in_app = 1
845
+ .prepare(`SELECT n.* FROM notifications n JOIN tasks t ON t.id = n.task_id
846
+ JOIN memberships m ON m.space_id = t.space_id AND m.user_id = n.user_id
847
+ WHERE n.user_id = ? AND n.in_app = 1
718
848
  ORDER BY n.read_at IS NOT NULL, n.created_at DESC, n.id DESC LIMIT ? OFFSET ?`)
719
849
  .all(userId, limit, offset);
720
850
  return rows.map(notificationFromRow);
@@ -722,8 +852,8 @@ export class Store {
722
852
  /** Nombre de notifications non lues affichées dans l'application d'un utilisateur. */
723
853
  countUnreadNotifications(userId) {
724
854
  const row = this.db
725
- .prepare(`SELECT COUNT(*) AS n FROM notifications n JOIN tasks t ON t.id = n.task_id
726
- JOIN memberships m ON m.space_id = t.space_id AND m.user_id = n.user_id
855
+ .prepare(`SELECT COUNT(*) AS n FROM notifications n JOIN tasks t ON t.id = n.task_id
856
+ JOIN memberships m ON m.space_id = t.space_id AND m.user_id = n.user_id
727
857
  WHERE n.user_id = ? AND n.in_app = 1 AND n.read_at IS NULL`)
728
858
  .get(userId);
729
859
  return row.n;
@@ -752,8 +882,8 @@ export class Store {
752
882
  */
753
883
  listChangesForUser(userId, since, limit) {
754
884
  const rows = this.db
755
- .prepare(`SELECT * FROM changes WHERE seq > ?
756
- AND (user_id = ? OR space_id IN (SELECT space_id FROM memberships WHERE user_id = ?))
885
+ .prepare(`SELECT * FROM changes WHERE seq > ?
886
+ AND (user_id = ? OR space_id IN (SELECT space_id FROM memberships WHERE user_id = ?))
757
887
  ORDER BY seq LIMIT ?`)
758
888
  .all(since, userId, userId, limit);
759
889
  return rows.map(changeFromRow);
@@ -780,6 +910,11 @@ export class Store {
780
910
  this.pendingRequestListeners.add(listener);
781
911
  return () => this.pendingRequestListeners.delete(listener);
782
912
  }
913
+ /** Abonne `listener` aux espaces où le runner vient d'être autorisé, après la validation de la mutation. */
914
+ onRunnerAllowed(listener) {
915
+ this.runnerAllowedListeners.add(listener);
916
+ return () => this.runnerAllowedListeners.delete(listener);
917
+ }
783
918
  /**
784
919
  * Point unique d'écriture. `fn` reçoit une `Mutation` et s'exécute dans une
785
920
  * transaction exclusive ; à sa sortie, les invariants sont vérifiés sur l'état
@@ -791,6 +926,7 @@ export class Store {
791
926
  throw new Error("Store.mutate is not reentrant: use the Mutation passed to the running mutation.");
792
927
  let emails = [];
793
928
  let pending = [];
929
+ let allowed = [];
794
930
  const run = this.db.transaction(() => {
795
931
  const tx = new Mutation(this, actor);
796
932
  this.activeMutation = tx;
@@ -799,6 +935,7 @@ export class Store {
799
935
  tx.finish();
800
936
  emails = tx.emailNotificationIds;
801
937
  pending = tx.pendingRequestIds;
938
+ allowed = tx.runnerAllowedSpaceIds;
802
939
  return result;
803
940
  }
804
941
  finally {
@@ -815,6 +952,11 @@ export class Store {
815
952
  listener(request);
816
953
  }
817
954
  }
955
+ for (const id of allowed) {
956
+ const space = this.getSpace(id);
957
+ for (const listener of [...this.runnerAllowedListeners])
958
+ listener(space);
959
+ }
818
960
  return result;
819
961
  }
820
962
  }
@@ -833,6 +975,8 @@ export class Mutation {
833
975
  emailNotificationIds = [];
834
976
  /** Demandes passées en attente par la mutation : créées, ou libérées. */
835
977
  pendingRequestIds = [];
978
+ /** Espaces où la mutation a autorisé le runner. */
979
+ runnerAllowedSpaceIds = [];
836
980
  /** Demande pour laquelle agit l'agent, lue au début de la mutation. */
837
981
  request;
838
982
  /** Jeton avec lequel agit l'agent. */
@@ -917,6 +1061,7 @@ export class Mutation {
917
1061
  displayName: input.displayName ?? null,
918
1062
  passwordHash: input.passwordHash ?? null,
919
1063
  status: input.status,
1064
+ isAdmin: input.isAdmin ?? false,
920
1065
  createdAt: this.now,
921
1066
  }, "user");
922
1067
  if (user.status !== "invited" && user.displayName === null) {
@@ -925,8 +1070,8 @@ export class Mutation {
925
1070
  if (this.store.findUserByEmail(user.email))
926
1071
  throw new InvariantError(`An account already exists for ${user.email}.`);
927
1072
  this.db
928
- .prepare("INSERT INTO users (id, email, display_name, password_hash, status, created_at) VALUES (?, ?, ?, ?, ?, ?)")
929
- .run(user.id, user.email, user.displayName, user.passwordHash, user.status, user.createdAt);
1073
+ .prepare("INSERT INTO users (id, email, display_name, password_hash, status, is_admin, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
1074
+ .run(user.id, user.email, user.displayName, user.passwordHash, user.status, user.isAdmin ? 1 : 0, user.createdAt);
930
1075
  this.db.prepare("INSERT INTO user_settings (user_id) VALUES (?)").run(user.id);
931
1076
  this.touch("user", user.id, null, user.id);
932
1077
  return user;
@@ -943,6 +1088,13 @@ export class Mutation {
943
1088
  this.touch("user", id, null, id);
944
1089
  return user;
945
1090
  }
1091
+ /** Accorde ou retire le rôle d'administrateur du site. */
1092
+ setUserAdmin(id, isAdmin) {
1093
+ const user = { ...this.store.getUser(id), isAdmin };
1094
+ this.db.prepare("UPDATE users SET is_admin = ? WHERE id = ?").run(isAdmin ? 1 : 0, id);
1095
+ this.touch("user", id, null, id);
1096
+ return user;
1097
+ }
946
1098
  // --- Sessions et liens d'accès ---
947
1099
  createSession(session) {
948
1100
  const valid = validate(SessionSchema, session, "session");
@@ -1009,13 +1161,13 @@ export class Mutation {
1009
1161
  createAgentToken(input) {
1010
1162
  if (this.actor.type !== "user")
1011
1163
  throw new InvariantError("Only a user can create an agent token.");
1012
- const token = validate(AgentTokenSchema, { id: newId(), userId: this.actor.userId, ...input, createdAt: this.now, lastUsedAt: null, revokedAt: null }, "agent token");
1164
+ const token = validate(AgentTokenSchema, { id: newId(), userId: this.actor.userId, ...input, isRunner: input.isRunner ?? false, createdAt: this.now, lastUsedAt: null, revokedAt: null }, "agent token");
1013
1165
  if (!this.store.isMember(token.spaceId, token.userId))
1014
1166
  throw new ForbiddenError("An agent token can only cover a space its owner is a member of.");
1015
1167
  this.db
1016
- .prepare(`INSERT INTO agent_tokens (id, user_id, space_id, name, prefix, token_hash, created_at, expires_at)
1017
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
1018
- .run(token.id, token.userId, token.spaceId, token.name, token.prefix, token.tokenHash, token.createdAt, token.expiresAt);
1168
+ .prepare(`INSERT INTO agent_tokens (id, user_id, space_id, name, prefix, token_hash, created_at, expires_at, is_runner)
1169
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1170
+ .run(token.id, token.userId, token.spaceId, token.name, token.prefix, token.tokenHash, token.createdAt, token.expiresAt, token.isRunner ? 1 : 0);
1019
1171
  this.touch("agent_token", token.id, null, token.userId);
1020
1172
  return token;
1021
1173
  }
@@ -1030,6 +1182,14 @@ export class Mutation {
1030
1182
  this.touch("agent_token", id, null, token.userId);
1031
1183
  return { ...token, revokedAt: this.now };
1032
1184
  }
1185
+ /** Remplace la valeur d'un jeton du runner : l'ancienne valeur est aussitôt refusée. */
1186
+ rotateRunnerToken(id, prefix, tokenHash) {
1187
+ const token = this.store.findAgentToken(id);
1188
+ if (!token || !token.isRunner)
1189
+ throw new NotFoundError(`Runner token ${id} not found.`);
1190
+ this.db.prepare("UPDATE agent_tokens SET prefix = ?, token_hash = ? WHERE id = ?").run(prefix, tokenHash, id);
1191
+ return { ...token, prefix, tokenHash };
1192
+ }
1033
1193
  /** Date du dernier usage d'un jeton ; le journal des changements n'en garde pas trace. */
1034
1194
  recordAgentTokenUse(id, at) {
1035
1195
  this.db.prepare("UPDATE agent_tokens SET last_used_at = ? WHERE id = ?").run(at, id);
@@ -1105,7 +1265,7 @@ export class Mutation {
1105
1265
  // --- Espaces et membres ---
1106
1266
  /** Crée un espace et en fait de son propriétaire le membre `owner`. */
1107
1267
  createSpace(input) {
1108
- const space = validate(SpaceSchema, { id: newId(), name: input.name, kind: input.kind, ownerId: input.ownerId, keyPrefix: input.keyPrefix, nextTaskNumber: 1, createdAt: this.now }, "space");
1268
+ const space = validate(SpaceSchema, { id: newId(), name: input.name, kind: input.kind, ownerId: input.ownerId, keyPrefix: input.keyPrefix, nextTaskNumber: 1, runnerAllowed: false, createdAt: this.now }, "space");
1109
1269
  this.store.getUser(space.ownerId);
1110
1270
  if (space.kind === "personal" && this.store.findPersonalSpace(space.ownerId)) {
1111
1271
  throw new InvariantError(`User ${space.ownerId} already has a personal space.`);
@@ -1117,6 +1277,15 @@ export class Mutation {
1117
1277
  this.insertMembership(space.id, space.ownerId, "owner");
1118
1278
  return space;
1119
1279
  }
1280
+ /** Autorise ou interdit le runner sur un espace. */
1281
+ setSpaceRunnerAllowed(id, allowed) {
1282
+ const space = { ...this.store.getSpace(id), runnerAllowed: allowed };
1283
+ this.db.prepare("UPDATE spaces SET runner_allowed = ? WHERE id = ?").run(allowed ? 1 : 0, id);
1284
+ if (allowed)
1285
+ this.runnerAllowedSpaceIds.push(id);
1286
+ this.touch("space", id, id, null);
1287
+ return space;
1288
+ }
1120
1289
  renameSpace(id, name) {
1121
1290
  const space = validate(SpaceSchema, { ...this.store.getSpace(id), name }, "space");
1122
1291
  this.db.prepare("UPDATE spaces SET name = ? WHERE id = ?").run(space.name, id);
@@ -1132,7 +1301,7 @@ export class Mutation {
1132
1301
  this.touch("membership", `${id}:${membership.userId}`, id, membership.userId);
1133
1302
  }
1134
1303
  this.db
1135
- .prepare(`DELETE FROM entity_versions WHERE (entity_type = 'task' AND entity_id IN (SELECT id FROM tasks WHERE space_id = ?))
1304
+ .prepare(`DELETE FROM entity_versions WHERE (entity_type = 'task' AND entity_id IN (SELECT id FROM tasks WHERE space_id = ?))
1136
1305
  OR (entity_type = 'idea' AND entity_id IN (SELECT id FROM ideas WHERE space_id = ?))`)
1137
1306
  .run(id, id);
1138
1307
  this.db.prepare("DELETE FROM spaces WHERE id = ?").run(id);
@@ -1158,6 +1327,8 @@ export class Mutation {
1158
1327
  if (!this.store.findMembership(spaceId, userId))
1159
1328
  throw new NotFoundError(`User ${userId} is not a member of space ${spaceId}.`);
1160
1329
  this.db.prepare("DELETE FROM memberships WHERE space_id = ? AND user_id = ?").run(spaceId, userId);
1330
+ this.db.prepare("DELETE FROM space_notification_settings WHERE space_id = ? AND user_id = ?").run(spaceId, userId);
1331
+ this.db.prepare("DELETE FROM board_views WHERE space_id = ? AND user_id = ?").run(spaceId, userId);
1161
1332
  this.touch("membership", `${spaceId}:${userId}`, spaceId, userId);
1162
1333
  const tokenIds = this.db.prepare("SELECT id FROM agent_tokens WHERE space_id = ? AND user_id = ? AND revoked_at IS NULL").pluck().all(spaceId, userId);
1163
1334
  this.db.prepare("UPDATE agent_tokens SET revoked_at = ? WHERE space_id = ? AND user_id = ? AND revoked_at IS NULL").run(this.now, spaceId, userId);
@@ -1195,8 +1366,8 @@ export class Mutation {
1195
1366
  version: 1,
1196
1367
  }, "task");
1197
1368
  this.db
1198
- .prepare(`INSERT INTO tasks (id, space_id, number, parent_id, depth, type, title, description, status, priority, position,
1199
- created_by, created_at, updated_at, version)
1369
+ .prepare(`INSERT INTO tasks (id, space_id, number, parent_id, depth, type, title, description, status, priority, position,
1370
+ created_by, created_at, updated_at, version)
1200
1371
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1201
1372
  .run(task.id, task.spaceId, task.number, task.parentId, task.depth, task.type, task.title, task.description, task.status, task.priority, task.position, task.createdBy, task.createdAt, task.updatedAt, task.version);
1202
1373
  this.db.prepare("UPDATE spaces SET next_task_number = next_task_number + 1 WHERE id = ?").run(space.id);
@@ -1230,7 +1401,7 @@ export class Mutation {
1230
1401
  const testedTaskId = fields.testedTaskId !== undefined ? fields.testedTaskId : type === "standard" ? null : current.testedTaskId;
1231
1402
  const task = validate(TaskSchema, { ...current, ...fields, parentId, depth, status, position, testedTaskId, updatedAt: this.now }, "task");
1232
1403
  this.db
1233
- .prepare(`UPDATE tasks SET parent_id = ?, depth = ?, type = ?, title = ?, description = ?, status = ?, priority = ?,
1404
+ .prepare(`UPDATE tasks SET parent_id = ?, depth = ?, type = ?, title = ?, description = ?, status = ?, priority = ?,
1234
1405
  position = ?, tested_task_id = ?, updated_at = ? WHERE id = ?`)
1235
1406
  .run(task.parentId, task.depth, task.type, task.title, task.description, task.status, task.priority, task.position, task.testedTaskId, task.updatedAt, id);
1236
1407
  this.touch("task", id, task.spaceId, null);
@@ -1489,7 +1660,7 @@ export class Mutation {
1489
1660
  updatedAt: this.now,
1490
1661
  }, "test result");
1491
1662
  this.db
1492
- .prepare(`INSERT INTO test_results (checkpoint_id, tester_id, result, comment, updated_at) VALUES (?, ?, ?, ?, ?)
1663
+ .prepare(`INSERT INTO test_results (checkpoint_id, tester_id, result, comment, updated_at) VALUES (?, ?, ?, ?, ?)
1493
1664
  ON CONFLICT (checkpoint_id, tester_id) DO UPDATE SET result = excluded.result, comment = excluded.comment, updated_at = excluded.updated_at`)
1494
1665
  .run(result.checkpointId, result.testerId, result.result, result.comment, result.updatedAt);
1495
1666
  this.touch("test_result", `${checkpointId}:${testerId}`, task.spaceId, null, task.id);
@@ -1652,7 +1823,7 @@ export class Mutation {
1652
1823
  createdAt: this.now,
1653
1824
  }, "idea");
1654
1825
  this.db
1655
- .prepare(`INSERT INTO ideas (id, space_id, author_id, text, origin, request_id, promoted_task_id, archived_at, created_at)
1826
+ .prepare(`INSERT INTO ideas (id, space_id, author_id, text, origin, request_id, promoted_task_id, archived_at, created_at)
1656
1827
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1657
1828
  .run(idea.id, idea.spaceId, idea.authorId, idea.text, idea.origin, idea.requestId, idea.promotedTaskId, idea.archivedAt, idea.createdAt);
1658
1829
  this.touch("idea", idea.id, idea.spaceId, null);
@@ -1684,6 +1855,43 @@ export class Mutation {
1684
1855
  this.db.prepare("DELETE FROM ideas WHERE id = ?").run(id);
1685
1856
  this.touch("idea", id, idea.spaceId, null);
1686
1857
  }
1858
+ // --- Vues du tableau de bord ---
1859
+ /** Ajoute une vue à celles d'un membre dans un espace, après la dernière. */
1860
+ createBoardView(spaceId, userId, settings) {
1861
+ if (!this.store.findMembership(spaceId, userId))
1862
+ throw new NotFoundError(`User ${userId} is not a member of space ${spaceId}.`);
1863
+ const last = this.db.prepare("SELECT MAX(position) AS max FROM board_views WHERE space_id = ? AND user_id = ?").get(spaceId, userId);
1864
+ const view = validate(BoardViewSchema, {
1865
+ id: newId(),
1866
+ spaceId,
1867
+ userId,
1868
+ ...normalizedSettings(settings),
1869
+ position: last.max === null ? 1 : Math.floor(last.max) + 1,
1870
+ createdAt: this.now,
1871
+ updatedAt: this.now,
1872
+ }, "board view");
1873
+ this.db
1874
+ .prepare(`INSERT INTO board_views (id, space_id, user_id, name, layout, group_by, then_by, show_empty_groups, statuses, priorities, position, created_at, updated_at)
1875
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1876
+ .run(view.id, view.spaceId, view.userId, view.name, view.layout, view.groupBy, view.thenBy, view.showEmptyGroups ? 1 : 0, JSON.stringify(view.statuses), JSON.stringify(view.priorities), view.position, view.createdAt, view.updatedAt);
1877
+ this.touch("board_view", view.id, null, userId);
1878
+ return view;
1879
+ }
1880
+ updateBoardView(id, patch) {
1881
+ const current = this.store.getBoardView(id);
1882
+ const view = validate(BoardViewSchema, { ...current, ...normalizedSettings({ ...current, ...definedFields(patch) }), updatedAt: this.now }, "board view");
1883
+ this.db
1884
+ .prepare(`UPDATE board_views SET name = ?, layout = ?, group_by = ?, then_by = ?, show_empty_groups = ?, statuses = ?, priorities = ?, updated_at = ?
1885
+ WHERE id = ?`)
1886
+ .run(view.name, view.layout, view.groupBy, view.thenBy, view.showEmptyGroups ? 1 : 0, JSON.stringify(view.statuses), JSON.stringify(view.priorities), view.updatedAt, id);
1887
+ this.touch("board_view", id, null, view.userId);
1888
+ return view;
1889
+ }
1890
+ deleteBoardView(id) {
1891
+ const view = this.store.getBoardView(id);
1892
+ this.db.prepare("DELETE FROM board_views WHERE id = ?").run(id);
1893
+ this.touch("board_view", id, null, view.userId);
1894
+ }
1687
1895
  // --- Demandes ---
1688
1896
  /** Dépose une demande `pending` de l'utilisateur acteur. */
1689
1897
  createAgentRequest(input) {
@@ -1699,6 +1907,7 @@ export class Mutation {
1699
1907
  text: input.text,
1700
1908
  status: "pending",
1701
1909
  reply: null,
1910
+ followUps: [],
1702
1911
  failureReason: null,
1703
1912
  createdAt: this.now,
1704
1913
  updatedAt: this.now,
@@ -1709,8 +1918,8 @@ export class Mutation {
1709
1918
  }, "request");
1710
1919
  this.store.getSpace(request.targetSpaceId);
1711
1920
  this.db
1712
- .prepare(`INSERT INTO agent_requests (id, author_id, target_space_id, kind, context_task_id, context_idea_id,
1713
- text, status, created_at, updated_at)
1921
+ .prepare(`INSERT INTO agent_requests (id, author_id, target_space_id, kind, context_task_id, context_idea_id,
1922
+ text, status, created_at, updated_at)
1714
1923
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1715
1924
  .run(request.id, request.authorId, request.targetSpaceId, request.kind, request.contextTaskId, request.contextIdeaId, request.text, request.status, request.createdAt, request.updatedAt);
1716
1925
  this.createdRequestIds.add(request.id);
@@ -1764,6 +1973,18 @@ export class Mutation {
1764
1973
  this.touchRequest(released);
1765
1974
  return released;
1766
1975
  }
1976
+ /** Termine en échec une demande `processing` dont l'agent a été arrêté, avec la raison montrée à son auteur. */
1977
+ abortAgentRequest(id, reason) {
1978
+ if (this.actor.type !== "user")
1979
+ throw new InvariantError("Only a user can abort a request.");
1980
+ const current = this.store.getAgentRequest(id);
1981
+ if (current.status !== "processing")
1982
+ throw new InvariantError(`Request ${id} is ${current.status}: only a processing request can be aborted.`);
1983
+ this.db.prepare("UPDATE agent_requests SET status = 'failed', failure_reason = ?, completed_at = ?, updated_at = ? WHERE id = ?").run(reason, this.now, this.now, id);
1984
+ const aborted = this.store.getAgentRequest(id);
1985
+ this.touchRequest(aborted);
1986
+ return aborted;
1987
+ }
1767
1988
  /** Demande et jeton de l'agent acteur. */
1768
1989
  agentRequest() {
1769
1990
  if (!this.request || !this.token)
@@ -1788,15 +2009,15 @@ export class Mutation {
1788
2009
  this.touchRequest(claimed);
1789
2010
  return claimed;
1790
2011
  }
1791
- /** Termine la demande de l'agent avec son message de compte rendu. */
1792
- completeAgentRequest(reply) {
1793
- return this.finishAgentRequest("done", reply, "reply");
2012
+ /** Termine la demande de l'agent avec son message de compte rendu et les points que l'auteur doit encore régler. */
2013
+ completeAgentRequest(reply, followUps) {
2014
+ return this.finishAgentRequest("done", reply, "reply", followUps);
1794
2015
  }
1795
2016
  /** Termine la demande de l'agent en échec, avec la raison montrée à son auteur. */
1796
2017
  failAgentRequest(reason) {
1797
- return this.finishAgentRequest("failed", reason, "reason");
2018
+ return this.finishAgentRequest("failed", reason, "reason", []);
1798
2019
  }
1799
- finishAgentRequest(status, message, what) {
2020
+ finishAgentRequest(status, message, what, followUps) {
1800
2021
  const { request, token } = this.agentRequest();
1801
2022
  this.assertRequestInTokenSpace(request, token);
1802
2023
  if (request.status !== "processing") {
@@ -1807,9 +2028,10 @@ export class Mutation {
1807
2028
  if (text === "")
1808
2029
  throw new OrganizerError(`The ${what} is empty: write a short message for the author of the request.`);
1809
2030
  const column = status === "done" ? "reply" : "failure_reason";
2031
+ const points = followUps.map((point) => point.trim()).filter((point) => point !== "");
1810
2032
  this.db
1811
- .prepare(`UPDATE agent_requests SET status = ?, ${column} = ?, completed_at = ?, updated_at = ? WHERE id = ?`)
1812
- .run(status, text, this.now, this.now, request.id);
2033
+ .prepare(`UPDATE agent_requests SET status = ?, ${column} = ?, follow_ups = ?, completed_at = ?, updated_at = ? WHERE id = ?`)
2034
+ .run(status, text, JSON.stringify(points), this.now, this.now, request.id);
1813
2035
  const finished = this.store.getAgentRequest(request.id);
1814
2036
  this.touchRequest(finished);
1815
2037
  return finished;
@@ -1835,7 +2057,7 @@ export class Mutation {
1835
2057
  tokenId: token.id,
1836
2058
  }, "agent action");
1837
2059
  this.db
1838
- .prepare(`INSERT INTO agent_actions (id, request_id, seq, entity_type, entity_id, operation, before, after, summary, created_at, token_id)
2060
+ .prepare(`INSERT INTO agent_actions (id, request_id, seq, entity_type, entity_id, operation, before, after, summary, created_at, token_id)
1839
2061
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1840
2062
  .run(action.id, action.requestId, action.seq, action.entityType, action.entityId, action.operation, action.before === null ? null : JSON.stringify(action.before), action.after === null ? null : JSON.stringify(action.after), action.summary, action.createdAt, action.tokenId);
1841
2063
  this.touch("agent_action", action.id, request.targetSpaceId, null, input.taskId);
@@ -1858,13 +2080,14 @@ export class Mutation {
1858
2080
  return this.actor.type === "user" && this.actor.userId === userId;
1859
2081
  }
1860
2082
  /**
1861
- * Notifie un utilisateur selon ses préférences : la notification apparaît
2083
+ * Notifie un utilisateur selon ses préférences dans l'espace de la tâche
2084
+ * (celles de l'espace, sinon celles du compte) : la notification apparaît
1862
2085
  * dans l'application si elle y est activée, et son identifiant est retenu
1863
2086
  * pour l'envoi de l'e-mail si celui-ci est activé. Rien n'est créé quand les
1864
2087
  * deux sont désactivés.
1865
2088
  */
1866
2089
  notify(type, userId, taskId, commentId) {
1867
- const settings = this.store.getUserSettings(userId);
2090
+ const settings = this.store.notificationPreferences(userId, this.store.getTask(taskId).spaceId);
1868
2091
  const inApp = type === "assigned" ? settings.notifyAssignApp : settings.notifyCommentApp;
1869
2092
  const email = type === "assigned" ? settings.notifyAssignEmail : settings.notifyCommentEmail;
1870
2093
  if (!inApp && !email)
@@ -1885,7 +2108,7 @@ export class Mutation {
1885
2108
  emailError: null,
1886
2109
  }, "notification");
1887
2110
  this.db
1888
- .prepare(`INSERT INTO notifications (id, user_id, type, task_id, actor_type, actor_id, request_id, comment_id, in_app, created_at)
2111
+ .prepare(`INSERT INTO notifications (id, user_id, type, task_id, actor_type, actor_id, request_id, comment_id, in_app, created_at)
1889
2112
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1890
2113
  .run(notification.id, notification.userId, notification.type, notification.taskId, notification.actorType, notification.actorId, notification.requestId, notification.commentId, inApp ? 1 : 0, notification.createdAt);
1891
2114
  if (inApp)
@@ -1927,12 +2150,70 @@ export class Mutation {
1927
2150
  updateUserSettings(userId, patch) {
1928
2151
  const settings = validate(UserSettingsSchema, { ...this.store.getUserSettings(userId), ...definedFields(patch) }, "settings");
1929
2152
  this.db
1930
- .prepare(`UPDATE user_settings SET notify_assign_app = ?, notify_assign_email = ?, notify_comment_app = ?, notify_comment_email = ?
1931
- WHERE user_id = ?`)
1932
- .run(settings.notifyAssignApp ? 1 : 0, settings.notifyAssignEmail ? 1 : 0, settings.notifyCommentApp ? 1 : 0, settings.notifyCommentEmail ? 1 : 0, userId);
2153
+ .prepare(`UPDATE user_settings SET notify_assign_app = ?, notify_assign_email = ?, notify_comment_app = ?, notify_comment_email = ?,
2154
+ assistant_history = ? WHERE user_id = ?`)
2155
+ .run(settings.notifyAssignApp ? 1 : 0, settings.notifyAssignEmail ? 1 : 0, settings.notifyCommentApp ? 1 : 0, settings.notifyCommentEmail ? 1 : 0, settings.assistantHistory, userId);
1933
2156
  this.touch("user_settings", userId, null, userId);
1934
2157
  return settings;
1935
2158
  }
2159
+ /**
2160
+ * Fixe les préférences de notification d'un membre propres à un espace ;
2161
+ * null les retire, et il y suit de nouveau celles de son compte.
2162
+ */
2163
+ setSpaceNotificationSettings(userId, spaceId, preferences) {
2164
+ if (!this.store.findMembership(spaceId, userId))
2165
+ throw new NotFoundError(`User ${userId} is not a member of space ${spaceId}.`);
2166
+ this.touch("user_settings", userId, null, userId);
2167
+ if (preferences === null) {
2168
+ this.db.prepare("DELETE FROM space_notification_settings WHERE user_id = ? AND space_id = ?").run(userId, spaceId);
2169
+ return null;
2170
+ }
2171
+ const settings = validate(SpaceNotificationSettingsSchema, { userId, spaceId, ...preferences }, "space notification settings");
2172
+ this.db
2173
+ .prepare(`INSERT INTO space_notification_settings (user_id, space_id, notify_assign_app, notify_assign_email, notify_comment_app, notify_comment_email)
2174
+ VALUES (?, ?, ?, ?, ?, ?)
2175
+ ON CONFLICT (user_id, space_id) DO UPDATE SET notify_assign_app = excluded.notify_assign_app, notify_assign_email = excluded.notify_assign_email,
2176
+ notify_comment_app = excluded.notify_comment_app, notify_comment_email = excluded.notify_comment_email`)
2177
+ .run(userId, spaceId, settings.notifyAssignApp ? 1 : 0, settings.notifyAssignEmail ? 1 : 0, settings.notifyCommentApp ? 1 : 0, settings.notifyCommentEmail ? 1 : 0);
2178
+ return settings;
2179
+ }
2180
+ /**
2181
+ * Fixe les instructions de l'agent d'un espace, ou celles du site quand
2182
+ * `spaceId` est null ; un texte vide les retire.
2183
+ */
2184
+ setAgentInstructions(spaceId, text) {
2185
+ if (this.actor.type !== "user")
2186
+ throw new InvariantError("Only a user can change the agent instructions.");
2187
+ if (spaceId !== null)
2188
+ this.store.getSpace(spaceId);
2189
+ this.touch("agent_instructions", spaceId ?? "site", spaceId, null);
2190
+ this.db.prepare("DELETE FROM agent_instructions WHERE space_id IS ?").run(spaceId);
2191
+ if (text.trim() === "")
2192
+ return null;
2193
+ const instructions = validate(AgentInstructionsSchema, { spaceId, text, updatedAt: this.now, updatedBy: this.actor.userId }, "agent instructions");
2194
+ this.db
2195
+ .prepare("INSERT INTO agent_instructions (space_id, text, updated_at, updated_by) VALUES (?, ?, ?, ?)")
2196
+ .run(instructions.spaceId, instructions.text, instructions.updatedAt, instructions.updatedBy);
2197
+ return instructions;
2198
+ }
2199
+ /** Fixe les limites d'une session du runner. */
2200
+ setRunnerSettings(settings) {
2201
+ if (this.actor.type !== "user")
2202
+ throw new InvariantError("Only a user can change the runner settings.");
2203
+ const valid = validate(RunnerSettingsSchema, settings, "runner settings");
2204
+ this.db
2205
+ .prepare("UPDATE runner_settings SET max_turns = ?, max_minutes = ?, max_budget_usd = ?, updated_at = ?, updated_by = ? WHERE id = 1")
2206
+ .run(valid.maxTurns, valid.maxMinutes, valid.maxBudgetUsd, this.now, this.actor.userId);
2207
+ return valid;
2208
+ }
2209
+ /** Enregistre le relevé d'une session du runner terminée. */
2210
+ recordRunnerSession(record) {
2211
+ const valid = validate(RunnerSessionRecordSchema, record, "runner session");
2212
+ this.db
2213
+ .prepare(`INSERT INTO runner_sessions (id, space_id, space_name, started_at, ended_at, outcome, model, turns, cost_usd, input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens)
2214
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
2215
+ .run(valid.id, valid.spaceId, valid.spaceName, valid.startedAt, valid.endedAt, valid.outcome, valid.model, valid.turns, valid.costUsd, valid.inputTokens, valid.outputTokens, valid.cacheReadTokens, valid.cacheCreationTokens);
2216
+ }
1936
2217
  // --- Fin de mutation ---
1937
2218
  /** Vérifie les invariants sur l'état final, puis écrit les versions et le journal. */
1938
2219
  finish() {
@@ -2009,8 +2290,8 @@ export class Mutation {
2009
2290
  }
2010
2291
  }
2011
2292
  const outsiders = this.db
2012
- .prepare(`SELECT t.number AS number, x.user_id AS user_id FROM task_assignees x JOIN tasks t ON t.id = x.task_id
2013
- WHERE t.space_id = ? AND NOT EXISTS (SELECT 1 FROM memberships m WHERE m.space_id = t.space_id AND m.user_id = x.user_id)
2293
+ .prepare(`SELECT t.number AS number, x.user_id AS user_id FROM task_assignees x JOIN tasks t ON t.id = x.task_id
2294
+ WHERE t.space_id = ? AND NOT EXISTS (SELECT 1 FROM memberships m WHERE m.space_id = t.space_id AND m.user_id = x.user_id)
2014
2295
  ORDER BY t.number LIMIT 1`)
2015
2296
  .get(space.id);
2016
2297
  if (outsiders) {
@@ -2082,7 +2363,7 @@ export class Mutation {
2082
2363
  const actorId = this.actingUserId;
2083
2364
  const requestId = this.request?.id ?? null;
2084
2365
  const tokenId = this.token?.id ?? null;
2085
- const insert = this.db.prepare(`INSERT INTO entity_versions (entity_type, entity_id, version, snapshot, actor_type, actor_id, request_id, created_at, token_id)
2366
+ const insert = this.db.prepare(`INSERT INTO entity_versions (entity_type, entity_id, version, snapshot, actor_type, actor_id, request_id, created_at, token_id)
2086
2367
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
2087
2368
  for (const entry of this.touched.values()) {
2088
2369
  if (!VERSIONED.has(entry.entityType))
@@ -2104,7 +2385,7 @@ export class Mutation {
2104
2385
  }
2105
2386
  /** Une ligne du journal par entité modifiée, avec l'auteur de la mutation. */
2106
2387
  writeChanges() {
2107
- const insert = this.db.prepare(`INSERT INTO changes (space_id, user_id, entity_type, entity_id, task_id, at, actor_type, actor_id, request_id)
2388
+ const insert = this.db.prepare(`INSERT INTO changes (space_id, user_id, entity_type, entity_id, task_id, at, actor_type, actor_id, request_id)
2108
2389
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
2109
2390
  const actorId = this.actingUserId;
2110
2391
  const requestId = this.request?.id ?? null;
@@ -2113,6 +2394,19 @@ export class Mutation {
2113
2394
  }
2114
2395
  }
2115
2396
  }
2397
+ /** Réglages d'une vue avec des filtres sans doublon, dans l'ordre des statuts et des priorités. */
2398
+ function normalizedSettings(settings) {
2399
+ const { name, layout, groupBy, thenBy, showEmptyGroups, statuses, priorities } = settings;
2400
+ return {
2401
+ name,
2402
+ layout,
2403
+ groupBy,
2404
+ thenBy,
2405
+ showEmptyGroups,
2406
+ statuses: TASK_STATUSES.filter((status) => statuses.includes(status)),
2407
+ priorities: TASK_PRIORITIES.filter((priority) => priorities.includes(priority)),
2408
+ };
2409
+ }
2116
2410
  /** Champs de `patch` dont la valeur n'est pas `undefined`. */
2117
2411
  function definedFields(patch) {
2118
2412
  return Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined));