@imenam/mcp-organizer 1.0.15 → 1.0.17

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 (37) hide show
  1. package/README.md +13 -9
  2. package/dist/shared/schemas/agent-api.schema.d.ts +3 -0
  3. package/dist/shared/schemas/agent-tools.schema.d.ts +155 -1
  4. package/dist/shared/schemas/agent-tools.schema.js +53 -3
  5. package/dist/shared/schemas/entities.schema.d.ts +62 -4
  6. package/dist/shared/schemas/entities.schema.js +39 -4
  7. package/dist/shared/schemas/enums.schema.d.ts +2 -1
  8. package/dist/shared/schemas/enums.schema.js +1 -0
  9. package/dist/shared/schemas/tasks-api.schema.d.ts +51 -0
  10. package/dist/shared/schemas/tasks-api.schema.js +23 -1
  11. package/dist/shared/schemas/views-api.schema.d.ts +4 -0
  12. package/dist/shared/schemas/views-api.schema.js +3 -1
  13. package/dist/src/agent-api/questions.d.ts +15 -0
  14. package/dist/src/agent-api/questions.js +128 -0
  15. package/dist/src/agent-api/router.js +2 -1
  16. package/dist/src/agent-api/tasks.js +5 -0
  17. package/dist/src/agent-api/views.js +32 -7
  18. package/dist/src/core/board-views.js +11 -4
  19. package/dist/src/core/history.js +23 -3
  20. package/dist/src/core/migrations.js +31 -0
  21. package/dist/src/core/questions.d.ts +13 -0
  22. package/dist/src/core/questions.js +33 -0
  23. package/dist/src/core/snapshots.d.ts +3 -3
  24. package/dist/src/core/snapshots.js +3 -1
  25. package/dist/src/core/store.d.ts +55 -1
  26. package/dist/src/core/store.js +219 -7
  27. package/dist/src/core/tasks.js +2 -0
  28. package/dist/src/gui-api.js +6 -1
  29. package/dist/src/mcp/start.d.ts +1 -1
  30. package/dist/src/mcp/start.js +3 -3
  31. package/dist/src/mcp/tools.js +62 -5
  32. package/gui/dist/assets/index-Bby49RH2.css +1 -0
  33. package/gui/dist/assets/index-CQZQd34A.js +99 -0
  34. package/gui/dist/index.html +2 -2
  35. package/package.json +1 -1
  36. package/gui/dist/assets/index-CVwckTU6.css +0 -1
  37. package/gui/dist/assets/index-DS_BdlK5.js +0 -99
@@ -1,6 +1,6 @@
1
1
  import { ForbiddenError, InvariantError, NotFoundError } from "./errors.js";
2
2
  import { CheckpointSnapshotSchema, isTracked, snapshotOf, taskIdOfAction } from "./snapshots.js";
3
- import { BoardViewSchema, ChecklistItemSchema, FollowUpSchema, CommentSchema, IdeaSchema, TaskSnapshotSchema, TestCheckpointSchema, } from "../../shared/schemas/entities.schema.js";
3
+ import { BoardViewSchema, ChecklistItemSchema, FollowUpSchema, QuestionSnapshotSchema, CommentSchema, IdeaSchema, TaskSnapshotSchema, TestCheckpointSchema, } from "../../shared/schemas/entities.schema.js";
4
4
  /**
5
5
  * Retour à un état antérieur : annulation d'une action de l'agent, après
6
6
  * comparaison de l'état courant de l'entité avec celui que l'action a
@@ -19,6 +19,10 @@ function comparable(entityType, snapshot) {
19
19
  const item = ChecklistItemSchema.parse(snapshot);
20
20
  return [item.text, item.done];
21
21
  }
22
+ case "task_question": {
23
+ const { text, multiple, otherAnswer, options } = QuestionSnapshotSchema.parse(snapshot);
24
+ return [text, multiple, otherAnswer, options.map(({ id, label, detail, recommended, selected }) => [id, label, detail, recommended, selected])];
25
+ }
22
26
  case "test_checkpoint":
23
27
  return [TestCheckpointSchema.parse(snapshot).text];
24
28
  case "comment":
@@ -35,8 +39,8 @@ function comparable(entityType, snapshot) {
35
39
  }
36
40
  /** Réglages d'une vue, comparés et restaurés par l'annulation. */
37
41
  function viewSettings(view) {
38
- const { name, layout, groupBy, thenBy, showEmptyGroups, statuses, priorities, assigneeIds, unassigned } = view;
39
- return { name, layout, groupBy, thenBy, showEmptyGroups, statuses, priorities, assigneeIds, unassigned };
42
+ const { name, layout, groupBy, thenBy, showEmptyGroups, statuses, priorities, assigneeIds, unassigned, tagIds } = view;
43
+ return { name, layout, groupBy, thenBy, showEmptyGroups, statuses, priorities, assigneeIds, unassigned, tagIds };
40
44
  }
41
45
  function sameState(entityType, a, b) {
42
46
  return JSON.stringify(comparable(entityType, a)) === JSON.stringify(comparable(entityType, b));
@@ -51,6 +55,8 @@ function describe(store, entityType, snapshot) {
51
55
  }
52
56
  case "checklist_item":
53
57
  return { label: `L'élément de checklist « ${ChecklistItemSchema.parse(snapshot).text} »`, feminine: false };
58
+ case "task_question":
59
+ return { label: `La question « ${excerpt(QuestionSnapshotSchema.parse(snapshot).text)} »`, feminine: true };
54
60
  case "test_checkpoint":
55
61
  return { label: `Le point de vérification « ${TestCheckpointSchema.parse(snapshot).text} »`, feminine: false };
56
62
  case "comment":
@@ -141,6 +147,7 @@ function remove(tx, entityType, current, label) {
141
147
  const dependents = [
142
148
  [store.listChildren(task.id).length, "des sous-tâches"],
143
149
  [store.listChecklist(task.id).length, "une checklist"],
150
+ [store.listQuestions(task.id).length, "des questions"],
144
151
  [store.listCheckpoints(task.id).length, "des points de vérification"],
145
152
  [store.listComments(task.id).length, "des commentaires"],
146
153
  [store.listAttachments(task.id).length, "des pièces jointes"],
@@ -155,6 +162,9 @@ function remove(tx, entityType, current, label) {
155
162
  case "checklist_item":
156
163
  tx.deleteChecklistItem(ChecklistItemSchema.parse(current).id);
157
164
  return;
165
+ case "task_question":
166
+ tx.deleteQuestion(QuestionSnapshotSchema.parse(current).id);
167
+ return;
158
168
  case "test_checkpoint": {
159
169
  const checkpoint = CheckpointSnapshotSchema.parse(current);
160
170
  if (checkpoint.results.length > 0)
@@ -188,6 +198,13 @@ function recreate(tx, entityType, before) {
188
198
  tx.restoreChecklistItem(item);
189
199
  return;
190
200
  }
201
+ case "task_question": {
202
+ const question = QuestionSnapshotSchema.parse(before);
203
+ if (!tx.store.findTask(question.taskId))
204
+ throw new InvariantError(`La tâche de la question « ${excerpt(question.text)} » n'existe plus : rien à recréer.`);
205
+ tx.restoreQuestion(question);
206
+ return;
207
+ }
191
208
  case "test_checkpoint": {
192
209
  const checkpoint = CheckpointSnapshotSchema.parse(before);
193
210
  if (!tx.store.findTask(checkpoint.taskId))
@@ -219,6 +236,9 @@ function restore(tx, entityType, entityId, before) {
219
236
  tx.updateChecklistItem(entityId, { text: item.text, done: item.done });
220
237
  return;
221
238
  }
239
+ case "task_question":
240
+ tx.replaceQuestion(QuestionSnapshotSchema.parse(before));
241
+ return;
222
242
  case "test_checkpoint":
223
243
  tx.updateCheckpoint(entityId, TestCheckpointSchema.parse(before).text);
224
244
  return;
@@ -570,6 +570,37 @@ export const MIGRATIONS = [
570
570
  CREATE INDEX agent_requests_target_status ON agent_requests(target_space_id, status, created_at);
571
571
  CREATE INDEX agent_requests_parent ON agent_requests(parent_request_id);
572
572
  CREATE INDEX agent_requests_comment ON agent_requests(comment_id);
573
+ `,
574
+ // Filtre des tags d'une vue du tableau de bord : tableau JSON d'identifiants de tags de l'espace,
575
+ // ajouté aussi aux états des vues enregistrés par les actions de l'agent.
576
+ `
577
+ ALTER TABLE board_views ADD COLUMN tag_ids TEXT NOT NULL DEFAULT '[]';
578
+ UPDATE agent_actions SET before = json_set(before, '$.tagIds', json('[]')) WHERE entity_type = 'board_view' AND before IS NOT NULL;
579
+ UPDATE agent_actions SET after = json_set(after, '$.tagIds', json('[]')) WHERE entity_type = 'board_view' AND after IS NOT NULL;
580
+ `,
581
+ // Questions posées par l'agent dans une tâche, leurs propositions et la réponse des membres.
582
+ `
583
+ CREATE TABLE task_questions (
584
+ id TEXT PRIMARY KEY,
585
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
586
+ text TEXT NOT NULL CHECK (text <> ''),
587
+ multiple INTEGER NOT NULL DEFAULT 0 CHECK (multiple IN (0, 1)),
588
+ other_answer TEXT CHECK (other_answer IS NULL OR other_answer <> ''),
589
+ answered_by TEXT REFERENCES users(id) ON DELETE SET NULL,
590
+ answered_at TEXT,
591
+ position REAL NOT NULL
592
+ );
593
+ CREATE INDEX task_questions_task ON task_questions(task_id, position);
594
+ CREATE TABLE question_options (
595
+ id TEXT PRIMARY KEY,
596
+ question_id TEXT NOT NULL REFERENCES task_questions(id) ON DELETE CASCADE,
597
+ label TEXT NOT NULL CHECK (label <> ''),
598
+ detail TEXT NOT NULL DEFAULT '',
599
+ recommended INTEGER NOT NULL DEFAULT 0 CHECK (recommended IN (0, 1)),
600
+ selected INTEGER NOT NULL DEFAULT 0 CHECK (selected IN (0, 1)),
601
+ position REAL NOT NULL
602
+ );
603
+ CREATE INDEX question_options_question ON question_options(question_id, position);
573
604
  `,
574
605
  ];
575
606
  /** Version du schéma attendue par ce code. */
@@ -0,0 +1,13 @@
1
+ import type { Store } from "./store.js";
2
+ import type { QuestionSnapshot } from "../../shared/schemas/entities.schema.js";
3
+ import type { AnswerQuestionRequest, QuestionView } from "../../shared/schemas/tasks-api.schema.js";
4
+ /**
5
+ * Questions d'une tâche côté site : l'agent les pose, tout membre de l'espace
6
+ * y répond. Une réponse est enregistrée sans rien envoyer à l'agent, qui la
7
+ * lit quand il consulte la tâche.
8
+ */
9
+ export declare function questionView(store: Store, question: QuestionSnapshot): QuestionView;
10
+ /** Questions d'une tâche, dans l'ordre. */
11
+ export declare function questionViews(store: Store, taskId: string): QuestionView[];
12
+ /** Enregistre la réponse d'un membre de l'espace de la tâche ; une question introuvable ou hors de ses espaces reçoit la même réponse. */
13
+ export declare function answerQuestion(store: Store, userId: string, questionId: string, answer: AnswerQuestionRequest): QuestionView;
@@ -0,0 +1,33 @@
1
+ import { NotFoundError } from "./errors.js";
2
+ /**
3
+ * Questions d'une tâche côté site : l'agent les pose, tout membre de l'espace
4
+ * y répond. Une réponse est enregistrée sans rien envoyer à l'agent, qui la
5
+ * lit quand il consulte la tâche.
6
+ */
7
+ export function questionView(store, question) {
8
+ const author = question.answeredBy === null ? null : store.findUser(question.answeredBy);
9
+ return {
10
+ id: question.id,
11
+ text: question.text,
12
+ multiple: question.multiple,
13
+ options: question.options.map(({ id, label, detail, recommended, selected }) => ({ id, label, detail, recommended, selected })),
14
+ otherAnswer: question.otherAnswer,
15
+ answeredBy: author ? (author.displayName ?? author.email) : null,
16
+ answeredAt: question.answeredAt,
17
+ };
18
+ }
19
+ /** Questions d'une tâche, dans l'ordre. */
20
+ export function questionViews(store, taskId) {
21
+ return store.listQuestions(taskId).map((question) => questionView(store, store.questionSnapshot(question.id)));
22
+ }
23
+ /** Enregistre la réponse d'un membre de l'espace de la tâche ; une question introuvable ou hors de ses espaces reçoit la même réponse. */
24
+ export function answerQuestion(store, userId, questionId, answer) {
25
+ const question = store.mutate({ type: "user", userId }, (tx) => {
26
+ const current = tx.store.findQuestion(questionId);
27
+ const task = current === null ? null : tx.store.findTask(current.taskId);
28
+ if (!current || !task || !tx.store.isMember(task.spaceId, userId))
29
+ throw new NotFoundError("Question introuvable.");
30
+ return tx.answerQuestion(questionId, answer, userId);
31
+ });
32
+ return questionView(store, question);
33
+ }
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import type { Store } from "./store.js";
3
3
  import type { EntityType } from "../../shared/schemas/enums.schema.js";
4
- import { type AgentAction, type BoardView, type ChecklistItem, type Comment, type FollowUp, type Idea, type TaskSnapshot } from "../../shared/schemas/entities.schema.js";
4
+ import { type AgentAction, type BoardView, type ChecklistItem, type Comment, type FollowUp, type Idea, type QuestionSnapshot, type TaskSnapshot } from "../../shared/schemas/entities.schema.js";
5
5
  /** Instantanés des entités que l'agent modifie : l'état avant et après chaque action de son lot. */
6
6
  /** Point de vérification avec les résultats saisis dessus. */
7
7
  export declare const CheckpointSnapshotSchema: z.ZodObject<{
@@ -24,9 +24,9 @@ export declare const CheckpointSnapshotSchema: z.ZodObject<{
24
24
  }, z.core.$strip>;
25
25
  export type CheckpointSnapshot = z.infer<typeof CheckpointSnapshotSchema>;
26
26
  /** Entités dont l'agent enregistre l'état avant et après chaque action. */
27
- export type TrackedEntityType = "task" | "checklist_item" | "test_checkpoint" | "comment" | "idea" | "board_view" | "follow_up";
27
+ export type TrackedEntityType = "task" | "checklist_item" | "task_question" | "test_checkpoint" | "comment" | "idea" | "board_view" | "follow_up";
28
28
  export declare function isTracked(entityType: EntityType): entityType is TrackedEntityType;
29
29
  /** Instantané courant d'une entité, ou null si elle n'existe pas. */
30
- export declare function snapshotOf(store: Store, entityType: TrackedEntityType, entityId: string): TaskSnapshot | ChecklistItem | CheckpointSnapshot | Comment | Idea | BoardView | FollowUp | null;
30
+ export declare function snapshotOf(store: Store, entityType: TrackedEntityType, entityId: string): TaskSnapshot | ChecklistItem | QuestionSnapshot | CheckpointSnapshot | Comment | Idea | BoardView | FollowUp | null;
31
31
  /** Tâche concernée par une action : la tâche elle-même, ou celle qui porte l'élément ; null pour une idée, une vue ou un point à régler. */
32
32
  export declare function taskIdOfAction(action: Pick<AgentAction, "entityType" | "entityId" | "before" | "after">): string | null;
@@ -3,7 +3,7 @@ import { TestCheckpointSchema, TestResultSchema } from "../../shared/schemas/ent
3
3
  /** Instantanés des entités que l'agent modifie : l'état avant et après chaque action de son lot. */
4
4
  /** Point de vérification avec les résultats saisis dessus. */
5
5
  export const CheckpointSnapshotSchema = TestCheckpointSchema.extend({ results: z.array(TestResultSchema) });
6
- const TRACKED = new Set(["task", "checklist_item", "test_checkpoint", "comment", "idea", "board_view", "follow_up"]);
6
+ const TRACKED = new Set(["task", "checklist_item", "task_question", "test_checkpoint", "comment", "idea", "board_view", "follow_up"]);
7
7
  export function isTracked(entityType) {
8
8
  return TRACKED.has(entityType);
9
9
  }
@@ -14,6 +14,8 @@ export function snapshotOf(store, entityType, entityId) {
14
14
  return store.findTask(entityId) ? store.taskSnapshot(entityId) : null;
15
15
  case "checklist_item":
16
16
  return store.findChecklistItem(entityId);
17
+ case "task_question":
18
+ return store.findQuestionSnapshot(entityId);
17
19
  case "test_checkpoint": {
18
20
  const checkpoint = store.findCheckpoint(entityId);
19
21
  if (!checkpoint)
@@ -1,7 +1,7 @@
1
1
  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
- import { type AccessLink, type AgentAction, type AgentInstructions, type AgentRequest, type AgentToken, type Attachment, type BoardView, type Change, type ChecklistItem, type Comment, 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";
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
5
  import { 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
@@ -114,6 +114,16 @@ export declare class Store {
114
114
  findChecklistItem(id: string): ChecklistItem | null;
115
115
  getChecklistItem(id: string): ChecklistItem;
116
116
  listChecklist(taskId: string): ChecklistItem[];
117
+ findQuestion(id: string): TaskQuestion | null;
118
+ getQuestion(id: string): TaskQuestion;
119
+ /** Questions d'une tâche, dans l'ordre. */
120
+ listQuestions(taskId: string): TaskQuestion[];
121
+ findQuestionOption(id: string): QuestionOption | null;
122
+ /** Propositions d'une question, dans l'ordre. */
123
+ listQuestionOptions(questionId: string): QuestionOption[];
124
+ /** Question et ses propositions, ou null si elle n'existe pas. */
125
+ findQuestionSnapshot(id: string): QuestionSnapshot | null;
126
+ questionSnapshot(id: string): QuestionSnapshot;
117
127
  findCheckpoint(id: string): TestCheckpoint | null;
118
128
  getCheckpoint(id: string): TestCheckpoint;
119
129
  /** Points de vérification d'une tâche de test, dans l'ordre. */
@@ -311,6 +321,12 @@ export interface UpdateIdeaInput {
311
321
  promotedTaskId?: string | null;
312
322
  archived?: boolean;
313
323
  }
324
+ /** Proposition d'une question à créer. */
325
+ export interface QuestionOptionInput {
326
+ label: string;
327
+ detail?: string;
328
+ recommended?: boolean;
329
+ }
314
330
  /** Réglages d'une vue du tableau de bord. */
315
331
  export interface BoardViewSettings {
316
332
  name: string;
@@ -322,6 +338,7 @@ export interface BoardViewSettings {
322
338
  priorities: TaskPriority[];
323
339
  assigneeIds: string[];
324
340
  unassigned: boolean;
341
+ tagIds: string[];
325
342
  }
326
343
  /** Action de l'agent à enregistrer dans le lot de sa demande. */
327
344
  export interface AgentActionInput {
@@ -490,6 +507,43 @@ export declare class Mutation {
490
507
  /** Remplace les tags d'une tâche ; un nom absent de l'espace y crée le tag (noms comparés sans la casse). */
491
508
  setTags(taskId: string, names: readonly string[]): Tag[];
492
509
  private createTag;
510
+ /** Ajoute une question en fin de liste d'une tâche, avec ses propositions dans l'ordre donné. */
511
+ addQuestion(taskId: string, input: {
512
+ text: string;
513
+ multiple: boolean;
514
+ options: readonly QuestionOptionInput[];
515
+ }): QuestionSnapshot;
516
+ /** Change le texte d'une question ou son type de choix ; un choix unique n'accepte qu'une réponse. */
517
+ updateQuestion(id: string, patch: {
518
+ text?: string;
519
+ multiple?: boolean;
520
+ }): QuestionSnapshot;
521
+ deleteQuestion(id: string): void;
522
+ /** Ajoute une proposition en fin de question. */
523
+ addQuestionOption(questionId: string, input: QuestionOptionInput): QuestionOption;
524
+ updateQuestionOption(id: string, patch: {
525
+ label?: string;
526
+ detail?: string;
527
+ recommended?: boolean;
528
+ }): QuestionOption;
529
+ deleteQuestionOption(id: string): void;
530
+ /**
531
+ * Réponse d'un membre : les propositions choisies et la réponse libre
532
+ * remplacent les précédentes. Une réponse vide efface l'auteur et la date.
533
+ */
534
+ answerQuestion(id: string, answer: {
535
+ selectedOptionIds: readonly string[];
536
+ otherAnswer: string | null;
537
+ }, userId: string): QuestionSnapshot;
538
+ /** Recrée une question supprimée, avec ses identifiants, ses propositions et sa réponse. */
539
+ restoreQuestion(snapshot: QuestionSnapshot): void;
540
+ /** Ramène une question à un état enregistré : texte, type de choix, réponse et propositions. */
541
+ replaceQuestion(snapshot: QuestionSnapshot): void;
542
+ private insertQuestion;
543
+ private insertQuestionOption;
544
+ /** Un choix unique a pour réponse une seule proposition ou la réponse libre. */
545
+ private requireSingleAnswer;
546
+ private touchQuestion;
493
547
  /** Ajoute un élément en fin de checklist d'une tâche standard. */
494
548
  addChecklistItem(taskId: string, text: string): ChecklistItem;
495
549
  updateChecklistItem(id: string, patch: {
@@ -4,7 +4,7 @@ import { positionBetween } from "../../shared/logic/positions.js";
4
4
  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
- import { AccessLinkSchema, AgentActionSchema, AgentInstructionsSchema, AgentTokenSchema, AgentRequestSchema, AttachmentSchema, BoardViewSchema, ChangeSchema, ChecklistItemSchema, CommentSchema, EntityVersionSchema, FollowUpSchema, IdeaSchema, IdeaSnapshotSchema, InvitationSchema, MembershipSchema, NotificationSchema, SessionSchema, SpaceSchema, TagSchema, TaskSchema, TaskSnapshotSchema, TestCheckpointSchema, TestResultSchema, TestReviewSchema, UserSchema, UserSettingsSchema, SpaceNotificationSettingsSchema, } from "../../shared/schemas/entities.schema.js";
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
8
  import { 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) {
@@ -183,6 +183,7 @@ function boardViewFromRow(row) {
183
183
  priorities: JSON.parse(row.priorities),
184
184
  assigneeIds: JSON.parse(row.assignee_ids),
185
185
  unassigned: bool(row.unassigned),
186
+ tagIds: JSON.parse(row.tag_ids),
186
187
  position: row.position,
187
188
  createdAt: row.created_at,
188
189
  updatedAt: row.updated_at,
@@ -253,6 +254,29 @@ function changeFromRow(row) {
253
254
  function tagFromRow(row) {
254
255
  return TagSchema.parse({ id: row.id, spaceId: row.space_id, name: row.name });
255
256
  }
257
+ function questionFromRow(row) {
258
+ return TaskQuestionSchema.parse({
259
+ id: row.id,
260
+ taskId: row.task_id,
261
+ text: row.text,
262
+ multiple: bool(row.multiple),
263
+ otherAnswer: row.other_answer,
264
+ answeredBy: row.answered_by,
265
+ answeredAt: row.answered_at,
266
+ position: row.position,
267
+ });
268
+ }
269
+ function questionOptionFromRow(row) {
270
+ return QuestionOptionSchema.parse({
271
+ id: row.id,
272
+ questionId: row.question_id,
273
+ label: row.label,
274
+ detail: row.detail,
275
+ recommended: bool(row.recommended),
276
+ selected: bool(row.selected),
277
+ position: row.position,
278
+ });
279
+ }
256
280
  function checklistItemFromRow(row) {
257
281
  return ChecklistItemSchema.parse({ id: row.id, taskId: row.task_id, text: row.text, done: bool(row.done), position: row.position });
258
282
  }
@@ -633,6 +657,42 @@ export class Store {
633
657
  const rows = this.db.prepare("SELECT * FROM checklist_items WHERE task_id = ? ORDER BY position").all(taskId);
634
658
  return rows.map(checklistItemFromRow);
635
659
  }
660
+ // --- Questions ---
661
+ findQuestion(id) {
662
+ const row = this.db.prepare("SELECT * FROM task_questions WHERE id = ?").get(id);
663
+ return row ? questionFromRow(row) : null;
664
+ }
665
+ getQuestion(id) {
666
+ const question = this.findQuestion(id);
667
+ if (!question)
668
+ throw new NotFoundError(`Question ${id} not found.`);
669
+ return question;
670
+ }
671
+ /** Questions d'une tâche, dans l'ordre. */
672
+ listQuestions(taskId) {
673
+ const rows = this.db.prepare("SELECT * FROM task_questions WHERE task_id = ? ORDER BY position").all(taskId);
674
+ return rows.map(questionFromRow);
675
+ }
676
+ findQuestionOption(id) {
677
+ const row = this.db.prepare("SELECT * FROM question_options WHERE id = ?").get(id);
678
+ return row ? questionOptionFromRow(row) : null;
679
+ }
680
+ /** Propositions d'une question, dans l'ordre. */
681
+ listQuestionOptions(questionId) {
682
+ const rows = this.db.prepare("SELECT * FROM question_options WHERE question_id = ? ORDER BY position").all(questionId);
683
+ return rows.map(questionOptionFromRow);
684
+ }
685
+ /** Question et ses propositions, ou null si elle n'existe pas. */
686
+ findQuestionSnapshot(id) {
687
+ const question = this.findQuestion(id);
688
+ return question ? { ...question, options: this.listQuestionOptions(id) } : null;
689
+ }
690
+ questionSnapshot(id) {
691
+ const snapshot = this.findQuestionSnapshot(id);
692
+ if (!snapshot)
693
+ throw new NotFoundError(`Question ${id} not found.`);
694
+ return snapshot;
695
+ }
636
696
  // --- Tâches de test ---
637
697
  findCheckpoint(id) {
638
698
  const row = this.db.prepare("SELECT * FROM test_checkpoints WHERE id = ?").get(id);
@@ -1571,6 +1631,157 @@ export class Mutation {
1571
1631
  this.touch("tag", tag.id, spaceId, null);
1572
1632
  return tag;
1573
1633
  }
1634
+ // --- Questions ---
1635
+ /** Ajoute une question en fin de liste d'une tâche, avec ses propositions dans l'ordre donné. */
1636
+ addQuestion(taskId, input) {
1637
+ const task = this.store.getTask(taskId);
1638
+ const last = this.store.listQuestions(taskId).at(-1);
1639
+ const question = validate(TaskQuestionSchema, {
1640
+ id: newId(),
1641
+ taskId,
1642
+ text: input.text,
1643
+ multiple: input.multiple,
1644
+ otherAnswer: null,
1645
+ answeredBy: null,
1646
+ answeredAt: null,
1647
+ position: positionBetween(last?.position ?? null, null),
1648
+ }, "question");
1649
+ this.insertQuestion(question);
1650
+ for (const option of input.options)
1651
+ this.addQuestionOption(question.id, option);
1652
+ this.touch("task_question", question.id, task.spaceId, null, taskId);
1653
+ return this.store.questionSnapshot(question.id);
1654
+ }
1655
+ /** Change le texte d'une question ou son type de choix ; un choix unique n'accepte qu'une réponse. */
1656
+ updateQuestion(id, patch) {
1657
+ const current = this.store.getQuestion(id);
1658
+ const question = validate(TaskQuestionSchema, { ...current, ...definedFields(patch) }, "question");
1659
+ if (!question.multiple)
1660
+ this.requireSingleAnswer(question, this.store.listQuestionOptions(id));
1661
+ this.db.prepare("UPDATE task_questions SET text = ?, multiple = ? WHERE id = ?").run(question.text, question.multiple ? 1 : 0, id);
1662
+ this.touchQuestion(question);
1663
+ return this.store.questionSnapshot(id);
1664
+ }
1665
+ deleteQuestion(id) {
1666
+ const question = this.store.getQuestion(id);
1667
+ this.db.prepare("DELETE FROM task_questions WHERE id = ?").run(id);
1668
+ this.touchQuestion(question);
1669
+ }
1670
+ /** Ajoute une proposition en fin de question. */
1671
+ addQuestionOption(questionId, input) {
1672
+ const question = this.store.getQuestion(questionId);
1673
+ const options = this.store.listQuestionOptions(questionId);
1674
+ if (options.length >= MAX_QUESTION_OPTIONS)
1675
+ throw new InvariantError(`A question has at most ${MAX_QUESTION_OPTIONS} options.`);
1676
+ const option = validate(QuestionOptionSchema, {
1677
+ id: newId(),
1678
+ questionId,
1679
+ label: input.label,
1680
+ detail: input.detail?.trim() ?? "",
1681
+ recommended: input.recommended ?? false,
1682
+ selected: false,
1683
+ position: positionBetween(options.at(-1)?.position ?? null, null),
1684
+ }, "question option");
1685
+ this.insertQuestionOption(option);
1686
+ this.touchQuestion(question);
1687
+ return option;
1688
+ }
1689
+ updateQuestionOption(id, patch) {
1690
+ const current = this.store.findQuestionOption(id);
1691
+ if (!current)
1692
+ throw new NotFoundError(`Question option ${id} not found.`);
1693
+ const option = validate(QuestionOptionSchema, { ...current, ...definedFields({ ...patch, detail: patch.detail?.trim() }) }, "question option");
1694
+ this.db.prepare("UPDATE question_options SET label = ?, detail = ?, recommended = ? WHERE id = ?").run(option.label, option.detail, option.recommended ? 1 : 0, id);
1695
+ this.touchQuestion(this.store.getQuestion(option.questionId));
1696
+ return option;
1697
+ }
1698
+ deleteQuestionOption(id) {
1699
+ const option = this.store.findQuestionOption(id);
1700
+ if (!option)
1701
+ throw new NotFoundError(`Question option ${id} not found.`);
1702
+ this.db.prepare("DELETE FROM question_options WHERE id = ?").run(id);
1703
+ this.touchQuestion(this.store.getQuestion(option.questionId));
1704
+ }
1705
+ /**
1706
+ * Réponse d'un membre : les propositions choisies et la réponse libre
1707
+ * remplacent les précédentes. Une réponse vide efface l'auteur et la date.
1708
+ */
1709
+ answerQuestion(id, answer, userId) {
1710
+ const current = this.store.getQuestion(id);
1711
+ const options = this.store.listQuestionOptions(id);
1712
+ const selected = new Set(answer.selectedOptionIds);
1713
+ for (const optionId of selected) {
1714
+ if (!options.some((option) => option.id === optionId))
1715
+ throw new NotFoundError(`Option ${optionId} is not an option of this question.`);
1716
+ }
1717
+ const otherAnswer = answer.otherAnswer?.trim() || null;
1718
+ const answered = selected.size > 0 || otherAnswer !== null;
1719
+ const question = validate(TaskQuestionSchema, { ...current, otherAnswer, answeredBy: answered ? userId : null, answeredAt: answered ? this.now : null }, "question");
1720
+ const next = options.map((option) => ({ ...option, selected: selected.has(option.id) }));
1721
+ if (!question.multiple)
1722
+ this.requireSingleAnswer(question, next);
1723
+ this.db
1724
+ .prepare("UPDATE task_questions SET other_answer = ?, answered_by = ?, answered_at = ? WHERE id = ?")
1725
+ .run(question.otherAnswer, question.answeredBy, question.answeredAt, id);
1726
+ const update = this.db.prepare("UPDATE question_options SET selected = ? WHERE id = ?");
1727
+ for (const option of next)
1728
+ update.run(option.selected ? 1 : 0, option.id);
1729
+ this.touchQuestion(question);
1730
+ return this.store.questionSnapshot(id);
1731
+ }
1732
+ /** Recrée une question supprimée, avec ses identifiants, ses propositions et sa réponse. */
1733
+ restoreQuestion(snapshot) {
1734
+ const { options, ...fields } = snapshot;
1735
+ const question = validate(TaskQuestionSchema, fields, "question");
1736
+ this.insertQuestion(question);
1737
+ for (const option of options)
1738
+ this.insertQuestionOption(validate(QuestionOptionSchema, option, "question option"));
1739
+ this.touchQuestion(question);
1740
+ }
1741
+ /** Ramène une question à un état enregistré : texte, type de choix, réponse et propositions. */
1742
+ replaceQuestion(snapshot) {
1743
+ const { options, ...fields } = snapshot;
1744
+ const question = validate(TaskQuestionSchema, fields, "question");
1745
+ this.db
1746
+ .prepare("UPDATE task_questions SET text = ?, multiple = ?, other_answer = ?, answered_by = ?, answered_at = ? WHERE id = ?")
1747
+ .run(question.text, question.multiple ? 1 : 0, question.otherAnswer, question.answeredBy, question.answeredAt, question.id);
1748
+ const kept = new Set(options.map((option) => option.id));
1749
+ for (const option of this.store.listQuestionOptions(question.id)) {
1750
+ if (!kept.has(option.id))
1751
+ this.db.prepare("DELETE FROM question_options WHERE id = ?").run(option.id);
1752
+ }
1753
+ for (const option of options) {
1754
+ const valid = validate(QuestionOptionSchema, option, "question option");
1755
+ if (this.store.findQuestionOption(valid.id)) {
1756
+ this.db
1757
+ .prepare("UPDATE question_options SET label = ?, detail = ?, recommended = ?, selected = ?, position = ? WHERE id = ?")
1758
+ .run(valid.label, valid.detail, valid.recommended ? 1 : 0, valid.selected ? 1 : 0, valid.position, valid.id);
1759
+ }
1760
+ else {
1761
+ this.insertQuestionOption(valid);
1762
+ }
1763
+ }
1764
+ this.touchQuestion(question);
1765
+ }
1766
+ insertQuestion(question) {
1767
+ this.db
1768
+ .prepare("INSERT INTO task_questions (id, task_id, text, multiple, other_answer, answered_by, answered_at, position) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
1769
+ .run(question.id, question.taskId, question.text, question.multiple ? 1 : 0, question.otherAnswer, question.answeredBy, question.answeredAt, question.position);
1770
+ }
1771
+ insertQuestionOption(option) {
1772
+ this.db
1773
+ .prepare("INSERT INTO question_options (id, question_id, label, detail, recommended, selected, position) VALUES (?, ?, ?, ?, ?, ?, ?)")
1774
+ .run(option.id, option.questionId, option.label, option.detail, option.recommended ? 1 : 0, option.selected ? 1 : 0, option.position);
1775
+ }
1776
+ /** Un choix unique a pour réponse une seule proposition ou la réponse libre. */
1777
+ requireSingleAnswer(question, options) {
1778
+ const answers = options.filter((option) => option.selected).length + (question.otherAnswer === null ? 0 : 1);
1779
+ if (answers > 1)
1780
+ throw new InvariantError(`"${question.text}" is a single-choice question: it takes one option or a free answer, not ${answers}.`);
1781
+ }
1782
+ touchQuestion(question) {
1783
+ this.touch("task_question", question.id, this.store.getTask(question.taskId).spaceId, null, question.taskId);
1784
+ }
1574
1785
  // --- Checklist ---
1575
1786
  /** Ajoute un élément en fin de checklist d'une tâche standard. */
1576
1787
  addChecklistItem(taskId, text) {
@@ -1964,18 +2175,18 @@ export class Mutation {
1964
2175
  }
1965
2176
  insertBoardView(view) {
1966
2177
  this.db
1967
- .prepare(`INSERT INTO board_views (id, space_id, user_id, name, layout, group_by, then_by, show_empty_groups, statuses, priorities, assignee_ids, unassigned, position, created_at, updated_at)
1968
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
1969
- .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), JSON.stringify(view.assigneeIds), view.unassigned ? 1 : 0, view.position, view.createdAt, view.updatedAt);
2178
+ .prepare(`INSERT INTO board_views (id, space_id, user_id, name, layout, group_by, then_by, show_empty_groups, statuses, priorities, assignee_ids, unassigned, tag_ids, position, created_at, updated_at)
2179
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
2180
+ .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), JSON.stringify(view.assigneeIds), view.unassigned ? 1 : 0, JSON.stringify(view.tagIds), view.position, view.createdAt, view.updatedAt);
1970
2181
  this.touch("board_view", view.id, null, view.userId, null, view.spaceId);
1971
2182
  }
1972
2183
  updateBoardView(id, patch) {
1973
2184
  const current = this.store.getBoardView(id);
1974
2185
  const view = validate(BoardViewSchema, { ...current, ...normalizedSettings({ ...current, ...definedFields(patch) }), updatedAt: this.now }, "board view");
1975
2186
  this.db
1976
- .prepare(`UPDATE board_views SET name = ?, layout = ?, group_by = ?, then_by = ?, show_empty_groups = ?, statuses = ?, priorities = ?, assignee_ids = ?, unassigned = ?, updated_at = ?
2187
+ .prepare(`UPDATE board_views SET name = ?, layout = ?, group_by = ?, then_by = ?, show_empty_groups = ?, statuses = ?, priorities = ?, assignee_ids = ?, unassigned = ?, tag_ids = ?, updated_at = ?
1977
2188
  WHERE id = ?`)
1978
- .run(view.name, view.layout, view.groupBy, view.thenBy, view.showEmptyGroups ? 1 : 0, JSON.stringify(view.statuses), JSON.stringify(view.priorities), JSON.stringify(view.assigneeIds), view.unassigned ? 1 : 0, view.updatedAt, id);
2189
+ .run(view.name, view.layout, view.groupBy, view.thenBy, view.showEmptyGroups ? 1 : 0, JSON.stringify(view.statuses), JSON.stringify(view.priorities), JSON.stringify(view.assigneeIds), view.unassigned ? 1 : 0, JSON.stringify(view.tagIds), view.updatedAt, id);
1979
2190
  this.touch("board_view", id, null, view.userId, null, view.spaceId);
1980
2191
  return view;
1981
2192
  }
@@ -2635,7 +2846,7 @@ export class Mutation {
2635
2846
  }
2636
2847
  /** Réglages d'une vue avec des filtres sans doublon, dans l'ordre des statuts et des priorités. */
2637
2848
  function normalizedSettings(settings) {
2638
- const { name, layout, groupBy, thenBy, showEmptyGroups, statuses, priorities, assigneeIds, unassigned } = settings;
2849
+ const { name, layout, groupBy, thenBy, showEmptyGroups, statuses, priorities, assigneeIds, unassigned, tagIds } = settings;
2639
2850
  return {
2640
2851
  name,
2641
2852
  layout,
@@ -2646,6 +2857,7 @@ function normalizedSettings(settings) {
2646
2857
  priorities: TASK_PRIORITIES.filter((priority) => priorities.includes(priority)),
2647
2858
  assigneeIds: [...new Set(assigneeIds)],
2648
2859
  unassigned,
2860
+ tagIds: [...new Set(tagIds)],
2649
2861
  };
2650
2862
  }
2651
2863
  /** Champs de `patch` dont la valeur n'est pas `undefined`. */
@@ -4,6 +4,7 @@ import { newId } from "./ids.js";
4
4
  import { requireMember } from "./spaces.js";
5
5
  import { MAX_ATTACHMENT_BYTES, } from "../../shared/schemas/tasks-api.schema.js";
6
6
  import { summarizeTest } from "../../shared/logic/test-summary.js";
7
+ import { questionViews } from "./questions.js";
7
8
  import { testDetail } from "./test-tasks.js";
8
9
  /**
9
10
  * Tâches, checklist, commentaires et pièces jointes, avec les droits de la
@@ -208,6 +209,7 @@ export function getTaskDetail(store, userId, taskId) {
208
209
  ancestors,
209
210
  testedTask: tested ? { id: tested.id, key: keyOf(space, tested), title: tested.title } : null,
210
211
  children: byId.get(task.id).children,
212
+ questions: questionViews(store, task.id),
211
213
  checklist,
212
214
  test: task.type === "test" ? testDetail(store, task) : null,
213
215
  comments,
@@ -3,8 +3,9 @@ import { ForbiddenError, InvariantError, NotFoundError, OrganizerError, Unauthor
3
3
  import { authenticate, changePassword, login, logout, redeemAccessLink, resolveAccessLink, updateDisplayName } from "./core/accounts.js";
4
4
  import { acceptReceivedInvitation, createSharedSpace, declineReceivedInvitation, deleteSpace, inviteToSpace, leaveSpace, listMembers, listMemberSuggestions, listReceivedInvitations, listSpaces, removeMember, renameSpace, resendInvitation, revokeInvitation, } from "./core/spaces.js";
5
5
  import { addChecklistItem, addComment, createTask, deleteAttachment, deleteChecklistItem, deleteComment, deleteTask, downloadAttachment, getBoard, getTaskDetail, listChanges, moveChecklistItem, moveTask, resolveTaskKey, setAssignees, setTags, updateChecklistItem, updateComment, updateTask, uploadAttachment, } from "./core/tasks.js";
6
+ import { answerQuestion } from "./core/questions.js";
6
7
  import { addCheckpoint, deleteCheckpoint, moveCheckpoint, saveReviewDraft, setTestResult, submitReview, updateCheckpoint } from "./core/test-tasks.js";
7
- import { AddChecklistItemRequestSchema, CheckpointTextRequestSchema, CommentRequestSchema, CreateTaskRequestSchema, MoveAfterRequestSchema, MoveTaskRequestSchema, ReviewDraftRequestSchema, SetAssigneesRequestSchema, SetTagsRequestSchema, SetTestResultRequestSchema, SubmitReviewRequestSchema, TaskFiltersSchema, TaskKeyQuerySchema, UpdateChecklistItemRequestSchema, UpdateTaskRequestSchema, UploadAttachmentRequestSchema, } from "../shared/schemas/tasks-api.schema.js";
8
+ import { AddChecklistItemRequestSchema, AnswerQuestionRequestSchema, CheckpointTextRequestSchema, CommentRequestSchema, CreateTaskRequestSchema, MoveAfterRequestSchema, MoveTaskRequestSchema, ReviewDraftRequestSchema, SetAssigneesRequestSchema, SetTagsRequestSchema, SetTestResultRequestSchema, SubmitReviewRequestSchema, TaskFiltersSchema, TaskKeyQuerySchema, UpdateChecklistItemRequestSchema, UpdateTaskRequestSchema, UploadAttachmentRequestSchema, } from "../shared/schemas/tasks-api.schema.js";
8
9
  import { getSettings, getSpaceNotificationSettings, listNotifications, markAllNotificationsRead, markNotificationRead, unreadCount, updateSettings, updateSpaceNotificationSettings } from "./core/notifications.js";
9
10
  import { NotificationListQuerySchema, UpdateSettingsRequestSchema, UpdateSpaceNotificationSettingsRequestSchema } from "../shared/schemas/notifications-api.schema.js";
10
11
  import { cancelRequest, createRequest, createSuite, getRequest, listRequests, relaunchRequest, setFollowUpDone, stopRequest, undoAction, undoRequest, updateRequest, } from "./core/requests.js";
@@ -249,6 +250,10 @@ route("DELETE", "/checklist/:itemId", (ctx, { user, params }) => {
249
250
  route("POST", "/checklist/:itemId/move", (ctx, { user, request, params }) => ({
250
251
  body: moveChecklistItem(ctx.store, user.id, params.itemId, parseBody(MoveAfterRequestSchema, request.body).afterId),
251
252
  }));
253
+ // --- Questions ------------------------------------------------------------------
254
+ route("PUT", "/questions/:questionId/answer", (ctx, { user, request, params }) => ({
255
+ body: answerQuestion(ctx.store, user.id, params.questionId, parseBody(AnswerQuestionRequestSchema, request.body)),
256
+ }));
252
257
  // --- Tâches de test ---------------------------------------------------------------
253
258
  route("POST", "/tasks/:taskId/checkpoints", (ctx, { user, request, params }) => ({
254
259
  body: addCheckpoint(ctx.store, user.id, params.taskId, parseBody(CheckpointTextRequestSchema, request.body).text),