@aksp/opencrew 1.12.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,23 @@
3
3
  All notable changes to opencrew are documented here.
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/).
5
5
 
6
+ ## [1.13.0] — 2026-10-07
7
+
8
+ Fase U5, fatia 2: "Runner dividido" (`specs/fase-u5b-runner-dividido.md`). Chega a quem já usa
9
+ com um `npx @aksp/opencrew@latest update`. Nenhuma regra mudou de texto: mudou de lugar.
10
+
11
+ ### Changed
12
+ - **O executor de pipeline ficou menor.** O `runner.pipeline.md`, lido no começo de toda execução,
13
+ foi de 872 para 543 linhas. Sete blocos que só valem em alguma condição passaram para arquivos
14
+ próprios em `_opencrew/core/runner/`, lidos só quando é o caso: seleção de agentes, migração do
15
+ formato da memória, Escritório, tarefas do agente, contrato de saída, fontes pendentes e o fim
16
+ da execução (memória, histórico, reflexão e menu final). No lugar de cada um ficou um trecho
17
+ curto que diz quando ler o arquivo. Numa execução comum a IA lê 654 linhas em vez de 872, e as
18
+ regras do fim da execução são lidas no fim, quando valem.
19
+ - O painel (Escritório) só custa leitura para quem o ligou.
20
+
21
+ ### Removed
22
+ - O resumo "Step Execution Order", que repetia a ordem dos passos já descrita logo acima dele.
6
23
  ## [1.12.0] — 2026-10-07
7
24
 
8
25
  Fase U5, fatia 1: "Polimento do uso" (`specs/fase-u5a-polimento-do-uso.md`). A U5 é a fase de
package/README.md CHANGED
@@ -181,7 +181,8 @@ meu-projeto/
181
181
  ├── _opencrew/
182
182
  │ ├── core/
183
183
  │ │ ├── system.md ← 🧠 sistema completo do OpenCrew
184
- │ │ ├── runner.pipeline.md ← executor de pipeline
184
+ │ │ ├── runner.pipeline.md ← executor de pipeline (o que toda execução usa)
185
+ │ │ ├── runner/ ← 7 partes do executor, lidas só quando é o caso (painel, fim da execução…)
185
186
  │ │ ├── skills.engine.md ← gerenciador de skills
186
187
  │ │ ├── architect.agent.yaml ← definição do Arquiteto
187
188
  │ │ ├── formato-da-crew.md ← o formato dos arquivos de uma crew (crew.yaml, pipeline.yaml, passos)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aksp/opencrew",
3
- "version": "1.12.0",
3
+ "version": "1.13.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -97,11 +97,8 @@ When running a crew:
97
97
  from `_opencrew/_memory/preferences.md` (used to check the Dashboard toggle)
98
98
  5. Load crew memory from `crews/{name}/_memory/memories.md`
99
99
  6. Read the pipeline runner instructions from `_opencrew/core/runner.pipeline.md`
100
- 7. **Pre-Execution Agent Selection** — only when `crew.yaml` declares
101
- `agent_dependencies:`. Analyze the user's request against the decision matrix,
102
- present the agents as a numbered multi-select (IDE-neutral), let the user
103
- confirm/adjust, warn about broken dependencies, and build the filtered step
104
- list. Crews without the field skip this and run all agents.
100
+ 7. **Pre-Execution Agent Selection** — the runner says when it applies (only when `crew.yaml`
101
+ declares `agent_dependencies:`) and which of its parts to read
105
102
  8. Execute the pipeline step by step following the runner instructions
106
103
 
107
104
  ## Dashboard (Optional)
@@ -1 +1 @@
1
- 1.12.0
1
+ 1.13.0
@@ -9,6 +9,7 @@ crews/{code}/
9
9
  ├── crew.yaml the crew: identity, sources, limits
10
10
  ├── crew-party.csv one row per agent (the names shown to the user)
11
11
  ├── agents/{agent-id}.agent.md
12
+ ├── agents/{agent-id}/tasks/ the task files of an agent that declares `tasks:` (optional)
12
13
  ├── pipeline/
13
14
  │ ├── pipeline.yaml the order of the steps
14
15
  │ ├── steps/step-NN-{name}.md
@@ -0,0 +1,33 @@
1
+ # Output Contract Validation
2
+
3
+ > Part of the Pipeline Runner (`_opencrew/core/runner.pipeline.md`). Read it only when the step's frontmatter declares an `output_contract:` field.
4
+
5
+ If the step's frontmatter declares an `output_contract:` field, apply structured validation
6
+ in the same call as the basic file existence check (Post-Step Output Validation):
7
+
8
+ 1. **Required sections check**: If `output_contract.required_sections` is defined, add
9
+ `--secoes {min_sections}` to the same `conferir` command: the file needs at least that many
10
+ lines starting with `## `.
11
+
12
+ 2. **TL;DR check**: If the output contract requires a TL;DR section, add `--tldr` to the same
13
+ `conferir` command.
14
+
15
+ 3. **If a check fails** (the last line is `CAMINHO:REPROVADO {motivo}`, with a motivo other than
16
+ `arquivo ausente ou vazio`; the script reports the first one):
17
+ - Present to user: "⚠️ Output from {Agent Name} is incomplete: {motivo}"
18
+ - Options as numbered list:
19
+ 1. Accept anyway and continue
20
+ 2. Retry step (re-execute the agent)
21
+ 3. Abort pipeline
22
+
23
+ 4. **If no `output_contract` is defined**, skip this validation entirely (backward compatible).
24
+
25
+ Example `output_contract` in step frontmatter:
26
+ ```yaml
27
+ output_contract:
28
+ required_sections:
29
+ - "Fontes Pesquisadas"
30
+ - "Principais Descobertas"
31
+ - "TL;DR"
32
+ min_sections: 3
33
+ ```
@@ -0,0 +1,37 @@
1
+ # Escritório (optional live view)
2
+
3
+ > Part of the Pipeline Runner (`_opencrew/core/runner.pipeline.md`). Read it only when `preferences.md` has `Dashboard: enabled`.
4
+
5
+ A local page that shows the crew at work, off by default. Follow this part only when the
6
+ already-loaded `preferences.md` has `Dashboard: enabled` (written `- **Dashboard:** enabled` or
7
+ plain `Dashboard: enabled`, any letter case); otherwise run none of these commands. When it is on,
8
+ run, from the project root, the one-line command of each moment:
9
+
10
+ | Moment | Command |
11
+ |---|---|
12
+ | Start of the run (Initialization, step 6) | `node _opencrew/core/scripts/estado.mjs "{name}" iniciar --passos {N}` |
13
+ | Right after `iniciar`, once per deselected agent | `node _opencrew/core/scripts/estado.mjs "{name}" pular --agente {id}` |
14
+ | Before each step, each time it starts | `node _opencrew/core/scripts/estado.mjs "{name}" passo --n {K} --agente {id} --rotulo "{rótulo}" --mensagem "{frase}"` |
15
+ | 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}"` |
16
+ | End of the run (After Pipeline Completion) | `node _opencrew/core/scripts/estado.mjs "{name}" concluir` |
17
+ | Run aborted after `iniciar`, by the user or by an error | `node _opencrew/core/scripts/estado.mjs "{name}" falhar --motivo "{motivo}"` |
18
+
19
+ - **One at a time** — Run these commands one at a time, waiting for the `ESTADO:` line of each
20
+ before the next — never in parallel or in the background (each one reads and rewrites the same file).
21
+ - **Values** — `{name}`: the crew code. `{N}`: how many steps will run, checkpoints included (a
22
+ deselected agent's steps do not count). `{K}`: the step's position among them, from 1. `{id}`: the agent's `id` column in
23
+ `crew-party.csv`; a step or checkpoint with no `agent:` goes without `--agente`
24
+ (the table shows the full form). `{rótulo}`: the step's name, in
25
+ a few words. `--mensagem` goes only when the agent changed since the last `passo` (so never on the first
26
+ one): one sentence on what the previous agent delivered — never look at the next step. `{motivo}`: why the run stopped.
27
+ - **Text on the command line** — `--rotulo`, `--mensagem` and `--motivo` go between double quotes,
28
+ on one line, starting with a letter or a digit, with only letters (accents included), digits,
29
+ spaces and `. , : ; - ( ) / ?`. Drop every other sign (quotes of any kind, `$`, backtick, `\`,
30
+ `%`, `!`, emoji). If no text is left, omit the option. Write them in the user's language.
31
+ - **After `iniciar`**, when it answers `ESTADO:OK`, show the user once:
32
+ `Escritório ligado. Se a página não estiver aberta, rode em outro terminal: node _opencrew/core/scripts/escritorio.mjs`
33
+ - **The Escritório never stops the run.** A command that fails, does not run or answers
34
+ `ESTADO:IGNORADO`: go on, do not repeat that event, ask nothing, and tell the user once per run,
35
+ in one line: `O escritório não foi atualizado nesta execução; o trabalho segue normalmente.` With
36
+ the reason "escritório desligado", say nothing and stop calling the script for the rest of this run.
37
+ - The script is the only writer: never read, write or describe `crews/{name}/state.json` yourself.
@@ -0,0 +1,110 @@
1
+ # End of the run
2
+
3
+ > Part of the Pipeline Runner (`_opencrew/core/runner.pipeline.md`). Read it when the pipeline has completed. It continues the list of "After Pipeline Completion" in the runner: items 2 and 3 below are the items 2 and 3 of that list; follow them in order.
4
+
5
+ 2. **Update crew memory** — write to BOTH files:
6
+
7
+ ### 2a. Update `memories.md` (living preferences)
8
+
9
+ 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.
10
+
11
+ For each candidate:
12
+ - If an equivalent memory already exists and is compatible → skip (no duplicate)
13
+ - If an equivalent memory exists but contradicts the new item → replace with the newer version
14
+ - If no equivalent exists → add to the correct semantic section:
15
+ - Writing style choices → `## Estilo de Escrita`
16
+ - Visual/design preferences → `## Design Visual`
17
+ - Content structure choices → `## Estrutura de Conteúdo`
18
+ - Explicit rejections or prohibitions → `## Proibições Explícitas`, in the canonical form
19
+ (`- Nunca usar "termo"` or `- Nunca usar "termo" → usar "outro"`)
20
+ - Crew-specific technical patterns → `## Técnico (específico do crew)`
21
+
22
+ **Never write to `memories.md`:**
23
+ - Runner inferences ("usuário parece preferir X")
24
+ - Run scores, review grades, output file paths, topics from past runs
25
+
26
+ **Technical routing:** For any technical learning (bugs, workarounds, API behavior):
27
+ - 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)
28
+ - 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
29
+
30
+ After applying all candidates, write the updated `memories.md`.
31
+
32
+ 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.
33
+
34
+ ### 2b. Prepend to `runs.md` (reverse-chronological log — newest run first)
35
+
36
+ If `crews/{name}/_memory/runs.md` does not exist, create it first with:
37
+ ```markdown
38
+ # Run History: {crew-name}
39
+
40
+ | Data | Run ID | Tema | Output | Score | Resultado |
41
+ |------|--------|------|--------|-------|-----------|
42
+ ```
43
+ Then proceed to prepend the new row.
44
+
45
+ Read `crews/{name}/_memory/runs.md`. Prepend one new row to the table (immediately after the header row), with:
46
+ - `Data`: the date of this run (the first 10 characters of the `run_id`)
47
+ - `Run ID`: the `run_id` for this execution
48
+ - `Tema`: the topic or user request from this run (1 sentence max)
49
+ - `Output`: brief description of what was generated (e.g., "Carrossel 9 slides", "Thread 7 posts")
50
+ - `Score`: `{approved}/{total}` agent outputs approved without corrections (e.g., `4/5`)
51
+ - `Resultado`: one of — `Aprovado` / `Rejeitado` / `Publicado` / `Abortado`
52
+
53
+ No other data.
54
+
55
+ 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).
56
+
57
+ ### 2c. Post-Run Reflection (pattern detection)
58
+
59
+ 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.
60
+
61
+ 1. **Collect this run's corrections**: From checkpoint responses, gather every user rejection or correction. A correction is:
62
+ - A rejected output with a reason ("tom muito informal", "cor não combina", "fonte sem data")
63
+ - A modification request during checkpoint ("muda o título para X", "usa azul em vez de verde")
64
+
65
+ 2. **Look for recurrence**: Compare each correction against past runs recorded in `memories.md`:
66
+ - Search `memories.md` for similar patterns (same category, same agent, same type of correction)
67
+ - Count: how many past runs have a correction matching this pattern?
68
+ - A "match" means the same agent + same type of error (e.g., "redator + tom informal", "designer + cores saturadas")
69
+
70
+ 3. **Promote to Regra de Ouro**: If the SAME pattern appears in **3 or more runs** (including this one):
71
+ a. Add a new entry under `## Regras de Ouro` in `memories.md`:
72
+ ```markdown
73
+ ## Regras de Ouro (promovidas após 3+ ocorrências)
74
+
75
+ - **{Agent role}**: SEMPRE {correct behavior}. {Why — grounded in user feedback}.
76
+ (Runs: #{run1}, #{run2}, #{run3})
77
+ ```
78
+ Example:
79
+ ```markdown
80
+ - **Redator**: SEMPRE verificar se o CTA contém link rastreável antes de finalizar.
81
+ (Runs: #2026-08-01-143022, #2026-08-05-091530, #2026-08-10-160845)
82
+ ```
83
+ b. Remove the individual entries from their original sections (`## Estilo de Escrita`, `## Design Visual`, etc.) — the Regra de Ouro replaces them.
84
+ c. Display to the user:
85
+ ```
86
+ 💡 Regra de Ouro detectada:
87
+ "{correct behavior}" aconteceu 3 vezes.
88
+ Vou aplicar automaticamente a partir de agora.
89
+ ```
90
+
91
+ 4. **Mark improvement**: If a previously recurring error did NOT happen this run:
92
+ - Add a `✅` marker to the Regra de Ouro entry: `✅ **Redator**: SEMPRE ...`
93
+ - This tracks that the crew is improving — the rule is working.
94
+
95
+ 5. **Bail out early**: If this run had zero corrections (all checkpoints approved), skip the entire reflection — nothing to learn.
96
+
97
+ 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.
98
+
99
+ 3. Present completion summary:
100
+ ```
101
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
102
+ ✅ Pipeline complete!
103
+ 📁 Delivery: crews/{name}/output/{run_id}/entrega/ — start with LEIA-ME.md
104
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
105
+
106
+ What would you like to do?
107
+ ● Run again (new topic)
108
+ ○ Edit this content
109
+ ○ Back to menu
110
+ ```
@@ -0,0 +1,21 @@
1
+ # Source check that did not end in FONTES:OK
2
+
3
+ > Part of the Pipeline Runner (`_opencrew/core/runner.pipeline.md`). Read it only when the source check of the Initialization (1c) ended in `FONTES:PENDENTE` or did not run.
4
+
5
+ If the last line is `FONTES:PENDENTE` (a cited file was moved, renamed or deleted), show the
6
+ report and ask — never continue silently with a missing source:
7
+ ```
8
+ Alguns arquivos que a crew usa não estão mais onde ela espera:
9
+ {resumo do relatório}
10
+
11
+ 1. Corrigir os caminhos sugeridos (troco nos arquivos da crew e guardo .bak)
12
+ 2. Seguir assim mesmo
13
+ 3. Parar
14
+ ```
15
+ On 1, run the same command with `--corrigir`, show the new result and re-read `crew.yaml` and
16
+ any agent file already loaded (it may have changed them); 1d then loads the sources from the
17
+ corrected paths. If the new result still ends in `FONTES:PENDENTE`, ask again with options 2 and
18
+ 3 only. Alerts — not portable (absolute paths) or "não conferido" (a network path or a site
19
+ address: the script never accesses the network) — are mentioned once, without stopping. If the
20
+ script did not run (no Node, an error, or no `FONTES:` status line), tell the user "⚠️ A
21
+ conferência de fontes não rodou: {motivo}" and continue; the final approval repeats the warning.
@@ -0,0 +1,55 @@
1
+ # Memory format
2
+
3
+ > Part of the Pipeline Runner (`_opencrew/core/runner.pipeline.md`). Read it only when `memories.md` has no `## Estilo de Escrita` section header, is empty or does not exist.
4
+
5
+ **Note on language**: The structural labels listed below are **fixed PT-BR** and must
6
+ never be translated — opencrew's primary supported audience is PT-BR (see AGENTS.md →
7
+ Language Handling). Only the *content* written under these headers follows the user's
8
+ preferred language.
9
+
10
+ | Fixed PT-BR header | Location | Purpose |
11
+ |---|---|---|
12
+ | `## Estilo de Escrita` | `memories.md` | Writing style rules accumulated per crew |
13
+ | `## Design Visual` | `memories.md` | Visual design preferences per crew |
14
+ | `## Estrutura de Conteúdo` | `memories.md` | Content structure rules per crew |
15
+ | `## Proibições Explícitas` | `memories.md` | User bans and hard blocks per crew |
16
+ | `## Técnico (específico do crew)` | `memories.md` | Technical crew-specific settings |
17
+ | `Data \| Run ID \| Tema \| Output \| Score \| Resultado` | `runs.md` | Run history table columns |
18
+
19
+ When adding new structural sections to `memories.md` or `runs.md`, keep headers in PT-BR
20
+ unless the user base expands beyond PT-BR — at that point, discuss a migration strategy
21
+ (e.g. i18n key mapping) rather than mixing languages in a single file.
22
+
23
+ ## Migration
24
+
25
+ **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).
26
+ - If it has the header → proceed normally.
27
+ - If it does not (or the file is empty / does not exist) → migrate before proceeding:
28
+ a0. If the file exists and is not empty, FIRST copy it to `crews/{name}/_memory/memories.md.bak`
29
+ (never lose what the crew learned), then tell the user in one line:
30
+ "Atualizei o formato da memória da crew; a versão anterior está em `memories.md.bak`."
31
+ Move every rule you can recognize from the old file into the matching new section.
32
+ a. Write `crews/{name}/_memory/memories.md` with the new sections format:
33
+ ```markdown
34
+ # Crew Memory: {crew-name}
35
+
36
+ ## Estilo de Escrita
37
+
38
+ ## Design Visual
39
+
40
+ ## Estrutura de Conteúdo
41
+
42
+ ## Proibições Explícitas
43
+
44
+ ## Técnico (específico do crew)
45
+ ```
46
+ (Use the crew's display name for `{crew-name}`, and the crew code for `{name}` in file paths — they refer to the same crew.)
47
+ b. Check if `crews/{name}/_memory/runs.md` exists (read tool — no command).
48
+ If it does not exist, create it with:
49
+ ```markdown
50
+ # Run History: {crew-name}
51
+
52
+ | Data | Run ID | Tema | Output | Score | Resultado |
53
+ |------|--------|------|--------|-------|-----------|
54
+ ```
55
+ - Do not pause execution for this migration (the one-line notice above is enough).
@@ -0,0 +1,79 @@
1
+ # Pre-Execution Agent Selection
2
+
3
+ > Part of the Pipeline Runner (`_opencrew/core/runner.pipeline.md`). Read it only when `crew.yaml` declares an `agent_dependencies:` field. It decides which agents actually run for this task.
4
+
5
+ Run this step ONLY if `crew.yaml` declares an `agent_dependencies:` field (even an
6
+ empty map `{}`). If the field is absent → skip this entire step and run ALL agents
7
+ exactly as before (legacy behavior).
8
+
9
+ When active, in this order:
10
+
11
+ a. **Capture the task** — Determine the user's request for this run:
12
+ - If the run was invoked with a description (e.g. `/opencrew run {name} {description}`),
13
+ use that text as the task.
14
+ - Otherwise ask: `📝 What is the task for this run? Reply in one line.`
15
+ Wait for the user's reply before continuing.
16
+
17
+ b. **Analyze against the decision matrix** — Scan the task text (case-insensitive,
18
+ PT-BR and EN keywords) for the signals below. Start with ALL agents suggested as
19
+ SELECTED (`required`). For each matching signal, find the affected agent(s) in
20
+ `crew-party.csv` by matching the role terms against the agent's `id` and `title`
21
+ (and `displayName` if ambiguous), then apply the suggested status:
22
+
23
+ | Signal in the task | Role terms to match (id / title) | Suggested status |
24
+ |--------------------|----------------------------------|------------------|
25
+ | "já pesquisei", "com base em", "fontes que tenho", "material pronto", "baseado nas fontes", "research already done" | researcher, pesquisad, research | optional |
26
+ | "revise", "melhore", "corrija", "refine", "edite" (sem criar do zero), "improve this draft" | copywriter, redator, writer, criador | optional |
27
+ | "só texto", "sem imagem", "sem visual", "sem arte", "no image" | designer, design, visual | skip |
28
+ | "já revisei", "já foi aprovado", "aprovado por terceiros", "revisão feita", "already reviewed" | reviewer, revisor | optional |
29
+ | "quero só revisar este texto", "apenas revisar", "review only" | researcher AND copywriter | skip |
30
+ | "tenho o conteúdo pronto", "forneço o documento", "docs em anexo", "segue o material", "here is the content" | copywriter, writer, creator | optional |
31
+
32
+ Resolution rules:
33
+ - `optional` = agent stays selected but may be unchecked.
34
+ - `skip` = agent is suggested deselected.
35
+ - Conflicting signals on the same agent → the more restrictive wins (`skip` > `optional`).
36
+ - Never suggest skipping an agent whose output is the run's final deliverable unless the
37
+ signal is explicit.
38
+ - No signal matches → suggest keeping all agents (no change).
39
+
40
+ c. **Present the selection** — IDE-neutral numbered multi-select. List every agent from
41
+ `crew-party.csv` in party order:
42
+ ```
43
+ 🧑‍🤝‍🧑 Which agents should work on this task?
44
+
45
+ Suggested selection:
46
+ 1. [x] {icon} {displayName} ({id}) — {title}
47
+ 2. [x] {icon} {displayName} ({id}) — {title}
48
+ 3. [ ] {icon} {displayName} ({id}) — {title}
49
+ ...
50
+ [x] = suggested selected · [ ] = suggested deselected
51
+
52
+ Reply with the numbers of the agents you want to INCLUDE, separated by commas.
53
+ Example: "1, 2" · Reply "all" to run everyone.
54
+ ```
55
+ Wait for the user's reply. Parse it into `selected_agents`. At least one agent must
56
+ be selected — if the user replies with none, repeat the prompt once.
57
+
58
+ d. **Dependency warnings** — Using `crew.yaml → agent_dependencies`
59
+ (e.g. `copywriter: [researcher]` = copywriter consumes researcher's output):
60
+ for every dependency `dependent → required_agent`, if `dependent` is selected but
61
+ `required_agent` is NOT, warn:
62
+ ```
63
+ ⚠️ {dependent} normally depends on {required_agent}'s output, which you deselected.
64
+
65
+ 1. Re-select {required_agent} (recommended)
66
+ 2. Keep going without it — I will supply the input myself
67
+ 3. Deselect {dependent} too
68
+ ```
69
+ Wait for the user's choice and apply it. If they pick option 2, set
70
+ `missing_dependency = true` in working memory (the existing Pre-Step Input
71
+ Validation recovery — "Skip step and continue / Abort" — then handles any
72
+ downstream gap).
73
+
74
+ e. **Build the filtered step list** — Set `skipped_agents = all party agents − selected_agents`.
75
+ Build `filtered_steps` by walking `pipeline.yaml` in order, keeping a step when:
76
+ - its frontmatter has NO `agent:` field (checkpoints / generic steps), OR
77
+ - its `agent:` value is in `selected_agents`.
78
+ Store `selected_agents`, `skipped_agents`, and `filtered_steps` in working memory for
79
+ the per-step loop (steps 5 and 6 of the Initialization reflect them).
@@ -0,0 +1,34 @@
1
+ # Task-Based Agent Execution
2
+
3
+ > Part of the Pipeline Runner (`_opencrew/core/runner.pipeline.md`). Read it only when the agent of the step has a `tasks:` field in its frontmatter.
4
+
5
+ When an agent's `.agent.md` frontmatter contains a `tasks:` field:
6
+
7
+ 1. **Load task list**: Read the `tasks:` array from the agent's frontmatter
8
+ - Each entry is a relative path to a task file (e.g., `tasks/analyze-source.md`)
9
+ - Tasks execute in the order listed
10
+
11
+ 2. **For each task in sequence**:
12
+ a. Read the task file from the agent's directory (`crews/{crew-name}/agents/{agent-id}/tasks/{task}.md`: a folder with the agent id, next to the agent file)
13
+ b. Construct the execution prompt:
14
+ - Agent persona + principles (from agent.md — fixed across all tasks)
15
+ - Task description and process (from task file)
16
+ - Task output format (from task file)
17
+ - Task quality criteria and veto conditions (from task file)
18
+ - Input: For the first task, use the step's input. For subsequent tasks, use the previous task's output.
19
+ c. Execute the task (inline or subagent, matching the step's execution mode)
20
+ d. Collect the task output
21
+ e. Check task veto conditions (same enforcement as the step veto conditions: "Veto Condition Enforcement", in the runner)
22
+
23
+ 3. **Final output**: The output of the LAST task in the chain becomes the step's output
24
+ - 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`
25
+ - Save to the **transformed** outputFile path
26
+ - This is what the next step (or checkpoint) receives
27
+
28
+ 4. **Progress reporting**: For inline execution, announce each task:
29
+ ```
30
+ {icon} {Agent Name} — Task {N}/{total}: {task name}...
31
+ ```
32
+
33
+ 5. **Backward compatibility**: If the agent's frontmatter does NOT contain a `tasks:` field,
34
+ execute the agent monolithically as before (current behavior unchanged).
@@ -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
@@ -128,82 +72,10 @@ Before starting execution:
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
  ```
@@ -227,39 +99,11 @@ Before starting execution:
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, 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
 
@@ -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
@@ -603,35 +420,9 @@ After a step produces output (subagent or inline) and BEFORE Veto Condition Enfo
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
 
@@ -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`: the date of this run (the first 10 characters of the `run_id`)
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