@aksp/opencrew 1.11.0 → 1.13.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.
Files changed (36) hide show
  1. package/CHANGELOG.md +66 -3
  2. package/README.md +7 -3
  3. package/package.json +1 -1
  4. package/templates/AGENTS.md +10 -8
  5. package/templates/_opencrew/.opencrew-version +1 -1
  6. package/templates/_opencrew/core/best-practices/_catalog.yaml +5 -0
  7. package/templates/_opencrew/core/best-practices/texto-livre.md +23 -0
  8. package/templates/_opencrew/core/formato-da-crew.md +2 -1
  9. package/templates/_opencrew/core/prompts/build.prompt.md +3 -3
  10. package/templates/_opencrew/core/prompts/design.prompt.md +5 -5
  11. package/templates/_opencrew/core/prompts/discovery.prompt.md +8 -6
  12. package/templates/_opencrew/core/prompts/documento.prompt.md +9 -5
  13. package/templates/_opencrew/core/prompts/entrega.prompt.md +7 -2
  14. package/templates/_opencrew/core/prompts/repair.prompt.md +1 -1
  15. package/templates/_opencrew/core/runner/contrato-de-saida.md +33 -0
  16. package/templates/_opencrew/core/runner/escritorio.md +37 -0
  17. package/templates/_opencrew/core/runner/fim-da-execucao.md +110 -0
  18. package/templates/_opencrew/core/runner/fontes-pendentes.md +21 -0
  19. package/templates/_opencrew/core/runner/memoria.md +55 -0
  20. package/templates/_opencrew/core/runner/selecao-de-agentes.md +79 -0
  21. package/templates/_opencrew/core/runner/tarefas-do-agente.md +34 -0
  22. package/templates/_opencrew/core/runner.pipeline.md +45 -373
  23. package/templates/_opencrew/core/scripts/caminho/argumentos.mjs +3 -1
  24. package/templates/_opencrew/core/scripts/caminho/nucleo.mjs +16 -0
  25. package/templates/_opencrew/core/scripts/caminho.mjs +11 -8
  26. package/templates/_opencrew/core/scripts/conferir-fontes/relatorio.mjs +4 -2
  27. package/templates/_opencrew/core/scripts/conferir-fontes.mjs +22 -16
  28. package/templates/_opencrew/core/scripts/conserto/achados.mjs +1 -1
  29. package/templates/_opencrew/core/scripts/documento/markdown.mjs +2 -1
  30. package/templates/_opencrew/core/scripts/documento/pacote.mjs +1 -0
  31. package/templates/_opencrew/core/scripts/documento/perfil.mjs +14 -0
  32. package/templates/_opencrew/core/scripts/entrega/pendencias.mjs +4 -1
  33. package/templates/_opencrew/core/scripts/entrega/separar.mjs +2 -1
  34. package/templates/_opencrew/core/scripts/verificar/documento.mjs +20 -0
  35. package/templates/_opencrew/core/scripts/verificar/medicao.mjs +2 -1
  36. package/templates/_opencrew/core/scripts/verificar.mjs +3 -1
@@ -35,77 +35,21 @@ Before starting execution:
35
35
 
36
36
  1a. **Escritório toggle** — the optional live view is off unless `preferences.md` turns it on (see "Escritório" below).
37
37
 
38
- > **Note on language**: The structural labels listed below are **fixed PT-BR** and must
39
- > never be translated — opencrew's primary supported audience is PT-BR (see AGENTS.md →
40
- > Language Handling). Only the *content* written under these headers follows the user's
41
- > preferred language.
42
- >
43
- > | Fixed PT-BR header | Location | Purpose |
44
- > |---|---|---|
45
- > | `## Estilo de Escrita` | `memories.md` | Writing style rules accumulated per crew |
46
- > | `## Design Visual` | `memories.md` | Visual design preferences per crew |
47
- > | `## Estrutura de Conteúdo` | `memories.md` | Content structure rules per crew |
48
- > | `## Proibições Explícitas` | `memories.md` | User bans and hard blocks per crew |
49
- > | `## Técnico (específico do crew)` | `memories.md` | Technical crew-specific settings |
50
- > | `Data \| Run ID \| Tema \| Output \| Score \| Resultado` | `runs.md` | Run history table columns |
51
- >
52
- > When adding new structural sections to `memories.md` or `runs.md`, keep headers in PT-BR
53
- > unless the user base expands beyond PT-BR — at that point, discuss a migration strategy
54
- > (e.g. i18n key mapping) rather than mixing languages in a single file.
55
-
56
- 1b. **Memory format migration** — After loading `memories.md`, check whether it uses the new format: it does when it has the `## Estilo de Escrita` section header (read the file with the read tool — no command).
57
- - If it has the header → proceed normally.
58
- - If it does not (or the file is empty / does not exist) → migrate before proceeding:
59
- a0. If the file exists and is not empty, FIRST copy it to `crews/{name}/_memory/memories.md.bak`
60
- (never lose what the crew learned), then tell the user in one line:
61
- "Atualizei o formato da memória da crew; a versão anterior está em `memories.md.bak`."
62
- Move every rule you can recognize from the old file into the matching new section.
63
- a. Write `crews/{name}/_memory/memories.md` with the new sections format:
64
- ```markdown
65
- # Crew Memory: {crew-name}
66
-
67
- ## Estilo de Escrita
68
-
69
- ## Design Visual
70
-
71
- ## Estrutura de Conteúdo
72
-
73
- ## Proibições Explícitas
74
-
75
- ## Técnico (específico do crew)
76
- ```
77
- (Use the crew's display name for `{crew-name}`, and the crew code for `{name}` in file paths — they refer to the same crew.)
78
- b. Check if `crews/{name}/_memory/runs.md` exists (read tool — no command).
79
- If it does not exist, create it with:
80
- ```markdown
81
- # Run History: {crew-name}
82
-
83
- | Data | Run ID | Tema | Output | Score | Resultado |
84
- |------|--------|------|--------|-------|-----------|
85
- ```
86
- - Do not pause execution for this migration (the one-line notice above is enough).
38
+ 1b. **Memory format** — check, with the read tool (no command), whether `memories.md` has the
39
+ `## Estilo de Escrita` section header. It has → proceed. It does not, or the file is empty or does not
40
+ exist → read `_opencrew/core/runner/memoria.md` completely and follow it before proceeding (it migrates
41
+ the file, with a `.bak` copy, without pausing the run). The section headers of `memories.md` (`## Estilo de
42
+ Escrita`, `## Design Visual`, `## Estrutura de Conteúdo`, `## Proibições Explícitas`, `## Técnico (específico do
43
+ crew)`) and the columns of `runs.md` are fixed PT-BR, whatever the user's language: never translate them.
87
44
 
88
45
  1c. **Source check** — before loading the project sources (1d), run:
89
46
  ```bash
90
47
  node _opencrew/core/scripts/conferir-fontes.mjs --crew "crews/{name}"
91
48
  ```
92
- If the last line is `FONTES:PENDENTE` (a cited file was moved, renamed or deleted), show the
93
- report and ask — never continue silently with a missing source:
94
- ```
95
- Alguns arquivos que a crew usa não estão mais onde ela espera:
96
- {resumo do relatório}
97
-
98
- 1. Corrigir os caminhos sugeridos (troco nos arquivos da crew e guardo .bak)
99
- 2. Seguir assim mesmo
100
- 3. Parar
101
- ```
102
- On 1, run the same command with `--corrigir`, show the new result and re-read `crew.yaml` and
103
- any agent file already loaded (it may have changed them); 1d then loads the sources from the
104
- corrected paths. If the new result still ends in `FONTES:PENDENTE`, ask again with options 2 and
105
- 3 only. Alerts — not portable (absolute paths) or "não conferido" (a network path or a site
106
- address: the script never accesses the network) — are mentioned once, without stopping. If the
107
- script did not run (no Node, an error, or no `FONTES:` status line), tell the user "⚠️ A
108
- conferência de fontes não rodou: {motivo}" and continue; the final approval repeats the warning.
49
+ If the last line is `FONTES:OK`, go on: an alert in the report (an absolute path, a network path or a
50
+ site address) is mentioned once, without stopping. Otherwise (`FONTES:PENDENTE`, or the script did not
51
+ run): read `_opencrew/core/runner/fontes-pendentes.md` completely and follow it — never continue
52
+ silently with a missing source.
109
53
 
110
54
  1d. **Project sources (`fontes:`)** — if `crew.yaml` has a `fontes:` list (files or folders of
111
55
  the user's project, paths relative to the project root), read them now: a file in full up to
@@ -121,89 +65,17 @@ Before starting execution:
121
65
  - If yes → read `_opencrew/core/skills.engine.md`, follow Operation 2 (Install)
122
66
  - If no → **ERROR**: stop pipeline
123
67
  b. Read SKILL.md, parse frontmatter for type
124
- c. If type: mcp, verify MCP is configured in `.claude/settings.local.json`
68
+ c. If type: mcp, verify the MCP server is configured in your IDE's MCP configuration (the project's `.mcp.json`, or the file your IDE uses)
125
69
  - If missing → **ERROR**: "Skill '{skill}' MCP not configured. Reinstall the skill."
126
70
  All skills must resolve successfully before the pipeline starts (fail fast).
127
71
  4. **Model tiers**: a `subagent` step declares its own `model_tier` (`fast` or `powerful`), set at crew creation by the crew's tier; inline steps carry none.
128
72
  - Read the crew's tier for the run header: `crew.tier` in `crew.yaml` (older crews: `tier` loose at the top level).
129
73
  - A subagent step with no `model_tier` → `powerful` at dispatch.
130
74
 
131
- 4b. **Pre-Execution Agent Selection** — Decide which agents actually run for this task.
132
- Run this step ONLY if `crew.yaml` declares an `agent_dependencies:` field (even an
133
- empty map `{}`). If the field is absent → skip this entire step and run ALL agents
134
- exactly as before (legacy behavior).
135
-
136
- When active, in this order:
137
-
138
- a. **Capture the task** — Determine the user's request for this run:
139
- - If the run was invoked with a description (e.g. `/opencrew run {name} {description}`),
140
- use that text as the task.
141
- - Otherwise ask: `📝 What is the task for this run? Reply in one line.`
142
- Wait for the user's reply before continuing.
143
-
144
- b. **Analyze against the decision matrix** — Scan the task text (case-insensitive,
145
- PT-BR and EN keywords) for the signals below. Start with ALL agents suggested as
146
- SELECTED (`required`). For each matching signal, find the affected agent(s) in
147
- `crew-party.csv` by matching the role terms against the agent's `id` and `title`
148
- (and `displayName` if ambiguous), then apply the suggested status:
149
-
150
- | Signal in the task | Role terms to match (id / title) | Suggested status |
151
- |--------------------|----------------------------------|------------------|
152
- | "já pesquisei", "com base em", "fontes que tenho", "material pronto", "baseado nas fontes", "research already done" | researcher, pesquisad, research | optional |
153
- | "revise", "melhore", "corrija", "refine", "edite" (sem criar do zero), "improve this draft" | copywriter, redator, writer, criador | optional |
154
- | "só texto", "sem imagem", "sem visual", "sem arte", "no image" | designer, design, visual | skip |
155
- | "já revisei", "já foi aprovado", "aprovado por terceiros", "revisão feita", "already reviewed" | reviewer, revisor | optional |
156
- | "quero só revisar este texto", "apenas revisar", "review only" | researcher AND copywriter | skip |
157
- | "tenho o conteúdo pronto", "forneço o documento", "docs em anexo", "segue o material", "here is the content" | copywriter, writer, creator | optional |
158
-
159
- Resolution rules:
160
- - `optional` = agent stays selected but may be unchecked.
161
- - `skip` = agent is suggested deselected.
162
- - Conflicting signals on the same agent → the more restrictive wins (`skip` > `optional`).
163
- - Never suggest skipping an agent whose output is the run's final deliverable unless the
164
- signal is explicit.
165
- - No signal matches → suggest keeping all agents (no change).
166
-
167
- c. **Present the selection** — IDE-neutral numbered multi-select. List every agent from
168
- `crew-party.csv` in party order:
169
- ```
170
- 🧑‍🤝‍🧑 Which agents should work on this task?
171
-
172
- Suggested selection:
173
- 1. [x] {icon} {displayName} ({id}) — {title}
174
- 2. [x] {icon} {displayName} ({id}) — {title}
175
- 3. [ ] {icon} {displayName} ({id}) — {title}
176
- ...
177
- [x] = suggested selected · [ ] = suggested deselected
178
-
179
- Reply with the numbers of the agents you want to INCLUDE, separated by commas.
180
- Example: "1, 2" · Reply "all" to run everyone.
181
- ```
182
- Wait for the user's reply. Parse it into `selected_agents`. At least one agent must
183
- be selected — if the user replies with none, repeat the prompt once.
184
-
185
- d. **Dependency warnings** — Using `crew.yaml → agent_dependencies`
186
- (e.g. `copywriter: [researcher]` = copywriter consumes researcher's output):
187
- for every dependency `dependent → required_agent`, if `dependent` is selected but
188
- `required_agent` is NOT, warn:
189
- ```
190
- ⚠️ {dependent} normally depends on {required_agent}'s output, which you deselected.
191
-
192
- 1. Re-select {required_agent} (recommended)
193
- 2. Keep going without it — I will supply the input myself
194
- 3. Deselect {dependent} too
195
- ```
196
- Wait for the user's choice and apply it. If they pick option 2, set
197
- `missing_dependency = true` in working memory (the existing Pre-Step Input
198
- Validation recovery — "Skip step and continue / Abort" — then handles any
199
- downstream gap).
200
-
201
- e. **Build the filtered step list** — Set `skipped_agents = all party agents − selected_agents`.
202
- Build `filtered_steps` by walking `pipeline.yaml` in order, keeping a step when:
203
- - its frontmatter has NO `agent:` field (checkpoints / generic steps), OR
204
- - its `agent:` value is in `selected_agents`.
205
- Store `selected_agents`, `skipped_agents`, and `filtered_steps` in working memory for
206
- the per-step loop (steps 5 and 6 below reflect them).
75
+ 4b. **Pre-Execution Agent Selection** — ONLY if `crew.yaml` declares an `agent_dependencies:` field (even an
76
+ empty map `{}`): read `_opencrew/core/runner/selecao-de-agentes.md` completely and follow it now; it
77
+ leaves `selected_agents`, `skipped_agents`, `filtered_steps` and `missing_dependency` in working memory.
78
+ If the field is absent, read nothing: run ALL agents, with no selection step.
207
79
 
208
80
  5. Inform the user that the crew is starting:
209
81
  ```
@@ -217,49 +89,21 @@ Before starting execution:
217
89
  ```
218
90
  When the selection step was skipped (no `agent_dependencies:` in crew.yaml), this is
219
91
  identical to today: all agents listed, no Skipped line.
220
- 5b. **Initialize run folder**: Generate a unique run ID for this execution:
221
- - Format: `YYYY-MM-DD-HHmmss` using the current timestamp (e.g. `2026-03-03-143022`)
222
- - Check (folder-listing tool, no command) if `crews/{name}/output/{run_id}/` already exists
223
- - If it does (sub-second collision), append `-2`, `-3`, etc. until the folder does not exist
224
- - Create the folder: run the `pasta` command (see "Output Path Transformation" below) — never create a folder by command yourself
92
+ 5b. **Initialize run folder**: the script names the run — never build the date or the time yourself:
93
+ - Run the `pasta` command (see "Output Path Transformation" below). It creates the folder of this run and answers `CAMINHO:OK crews/{name}/output/{run_id}`
94
+ - The `run_id` is the last segment of that path: `YYYY-MM-DD-HHmmss` from the computer's clock (e.g. `2026-03-03-143022`; `-2`, `-3` when that folder already exists)
95
+ - The date of this run, wherever one is asked below, is the first 10 characters of the `run_id`
96
+ - Never create a folder by command yourself
225
97
  - Store `run_id` in working memory for this run — it will be used for ALL output paths
226
98
  6. **Escritório** — if it is on, run `iniciar`, then one `pular` per deselected agent, one after the other (see "Escritório" below).
227
99
 
228
100
  ## Escritório (optional live view)
229
101
 
230
- A local page that shows the crew at work, off by default. Follow this section only when the
231
- already-loaded `preferences.md` has `Dashboard: enabled` (written `- **Dashboard:** enabled` or
232
- plain `Dashboard: enabled`, any letter case); otherwise run none of these commands. When it is on,
233
- run via Bash, from the project root, the one-line command of each moment:
234
-
235
- | Moment | Command |
236
- |---|---|
237
- | Start of the run (Initialization, step 6) | `node _opencrew/core/scripts/estado.mjs "{name}" iniciar --passos {N}` |
238
- | Right after `iniciar`, once per deselected agent | `node _opencrew/core/scripts/estado.mjs "{name}" pular --agente {id}` |
239
- | Before each step, each time it starts | `node _opencrew/core/scripts/estado.mjs "{name}" passo --n {K} --agente {id} --rotulo "{rótulo}" --mensagem "{frase}"` |
240
- | Before asking the question of a checkpoint (instead of `passo`) | `node _opencrew/core/scripts/estado.mjs "{name}" checkpoint --n {K} --agente {id} --rotulo "{rótulo}"` |
241
- | End of the run (After Pipeline Completion) | `node _opencrew/core/scripts/estado.mjs "{name}" concluir` |
242
- | Run aborted after `iniciar`, by the user or by an error | `node _opencrew/core/scripts/estado.mjs "{name}" falhar --motivo "{motivo}"` |
243
-
244
- - **One at a time** — Run these commands one at a time, waiting for the `ESTADO:` line of each
245
- before the next — never in parallel or in the background (each one reads and rewrites the same file).
246
- - **Values** — `{name}`: the crew code. `{N}`: how many steps will run, checkpoints included (a
247
- deselected agent's steps do not count). `{K}`: the step's position among them, from 1. `{id}`: the agent's `id` column in
248
- `crew-party.csv`; a step or checkpoint with no `agent:` goes without `--agente`
249
- (the table shows the full form). `{rótulo}`: the step's name, in
250
- a few words. `--mensagem` goes only when the agent changed since the last `passo` (so never on the first
251
- one): one sentence on what the previous agent delivered — never look at the next step. `{motivo}`: why the run stopped.
252
- - **Text on the command line** — `--rotulo`, `--mensagem` and `--motivo` go between double quotes,
253
- on one line, starting with a letter or a digit, with only letters (accents included), digits,
254
- spaces and `. , : ; - ( ) / ?`. Drop every other sign (quotes of any kind, `$`, backtick, `\`,
255
- `%`, `!`, emoji). If no text is left, omit the option. Write them in the user's language.
256
- - **After `iniciar`**, when it answers `ESTADO:OK`, show the user once:
257
- `Escritório ligado. Se a página não estiver aberta, rode em outro terminal: node _opencrew/core/scripts/escritorio.mjs`
258
- - **The Escritório never stops the run.** A command that fails, does not run or answers
259
- `ESTADO:IGNORADO`: go on, do not repeat that event, ask nothing, and tell the user once per run,
260
- in one line: `O escritório não foi atualizado nesta execução; o trabalho segue normalmente.` With
261
- the reason "escritório desligado", say nothing and stop calling the script for the rest of this run.
262
- - The script is the only writer: never read, write or describe `crews/{name}/state.json` yourself.
102
+ Only when the already-loaded `preferences.md` has `Dashboard: enabled` (written `- **Dashboard:** enabled`
103
+ or plain `Dashboard: enabled`, any letter case): read `_opencrew/core/runner/escritorio.md` completely,
104
+ once, and follow it at each moment it names (start of the run, each step, each checkpoint, end, abort).
105
+ With the Dashboard off, read nothing and run none of its commands. Either way: never read, write or
106
+ describe `crews/{name}/state.json` yourself, and a failure there never stops the run.
263
107
 
264
108
  ## Execution Rules
265
109
 
@@ -408,36 +252,9 @@ when passing prior agents' outputs as context:
408
252
 
409
253
  ### Task-Based Agent Execution
410
254
 
411
- When an agent's `.agent.md` frontmatter contains a `tasks:` field:
412
-
413
- 1. **Load task list**: Read the `tasks:` array from the agent's frontmatter
414
- - Each entry is a relative path to a task file (e.g., `tasks/analyze-source.md`)
415
- - Tasks execute in the order listed
416
-
417
- 2. **For each task in sequence**:
418
- a. Read the task file from the agent's directory (e.g., `crews/{crew-name}/agents/{agent}/tasks/{task}.md`)
419
- b. Construct the execution prompt:
420
- - Agent persona + principles (from agent.md — fixed across all tasks)
421
- - Task description and process (from task file)
422
- - Task output format (from task file)
423
- - Task quality criteria and veto conditions (from task file)
424
- - Input: For the first task, use the step's input. For subsequent tasks, use the previous task's output.
425
- c. Execute the task (inline or subagent, matching the step's execution mode)
426
- d. Collect the task output
427
- e. Check task veto conditions (same enforcement as step veto conditions below)
428
-
429
- 3. **Final output**: The output of the LAST task in the chain becomes the step's output
430
- - Resolve the `outputFile` path with the `saida` command (Output Path Transformation) before saving — this applies regardless of whether the step runs as `execution: inline` or `execution: subagent`
431
- - Save to the **transformed** outputFile path
432
- - This is what the next step (or checkpoint) receives
433
-
434
- 4. **Progress reporting**: For inline execution, announce each task:
435
- ```
436
- {icon} {Agent Name} — Task {N}/{total}: {task name}...
437
- ```
438
-
439
- 5. **Backward compatibility**: If the agent's frontmatter does NOT contain a `tasks:` field,
440
- execute the agent monolithically as before (current behavior unchanged).
255
+ Only when the agent's `.agent.md` frontmatter contains a `tasks:` field: read
256
+ `_opencrew/core/runner/tarefas-do-agente.md` completely and follow it for that step. Without the field,
257
+ execute the agent as a whole, as always.
441
258
 
442
259
  ### Output Path Transformation
443
260
 
@@ -448,7 +265,7 @@ root the one-line command of each moment and read the last line (`CAMINHO:OK {pa
448
265
 
449
266
  | Moment | Command |
450
267
  |---|---|
451
- | Start of the run (Initialization, step 5b) | `node _opencrew/core/scripts/caminho.mjs "{name}" pasta --run "{run_id}"` |
268
+ | Start of the run (Initialization, step 5b) | `node _opencrew/core/scripts/caminho.mjs "{name}" pasta` (no `--run`: the script creates the `run_id`) |
452
269
  | Before a step, for its `inputFile` | `node _opencrew/core/scripts/caminho.mjs "{name}" entrada --run "{run_id}" --arquivo "{inputFile}"` |
453
270
  | Before a step writes, for the first `outputFile` of each group | `node _opencrew/core/scripts/caminho.mjs "{name}" saida --run "{run_id}" --arquivo "{outputFile}"` |
454
271
  | After a step wrote, for each output file | `node _opencrew/core/scripts/caminho.mjs "{name}" conferir --arquivo "{path}"` |
@@ -476,7 +293,7 @@ root the one-line command of each moment and read the last line (`CAMINHO:OK {pa
476
293
  and reads `…/v1/pesquisa.md`. Never assume `v1`.
477
294
  - **Script that does not run** (no Node, an error, or no `CAMINHO:` line): tell the user once per
478
295
  run `Não consegui rodar a conferência de caminhos; sigo pela regra escrita e marco os arquivos como não verificados.`,
479
- build the path by the rule above (the Write tool creates the folder) and continue. A file handled
296
+ build the path by the rule above (your file-writing tool creates the folder) and continue. A file handled
480
297
  this way skips its gate and is listed at the final approval:
481
298
  `{arquivo} — não verificado: a conferência de caminhos não rodou`.
482
299
 
@@ -518,10 +335,10 @@ root the one-line command of each moment and read the last line (`CAMINHO:OK {pa
518
335
  - Read the step's `model_tier` frontmatter field (if present).
519
336
  Valid values: `fast` or `powerful`. If absent or any other value: default to `powerful`.
520
337
  - **Before building the subagent prompt**: Resolve all output paths referenced in the step file with the `saida` command (Output Path Transformation, once per group). Store the transformed path(s) in working memory — they will be used both in the prompt and in post-completion verification. Never pass raw paths from the step file to the subagent.
521
- - Use the Task tool to dispatch the step as a subagent:
338
+ - Dispatch the step with your IDE's subagent mechanism (an IDE without one: run the step inline, in this conversation):
522
339
  - If `model_tier: fast`: use the fastest/lightest model available in your current IDE.
523
340
  - If `model_tier: powerful` or absent/invalid: use the default model (no model override needed)
524
- - In the Task prompt, include:
341
+ - In the subagent's prompt, include:
525
342
  - The full agent persona from the party CSV
526
343
  - The full agent `.agent.md` content (persona, principles, voice guidance, anti-patterns)
527
344
  - If the agent has tasks: include ALL task files in order with instructions to execute sequentially, piping output from each task to the next
@@ -535,7 +352,7 @@ root the one-line command of each moment and read the last line (`CAMINHO:OK {pa
535
352
  - Proceed to Post-Step Output Validation (below) before advancing.
536
353
 
537
354
  #### If `execution: inline`
538
- - Switch to the agent's persona (read from party CSV)
355
+ - Switch to the agent's persona (read from party CSV); an agent with `tasks:` runs them as `Task-Based Agent Execution` says
539
356
  - Announce: `{icon} {Agent Name} is working...`
540
357
  - Follow the step instructions
541
358
  - Present output directly in the conversation
@@ -558,16 +375,16 @@ root the one-line command of each moment and read the last line (`CAMINHO:OK {pa
558
375
  (e.g. the organization's name, the main audience), ask: "Isso vale para todas as crews?
559
376
  Atualizo o perfil da empresa?" — change `company.md` only after a yes.
560
377
  - **If the step frontmatter contains `outputFile`**: after collecting the user's full response,
561
- insert only the run_id in the `outputFile` path (item 1 of the rule in Output Path Transformation — no version folder, no `saida` command), then write the response to that path using the Write tool (it creates the folder) before moving to the next step. Checkpoint files are user input captures, not versioned output: they live in the group itself, where `entrada` finds them.
378
+ insert only the run_id in the `outputFile` path (item 1 of the rule in Output Path Transformation — no version folder, no `saida` command), then write the response to that path with your file-writing tool (it creates the folder) before moving to the next step. Checkpoint files are user input captures, not versioned output: they live in the group itself, where `entrada` finds them.
562
379
  For the checkpoint that precedes the researcher, use this format:
563
380
  ```
564
381
  # Research Focus
565
382
 
566
383
  **Topic:** {user's typed topic}
567
384
  **Time Range:** {selected time range label, e.g., "Últimos 7 dias"}
568
- **Date:** {today's date in YYYY-MM-DD format}
385
+ **Date:** {the date of this run, YYYY-MM-DD}
569
386
  ```
570
- For any other checkpoint: `# {the checkpoint's title}`, the user's answer as given (the option chosen and every comment), and `**Date:** {today, YYYY-MM-DD}`.
387
+ For any other checkpoint: `# {the checkpoint's title}`, the user's answer as given (the option chosen and every comment), and `**Date:** {the date of this run, YYYY-MM-DD}`.
571
388
  This file is the `inputFile` of the step that follows.
572
389
 
573
390
  ### Post-Step Output Validation
@@ -599,39 +416,13 @@ After a step produces output (subagent or inline) and BEFORE Veto Condition Enfo
599
416
  - If the step does not declare an `outputFile` (e.g., steps that only produce inline console output) → skip output validation.
600
417
  - Checkpoint steps (`type: checkpoint`) are exempt — their output is the user's response, not a file.
601
418
 
602
- **IMPORTANT**: Do NOT rely on reading the file with the Read tool to "verify" output. The Read tool returns content that can be misinterpreted. Use ONLY the `conferir` command — its last line is binary and cannot be hallucinated.
419
+ **IMPORTANT**: Do NOT rely on reading the file yourself to "verify" output: what you read can be misinterpreted. Use ONLY the `conferir` command — its last line is binary and cannot be hallucinated.
603
420
 
604
421
  ### Output Contract Validation
605
422
 
606
- If the step's frontmatter declares an `output_contract:` field, apply structured validation
607
- in the same call as the basic file existence check (Post-Step Output Validation):
608
-
609
- 1. **Required sections check**: If `output_contract.required_sections` is defined, add
610
- `--secoes {min_sections}` to the same `conferir` command: the file needs at least that many
611
- lines starting with `## `.
612
-
613
- 2. **TL;DR check**: If the output contract requires a TL;DR section, add `--tldr` to the same
614
- `conferir` command.
615
-
616
- 3. **If a check fails** (the last line is `CAMINHO:REPROVADO {motivo}`, with a motivo other than
617
- `arquivo ausente ou vazio`; the script reports the first one):
618
- - Present to user: "⚠️ Output from {Agent Name} is incomplete: {motivo}"
619
- - Options as numbered list:
620
- 1. Accept anyway and continue
621
- 2. Retry step (re-execute the agent)
622
- 3. Abort pipeline
623
-
624
- 4. **If no `output_contract` is defined**, skip this validation entirely (backward compatible).
625
-
626
- Example `output_contract` in step frontmatter:
627
- ```yaml
628
- output_contract:
629
- required_sections:
630
- - "Fontes Pesquisadas"
631
- - "Principais Descobertas"
632
- - "TL;DR"
633
- min_sections: 3
634
- ```
423
+ Only when the step's frontmatter declares an `output_contract:` field: read
424
+ `_opencrew/core/runner/contrato-de-saida.md` completely and follow it — it adds `--secoes` and `--tldr`
425
+ to the same `conferir` call of the Post-Step Output Validation. Without the field, skip this validation.
635
426
 
636
427
  ### Veto Condition Enforcement
637
428
 
@@ -643,7 +434,7 @@ After an agent completes a step (before moving to the next step):
643
434
  - Check each condition (e.g., "slides exceed 30 words", "no CTA", "missing sources")
644
435
  3. If ANY veto condition is triggered:
645
436
  - Inform user: "⚠️ {Agent Name}'s output triggered a veto: {condition}"
646
- - Ask the agent to fix the specific issue (re-execute with targeted correction)
437
+ - Ask the agent to fix the specific issue (re-execute with targeted correction), then run the `conferir` command on the rewritten file again (Post-Step Output Validation) before judging the veto once more
647
438
  - Maximum 2 veto fix attempts per step
648
439
  - After 2 failed attempts, present to user for manual decision
649
440
  - **Never auto-fix an irreversible step** (`side_effects: irreversible`): re-executing it
@@ -706,23 +497,6 @@ When a step has `on_reject: {step-id}` (a review step):
706
497
  and write it into the text before approving. If the user does not have it, do not insist and
707
498
  never invent: keep the `[PREENCHER]`, say `Sem problema: deixo [PREENCHER: {o que falta}] no texto. Na entrega você escolhe entre preencher depois e entregar assim mesmo, com ressalva.` and go on.
708
499
 
709
- ### Step Execution Order (Summary)
710
-
711
- For reference, the complete execution order for each pipeline step is:
712
-
713
- ```
714
- 0. Agent deselection check (skip step if its agent was deselected)
715
- 0b. Escritório command (passo or checkpoint) — only if it is on
716
- 0c. Entrega (delivery script) — only before the first step that publishes or sends
717
- 1. Pre-Step Input Validation (script gate: `entrada`)
718
- 2. Read step file
719
- 3. Check execution mode and execute (subagent / inline / checkpoint)
720
- 4. Post-Step Output Validation (script gate: `conferir`)
721
- 5. Veto Condition Enforcement
722
- ```
723
-
724
- Steps 1 and 4 are binary script gates. If either fails, the pipeline does NOT advance — the user is consulted.
725
-
726
500
  ### Entrega
727
501
 
728
502
  One script turns the approved files into `crews/{name}/output/{run_id}/entrega/` (a folder per channel, text ready to paste, a `LEIA-ME.md`) and copies what is ready to the folder of the project the user chose. Read `_opencrew/core/prompts/entrega.prompt.md` and follow it: how to build `{lista}`, when to add `--vai-publicar`, what to do with `ENTREGA:OK`, `ENTREGA:COM_RESSALVA` and `ENTREGA:INCOMPLETA`, the question about the folder of the project that keeps a copy (asked once per crew) and what to do with a script that did not run.
@@ -737,112 +511,10 @@ One script turns the approved files into `crews/{name}/output/{run_id}/entrega/`
737
511
  1. **Entrega** — if the delivery has not run in this run, run it now (see "Entrega" above).
738
512
  1b. **Escritório** — if it is on, run `concluir` (see "Escritório" above).
739
513
 
740
- 2. **Update crew memory** — write to BOTH files:
741
-
742
- ### 2a. Update `memories.md` (living preferences)
743
-
744
- Read `crews/{name}/_memory/memories.md` in full. Then identify candidates from this run: **only explicit user feedback** — approvals with comments, rejections with reasons, direct requests ("prefiro X", "não quero Y"). Never infer preferences.
745
-
746
- For each candidate:
747
- - If an equivalent memory already exists and is compatible → skip (no duplicate)
748
- - If an equivalent memory exists but contradicts the new item → replace with the newer version
749
- - If no equivalent exists → add to the correct semantic section:
750
- - Writing style choices → `## Estilo de Escrita`
751
- - Visual/design preferences → `## Design Visual`
752
- - Content structure choices → `## Estrutura de Conteúdo`
753
- - Explicit rejections or prohibitions → `## Proibições Explícitas`, in the canonical form
754
- (`- Nunca usar "termo"` or `- Nunca usar "termo" → usar "outro"`)
755
- - Crew-specific technical patterns → `## Técnico (específico do crew)`
756
-
757
- **Never write to `memories.md`:**
758
- - Runner inferences ("usuário parece preferir X")
759
- - Run scores, review grades, output file paths, topics from past runs
760
-
761
- **Technical routing:** For any technical learning (bugs, workarounds, API behavior):
762
- - If it affects any crew (Playwright bugs, OS rendering quirks, API limits) → write to `_opencrew/best-practices.local/{format}.md` instead of `memories.md` (copy the core file there first if the local one does not exist yet — the core folder is replaced by every `update`; the local one is never touched)
763
- - If it is specific to this crew's output type or toolchain → add to `## Técnico (específico do crew)` following the dedup rules above
764
-
765
- After applying all candidates, write the updated `memories.md`.
766
-
767
- If no candidates are found (the run had no explicit user feedback), skip writing `memories.md` entirely — do not write an unmodified copy. Always proceed to step 2b regardless.
768
-
769
- ### 2b. Prepend to `runs.md` (reverse-chronological log — newest run first)
770
-
771
- If `crews/{name}/_memory/runs.md` does not exist, create it first with:
772
- ```markdown
773
- # Run History: {crew-name}
774
-
775
- | Data | Run ID | Tema | Output | Score | Resultado |
776
- |------|--------|------|--------|-------|-----------|
777
- ```
778
- Then proceed to prepend the new row.
779
-
780
- Read `crews/{name}/_memory/runs.md`. Prepend one new row to the table (immediately after the header row), with:
781
- - `Data`: today's date in YYYY-MM-DD format
782
- - `Run ID`: the `run_id` for this execution
783
- - `Tema`: the topic or user request from this run (1 sentence max)
784
- - `Output`: brief description of what was generated (e.g., "Carrossel 9 slides", "Thread 7 posts")
785
- - `Score`: `{approved}/{total}` agent outputs approved without corrections (e.g., `4/5`)
786
- - `Resultado`: one of — `Aprovado` / `Rejeitado` / `Publicado` / `Abortado`
787
-
788
- No other data.
789
-
790
- The `Score` column tracks how many agent outputs were approved by the user without corrections in this run. Count only explicit checkpoint approvals (not "skip" or "continue"). Format: `{approved}/{total checkpoints}` (e.g., `4/5` means 4 of 5 agent outputs were approved as-is).
791
-
792
- ### 2c. Post-Run Reflection (pattern detection)
793
-
794
- After updating `memories.md` and `runs.md`, run a reflection pass. This is a lightweight analysis — not a full agent execution, just pattern matching on the run's feedback and past memory.
795
-
796
- 1. **Collect this run's corrections**: From checkpoint responses, gather every user rejection or correction. A correction is:
797
- - A rejected output with a reason ("tom muito informal", "cor não combina", "fonte sem data")
798
- - A modification request during checkpoint ("muda o título para X", "usa azul em vez de verde")
799
-
800
- 2. **Look for recurrence**: Compare each correction against past runs recorded in `memories.md`:
801
- - Search `memories.md` for similar patterns (same category, same agent, same type of correction)
802
- - Count: how many past runs have a correction matching this pattern?
803
- - A "match" means the same agent + same type of error (e.g., "redator + tom informal", "designer + cores saturadas")
804
-
805
- 3. **Promote to Regra de Ouro**: If the SAME pattern appears in **3 or more runs** (including this one):
806
- a. Add a new entry under `## Regras de Ouro` in `memories.md`:
807
- ```markdown
808
- ## Regras de Ouro (promovidas após 3+ ocorrências)
809
-
810
- - **{Agent role}**: SEMPRE {correct behavior}. {Why — grounded in user feedback}.
811
- (Runs: #{run1}, #{run2}, #{run3})
812
- ```
813
- Example:
814
- ```markdown
815
- - **Redator**: SEMPRE verificar se o CTA contém link rastreável antes de finalizar.
816
- (Runs: #2026-08-01-143022, #2026-08-05-091530, #2026-08-10-160845)
817
- ```
818
- b. Remove the individual entries from their original sections (`## Estilo de Escrita`, `## Design Visual`, etc.) — the Regra de Ouro replaces them.
819
- c. Display to the user:
820
- ```
821
- 💡 Regra de Ouro detectada:
822
- "{correct behavior}" aconteceu 3 vezes.
823
- Vou aplicar automaticamente a partir de agora.
824
- ```
825
-
826
- 4. **Mark improvement**: If a previously recurring error did NOT happen this run:
827
- - Add a `✅` marker to the Regra de Ouro entry: `✅ **Redator**: SEMPRE ...`
828
- - This tracks that the crew is improving — the rule is working.
829
-
830
- 5. **Bail out early**: If this run had zero corrections (all checkpoints approved), skip the entire reflection — nothing to learn.
831
-
832
- 6. **Reflection budget**: Maximum 30 seconds of analysis. If the crew has a long history (>20 past runs), sample the most recent 10 runs for pattern matching. This is a quick scan, not an exhaustive audit.
833
-
834
- 3. Present completion summary:
835
- ```
836
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
837
- ✅ Pipeline complete!
838
- 📁 Delivery: crews/{name}/output/{run_id}/entrega/ — start with LEIA-ME.md
839
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
840
-
841
- What would you like to do?
842
- ● Run again (new topic)
843
- ○ Edit this content
844
- ○ Back to menu
845
- ```
514
+ 2. **Close the run** — read `_opencrew/core/runner/fim-da-execucao.md` completely and follow it, in its
515
+ order: update `memories.md`, add the line to `runs.md`, the post-run reflection and the completion
516
+ summary with the final menu. Never skip it, and never write the memory or the history from what you
517
+ remember of it.
846
518
 
847
519
  ## Error Handling
848
520
 
@@ -41,7 +41,9 @@ export function erroDeArgumentos({ crew, acao, run, arquivo, secoes }) {
41
41
  if (!crew) return 'Falta o nome da crew.';
42
42
  if (!acao) return `Falta a ação. Ações: ${LISTA}.`;
43
43
  if (!ACOES.includes(acao)) return `Ação desconhecida: ${limpar(acao)}. Ações: ${LISTA}.`;
44
- if (acao !== 'conferir' && !run) return MSG.faltaOpcao('--run');
44
+ // `pasta` sem --run: o script dá o nome à execução (data e hora do computador).
45
+ if (acao !== 'conferir' && acao !== 'pasta' && !run) return MSG.faltaOpcao('--run');
46
+ if (run === '') return MSG.faltaOpcao('--run'); // `--run` sem valor não vira "sem --run"
45
47
  if (run !== undefined && !RUN.test(run)) return 'O --run só aceita letras, dígitos, ponto, sublinhado e hífen.';
46
48
  if (acao !== 'pasta' && !arquivo) return MSG.faltaOpcao('--arquivo');
47
49
  if (secoes !== undefined && !INTEIRO.test(secoes)) return 'O --secoes é um número inteiro a partir de 1.';
@@ -29,6 +29,22 @@ export function naExecucao(declarado, crew, run) {
29
29
  return { grupo: [`${saida}${run}`, ...partes].join('/'), nome };
30
30
  }
31
31
 
32
+ const dois = (n) => String(n).padStart(2, '0');
33
+
34
+ /**
35
+ * O nome de uma execução nova: `AAAA-MM-DD-HHmmss` na hora local; se já existe pasta com esse
36
+ * nome, `-2`, `-3`… (spec fase-u5a-polimento-do-uso.md, decisão 2).
37
+ * @param {Date} agora · @param {string[]} existentes as pastas que já estão em `output/`
38
+ */
39
+ export function novoRun(agora, existentes) {
40
+ const base = `${agora.getFullYear()}-${dois(agora.getMonth() + 1)}-${dois(agora.getDate())}-${dois(agora.getHours())}${dois(agora.getMinutes())}${dois(agora.getSeconds())}`;
41
+ const usados = new Set(existentes);
42
+ for (let n = 1; ; n++) {
43
+ const nome = n === 1 ? base : `${base}-${n}`;
44
+ if (!usados.has(nome)) return nome;
45
+ }
46
+ }
47
+
32
48
  /** O número de uma pasta de versão (`v` + número), ou `null` para qualquer outro nome. */
33
49
  function numero(nome) {
34
50
  const [, digitos] = /^v(\d{1,9})$/.exec(nome) ?? [];