@winning-sales/nexo 0.4.0 → 0.6.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.
@@ -1,10 +1,15 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { join, relative, resolve } from 'node:path';
3
- import { printJson, printLine } from '../context.js';
4
- import { usageError } from '../errors.js';
3
+ import { currentSession, profileName } from '../config/session.js';
4
+ import { clientOf, printJson, printLine, printNotice } from '../context.js';
5
+ import { CliError, usageError } from '../errors.js';
6
+ import { NexoApiError } from '../http/problem.js';
7
+ import { LEVEL_LABELS, clientLevelOnly, remoteIndex, remoteSkill } from '../skills/remote-skills.js';
8
+ import { staleBundledSkills, staleNotice } from '../skills/bundled-freshness.js';
5
9
  import { bundledSkills } from '../skills/skill-files.js';
6
10
  import { SKILL_TARGETS } from '../skills/skill-targets.types.js';
7
11
  import { detectedTargets, installSkills } from '../skills/targets.js';
12
+ import { homeOf, installedUserTools, syncUserSkills, userToolsFor } from '../skills/user-skills.js';
8
13
  function chosenTargets(options, directory) {
9
14
  if (options.all === true) {
10
15
  return SKILL_TARGETS;
@@ -19,42 +24,157 @@ function chosenTargets(options, directory) {
19
24
  }
20
25
  return detected;
21
26
  }
22
- export function skillsInstall(context, options) {
27
+ function reasonOf(error) {
28
+ if (error instanceof NexoApiError || error instanceof CliError || error instanceof Error) {
29
+ return error.message;
30
+ }
31
+ return String(error);
32
+ }
33
+ /** The skills of the four levels, read with the token at the time of use; with no token or no network the CLI says why and goes on. */
34
+ async function remoteState(context, options) {
35
+ const session = currentSession(context.store, profileName(options.profile, context.env), context.env);
36
+ if (session === null) {
37
+ return { kind: 'logged-out' };
38
+ }
39
+ try {
40
+ return { kind: 'ok', session, entries: await remoteIndex(clientOf(context, session)) };
41
+ }
42
+ catch (error) {
43
+ return { kind: 'failed', reason: reasonOf(error) };
44
+ }
45
+ }
46
+ /** With network, compares the skills that came with the CLI against the ones the Nexo serves, and warns when they are old. */
47
+ async function staleSkillsNotice(context) {
48
+ const stale = await staleBundledSkills(context.fetchFn);
49
+ if (stale !== null && stale.length > 0) {
50
+ printNotice(context, staleNotice(stale));
51
+ }
52
+ }
53
+ function remoteNotice(context, state) {
54
+ if (state.kind === 'logged-out') {
55
+ printNotice(context, 'Sem login: só as skills de produto, que vêm com a CLI. Rode `nexo login` para ter também as da sua empresa, área e time.');
56
+ }
57
+ if (state.kind === 'failed') {
58
+ printNotice(context, `Não consegui ler as skills da empresa (${state.reason}). Ficam as de produto, que vêm com a CLI.`);
59
+ }
60
+ }
61
+ async function installClientSkills(context, state, targets) {
62
+ if (state.kind !== 'ok') {
63
+ return null;
64
+ }
65
+ try {
66
+ const client = clientOf(context, state.session);
67
+ const entries = clientLevelOnly(state.entries);
68
+ const home = homeOf(context.env);
69
+ const tools = userToolsFor(home, targets);
70
+ const sync = await syncUserSkills(home, tools, state.session.profile, entries, (entry) => remoteSkill(client, entry.name));
71
+ return { tools, skills: entries.map((entry) => entry.name), sync };
72
+ }
73
+ catch (error) {
74
+ printNotice(context, `Não consegui baixar as skills da empresa (${reasonOf(error)}); as que já estavam na sua pasta ficaram como estavam.`);
75
+ return null;
76
+ }
77
+ }
78
+ function clientSummary(client) {
79
+ const { written, upToDate, removed } = client.sync;
80
+ const parts = [
81
+ `${String(client.skills.length - upToDate.length)} novas ou atualizadas`,
82
+ `${String(upToDate.length)} já em dia`,
83
+ `${String(removed.length)} removidas`
84
+ ];
85
+ return `${String(client.skills.length)} skills da sua empresa, área e time na sua pasta (${client.tools.join(', ')}), fora do projeto: ${parts.join(', ')}.${written.length === 0 && removed.length === 0 ? ' Nada mudou desde o último install.' : ''}`;
86
+ }
87
+ export async function skillsInstall(context, options) {
23
88
  const directory = resolve(options.dir ?? '.');
24
89
  const skills = bundledSkills();
25
90
  const targets = chosenTargets(options, directory);
26
91
  const written = targets.flatMap((target) => installSkills(directory, target, skills));
92
+ const state = await remoteState(context, options);
93
+ const client = await installClientSkills(context, state, targets);
27
94
  if (options.json === true) {
28
- printJson(context, { directory, targets, skills: skills.map((skill) => skill.name), files: written });
95
+ printJson(context, {
96
+ directory,
97
+ targets,
98
+ skills: skills.map((skill) => skill.name),
99
+ files: written,
100
+ clientSkills: client === null ? [] : client.skills,
101
+ clientTools: client === null ? [] : client.tools,
102
+ clientFiles: client === null ? [] : client.sync.written,
103
+ clientUpToDate: client === null ? [] : client.sync.upToDate,
104
+ clientRemoved: client === null ? [] : client.sync.removed
105
+ });
29
106
  return;
30
107
  }
31
108
  for (const file of written) {
32
109
  printLine(context, ` ${relative(directory, file)}`);
33
110
  }
34
111
  printLine(context, `${String(skills.length)} skills do Nexo em ${targets.join(', ')}. Rode de novo depois de atualizar a CLI.`);
112
+ if (client !== null) {
113
+ printLine(context, clientSummary(client));
114
+ }
115
+ remoteNotice(context, state);
116
+ await staleSkillsNotice(context);
35
117
  }
36
118
  function installedIn(directory, skill) {
37
119
  const paths = {
38
120
  claude: join(directory, '.claude', 'skills', skill.name, 'SKILL.md'),
39
- cursor: join(directory, '.cursor', 'rules', `${skill.name}.mdc`),
121
+ cursor: join(directory, '.cursor', 'skills', skill.name, 'SKILL.md'),
40
122
  agents: join(directory, '.nexo', 'skills', `${skill.name}.md`)
41
123
  };
42
124
  return SKILL_TARGETS.filter((target) => existsSync(paths[target]));
43
125
  }
44
- export function skillsList(context, options) {
45
- const directory = resolve(options.dir ?? '.');
46
- const skills = bundledSkills();
47
- const rows = skills.map((skill) => ({
126
+ function productRows(directory) {
127
+ return bundledSkills().map((skill) => ({
48
128
  name: skill.name,
129
+ level: LEVEL_LABELS.product,
49
130
  description: skill.description,
50
131
  installed: installedIn(directory, skill)
51
132
  }));
133
+ }
134
+ function clientRows(context, state) {
135
+ if (state.kind !== 'ok') {
136
+ return [];
137
+ }
138
+ const home = homeOf(context.env);
139
+ return clientLevelOnly(state.entries).map((entry) => ({
140
+ name: entry.name,
141
+ level: entry.status === 'tentative' ? `${LEVEL_LABELS[entry.level]}, em teste` : LEVEL_LABELS[entry.level],
142
+ description: entry.description,
143
+ installed: installedUserTools(home, state.session.profile, entry)
144
+ }));
145
+ }
146
+ export async function skillsList(context, options) {
147
+ const directory = resolve(options.dir ?? '.');
148
+ const state = await remoteState(context, options);
149
+ const rows = [...productRows(directory), ...clientRows(context, state)];
52
150
  if (options.json === true) {
53
151
  printJson(context, rows);
54
152
  return;
55
153
  }
56
154
  for (const row of rows) {
57
155
  const where = row.installed.length === 0 ? 'não instalada aqui' : `instalada: ${row.installed.join(', ')}`;
58
- printLine(context, `${row.name} (${where})\n ${row.description}`);
156
+ printLine(context, `${row.name} [${row.level}] (${where})\n ${row.description}`);
157
+ }
158
+ remoteNotice(context, state);
159
+ await staleSkillsNotice(context);
160
+ }
161
+ function bundledNamed(name) {
162
+ return bundledSkills().find((skill) => skill.name === name);
163
+ }
164
+ /** Prints one skill and writes nothing: the body of a skill of the client is read with the token at the time of use. */
165
+ export async function skillsShow(context, name, options) {
166
+ const state = await remoteState(context, options);
167
+ const bundled = bundledNamed(name);
168
+ const entry = state.kind === 'ok' ? state.entries.find((each) => each.name === name) : undefined;
169
+ if (state.kind === 'ok' && entry !== undefined && entry.level !== 'product') {
170
+ const skill = await remoteSkill(clientOf(context, state.session), name);
171
+ printLine(context, options.json === true ? JSON.stringify(skill, null, 2) : skill.body);
172
+ return;
173
+ }
174
+ if (bundled === undefined) {
175
+ remoteNotice(context, state);
176
+ throw usageError(`Não achei a skill ${name}.`, 'Veja os nomes com `nexo skills list`.');
59
177
  }
178
+ printLine(context, options.json === true ? JSON.stringify({ name, level: 'product', body: bundled.body }, null, 2) : bundled.content);
179
+ remoteNotice(context, state);
60
180
  }
@@ -0,0 +1,279 @@
1
+ import { createReadStream, writeFileSync } from 'node:fs';
2
+ import { clientOf, printJson, printLine, printNotice, sessionOf } from '../context.js';
3
+ import { CliError, usageError } from '../errors.js';
4
+ import { EXIT_CODES } from '../exit-codes.types.js';
5
+ import { confirmed } from '../input/confirm.js';
6
+ import { readAll } from '../input/read-input.js';
7
+ async function call(context, options, method, path, body) {
8
+ const response = await clientOf(context, sessionOf(context, options)).request({
9
+ method,
10
+ path,
11
+ ...(body === undefined ? {} : { body })
12
+ });
13
+ return response.body;
14
+ }
15
+ function templatePath(templateId) {
16
+ return `/v1/message-templates/${encodeURIComponent(templateId)}`;
17
+ }
18
+ async function jsonInput(context, input) {
19
+ const label = input === '-' ? 'stdin' : input;
20
+ let text;
21
+ try {
22
+ text = await readAll(input === '-' ? context.stdin : createReadStream(input));
23
+ }
24
+ catch {
25
+ throw usageError(`Não consegui ler ${label}.`);
26
+ }
27
+ try {
28
+ return JSON.parse(text);
29
+ }
30
+ catch {
31
+ throw usageError(`O conteúdo de ${label} não é JSON válido.`);
32
+ }
33
+ }
34
+ function isRecord(value) {
35
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
36
+ }
37
+ function saveFile(context, path, text, label) {
38
+ try {
39
+ writeFileSync(path, text);
40
+ }
41
+ catch {
42
+ throw new CliError(`Não consegui gravar ${path}.`, EXIT_CODES.failure);
43
+ }
44
+ printNotice(context, `${label} gravado em ${path}.`);
45
+ }
46
+ function formatOf(content) {
47
+ const nodes = content.document?.json.content;
48
+ if (content.document === null) {
49
+ return 'texto simples';
50
+ }
51
+ return nodes !== undefined && nodes.length > 0 && nodes.every((node) => node.type === 'section')
52
+ ? 'estruturado, com a marca'
53
+ : 'blocos, formato antigo';
54
+ }
55
+ function printBrand(context, brand) {
56
+ if (brand === null || brand === undefined) {
57
+ return;
58
+ }
59
+ printLine(context, `Marca: identidade ${brand.identidade}${brand.falta.length === 0 ? '' : `, falta ${brand.falta.join(' e ')}`}`);
60
+ if (brand.aviso !== null && brand.aviso !== undefined) {
61
+ printLine(context, brand.aviso);
62
+ return;
63
+ }
64
+ if (brand.onde !== null) {
65
+ printLine(context, `Cadastre em ${brand.onde}${brand.caminho === null ? '' : ` (${brand.caminho})`}.`);
66
+ }
67
+ }
68
+ const IDENTITY_LABELS = {
69
+ complete: 'completa',
70
+ partial: 'parcial',
71
+ absent: 'ausente'
72
+ };
73
+ function printStructureBrand(context, brand) {
74
+ if (brand === null || brand === undefined) {
75
+ return;
76
+ }
77
+ printLine(context, `Marca: identidade ${IDENTITY_LABELS[brand.identity]}${brand.missing.length === 0 ? '' : `, falta ${brand.missing.join(' e ')}`}`);
78
+ if (brand.text !== null) {
79
+ printLine(context, brand.text);
80
+ }
81
+ }
82
+ function row(template) {
83
+ const kit = template.fromKit ? ' (kit)' : '';
84
+ return `${template.id} ${template.channel.padEnd(8)} ${template.state.padEnd(8)} v${String(template.currentSeq)} ${template.name}${kit}`;
85
+ }
86
+ export async function templatesList(context, options) {
87
+ const query = new URLSearchParams();
88
+ for (const [key, value] of [
89
+ ['channel', options.channel],
90
+ ['state', options.state],
91
+ ['subjectType', options.subjectType]
92
+ ]) {
93
+ if (value !== undefined) {
94
+ query.set(key, value);
95
+ }
96
+ }
97
+ const suffix = query.size === 0 ? '' : `?${query.toString()}`;
98
+ const list = (await call(context, options, 'GET', `/v1/message-templates${suffix}`));
99
+ if (options.json === true) {
100
+ printJson(context, list);
101
+ return;
102
+ }
103
+ if (list.items.length === 0) {
104
+ printLine(context, 'Nenhum modelo de mensagem.');
105
+ return;
106
+ }
107
+ list.items.forEach((template) => {
108
+ printLine(context, row(template));
109
+ });
110
+ }
111
+ export async function templatesGet(context, templateId, options) {
112
+ const template = (await call(context, options, 'GET', templatePath(templateId)));
113
+ if (options.json === true) {
114
+ printJson(context, template);
115
+ return;
116
+ }
117
+ printLine(context, row(template));
118
+ if (template.channel === 'email') {
119
+ printLine(context, `Formato: ${formatOf(template.content)}`);
120
+ printLine(context, `Assunto: ${template.content.subject ?? '—'}`);
121
+ }
122
+ if (template.content.body !== '') {
123
+ printLine(context, template.content.body);
124
+ }
125
+ if (template.rules.length > 0) {
126
+ printLine(context, 'Regras que usam o modelo:');
127
+ template.rules.forEach((rule) => {
128
+ printLine(context, ` ${rule.name} (${rule.status})${rule.sendsAutomatically ? ', envia sozinha' : ''}`);
129
+ });
130
+ }
131
+ printNotice(context, 'Para ler os blocos, use `nexo templates get <id> --json`.');
132
+ }
133
+ export async function templatesPreview(context, templateId, options) {
134
+ const preview = (await call(context, options, 'POST', `${templatePath(templateId)}/preview`, {}));
135
+ if (options.json === true) {
136
+ printJson(context, preview);
137
+ saveHtml(context, options, preview.previews[0]?.email?.html ?? null);
138
+ return;
139
+ }
140
+ preview.previews.forEach((each) => {
141
+ printLine(context, `Assunto: ${each.subject ?? '—'}`);
142
+ printLine(context, each.email === null ? each.body : each.email.text);
143
+ });
144
+ printNotice(context, 'A prévia usa só amostras fixas, nunca registros reais da empresa.');
145
+ saveHtml(context, options, preview.previews[0]?.email?.html ?? null);
146
+ }
147
+ function saveHtml(context, options, html) {
148
+ if (options.html !== undefined && html !== null) {
149
+ saveFile(context, options.html, html, 'O HTML do e-mail');
150
+ }
151
+ }
152
+ export async function templatesStructure(context, options) {
153
+ if ((options.template === undefined) === (options.input === undefined)) {
154
+ throw usageError('Diga o conteúdo a estruturar com --template <id> ou com --input <arquivo>, só um dos dois.');
155
+ }
156
+ const content = options.template === undefined
157
+ ? await jsonInput(context, options.input ?? '-')
158
+ : (await call(context, options, 'GET', templatePath(options.template))).content;
159
+ const structured = (await call(context, options, 'POST', '/v1/message-templates/professional-structure', {
160
+ content
161
+ }));
162
+ if (options.out !== undefined) {
163
+ saveFile(context, options.out, `${JSON.stringify(structured.content, null, 2)}\n`, 'O conteúdo estruturado');
164
+ }
165
+ if (options.json === true) {
166
+ printJson(context, structured);
167
+ return;
168
+ }
169
+ printLine(context, structured.converted ? 'O modelo foi colocado na estrutura nova da marca.' : 'O modelo já estava estruturado, ou vazio: nada mudou.');
170
+ printStructureBrand(context, structured.brand);
171
+ printNotice(context, 'Nada foi gravado. Para gravar, use `nexo templates change`.');
172
+ }
173
+ function listOf(value, label) {
174
+ const list = isRecord(value) ? value['blocos'] : value;
175
+ if (!Array.isArray(list)) {
176
+ throw usageError(`${label} pede a lista de blocos, ou um objeto com "blocos".`);
177
+ }
178
+ return list;
179
+ }
180
+ async function requestOf(context, action, templateId, options) {
181
+ const base = options.input === undefined ? {} : await jsonInput(context, options.input);
182
+ if (!isRecord(base)) {
183
+ throw usageError('O arquivo de --input pede um objeto JSON com os campos do pedido.');
184
+ }
185
+ const request = { ...base, acao: action };
186
+ delete request['confirmationToken'];
187
+ const fields = [
188
+ ['modeloId', templateId],
189
+ ['canal', options.channel],
190
+ ['nome', options.name],
191
+ ['assunto', options.subject],
192
+ ['texto', options.text],
193
+ ['rodape', options.footer],
194
+ ['categoria', options.category],
195
+ ['cabecalho', options.header],
196
+ ['registro', options.record]
197
+ ];
198
+ for (const [key, value] of fields) {
199
+ if (value !== undefined) {
200
+ request[key] = value;
201
+ }
202
+ }
203
+ if (options.blocks !== undefined) {
204
+ request['blocos'] = listOf(await jsonInput(context, options.blocks), '--blocks');
205
+ }
206
+ if (options.structure === false) {
207
+ request['semEstrutura'] = true;
208
+ }
209
+ return request;
210
+ }
211
+ function printProblems(context, problems) {
212
+ problems.forEach((problem) => {
213
+ printLine(context, ` - ${problem.nodeKey === null ? '' : `${problem.nodeKey}: `}${problem.reason}`);
214
+ });
215
+ }
216
+ function printCard(context, card) {
217
+ printLine(context, card.title);
218
+ card.details.forEach((line) => {
219
+ printLine(context, ` ${line}`);
220
+ });
221
+ if (card.change.changes.length > 0) {
222
+ printLine(context, 'O que sai e o que entra:');
223
+ card.change.changes.forEach((line) => {
224
+ printLine(context, ` ${line}`);
225
+ });
226
+ }
227
+ const subject = card.change.previews[0]?.subject;
228
+ if (subject !== undefined && subject !== null) {
229
+ printLine(context, `Assunto da prévia: ${subject}`);
230
+ }
231
+ printBrand(context, card.change.brand);
232
+ }
233
+ function printApplied(context, applied) {
234
+ printLine(context, `${applied.mensagem} (${applied.modelo}: ${applied.situacao}, versão ${String(applied.versao)})`);
235
+ if (applied.avisoFormato !== undefined) {
236
+ printLine(context, applied.avisoFormato);
237
+ }
238
+ printBrand(context, applied.marca);
239
+ applied.meta?.forEach((line) => {
240
+ printLine(context, `Meta: ${line}`);
241
+ });
242
+ }
243
+ async function change(context, action, templateId, options) {
244
+ const request = await requestOf(context, action, templateId, options);
245
+ const card = (await call(context, options, 'POST', '/v1/message-template-changes/preview', request));
246
+ saveHtml(context, options, card.change.previews[0]?.html ?? null);
247
+ if (options.json !== true) {
248
+ printCard(context, card);
249
+ }
250
+ if (card.change.problems.length > 0) {
251
+ printLine(context, 'O Nexo não aceitou o pedido, corrija e rode de novo:');
252
+ printProblems(context, card.change.problems);
253
+ throw new CliError('Nada foi gravado: o pedido tem problemas.', EXIT_CODES.failure);
254
+ }
255
+ if (!(await confirmed(context, options.yes, 'Gravar assim?'))) {
256
+ if (options.json === true) {
257
+ printJson(context, card);
258
+ }
259
+ return;
260
+ }
261
+ const applied = (await call(context, options, 'POST', '/v1/message-template-changes/apply', {
262
+ ...request,
263
+ confirmationToken: card.confirmation.token
264
+ }));
265
+ if (options.json === true) {
266
+ printJson(context, applied);
267
+ return;
268
+ }
269
+ printApplied(context, applied);
270
+ }
271
+ export async function templatesCreate(context, options) {
272
+ await change(context, 'criar_modelo', undefined, options);
273
+ }
274
+ export async function templatesChange(context, templateId, options) {
275
+ await change(context, 'mudar_modelo', templateId, options);
276
+ }
277
+ export async function templatesPublish(context, templateId, options) {
278
+ await change(context, 'publicar_modelo', templateId, options);
279
+ }
@@ -17,12 +17,20 @@ export async function fetchMe(context, session) {
17
17
  }
18
18
  return response.body;
19
19
  }
20
+ function companyLines(me) {
21
+ if (me.platform?.global !== true) {
22
+ return [`Empresa: ${me.company.name}`];
23
+ }
24
+ return me.platform.activeCompanyId === null
25
+ ? ['Conexão de plataforma: nenhuma empresa escolhida; rode `nexo companies` e `nexo use <empresa>`']
26
+ : [`Conexão de plataforma, empresa ativa: ${me.company.name} (${me.platform.activeCompanyId})`];
27
+ }
20
28
  export function describeMe(me, session) {
21
29
  const expires = new Date(me.credential.expiresAt).toLocaleDateString('pt-BR', { timeZone: me.company.timezone });
22
30
  const source = session.source === 'env' ? 'NEXO_TOKEN' : `perfil ${session.profile}`;
23
31
  return [
24
32
  `${me.user.name} <${me.user.email}>, ${profilesOf(me)}`,
25
- `Empresa: ${me.company.name}`,
33
+ ...companyLines(me),
26
34
  `Credencial: ${me.credential.name} (${source}), vale até ${expires}`,
27
35
  `Escopos: ${me.credential.scopes.join(', ')}`,
28
36
  `API: ${session.apiUrl}`
@@ -42,8 +42,14 @@ const HINT_BY_STATUS = {
42
42
  429: 'Espere um pouco: o limite é da empresa, somando todos os tokens.'
43
43
  };
44
44
  const HINT_BY_TYPE = {
45
+ 'public_api.platform_company_required': 'Escolha uma empresa: `nexo companies` lista, `nexo use <empresa>` escolhe.',
46
+ 'public_api.platform_connection_only': 'Só a conexão de plataforma (login do admin da empresa do Nexo) escolhe empresa.',
45
47
  'agents.writing_budget': null,
46
48
  'core.too_many_attempts': 'Espere alguns minutos: o limite é por pessoa e por empresa, somado ao do app.',
49
+ 'copilot.confirmation_stale': 'O modelo mudou depois da prévia: rode o comando de novo e confirme.',
50
+ 'brain.skill_shrink_needs_confirmation': 'A edição tira item ou encolhe a skill em mais de 30%: mostre à pessoa e, depois do sim, rode de novo com --confirm-shrink.',
51
+ 'brain.layer_skill_refused': 'O texto foi recusado (ordem ao assistente, número da empresa ou skill repetida): reescreva o item como um jeito de fazer.',
52
+ 'brain.skill_without_usage_condition': 'Falta dizer quando usar: ajuste o objetivo e o momento.',
47
53
  'agents.template_required': 'Diga o modelo da versão nova com --template <id>.'
48
54
  };
49
55
  function hintOf(problem) {
@@ -0,0 +1,111 @@
1
+ import { brainAreas, brainBlindTest, brainChoose, brainCreate, brainEdit, brainFromTemplate, brainList, brainMoments, brainRemove, brainTemplates } from './commands/brain.js';
2
+ function collect(value, previous) {
3
+ return [...previous, value];
4
+ }
5
+ const LEVEL = '<nível>';
6
+ const LEVEL_HELP = 'company (empresa), area, team (time) ou person (pessoal)';
7
+ function addReadCommands(brain, context) {
8
+ brain
9
+ .command('areas')
10
+ .description('As áreas da empresa (o id vai em --area)')
11
+ .action(async (_options, command) => {
12
+ await brainAreas(context, command.optsWithGlobals());
13
+ });
14
+ brain
15
+ .command('moments')
16
+ .description('Os momentos que aceitam skill nova (só os que têm o teste "não piora" funcionando)')
17
+ .action(async (_options, command) => {
18
+ await brainMoments(context, command.optsWithGlobals());
19
+ });
20
+ brain
21
+ .command('list')
22
+ .description('Lista as skills de um nível (a pessoal é só sua)')
23
+ .argument(LEVEL, LEVEL_HELP)
24
+ .option('--scope <id>', 'só de uma área ou de um time')
25
+ .action(async (level, _options, command) => {
26
+ await brainList(context, level, command.optsWithGlobals());
27
+ });
28
+ }
29
+ function addWriteCommands(brain, context) {
30
+ brain
31
+ .command('create')
32
+ .description('Cria uma skill pela ideia; o Cérebro escreve o SKILL.md e a skill nasce em teste. Só admin, com calibration:write')
33
+ .argument(LEVEL, LEVEL_HELP)
34
+ .option('--area <id>', 'a área da skill (nível area)')
35
+ .option('--team <id>', 'o time da skill (nível team)')
36
+ .option('--objective <texto>', 'o objetivo, em uma linha')
37
+ .option('--moment <momento>', 'o momento da lista (nexo brain moments)')
38
+ .option('--always <texto>', 'o que fazer sempre (repita para mais de um)', collect, [])
39
+ .option('--never <texto>', 'o que nunca fazer (repita para mais de um)', collect, [])
40
+ .option('--example <texto>', 'um exemplo de como deve sair, em uma linha')
41
+ .action(async (level, _options, command) => {
42
+ await brainCreate(context, level, command.optsWithGlobals());
43
+ });
44
+ }
45
+ function addPersonCommands(brain, context) {
46
+ brain
47
+ .command('templates')
48
+ .description('Os modelos da Winning para skill pessoal, com os campos de cada um')
49
+ .action(async (_options, command) => {
50
+ await brainTemplates(context, command.optsWithGlobals());
51
+ });
52
+ brain
53
+ .command('from-template')
54
+ .description('Cria uma skill pessoal de um modelo: você preenche os campos, nunca o texto')
55
+ .argument('<modelo>', 'id do modelo (nexo brain templates)')
56
+ .option('--answer <campo=texto>', 'a resposta de um campo do modelo (repita; todos são obrigatórios)', collect, [])
57
+ .action(async (templateId, _options, command) => {
58
+ await brainFromTemplate(context, templateId, command.optsWithGlobals());
59
+ });
60
+ brain
61
+ .command('blind-test')
62
+ .description('Compara às cegas, para uma skill pessoal: dois textos A e B, sem dizer qual tem a skill')
63
+ .argument('<skill>', 'id da skill pessoal')
64
+ .action(async (skillId, _options, command) => {
65
+ await brainBlindTest(context, skillId, command.optsWithGlobals());
66
+ });
67
+ brain
68
+ .command('choose')
69
+ .description('Escolhe A ou B na comparação às cegas; só então diz qual tinha a skill')
70
+ .argument('<comparação>', 'id da comparação (nexo brain blind-test)')
71
+ .argument('<escolha>', 'a ou b')
72
+ .action(async (choiceId, chosen, _options, command) => {
73
+ await brainChoose(context, choiceId, chosen, command.optsWithGlobals());
74
+ });
75
+ }
76
+ function addChangeCommands(brain, context) {
77
+ brain
78
+ .command('edit')
79
+ .description('Edita uma skill por item: soma, atualiza ou remove um item; nenhuma outra linha muda')
80
+ .argument(LEVEL, LEVEL_HELP)
81
+ .argument('<skill>', 'id da skill')
82
+ .option('--add-always <texto>', 'soma um item em "sempre" (repita)', collect, [])
83
+ .option('--add-never <texto>', 'soma um item em "nunca" (repita)', collect, [])
84
+ .option('--update-always <troca>', 'troca um item de "sempre": "atual => novo" (repita)', collect, [])
85
+ .option('--update-never <troca>', 'troca um item de "nunca": "atual => novo" (repita)', collect, [])
86
+ .option('--remove-always <texto>', 'tira um item de "sempre" (repita)', collect, [])
87
+ .option('--remove-never <texto>', 'tira um item de "nunca" (repita)', collect, [])
88
+ .option('--confirm-shrink', 'confirma a edição que tira item ou encolhe a skill em mais de 30%')
89
+ .action(async (level, skillId, _options, command) => {
90
+ await brainEdit(context, level, skillId, command.optsWithGlobals());
91
+ });
92
+ brain
93
+ .command('remove')
94
+ .description('Apaga uma skill de qualquer nível (a pessoal dá para restaurar em 30 dias, pelo app)')
95
+ .argument(LEVEL, LEVEL_HELP)
96
+ .argument('<skill>', 'id da skill')
97
+ .option('-y, --yes', 'apaga sem perguntar (só depois do sim da pessoa)')
98
+ .action(async (level, skillId, _options, command) => {
99
+ await brainRemove(context, level, skillId, command.optsWithGlobals());
100
+ });
101
+ }
102
+ export function addBrainCommands(program, context) {
103
+ const brain = program
104
+ .command('brain')
105
+ .alias('cerebro')
106
+ .description('O Cérebro: as skills da empresa, das áreas e dos times, criadas pela ideia e editadas por item (nunca pelo texto)');
107
+ addReadCommands(brain, context);
108
+ addWriteCommands(brain, context);
109
+ addPersonCommands(brain, context);
110
+ addChangeCommands(brain, context);
111
+ }