@memoring/cli 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -55,7 +55,8 @@ Os itens enviados nascem **PENDING_REVIEW** — nada entra nas suas listagens ne
55
55
  | --- | --- |
56
56
  | `memoring auth` | login / logout / status |
57
57
  | `memoring stage` | schema (o contrato + seus limites por tipo + as regras de qualidade e suas instruções custom — tudo que o agente deve seguir) / caps (mostra/grava os limites — valem para o app e para os agentes) / create (envia o lote, `--file` ou stdin, `--replace` esvazia a caixa antes; `--max-*` vence a preferência por lote) |
58
- | `memoring inbox` | list / accept `<id>` / accept-all / discard `<id>` / discard-all / update `<id>` (edita item PENDENTE — merge do `--file` parcial e/ou flags `--title --front --back --tags a,b ...`) |
58
+ | `memoring inbox` | list / accept `<id>` / accept-all / discard `<id>` / discard-all / update `<id>` (edita item PENDENTE — merge do `--file` parcial e/ou flags `--title --front --back --tags a,b --deck nome ...`) |
59
+ | `memoring deck` | list (seus baralhos) / create `<nome>` (idempotente; `--parent` p/ sub-baralho) |
59
60
  | `memoring update` | atualiza a CLI para a última versão (via npm) |
60
61
  | `memoring skill` | imprime o guia completo da CLI para agentes de IA (o SKILL.md empacotado) |
61
62
  | `memoring version` | versão da CLI |
@@ -92,6 +93,7 @@ Cada item do lote (1 a 50, all-or-nothing):
92
93
  ```
93
94
 
94
95
  - `type`: `NOTE` (nota, exige `content` em markdown; `NORMAL` legado é aceito e mapeado para `NOTE`), `FLASHCARD` ou `ONE_SHOT` (exigem `front` + `back`), `QUESTION` (exige `question`: `kind` `MULTIPLA_ESCOLHA`/`CERTO_ERRADO`, `statementHtml`, `correctAlternative` 1-based — 1=Certo/2=Errado —, `alternatives` 2–5 só em múltipla escolha, `commentHtml`).
96
+ - `deckName`: **obrigatório** (ou `--deck` no create) — cartão não fica sem baralho; o nome de um baralho existente (`memoring deck list`) é reutilizado, nome novo vira baralho criado no envio.
95
97
  - `source`: origem do material — default `"Importação assistida (CLI)"`.
96
98
  - Limites por tipo: `memoring stage caps` mostra/grava sua preferência (`livre`/`-1` = à vontade — o padrão; `0` = não gerar o tipo) — o `stage schema` a expõe ao agente (`userCaps`) e o `create` a impõe; flags `--max-*` no `create` vencem por lote.
97
99
  - Sem sessão, o `stage schema --json` sai com `authenticated: false`, `userCaps`/`qualityRules`/`customInstructions` nulos e um `warning` — agentes devem logar (`auth login`) e reler o schema ANTES de gerar.
@@ -0,0 +1,99 @@
1
+ import { apiFetch, ApiError } from '../api.js';
2
+ import { fail, green, printJson, printTable, stringFlag } from './shared.js';
3
+ export async function listDecks() {
4
+ return (await apiFetch('/notes/decks'));
5
+ }
6
+ /**
7
+ * Resolve uma referência de baralho ("123" por id ou nome exato, case-insensitive)
8
+ * contra a lista do usuário. Null quando não existe — quem chama decide se cria
9
+ * (stage create) ou falha (inbox update).
10
+ */
11
+ export function resolveDeck(decks, ref) {
12
+ const asNumber = Number(ref);
13
+ if (Number.isInteger(asNumber) && asNumber > 0) {
14
+ return decks.find((d) => d.id === asNumber) ?? null;
15
+ }
16
+ const norm = ref.trim().toLowerCase();
17
+ return decks.find((d) => d.name.trim().toLowerCase() === norm) ?? null;
18
+ }
19
+ /** Cria o baralho (parentId null = baralho raiz/matéria). */
20
+ export async function createDeck(name, parentId = null) {
21
+ try {
22
+ return (await apiFetch('/notes/decks', { method: 'POST', body: { name, parentId } }));
23
+ }
24
+ catch (e) {
25
+ if (e instanceof ApiError) {
26
+ fail(`o servidor rejeitou a criação do baralho "${name}" (${e.status}): ${e.body}`);
27
+ }
28
+ throw e;
29
+ }
30
+ }
31
+ export async function deckCommand(parsed) {
32
+ const [sub, ...rest] = parsed._;
33
+ switch (sub) {
34
+ case 'list': {
35
+ const decks = await listDecks();
36
+ if (parsed.flags.json) {
37
+ printJson(decks);
38
+ return;
39
+ }
40
+ if (decks.length === 0) {
41
+ process.stdout.write('Nenhum baralho — crie com `memoring deck create "<nome>"`.\n');
42
+ return;
43
+ }
44
+ const nameById = new Map(decks.map((d) => [d.id, d.name]));
45
+ printTable(decks.map((d) => ({
46
+ id: `#${d.id}`,
47
+ name: d.name,
48
+ parent: d.parentId !== null ? (nameById.get(d.parentId) ?? `#${d.parentId}`) : '—',
49
+ due: d.dueCount,
50
+ })), [
51
+ { key: 'id', label: 'ID' },
52
+ { key: 'name', label: 'NOME' },
53
+ { key: 'parent', label: 'BARALHO-PAI' },
54
+ { key: 'due', label: 'A REVISAR' },
55
+ ]);
56
+ process.stdout.write(`\n${decks.length} baralho(s).\n`);
57
+ return;
58
+ }
59
+ case 'create': {
60
+ const name = rest.join(' ').trim();
61
+ if (name === '') {
62
+ fail('informe o nome: memoring deck create "Direito Tributário" [--parent <id>].');
63
+ }
64
+ let parentId = null;
65
+ const parentRef = stringFlag(parsed.flags, 'parent');
66
+ if (parentRef !== undefined) {
67
+ const parent = resolveDeck(await listDecks(), parentRef);
68
+ if (!parent) {
69
+ fail(`baralho-pai "${parentRef}" não encontrado — veja os ids/nomes com \`memoring deck list\`.`);
70
+ }
71
+ parentId = parent.id;
72
+ }
73
+ const existing = resolveDeck(await listDecks(), name);
74
+ if (existing) {
75
+ if (parsed.flags.json) {
76
+ printJson({ deck: existing, alreadyExisted: true });
77
+ return;
78
+ }
79
+ process.stdout.write(`Baralho "${existing.name}" já existe (#${existing.id}).\n`);
80
+ return;
81
+ }
82
+ const deck = await createDeck(name, parentId);
83
+ if (parsed.flags.json) {
84
+ printJson({ deck, alreadyExisted: false });
85
+ return;
86
+ }
87
+ process.stdout.write(green(`Baralho "${deck.name}" criado (#${deck.id}).\n`));
88
+ return;
89
+ }
90
+ default:
91
+ process.stdout.write('Uso: memoring deck <list|create> [nome] [--parent <id>] [--json]\n' +
92
+ ' list lista seus baralhos (id, nome, pai, cartões a revisar)\n' +
93
+ ' create <nome> cria um baralho (idempotente: nome existente só retorna o atual)\n' +
94
+ ' --parent <id|nome> cria como sub-baralho\n');
95
+ if (sub) {
96
+ process.exitCode = 1;
97
+ }
98
+ }
99
+ }
@@ -1,5 +1,6 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { apiFetch, ApiError } from '../api.js';
3
+ import { listDecks, resolveDeck } from './deck.js';
3
4
  import { fail, green, printJson, printTable, stringFlag } from './shared.js';
4
5
  async function listInbox() {
5
6
  return (await apiFetch('/notes/review-inbox'));
@@ -40,6 +41,15 @@ async function updateInboxItem(parsed, id) {
40
41
  }
41
42
  const flags = parsed.flags;
42
43
  const tagsFlag = stringFlag(flags, 'tags');
44
+ const deckRef = stringFlag(flags, 'deck');
45
+ let deckId;
46
+ if (deckRef !== undefined) {
47
+ const deck = resolveDeck(await listDecks(), deckRef);
48
+ if (!deck) {
49
+ fail(`baralho "${deckRef}" não encontrado — veja \`memoring deck list\` ou crie com \`memoring deck create "${deckRef}"\` e tente de novo.`);
50
+ }
51
+ deckId = deck.id;
52
+ }
43
53
  const merged = {
44
54
  type: overrides.type ?? stringFlag(flags, 'type') ?? current.type,
45
55
  title: overrides.title ?? stringFlag(flags, 'title') ?? current.title,
@@ -50,7 +60,7 @@ async function updateInboxItem(parsed, id) {
50
60
  subtopicName: overrides.subtopicName ?? stringFlag(flags, 'subtopic') ?? current.subtopicName ?? null,
51
61
  tags: overrides.tags ?? (tagsFlag !== undefined ? parseTagsFlag(tagsFlag) : current.tags ?? []),
52
62
  source: overrides.source ?? stringFlag(flags, 'source') ?? current.source ?? null,
53
- deckId: overrides.deckId ?? current.deckId ?? null,
63
+ deckId: deckId ?? overrides.deckId ?? current.deckId ?? null,
54
64
  question: overrides.question ?? current.question ?? null,
55
65
  };
56
66
  let updated;
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { apiFetch, ApiDedupedError, ApiError } from '../api.js';
4
4
  import { hasSession } from '../config.js';
5
+ import { createDeck, listDecks, resolveDeck } from './deck.js';
5
6
  import { dim, fail, green, printJson, stringFlag, yellow } from './shared.js';
6
7
  const TYPES = ['NOTE', 'FLASHCARD', 'ONE_SHOT', 'QUESTION'];
7
8
  // Retrocompat: itens.json antigos com "type": "NORMAL" são normalizados para "NOTE".
@@ -146,6 +147,7 @@ const SCHEMA_JSON = {
146
147
  subjectName: 'string? — matéria (ex.: "Direito Constitucional")',
147
148
  subtopicName: 'string? — subtópico',
148
149
  tags: 'string[]?',
150
+ deckName: 'string (OBRIGATÓRIO — cartão não fica sem baralho: consulte `memoring deck list`, reutilize um existente ou crie com `memoring deck create`; nome inexistente é criado no envio. A flag --deck do create vale como padrão do lote)',
149
151
  question: 'objeto? — snapshot da questão (obrigatório quando type=QUESTION; contrato em questionContract)',
150
152
  source: `string? — origem do material (default: "${DEFAULT_SOURCE}")`,
151
153
  },
@@ -157,6 +159,7 @@ const SCHEMA_JSON = {
157
159
  front: 'Quais são os quatro objetivos fundamentais da República (art. 3º da CF/88)?',
158
160
  back: 'I — construir uma sociedade livre, justa e solidária; II — garantir o desenvolvimento nacional; III — erradicar a pobreza e reduzir as desigualdades; IV — promover o bem de todos.',
159
161
  subjectName: 'Direito Constitucional',
162
+ deckName: 'Direito Constitucional',
160
163
  tags: ['cf88', 'art-3'],
161
164
  source: 'Apostila constitucional.pdf',
162
165
  },
@@ -164,6 +167,7 @@ const SCHEMA_JSON = {
164
167
  type: 'QUESTION',
165
168
  title: 'IBAMA 2025 — conceito de tributo',
166
169
  subjectName: 'Direito Tributário',
170
+ deckName: 'Direito Tributário',
167
171
  tags: ['ctn', 'art-3'],
168
172
  source: 'aula-00.pdf',
169
173
  question: {
@@ -183,6 +187,9 @@ const SCHEMA_TEXT = `Contrato dos itens da caixa de revisão (POST /api/notes/re
183
187
  content string — corpo da nota (markdown) (obrigatório quando type=NOTE)
184
188
  front, back string — pergunta e resposta (obrigatório quando type=FLASHCARD|ONE_SHOT)
185
189
  question objeto — snapshot da questão (obrigatório quando type=QUESTION)
190
+ deckName string — baralho de destino (OBRIGATÓRIO — cartão não fica sem baralho:
191
+ veja \`memoring deck list\`, reutilize ou crie
192
+ com \`memoring deck create\`; --deck = padrão do lote)
186
193
  subjectName? string — matéria (ex.: "Direito Constitucional")
187
194
  subtopicName? string — subtópico
188
195
  tags? string[]
@@ -205,6 +212,90 @@ Dica: FLASHCARD entra na fila de revisão espaçada (FSRS); ONE_SHOT é pergunta
205
212
  QUESTION treina verificação objetiva (aproveite questões prontas do material).
206
213
  Limites por tipo: a preferência do usuário (abaixo, quando logado) vale por padrão;
207
214
  --max-notes N | --max-flashcards N | --max-one-shots N | --max-questions N no create vencem por lote ("livre" = à vontade).`;
215
+ const NO_DECK_HINT = 'cartão não fica sem baralho: informe deckName no item ou --deck "<nome>" no lote. ' +
216
+ 'Veja `memoring deck list` e reutilize um existente, ou crie com `memoring deck create "<nome>"`.';
217
+ /** Exige baralho em TODO o lote: deckName no item ou a flag --deck como padrão. */
218
+ function enforceDeck(items, flags) {
219
+ const batchDeck = stringFlag(flags, 'deck');
220
+ const index = items.findIndex((it) => !batchDeck && (typeof it.deckName !== 'string' || it.deckName.trim() === ''));
221
+ if (index >= 0) {
222
+ fail(`item #${index + 1} (${items[index].title}) está sem baralho — ${NO_DECK_HINT}`);
223
+ }
224
+ }
225
+ /**
226
+ * Resolve os baralhos do lote ANTES do POST: referências existentes são reutilizadas
227
+ * (id numérico ou nome exato case-insensitive) e nomes novos viram baralhos criados
228
+ * na hora — o agente nunca precisa sair do fluxo para criar estrutura.
229
+ */
230
+ async function resolveBatchDecks(items, flags) {
231
+ const batchDeck = stringFlag(flags, 'deck')?.trim();
232
+ const refOf = (it) => typeof it.deckName === 'string' && it.deckName.trim() !== '' ? it.deckName.trim() : batchDeck;
233
+ const refs = new Set();
234
+ for (const it of items) {
235
+ const ref = refOf(it);
236
+ if (ref) {
237
+ refs.add(ref);
238
+ }
239
+ }
240
+ if (refs.size === 0) {
241
+ return { deckIds: items.map(() => null), createdNames: [] };
242
+ }
243
+ const decks = await listDecks();
244
+ const idByRef = new Map();
245
+ const createdNames = [];
246
+ for (const ref of refs) {
247
+ const existing = resolveDeck(decks, ref);
248
+ if (existing) {
249
+ idByRef.set(ref, existing.id);
250
+ continue;
251
+ }
252
+ if (Number.isInteger(Number(ref)) && Number(ref) > 0) {
253
+ fail(`baralho #${ref} não existe — ${NO_DECK_HINT}`);
254
+ }
255
+ const deck = await createDeck(ref);
256
+ decks.push(deck);
257
+ idByRef.set(ref, deck.id);
258
+ createdNames.push(ref);
259
+ }
260
+ return { deckIds: items.map((it) => idByRef.get(refOf(it) ?? '') ?? null), createdNames };
261
+ }
262
+ /**
263
+ * Atribui o baralho aos itens recém-estagiados (o POST da caixa de revisão não tem
264
+ * deckId — a atribuição é um PUT /notes/{id} por item, com o payload completo do
265
+ * item + deckId). Devolve os rótulos dos itens cuja atribuição falhou.
266
+ */
267
+ async function assignDecks(items, created, deckIds) {
268
+ const failures = [];
269
+ for (let i = 0; i < created.length; i++) {
270
+ const deckId = deckIds[i];
271
+ if (deckId === null || deckId === undefined) {
272
+ continue;
273
+ }
274
+ const item = items[i];
275
+ try {
276
+ await apiFetch(`/notes/${created[i].id}`, {
277
+ method: 'PUT',
278
+ body: {
279
+ type: item.type,
280
+ title: item.title,
281
+ content: item.content ?? null,
282
+ front: item.front ?? null,
283
+ back: item.back ?? null,
284
+ subjectName: item.subjectName ?? null,
285
+ subtopicName: item.subtopicName ?? null,
286
+ tags: item.tags ?? [],
287
+ source: item.source ?? null,
288
+ deckId,
289
+ question: item.question ?? null,
290
+ },
291
+ });
292
+ }
293
+ catch {
294
+ failures.push(`#${created[i].id} (${item.title})`);
295
+ }
296
+ }
297
+ return failures;
298
+ }
208
299
  async function readStdin() {
209
300
  const chunks = [];
210
301
  for await (const chunk of process.stdin) {
@@ -435,18 +526,24 @@ export async function stageCommand(parsed) {
435
526
  fail(`JSON inválido: ${e.message}`);
436
527
  }
437
528
  const items = validateItems(parsedJson);
529
+ enforceDeck(items, parsed.flags);
438
530
  enforceTypeCaps(items, parsed.flags, await fetchStoredCaps());
531
+ const batchDecks = await resolveBatchDecks(items, parsed.flags);
439
532
  if (parsed.flags.replace) {
440
533
  const removed = await emptyInbox();
441
534
  if (!parsed.flags.json) {
442
535
  process.stdout.write(dim(`${removed} item(ns) pendente(s) removido(s) da caixa de revisão.\n`));
443
536
  }
444
537
  }
538
+ if (batchDecks.createdNames.length > 0 && !parsed.flags.json) {
539
+ process.stdout.write(dim(`Baralho(s) criado(s): ${batchDecks.createdNames.join(', ')}.\n`));
540
+ }
445
541
  let created;
446
542
  try {
447
543
  const res = (await apiFetch('/notes/review-inbox', {
448
544
  method: 'POST',
449
- body: { items },
545
+ // deckName não faz parte do contrato do POST — o baralho é atribuído via PUT abaixo
546
+ body: { items: items.map(({ deckName, ...rest }) => (void deckName, rest)) },
450
547
  requestId: batchRequestId(raw),
451
548
  }));
452
549
  created = res.created;
@@ -468,8 +565,20 @@ export async function stageCommand(parsed) {
468
565
  }
469
566
  throw e;
470
567
  }
568
+ const deckFailures = await assignDecks(items, created, batchDecks.deckIds);
569
+ if (deckFailures.length > 0) {
570
+ process.stderr.write(yellow(`aviso: ${deckFailures.length} item(ns) ficaram sem baralho por erro no PUT — corrija com \`memoring inbox update <id> --deck\`: ${deckFailures.join(', ')}\n`));
571
+ }
471
572
  if (parsed.flags.json) {
472
- printJson({ created, ids: created.map((note) => note.id) });
573
+ printJson({
574
+ created,
575
+ ids: created.map((note) => note.id),
576
+ decks: {
577
+ created: batchDecks.createdNames,
578
+ assigned: created.length - deckFailures.length - batchDecks.deckIds.filter((id) => id === null).length,
579
+ failed: deckFailures,
580
+ },
581
+ });
473
582
  return;
474
583
  }
475
584
  process.stdout.write(green(`OK — ${created.length} item(ns) aguardando revisão em /cards/inbox:\n`));
@@ -487,6 +596,8 @@ export async function stageCommand(parsed) {
487
596
  ' --max-one-shots N | --max-questions N; 0 = não gerar o tipo)\n' +
488
597
  ' create envia o lote para a caixa de revisão (arquivo ou stdin)\n' +
489
598
  ' tipos: NOTE | FLASHCARD | ONE_SHOT | QUESTION\n' +
599
+ ' baralho OBRIGATÓRIO: deckName por item ou --deck "<nome|id>" no lote\n' +
600
+ ' (nomes inexistentes são criados; veja `memoring deck list`)\n' +
490
601
  ' --replace esvazia a caixa antes de enviar\n' +
491
602
  ' --max-notes N | --max-flashcards N | --max-one-shots N | --max-questions N\n' +
492
603
  ' vencem a preferência gravada por lote (validação local)\n');
package/dist/main.js CHANGED
@@ -2,13 +2,14 @@
2
2
  import { ApiError } from './api.js';
3
3
  import { CliError, setColorEnabled, yellow } from './output.js';
4
4
  import { authCommand } from './commands/auth.js';
5
+ import { deckCommand } from './commands/deck.js';
5
6
  import { inboxCommand } from './commands/inbox.js';
6
7
  import { stageCommand } from './commands/stage.js';
7
8
  import { updateCommand } from './commands/update.js';
8
9
  import { skillCommand } from './commands/skill.js';
9
10
  import { parseArgs as parse } from './commands/shared.js';
10
11
  import { newerVersionAvailable, scheduleUpdateCheck } from './update.js';
11
- const VERSION = '0.8.0';
12
+ const VERSION = '0.9.0';
12
13
  const HELP = `Memoring CLI — flashcards e notas por IA, direto do terminal.
13
14
 
14
15
  Uso: memoring <comando> [subcomando] [flags]
@@ -25,7 +26,10 @@ Comandos:
25
26
  inbox accept <id>|accept-all aceita itens (entram nas listagens e na fila FSRS)
26
27
  inbox discard <id> descarta um item pendente
27
28
  inbox discard-all descarta todos os itens pendentes
28
- inbox update <id> edita um item pendente (--file parcial e/ou flags)
29
+ inbox update <id> edita um item pendente (--file parcial e/ou flags,
30
+ inclui --deck <id|nome>)
31
+ deck list seus baralhos (id, nome, pai)
32
+ deck create <nome> cria um baralho (--parent <id> p/ sub-baralho)
29
33
  update atualiza a CLI para a versão mais recente (via npm)
30
34
  skill guia completo da CLI para agentes de IA (imprime o SKILL.md)
31
35
  version versão da CLI
@@ -88,6 +92,9 @@ async function main() {
88
92
  case 'inbox':
89
93
  await inboxCommand(sub);
90
94
  return;
95
+ case 'deck':
96
+ await deckCommand(sub);
97
+ return;
91
98
  case 'update':
92
99
  await updateCommand(VERSION);
93
100
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@memoring/cli",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "CLI do Memoring — envie flashcards/notas gerados por IA para a sua caixa de revisão, direto do terminal.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -20,7 +20,9 @@ O Memoring é um app de estudos com revisão espaçada (FSRS). A CLI `memoring`
20
20
  | `memoring auth login\|logout\|status` | sessão (device flow — sem senha no terminal) |
21
21
  | `memoring stage schema [--json]` | O CONTRATO dos itens + limites por tipo + regras de qualidade — leia SEMPRE, logado, antes de gerar |
22
22
  | `memoring stage caps [--max-* N\|livre]` | limites por tipo do usuário (preferência DELE — nunca escreva sem ele pedir) |
23
- | `memoring stage create --file f [--replace] [--max-* N]` | envia o lote (1 a 50 itens) para a caixa de revisão; `--json` devolve `created` + `ids` |
23
+ | `memoring stage create --file f [--replace] [--max-* N] [--deck nome]` | envia o lote (1 a 50 itens) para a caixa de revisão — **baralho OBRIGATÓRIO** (deckName por item ou `--deck` no lote; nomes novos viram baralhos); `--json` devolve `created` + `ids` |
24
+ | `memoring deck list` | seus baralhos (id, nome, pai) — consulte ANTES de gerar |
25
+ | `memoring deck create <nome> [--parent id]` | cria baralho (idempotente) |
24
26
  | `memoring inbox list` | itens pendentes de revisão |
25
27
  | `memoring inbox accept <id>\|accept-all` | aceita itens (entram nas listagens e na fila FSRS) |
26
28
  | `memoring inbox discard <id>\|discard-all` | descarta item(ns) pendente(s) |
@@ -35,15 +37,17 @@ Flags globais: `--json` (saída legível por máquina), `--no-color`, `--api-bas
35
37
  1. **Entenda o pedido** — qual pasta/arquivo/material vira flashcards/notas e se o usuário pediu quantidades.
36
38
  2. **Confira a sessão**: `memoring auth status --json`. Sem `authenticated: true`, PARE e peça o login (ver Pré-requisitos).
37
39
  3. **Leia o contrato, os limites e as regras**: `memoring stage schema --json` (logado). Além do contrato, a saída traz: `userCaps` — os limites por tipo DO USUÁRIO (`-1` = à vontade, `0` = não gerar o tipo, `N` = teto), respeite-os SEMPRE; `qualityRules` — as regras de qualidade INTEGRAIS (as mesmas que o app envia à LLM), aplique-as em TODOS os itens; `customInstructions` — instruções adicionais do usuário (quando não-nulas), também sempre aplicadas. Tudo isso vale mesmo sem pedido explícito no chat.
38
- 4. **Leia os materiais** e gere os itens no contrato, num arquivo JSON (array ou `{ "items": [...] }`).
39
- 5. **Envie**: `memoring stage create --file <arquivo> --json`. Se o lote for rejeitado por limite de tipo, ajuste o LOTE — não relaxe o limite do usuário.
40
- 6. **Guarde os `ids` retornados** pelo create: enquanto os itens estiverem PENDING_REVIEW você pode corrigi-los com `memoring inbox update <id>` — sem precisar descartar e reenviar.
41
- 7. **Avise o usuário**: quantos itens foram para a caixa de revisão e onde aceitar — no app em `/cards/inbox` ou `memoring inbox list` / `memoring inbox accept-all`.
40
+ 4. **Defina o baralho** — cartão NÃO fica sem baralho. Rode `memoring deck list`, escolha o baralho adequado ao material e reutilize o nome; se não existir, crie com `memoring deck create "<nome>"` (ou deixe o próprio `stage create` criar pelo nome). Todo item do lote deve levar `deckName` — ou use `--deck "<nome>"` no create como padrão do lote. Lote sem baralho é REJEITADO pela validação local.
41
+ 5. **Leia os materiais** e gere os itens no contrato, num arquivo JSON (array ou `{ "items": [...] }`).
42
+ 6. **Envie**: `memoring stage create --file <arquivo> --json`. Se o lote for rejeitado por limite de tipo, ajuste o LOTE — não relaxe o limite do usuário.
43
+ 7. **Guarde os `ids` retornados** pelo create: enquanto os itens estiverem PENDING_REVIEW você pode corrigi-los com `memoring inbox update <id>` — sem precisar descartar e reenviar.
44
+ 8. **Avise o usuário**: quantos itens foram para a caixa de revisão e onde aceitar — no app em `/cards/inbox` ou `memoring inbox list` / `memoring inbox accept-all`.
42
45
 
43
46
  ## O contrato (a fonte da verdade é `stage schema`)
44
47
 
45
48
  - `type`: `NOTE` (nota, exige `content` markdown; `NORMAL` legado é aceito e mapeado para `NOTE`), `FLASHCARD` ou `ONE_SHOT` (exigem `front` + `back`) ou `QUESTION` (exige `question` — ver abaixo).
46
49
  - `title` sempre obrigatório; lote de 1 a 50 itens, all-or-nothing — qualquer item inválido rejeita o lote inteiro.
50
+ - `deckName` **OBRIGATÓRIO** (ou `--deck` no create como padrão do lote): cartão não fica sem baralho. Use o nome de um baralho de `memoring deck list`; nome inexistente é criado no envio.
47
51
  - `ONE_SHOT` = pergunta de resposta única (UMA palavra ou termo curto, texto puro). Ative o tipo sempre que o cobrável for recall de termo puro — nome de princípio/instituto, termo em latim, sigla, número de lei/artigo, data, prazo. Resposta cabe num termo → `ONE_SHOT`; exige frase ou explicação → `FLASHCARD`.
48
52
  - `QUESTION` = questão objetiva para verificação: `question.kind` (`MULTIPLA_ESCOLHA` | `CERTO_ERRADO`), `question.statementHtml` (enunciado), `question.correctAlternative` (gabarito, int 1-based; em CERTO_ERRADO, 1 = Certo, 2 = Errado), `question.alternatives` (2 a 5 textos — só em MULTIPLA_ESCOLHA), `question.commentHtml` (explicação do gabarito). **Se o material contiver questões prontas (provas, simulados, listas C/E), APROVEITE-AS como QUESTION** preservando enunciado e gabarito — não as achate em flashcards.
49
53
  - Preencha `source` com a origem real do material (nome do arquivo/pasta) — não use o default quando souber a origem.