wendkeep 0.58.1 → 0.59.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 (78) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/README.en.md +70 -40
  3. package/README.md +70 -40
  4. package/bin/wendkeep.mjs +54 -6
  5. package/docs/en/commands/changes-and-verification.md +85 -0
  6. package/docs/en/commands/costs-and-observability.md +65 -0
  7. package/docs/en/commands/getting-started.md +86 -0
  8. package/docs/en/commands/maintenance-and-diagnostics.md +77 -0
  9. package/docs/en/commands/memory-migration.md +73 -0
  10. package/docs/en/commands/memory.md +102 -0
  11. package/docs/en/commands/notes-and-knowledge.md +70 -0
  12. package/docs/en/commands/operating-profiles.md +173 -0
  13. package/docs/en/commands/retroactive-import.md +67 -0
  14. package/docs/en/commands/sessions-and-import.md +89 -0
  15. package/docs/en/commands/verify.md +92 -0
  16. package/docs/pt-BR/commands/changes-and-verification.md +85 -0
  17. package/docs/pt-BR/commands/costs-and-observability.md +65 -0
  18. package/docs/pt-BR/commands/getting-started.md +87 -0
  19. package/docs/pt-BR/commands/maintenance-and-diagnostics.md +77 -0
  20. package/docs/pt-BR/commands/memory-migration.md +73 -0
  21. package/docs/pt-BR/commands/memory.md +99 -0
  22. package/docs/pt-BR/commands/notes-and-knowledge.md +69 -0
  23. package/docs/pt-BR/commands/operating-profiles.md +171 -0
  24. package/docs/pt-BR/commands/retroactive-import.md +67 -0
  25. package/docs/pt-BR/commands/sessions-and-import.md +89 -0
  26. package/docs/pt-BR/commands/verify.md +93 -0
  27. package/hooks/brain-core.mjs +159 -159
  28. package/hooks/brain-inject.mjs +83 -26
  29. package/hooks/brain-recall.mjs +32 -32
  30. package/hooks/brain-reindex.mjs +13 -13
  31. package/hooks/change-context.mjs +24 -10
  32. package/hooks/change-core.mjs +174 -37
  33. package/hooks/change-guard.mjs +115 -16
  34. package/hooks/change-nag.mjs +20 -5
  35. package/hooks/change-warn.mjs +27 -9
  36. package/hooks/decision-capture.mjs +1 -1
  37. package/hooks/derived-sections.mjs +1 -1
  38. package/hooks/flow-core.mjs +891 -0
  39. package/hooks/flow-protected-policy.mjs +218 -0
  40. package/hooks/frontmatter-repair.mjs +3 -1
  41. package/hooks/git-snapshot.mjs +722 -0
  42. package/hooks/import-sessions.mjs +10 -5
  43. package/hooks/memory-mode.mjs +63 -13
  44. package/hooks/memory-store.mjs +309 -69
  45. package/hooks/obsidian-common.mjs +119 -84
  46. package/hooks/operating-profile-runtime.mjs +157 -0
  47. package/hooks/plan-capture.mjs +14 -3
  48. package/hooks/sensors-core.mjs +15 -3
  49. package/hooks/session-backfill.mjs +7 -2
  50. package/hooks/session-ensure.mjs +21 -12
  51. package/hooks/session-iteration.mjs +65 -0
  52. package/hooks/session-memory-lifecycle.mjs +335 -0
  53. package/hooks/session-note-io.mjs +130 -15
  54. package/hooks/session-observability.mjs +4 -2
  55. package/hooks/session-stop.mjs +181 -59
  56. package/hooks/spec-core.mjs +91 -12
  57. package/hooks/subagent-stop.mjs +4 -1
  58. package/hooks/subagent-usage.mjs +2 -2
  59. package/hooks/task-log.mjs +3 -1
  60. package/hooks/token-usage.mjs +1 -1
  61. package/hooks/vault-health.mjs +268 -25
  62. package/hooks/vault-path-safety.mjs +558 -0
  63. package/hooks/vault-runtime-store.mjs +558 -0
  64. package/package.json +5 -3
  65. package/src/change.mjs +2 -1
  66. package/src/flow.mjs +232 -0
  67. package/src/init.mjs +26 -3
  68. package/src/memory.mjs +785 -35
  69. package/src/operating-profile.mjs +133 -0
  70. package/src/profile.mjs +224 -0
  71. package/src/project-vault.mjs +110 -5
  72. package/src/rebuild-costs.mjs +11 -4
  73. package/src/skills-seed.mjs +38 -16
  74. package/src/sync-defs.mjs +16 -7
  75. package/src/sync.mjs +9 -1
  76. package/src/taxonomy.mjs +9 -0
  77. package/src/validate-memory.mjs +21 -8
  78. package/src/verify.mjs +12 -2
package/CHANGELOG.md CHANGED
@@ -4,6 +4,126 @@ All notable changes to **wendkeep** are documented here. Format based on
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this project follows
5
5
  [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.59.0] — 2026-07-27
8
+
9
+ ### Added
10
+
11
+ - **Perfis de Operação separam memória persistente de governança:** `OFF`, `FLOW`, `GUIDE`,
12
+ `GOVERN` e `ASSURE`, com resolução explícita por sessão ou projeto e fallback conservador para
13
+ `GOVERN`. O novo `wendkeep profile status|use` torna a escolha e sua origem auditáveis.
14
+ - **FLOW executa ajustes pequenos por um microcontrato E → V:** `flow start/status/show/finish`
15
+ exige allowlist e sensores, registra baseline Git e tentativas no Vault e produz um recibo
16
+ terminal imutável sem criar change, ADR ou veredicto independente. `flow promote` preserva a
17
+ evidência ao converter o trabalho em uma change normal, sem `--force`.
18
+
19
+ ### Changed
20
+
21
+ - **Keep Core agora é explicitamente inegociável e sempre ativo.** Vault, identidade, sessões,
22
+ CORE, SHARED_MEMORY, lessons e persistência continuam funcionando em todos os perfis; apenas o
23
+ Wend Runtime de governança é desligado em `OFF`. Hooks, skills, `init` e `sync` respeitam a mesma
24
+ fronteira, e instalações novas começam em `GOVERN`.
25
+ - **Artefatos de runtime FLOW vivem em `.brain/runtime/flows/`.** A fronteira arquitetural impede
26
+ dependências do Vault para o harness/perfil e mantém aberta uma modularização física posterior
27
+ em `cli`, `harness`, `vault`, `mcp`, `integration` e `pi`.
28
+
29
+ ### Fixed
30
+
31
+ - **Retries concorrentes do mesmo evento de memória convergem durante a publicação.** O perdedor
32
+ do `open(..., 'wx')` tolera por uma janela limitada apenas o JSON ainda parcial do produtor
33
+ vencedor, revalidando a fronteira física do Vault a cada leitura; payload diferente, arquivo
34
+ permanentemente ilegível e aliases inseguros continuam falhando fechado. Fixtures de CLI também
35
+ isolam `WENDKEEP_SENSOR_VAULT`, permitindo que a suíte rode dentro do próprio `verify --vault`.
36
+ - **Handoffs sequenciais da mesma ativação respeitam causalidade.** Um turno mais novo da mesma
37
+ sessão/ativação substitui o anterior em vez de abrir conflito; ativações realmente distintas
38
+ continuam exigindo resolução humana.
39
+ - **Todas as tags de sensor de uma tarefa entram no gate.** `verify` não descarta mais tags
40
+ `[sensor:]` adicionais na mesma linha: IDs distintos executam uma vez, na ordem declarada, e o
41
+ primeiro continua disponível como alias legado para consumidores antigos.
42
+ - **Reconciliação de memória separa reparo estrutural de decisão semântica.** O novo `memory
43
+ reconcile` é dry-run por padrão, reprojeta o ledger sem consumir outbox, distingue cursor físico
44
+ de ordem causal e usa os mesmos invariantes do CORE no projector e no health check. `verify` e
45
+ `flow finish` agora executam sensores contra o Vault efetivamente selecionado. `memory repair`
46
+ reconhece e migra por CAS checkpoints causais válidos pré-0.59, com backup/auditoria, enquanto
47
+ locks owner-aware por PID/token impedem reap de processos vivos e remoção ABA.
48
+ - **Iterações truncadas preservam Markdown válido.** Backticks inline ou fences cortados pelo
49
+ limite de tamanho são escapados antes da escrita e não engolem mais a linha seguinte.
50
+ - **`sync` preserva seu estágio de reparo sem reabrir fallback global.** A CLI não tenta resolver
51
+ o Vault antes do `init`; binding inválido falha fechado nessa primeira etapa, e apenas o vínculo
52
+ validado é repassado a `sync-defs` e `doctor`.
53
+
54
+ ### Security
55
+
56
+ - **FLOW falha fechado fora do contrato.** Escapes da allowlist, superfícies protegidas, mudança
57
+ de configuração de sensores, metadata/flags ocultas do Git, sensores críticos vermelhos ou
58
+ mutantes, symlink/junction/reparse/hardlink, submodules e superfícies ignoradas bloqueiam o
59
+ recibo. ProjectRoot/sensor cwd ficam congelados e um snapshot terminal fecha a janela após os
60
+ sensores. Raízes adicionais podem ser declaradas por `harness.flow.protectedRoots`; uma política
61
+ canônica gera classifier, discovery e topologia. Escritas/locks do Vault falham antes de escapar,
62
+ usando owner+lease sem reap de processo vivo ou liberação ABA. Uma descoberta no-follow limitada
63
+ inclui aliases protegidos vazios/ignorados sem entrar no Vault, `.git` ou caches. Promoção
64
+ cross-process elege um dono, vincula semanticamente contrato/reserva/recibo/origem, preflighta
65
+ destinos multi-spec e permite ao perdedor repetir com `--change-slug`. IDs não atravessam o
66
+ runtime root, artefatos corrompidos nunca reabrem o FLOW, não existe `--force`, e promoção nunca
67
+ toma outra change ou repositório. Ledger, outbox, CORE/SHARED, registry, notas, sidecars,
68
+ temporários e backups também falham fechados em aliases físicos ou hardlinks externos.
69
+ - **Supersession ambígua exige autorização auditável e CAS exato.** A aplicação nomeia a sessão
70
+ sucessora e o motivo, prova que cada evento pertence à identidade causal nomeada, rejeita flags
71
+ ambíguas antes de I/O, limita a mutação às duas sessões, preserva o attempt original e cria backup
72
+ exato do registry antes da troca.
73
+ - **Binding ilegível não desliga governança silenciosamente.** Hooks mutantes falham fechados;
74
+ quando um Vault explícito ou legado é inequívoco, Keep Core continua injetado sob fallback
75
+ `GOVERN` junto do diagnóstico de corrupção. Config legada mais próxima inválida, shape tipado
76
+ incorreto, marcador ausente ou identidade divergente não herdam Vault pai/global; `profile`
77
+ expõe `binding_error` e rejeita flags duplicadas/ambíguas antes de I/O. O guard cobre caixa,
78
+ shims locais, entrypoint Node e paths/call operator de Git nos gates force/no-verify.
79
+
80
+ ## [0.58.3] — 2026-07-26
81
+
82
+ ### Fixed
83
+
84
+ - **O primeiro `SessionStop` elegível após a migração legacy → v2 volta a publicar o handoff.**
85
+ A activation passa a representar um epoch com múltiplos Stops, e `UserPromptSubmit` recupera
86
+ uma única activation ausente sob lock. Identidade nativa de sessão/turno e a ordem física do
87
+ transcript impedem que Stops duplicados, atrasados ou de uma activation anterior publiquem de
88
+ novo ou sobrescrevam checkpoints mais recentes.
89
+ - **A publicação de memória ficou durável e observável de ponta a ponta.** O evento é enfileirado
90
+ antes de registrar `enqueued`, a projeção ocorre fora do lock e retries reutilizam a tentativa
91
+ congelada. Falhas preservam a outbox como `degraded`, enquanto retornos ambíguos deixam evidência
92
+ diagnóstica em vez de encerrar silenciosamente.
93
+ - **`wendkeep doctor` agora detecta memória v2 realmente estagnada sem acusar uma migração nova.**
94
+ O diagnóstico correlaciona tentativa, ledger, outbox, revisão e checkpoint; revision 0 logo após
95
+ uma migração válida continua saudável, mas perda causal, ambiguidade e divergência bloqueiam.
96
+
97
+ ### Changed
98
+
99
+ - **Os guias bilíngues de memória, sessões, migração e diagnóstico descrevem o lifecycle real.**
100
+ A documentação cobre epochs multi-Stop, recuperação única, retries idempotentes, estados
101
+ `enqueued|projected|degraded|ambiguous` e como interpretar revision 0.
102
+
103
+ ### Security
104
+
105
+ - **Fixtures persistíveis de lifecycle são integralmente sintéticas.** Um gate de privacidade
106
+ verifica arquivos rastreados e novos e reporta somente arquivo, linha e categoria, evitando que
107
+ caminhos ou identificadores locais entrem em testes, commits e artefatos.
108
+
109
+ ## [0.58.2] — 2026-07-26
110
+
111
+ ### Added
112
+
113
+ - **Referência completa dos comandos agora é bilíngue e orientada por tarefa.** Sete guias por
114
+ domínio e três guias profundos cobrem instalação, changes, verificação, memória, sessões,
115
+ importação, notas, custos e manutenção em PT-BR e inglês, com sintaxe, exits, exemplos,
116
+ resultados esperados e diagnóstico.
117
+ - **Paridade documental virou gate automatizado.** O novo sensor `docs-bilingual` bloqueia pares
118
+ ausentes, comandos públicos sem cobertura, links quebrados, estrutura divergente, drift da regra
119
+ local e guias ausentes no tarball.
120
+
121
+ ### Changed
122
+
123
+ - **Os READMEs agora apresentam as funcionalidades por grupos.** A referência extensa deu lugar a
124
+ um mapa navegável que leva ao guia correto no GitHub e no npm. O fluxo de `verify` deixa explícito
125
+ que exit 2 por ausência de change é contexto ocioso, não falha de saúde do projeto.
126
+
7
127
  ## [0.58.1] — 2026-07-26
8
128
 
9
129
  ### Fixed
package/README.en.md CHANGED
@@ -13,7 +13,7 @@
13
13
 
14
14
  **In the graph:** 🔵 session · 🟣 decision · 🔴 bug · 🟢 learning · 🟡 change — every note, backlinked.
15
15
 
16
- **A persistent‑memory harness for AI coding agents, built on your Obsidian vault.** Every Claude Code **and Codex** session is captured turnbyturn into local Markdown — `init` wires both (Codex asks you to approve its hooks once; `import` backfills past sessions either way) — with token/cost tracking, auto‑extracted decisions, bugs and learnings, and a curated memory layer injected back at the start of the next session. On top of that memory core sits a native, zerodependency **change lifecycle** (spec → change → TDD → sensorgated archive) that keeps intent, work and proof wikilinked in one graph. 100% local, opencore.
16
+ **Persistent memory for AI coding agents, built on your Obsidian vault.** Every Claude Code **and Codex** session is captured turn by turn into local Markdown — `init` wires both (Codex asks you to approve its hooks once; `import` backfills past sessions either way) — with token/cost tracking and automatically extracted decisions, bugs, and learnings. That always-on plane is **Keep Core**. On top of it, **Wend Runtime** provides a native, zero-dependency lifecycle (spec → change → TDD → sensor-gated archive), selected through the `OFF`, `FLOW`, `GUIDE`, `GOVERN`, and `ASSURE` Operating Profiles. 100% local, open-core.
17
17
 
18
18
  ```bash
19
19
  npm i -D wendkeep && npx wendkeep init # captures from the next session on
@@ -120,6 +120,9 @@ one command:
120
120
  npm install --save-dev wendkeep@latest && npx --no-install wendkeep sync --project . --yes
121
121
  ```
122
122
 
123
+ `sync` lets its own `init` stage validate or rebuild the binding before resolving the Vault for
124
+ later stages. An invalid `.wendkeep.json` stops at `init` without falling back to an inherited global Vault.
125
+
123
126
  The install stays outside `sync` on purpose: a running process cannot replace itself and
124
127
  keep going — the code in memory would still be the old one.
125
128
 
@@ -156,41 +159,52 @@ stop reporting `defs stale` without a single skill having been updated. If you h
156
159
  `wk-*`, that edit is overwritten; your own customisation belongs in a skill of your own,
157
160
  which the reseed never touches.
158
161
 
159
- ## Commands
160
-
161
- | Command | What it does |
162
- |---|---|
163
- | `wendkeep init` | Set up wendkeep in a project (vault taxonomy + settings + MCP + skills). |
164
- | `wendkeep sync [--project P]` | **One-command update**: runs `init` → `sync-defs` → `doctor` on the current project, stopping at the first failing step. Install the package first (a running process cannot replace itself). `--vault P` · `--yes` to skip the companions picker. |
165
- | `wendkeep hook <name>` | Run a session hook; invoked by `settings.json` (reads agent JSON on stdin). |
166
- | `wendkeep change <sub>` | Change lifecycle: `new <slug> [--simple]` / `use <slug>` (switch focus) / `continue <archived> <new> [--simple]` / `bind <slug> --session <id>` / `list` (global backlog) / `show <slug>` / `status [slug]` / `done <id> [--change slug]` / `undone <id> [--change slug]` / `relink [--apply] [--json]` (repair change wikilinks; preview by default) / `diff [slug]` / `archive [slug] [--force]` / `abandon [slug]` (drop it, no ADR) / `backlink [--apply]` (inject the proposal backlink into orphan design/tasks/spec files). `diff`, `archive` and `abandon` fall back to the active change when you omit the slug; bare `status` lists every open one. |
167
- | `wendkeep verify [--deep] [--change s]` | Run the change's task sensors; `--deep` assembles the independent-verification package. `--change` targets a change other than the active one; `--project <root>` runs it from outside the root. |
168
- | `wendkeep spec <sub>` | `list` / `show <capability>` generated contracts; `effective [--change <slug>] [--json]` (living contract + delta; defaults to the active change); `migrate`; `rebase [--accept-current]` (stops on conflicts unless you accept the living spec's side). |
169
- | `wendkeep sensors <sub>` | `list` / `add <id> "<command>"` with `--severity` / `--type` / `--report` / `--name` / `--description` / `--project` — view/edit `wendkeep.sensors.json` (JSON Schema shipped). |
170
- | `wendkeep cost [opts]` | Aggregate AI-coding spend across the vault's sessions — total, by model, by day. `--since <date>` / `--top [N]` (priciest) / `--trend [day\|week\|month]` (+ run-rate projection) / `--write` (generate `00-Custo.md`) / `--json`. |
171
- | `wendkeep cost rebuild [opts]` | Recalculate historical parent + subagent costs from `SESSION_REGISTRY`. Dry-run by default; `--apply` updates the notes and writes `.brain/COST_REBUILD.json`. Also `--session <id\|file>` / `--limit n` / `--json`. |
172
- | `wendkeep stats [--vault P]` | One shareable line: sessions · prompts · spend · span · models (`--json`). |
173
- | `wendkeep import [opts]` | **Retroactive memory** — backfill past **Claude + Codex** sessions into the vault (deduped by `session_id`). `--source all\|claude\|codex` / `--stamp-ids` / `--rescan-decisions` / `--from <dir>` / `--codex-from <dir>` / `--since d` / `--limit n` / `--dry-run` / `--json`. |
174
- | `wendkeep session list\|show\|use` | List the multi-session registry, show one conversation, or move only the human focus in `CURRENT_SESSION.md`. |
175
- | `wendkeep dashboard [--force]` | (Re)generate the vault's folder-filtered Bases + the `00-Dashboard` MOC. |
176
- | `wendkeep note new --type bug\|learning "<title>"` | Create a **numbered** derived note (`BUG-`/`APR-NNNN`) in the month folder and print its vault path. `--date YYYY-MM-DD`. |
177
- | `wendkeep note relink [--apply]` | Backfill provenance on orphan derived notes (BUG/APR with no source session), inheriting the modal session of their type/month cohort. Preview by default. |
178
- | `wendkeep note repair-frontmatter [--apply]` | Merge stacked frontmatter blocks in a session note damage from the concurrent writes of pre-0.50 versions. Base keys from the original block, values from the newest; preview by default · `--json`. |
179
- | `wendkeep note repair-sections [--apply]` | Rebuild the `## Decisions/Bugs/Learnings generated in this session` sections from the linked derived notes — the body used to lag behind the closing block. Preview by default · `--json`. |
180
- | `wendkeep renumber-decisions` | Renumber `04-Decisões` to `ADR-NNNN-<slug>` chronologically, move notes out of legacy `DIA N` subfolders into the month folder, and rewrite wikilinks. Preview by default; `--apply` / `--json`. |
181
- | `wendkeep renumber-bugs` | Same for `05-Bugs` `BUG-NNNN-<slug>`. |
182
- | `wendkeep renumber-learnings` | Same for `06-Aprendizados`/`06-Learnings` → `APR-NNNN-<slug>`. |
183
- | `wendkeep lesson add "t" "l"` | Record a project-local lesson (injected at the next SessionStart). `--change <slug>` ties the lesson to a change; `--vault P`. |
184
- | `wendkeep sync-defs` | Copy `.brain/agents\|skills` into `.codex/agents`, `.claude/skills`, `.agents/skills`; `--check` detects drift, `--reseed` refreshes the `wk-*` skills from the installed version's seeds. |
185
- | `wendkeep memory status [--gate] --vault P` | Inspect the v2 bundle without mutating it. `--gate` exits 1 only for a blocking state; warnings keep exit code 0. |
186
- | `wendkeep memory migrate [--apply] --vault P` | Convert a legacy `SHARED_MEMORY.md`. Dry-run by default; `--apply` creates a backup, turns legacy content into candidates, and publishes a valid v2 projection without editing CORE. |
187
- | `wendkeep memory repair --vault P` | Repair a partial/corrupt ledger under lock, preserving the original bytes in a `.bak`, retaining valid events, and re-projecting state. |
188
- | `wendkeep memory promote <candidate> --vault P` | Promote a candidate by ID by appending an auditable event; never edits the ledger in place. |
189
- | `wendkeep memory reject <candidate> --vault P` | Reject a candidate by ID by appending the decision to the audit history. |
190
- | `wendkeep validate-memory [path]` | Compatibility mode: validate `.brain/CORE.md` only (cap 25, 3 sections, no secrets/PII). Use `--vault <path>` to validate CORE + ledger + SHARED as a v2 bundle. |
191
- | `wendkeep theme sync [--vault P]` | Re-apply the colour system (CSS snippet + graph groups) to an existing vault — recovers a grey graph without re-running `init`. |
192
- | `wendkeep doctor [--vault P]` | Read-only vault health check. Beyond sessions/registry, links, notes, prices, and derived sections, it checks the v2 bundle and points to `memory status --gate` or `memory repair`; doctor never projects or repairs by itself. |
193
- | `wendkeep --version` / `--help` | Version / usage. |
162
+ ## Features by group
163
+
164
+ The README is the map; the guides provide syntax, options, exit codes, examples, and diagnosis.
165
+
166
+ | Group | Use it for | Detailed guide |
167
+ |---|---|---|
168
+ | **Installation and updates** | `init`, `sync`, companions, and the first project↔vault binding | [Installation and first use](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/getting-started.md) |
169
+ | **Operating profiles** | `profile`, `flow`, always-on Keep Core, and Wend Runtime governance | [Operating profiles](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/operating-profiles.md) |
170
+ | **Changes and verification** | `change`, specs, sensors, TDD, evidence, and archive | [Changes and verification](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/changes-and-verification.md) |
171
+ | **Shared memory** | CORE, SHARED, status, validation, repair, and curation | [Memory](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/memory.md) |
172
+ | **Sessions and import** | hooks, registry, session focus, and Claude/Codex backfill | [Sessions and import](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/sessions-and-import.md) |
173
+ | **Notes and knowledge** | BUG/APR/ADR, repairs, renumbering, lessons, and dashboard | [Notes and knowledge](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/notes-and-knowledge.md) |
174
+ | **Costs and observability** | stats, aggregation, trends, and historical rebuild | [Costs and observability](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/costs-and-observability.md) |
175
+ | **Maintenance and diagnostics** | doctor, definition drift, theme, version, and help | [Maintenance and diagnostics](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/maintenance-and-diagnostics.md) |
176
+
177
+ Operations that deserve step-by-step guidance: [verify and exits 0/1/2](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/verify.md),
178
+ [legacy-memory migration](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/memory-migration.md), and
179
+ [safe retroactive import](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/retroactive-import.md).
180
+
181
+ ## Operating ProfilesKeep Core is always active
182
+
183
+ **Keep Core is always active**: the Vault, sessions, identity, CORE/SHARED, lessons, costs,
184
+ and persistence do not turn off with the harness. **Wend Runtime** controls only the governance
185
+ layer:
186
+
187
+ | Profile | Route | Use |
188
+ |---|---|---|
189
+ | `OFF` | LLM-native harness | No Wend router, skill gate, or gates; explicit selection only. |
190
+ | `FLOW` | E V | Microcontract with Git baseline, allowlist, sensor, and receipt, without a change. |
191
+ | `GUIDE` | P E V | Compact guided change. |
192
+ | `GOVERN` | P R E V | Current a2 loop and compatible fallback. |
193
+ | `ASSURE` | P R E V C | Governance with confirmation and handoff. |
194
+
195
+ A corrupt binding never selects `OFF`: with one unambiguous explicit or legacy Vault, Keep Core
196
+ remains active under `GOVERN`, the error stays visible, and mutation guards fail closed. Additional
197
+ roots that FLOW must protect can be declared as project-relative paths under
198
+ `harness.flow.protectedRoots` in `.wendkeep.json`; any change below them requires promotion.
199
+ Invalid local config, marker, or identity never silently falls back to a parent/global Vault.
200
+
201
+ `wendkeep profile status/use` makes the choice observable; `wendkeep flow
202
+ start/finish/promote` handles local adjustments without manufacturing an ADR and fails closed on
203
+ physical escapes, Git metadata/hidden flags, mutating sensors, protected surfaces, or incomplete
204
+ session projection. Bounded no-follow discovery sees empty/ignored protected aliases; Vault writes
205
+ and owner+lease locks validate physical topology. Concurrent promotion elects one owner and supports
206
+ retry through `--change-slug`. Read the complete
207
+ [Operating profiles guide](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/operating-profiles.md).
194
208
 
195
209
  ## Shared Project Memory v2
196
210
 
@@ -198,11 +212,17 @@ Hot memory now separates human authorship, operational state, and evidence:
198
212
 
199
213
  - **`CORE.md` is canonical.** It is the short, hand-curated nucleus for durable preferences, active patterns, and open issues; no projector may infer or overwrite it.
200
214
  - **`SHARED_MEMORY.md` is generated operational state.** The `Stop` hook turns the session handoff into sanitized events; the projector deterministically reduces the ledger and publishes a verifiable revision, cursor, and hash. Facts are `verified` only with local evidence; unsupported reports remain `reported`, and disagreements become candidates for human judgment.
201
- - **`MEMORY_EVENTS.jsonl` is the append-only authority.** Producers publish to the outbox with exclusive creation, then the projector serializes append + projection under a lock. Repeating an identical `event_id`/payload is a no-op; reusing the ID with different bytes is observable corruption.
215
+ - **`MEMORY_EVENTS.jsonl` is the append-only authority.** `Stop` makes events durable in the outbox before acknowledging the attempt; the projector runs outside the registry lock and retries reuse the same IDs. Repeating an identical `event_id`/payload is a no-op; reusing the ID with different bytes is observable corruption.
202
216
  - **`MEMORY_CANDIDATES.jsonl` is the curation queue.** Conflicts and legacy content are never silently promoted. `promote` and `reject` record the decision as a new event.
203
217
 
204
218
  Artifacts stay under `.brain/` only. Sanitization strips secrets, tokens, local paths, transcripts, and harness payloads both before persistence and before injection. Events carry a `project_id`, and one vault never accepts another project's events.
205
219
 
220
+ Lifecycle in brief: each `SessionStart` opens an epoch that spans multiple `Stop` events;
221
+ `UserPromptSubmit` advances the native turn and recovers exactly one closed legacy activation.
222
+ Codex uses `session_id`/`turn_id` plus transcript order, with no artificial causal fields. See
223
+ [sessions and hooks](docs/en/commands/sessions-and-import.md) and
224
+ [memory](docs/en/commands/memory.md).
225
+
206
226
  ### Injection and budgets
207
227
 
208
228
  `brain-inject` delivers the same revision/hash on `startup`, `/clear`, and `/compact` `SessionStart` events, always placing CORE and SHARED before change context. The full envelope is capped at 24 KiB; CORE reserves up to 4 KiB, SHARED up to 6 KiB, and each line is capped at 320 characters. Under pressure, lessons are removed first, then non-current changes. CORE and SHARED are never prefix-sliced: a missing, invalid, or over-budget layer becomes a visible, repairable `<wk_memory_error>`.
@@ -217,9 +237,19 @@ wendkeep memory migrate --apply --vault .MyApp-vault # backup + candidates + v2
217
237
 
218
238
  ### Health and recovery
219
239
 
220
- Use `wendkeep memory status --gate --vault <vault>` in CI and before `verify`/`archive`. The critical `memory-health` sensor blocks ledger/outbox/bundle corruption, revision/cursor/hash lag, and active conflicts. A valid pending outbox or ordinary candidate is recoverable and remains a warning rather than blocking.
240
+ Use `wendkeep memory status --gate --vault <vault>` in CI and before `verify`/`archive`. Revision 0
241
+ immediately after valid migration is healthy. The gate correlates `last_memory_attempt`, outbox,
242
+ ledger, SHARED, and checkpoint: `degraded` with a durable outbox is a warning; an ambiguous attempt,
243
+ lost publication, or mismatched checkpoint blocks. See [migration](docs/en/commands/memory-migration.md)
244
+ and [diagnostics](docs/en/commands/maintenance-and-diagnostics.md).
221
245
 
222
- If status blocks, preserve the evidence and run `wendkeep memory repair --vault <vault>` to save a backup of the corrupt ledger, retain valid lines, and re-project. Then run `status --gate` again. Conflicts require explicit curation with `memory promote <id>` or `memory reject <id>`; doctor only diagnoses.
246
+ If status blocks, preserve the evidence and run `wendkeep memory repair --vault <vault>` to back up
247
+ the corrupt ledger, retain valid lines, and re-project. Repair never reclassifies attempts. A
248
+ valid pre-0.59 causal checkpoint is CAS-migrated to the physical boundary with backup/audit. A
249
+ demonstrably superseded ambiguity uses `memory reconcile <session> --by-session <successor>
250
+ --reason <reason>` as a dry run and requires `--apply`; the decision is backed up and audited
251
+ without rewriting ledger, CORE, or notes. Run `status --gate` again afterwards. Conflicts require
252
+ explicit curation with `memory promote <id>` or `memory reject <id>`; doctor only diagnoses.
223
253
 
224
254
  Session notes use one live `## Agentes, tokens e custos` snapshot. Main-agent and subagent hooks recompose it atomically, with costs, token dimensions, reasoning tokens and effort per model/source. Every hook that rewrites a session note takes a per-file lock and writes through a temp file + rename, so the `SubagentStop` fan-out (one hook run per subagent) can never leave a note half-written; a note whose frontmatter reads back damaged is left untouched rather than patched.
225
255
 
@@ -287,7 +317,7 @@ explore → propose → apply (TDD) → verify → archive
287
317
  ```
288
318
 
289
319
  - **Propose** — `wendkeep change new <slug>` scaffolds `08-Mudanças/<slug>/` (`proposta.md`, `design.md`, `tarefas.md`; `--simple` skips the design). It becomes the global *current* change. When the change declares `spec_impact: required`, you author the delta yourself at `specs/<capability>/spec.md` — there is no placeholder to delete. Multiple changes may remain open: `change list`/`status` and the hooks show every pending one, while commands without `--change` act on the current one alone. `change use <slug>` changes focus and `change continue <archived> <new>` creates an auditable continuation.
290
- - **Apply** — implement each `tarefas.md` task. Tag a task that needs machine proof with `[sensor:<id>]` one sensor per task (a task carries a single sensor; split it in two if you need two) and the requirement it satisfies with `[req:<ID>]`, of which a task may declare several.
320
+ - **Apply** — implement each `tarefas.md` task. Mark machine proof with one or more `[sensor:<id>]` tags on the same task: every distinct ID enters the gate once, in declaration order. Also mark satisfied requirements with one or more `[req:<ID>]` tags.
291
321
  - **Verify** — `wendkeep verify` runs the sensors your tasks declared (from `wendkeep.sensors.json` at the project root) and writes `evidencia.json`. A red `critical` fails the gate; a red `warning` is advisory. `verify --deep` builds a self-contained package with complete effective requirements (living contract + this change's delta), so the independent verifier never needs to reconstruct unarchived requirements from `07-Specs`. Every change needs a `verdict.json` to archive; `verify --deep` writes a trivial one automatically when the change declares no `[req:]`.
292
322
  - **Archive** — `wendkeep change archive <slug>` **gates** on the evidence (blocks unless every declared critical sensor is green), promotes each capability's spec delta (`ADDED`/`MODIFIED`/`REMOVED`) into the living `07-Specs/<capability>.md`, moves the change to `_arquivo/`, and mints an ADR in `04-Decisões/`.
293
323
 
package/README.md CHANGED
@@ -13,7 +13,7 @@
13
13
 
14
14
  **In the graph:** 🔵 session · 🟣 decision · 🔴 bug · 🟢 learning · 🟡 change — every note, backlinked.
15
15
 
16
- **A persistent‑memory harness for AI coding agents, built on your Obsidian vault.** Every Claude Code **and Codex** session is captured turnbyturn into local Markdown — `init` wires both (Codex asks you to approve its hooks once; `import` backfills past sessions either way) — with token/cost tracking, auto‑extracted decisions, bugs and learnings, and a curated memory layer injected back at the start of the next session. On top of that memory core sits a native, zerodependency **change lifecycle** (spec → change → TDD → sensorgated archive) that keeps intent, work and proof wikilinked in one graph. 100% local, opencore.
16
+ **Persistent memory for AI coding agents, built on your Obsidian vault.** Every Claude Code **and Codex** session is captured turn by turn into local Markdown — `init` wires both (Codex asks you to approve its hooks once; `import` backfills past sessions either way) — with token/cost tracking and automatically extracted decisions, bugs, and learnings. That always-on plane is **Keep Core**. On top of it, **Wend Runtime** provides a native, zero-dependency lifecycle (spec → change → TDD → sensor-gated archive), selected through the `OFF`, `FLOW`, `GUIDE`, `GOVERN`, and `ASSURE` Operating Profiles. 100% local, open-core.
17
17
 
18
18
  ```bash
19
19
  npm i -D wendkeep && npx wendkeep init # captures from the next session on
@@ -120,6 +120,9 @@ one command:
120
120
  npm install --save-dev wendkeep@latest && npx --no-install wendkeep sync --project . --yes
121
121
  ```
122
122
 
123
+ `sync` lets its own `init` stage validate or rebuild the binding before resolving the Vault for
124
+ later stages. An invalid `.wendkeep.json` stops at `init` without falling back to an inherited global Vault.
125
+
123
126
  The install stays outside `sync` on purpose: a running process cannot replace itself and
124
127
  keep going — the code in memory would still be the old one.
125
128
 
@@ -156,41 +159,52 @@ stop reporting `defs stale` without a single skill having been updated. If you h
156
159
  `wk-*`, that edit is overwritten; your own customisation belongs in a skill of your own,
157
160
  which the reseed never touches.
158
161
 
159
- ## Commands
160
-
161
- | Command | What it does |
162
- |---|---|
163
- | `wendkeep init` | Set up wendkeep in a project (vault taxonomy + settings + MCP + skills). |
164
- | `wendkeep sync [--project P]` | **One-command update**: runs `init` → `sync-defs` → `doctor` on the current project, stopping at the first failing step. Install the package first (a running process cannot replace itself). `--vault P` · `--yes` to skip the companions picker. |
165
- | `wendkeep hook <name>` | Run a session hook; invoked by `settings.json` (reads agent JSON on stdin). |
166
- | `wendkeep change <sub>` | Change lifecycle: `new <slug> [--simple]` / `use <slug>` (switch focus) / `continue <archived> <new> [--simple]` / `bind <slug> --session <id>` / `list` (global backlog) / `show <slug>` / `status [slug]` / `done <id> [--change slug]` / `undone <id> [--change slug]` / `relink [--apply] [--json]` (repair change wikilinks; preview by default) / `diff [slug]` / `archive [slug] [--force]` / `abandon [slug]` (drop it, no ADR) / `backlink [--apply]` (inject the proposal backlink into orphan design/tasks/spec files). `diff`, `archive` and `abandon` fall back to the active change when you omit the slug; bare `status` lists every open one. |
167
- | `wendkeep verify [--deep] [--change s]` | Run the change's task sensors; `--deep` assembles the independent-verification package. `--change` targets a change other than the active one; `--project <root>` runs it from outside the root. |
168
- | `wendkeep spec <sub>` | `list` / `show <capability>` generated contracts; `effective [--change <slug>] [--json]` (living contract + delta; defaults to the active change); `migrate`; `rebase [--accept-current]` (stops on conflicts unless you accept the living spec's side). |
169
- | `wendkeep sensors <sub>` | `list` / `add <id> "<command>"` with `--severity` / `--type` / `--report` / `--name` / `--description` / `--project` — view/edit `wendkeep.sensors.json` (JSON Schema shipped). |
170
- | `wendkeep cost [opts]` | Aggregate AI-coding spend across the vault's sessions — total, by model, by day. `--since <date>` / `--top [N]` (priciest) / `--trend [day\|week\|month]` (+ run-rate projection) / `--write` (generate `00-Custo.md`) / `--json`. |
171
- | `wendkeep cost rebuild [opts]` | Recalculate historical parent + subagent costs from `SESSION_REGISTRY`. Dry-run by default; `--apply` updates the notes and writes `.brain/COST_REBUILD.json`. Also `--session <id\|file>` / `--limit n` / `--json`. |
172
- | `wendkeep stats [--vault P]` | One shareable line: sessions · prompts · spend · span · models (`--json`). |
173
- | `wendkeep import [opts]` | **Retroactive memory** — backfill past **Claude + Codex** sessions into the vault (deduped by `session_id`). `--source all\|claude\|codex` / `--stamp-ids` / `--rescan-decisions` / `--from <dir>` / `--codex-from <dir>` / `--since d` / `--limit n` / `--dry-run` / `--json`. |
174
- | `wendkeep session list\|show\|use` | List the multi-session registry, show one conversation, or move only the human focus in `CURRENT_SESSION.md`. |
175
- | `wendkeep dashboard [--force]` | (Re)generate the vault's folder-filtered Bases + the `00-Dashboard` MOC. |
176
- | `wendkeep note new --type bug\|learning "<title>"` | Create a **numbered** derived note (`BUG-`/`APR-NNNN`) in the month folder and print its vault path. `--date YYYY-MM-DD`. |
177
- | `wendkeep note relink [--apply]` | Backfill provenance on orphan derived notes (BUG/APR with no source session), inheriting the modal session of their type/month cohort. Preview by default. |
178
- | `wendkeep note repair-frontmatter [--apply]` | Merge stacked frontmatter blocks in a session note damage from the concurrent writes of pre-0.50 versions. Base keys from the original block, values from the newest; preview by default · `--json`. |
179
- | `wendkeep note repair-sections [--apply]` | Rebuild the `## Decisions/Bugs/Learnings generated in this session` sections from the linked derived notes — the body used to lag behind the closing block. Preview by default · `--json`. |
180
- | `wendkeep renumber-decisions` | Renumber `04-Decisões` to `ADR-NNNN-<slug>` chronologically, move notes out of legacy `DIA N` subfolders into the month folder, and rewrite wikilinks. Preview by default; `--apply` / `--json`. |
181
- | `wendkeep renumber-bugs` | Same for `05-Bugs` `BUG-NNNN-<slug>`. |
182
- | `wendkeep renumber-learnings` | Same for `06-Aprendizados`/`06-Learnings` → `APR-NNNN-<slug>`. |
183
- | `wendkeep lesson add "t" "l"` | Record a project-local lesson (injected at the next SessionStart). `--change <slug>` ties the lesson to a change; `--vault P`. |
184
- | `wendkeep sync-defs` | Copy `.brain/agents\|skills` into `.codex/agents`, `.claude/skills`, `.agents/skills`; `--check` detects drift, `--reseed` refreshes the `wk-*` skills from the installed version's seeds. |
185
- | `wendkeep memory status [--gate] --vault P` | Inspect the v2 bundle without mutating it. `--gate` exits 1 only for a blocking state; warnings keep exit code 0. |
186
- | `wendkeep memory migrate [--apply] --vault P` | Convert a legacy `SHARED_MEMORY.md`. Dry-run by default; `--apply` creates a backup, turns legacy content into candidates, and publishes a valid v2 projection without editing CORE. |
187
- | `wendkeep memory repair --vault P` | Repair a partial/corrupt ledger under lock, preserving the original bytes in a `.bak`, retaining valid events, and re-projecting state. |
188
- | `wendkeep memory promote <candidate> --vault P` | Promote a candidate by ID by appending an auditable event; never edits the ledger in place. |
189
- | `wendkeep memory reject <candidate> --vault P` | Reject a candidate by ID by appending the decision to the audit history. |
190
- | `wendkeep validate-memory [path]` | Compatibility mode: validate `.brain/CORE.md` only (cap 25, 3 sections, no secrets/PII). Use `--vault <path>` to validate CORE + ledger + SHARED as a v2 bundle. |
191
- | `wendkeep theme sync [--vault P]` | Re-apply the colour system (CSS snippet + graph groups) to an existing vault — recovers a grey graph without re-running `init`. |
192
- | `wendkeep doctor [--vault P]` | Read-only vault health check. Beyond sessions/registry, links, notes, prices, and derived sections, it checks the v2 bundle and points to `memory status --gate` or `memory repair`; doctor never projects or repairs by itself. |
193
- | `wendkeep --version` / `--help` | Version / usage. |
162
+ ## Features by group
163
+
164
+ The README is the map; the guides provide syntax, options, exit codes, examples, and diagnosis.
165
+
166
+ | Group | Use it for | Detailed guide |
167
+ |---|---|---|
168
+ | **Installation and updates** | `init`, `sync`, companions, and the first project↔vault binding | [Installation and first use](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/getting-started.md) |
169
+ | **Operating profiles** | `profile`, `flow`, always-on Keep Core, and Wend Runtime governance | [Operating profiles](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/operating-profiles.md) |
170
+ | **Changes and verification** | `change`, specs, sensors, TDD, evidence, and archive | [Changes and verification](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/changes-and-verification.md) |
171
+ | **Shared memory** | CORE, SHARED, status, validation, repair, and curation | [Memory](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/memory.md) |
172
+ | **Sessions and import** | hooks, registry, session focus, and Claude/Codex backfill | [Sessions and import](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/sessions-and-import.md) |
173
+ | **Notes and knowledge** | BUG/APR/ADR, repairs, renumbering, lessons, and dashboard | [Notes and knowledge](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/notes-and-knowledge.md) |
174
+ | **Costs and observability** | stats, aggregation, trends, and historical rebuild | [Costs and observability](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/costs-and-observability.md) |
175
+ | **Maintenance and diagnostics** | doctor, definition drift, theme, version, and help | [Maintenance and diagnostics](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/maintenance-and-diagnostics.md) |
176
+
177
+ Operations that deserve step-by-step guidance: [verify and exits 0/1/2](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/verify.md),
178
+ [legacy-memory migration](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/memory-migration.md), and
179
+ [safe retroactive import](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/retroactive-import.md).
180
+
181
+ ## Operating ProfilesKeep Core is always active
182
+
183
+ **Keep Core is always active**: the Vault, sessions, identity, CORE/SHARED, lessons, costs,
184
+ and persistence do not turn off with the harness. **Wend Runtime** controls only the governance
185
+ layer:
186
+
187
+ | Profile | Route | Use |
188
+ |---|---|---|
189
+ | `OFF` | LLM-native harness | No Wend router, skill gate, or gates; explicit selection only. |
190
+ | `FLOW` | E V | Microcontract with Git baseline, allowlist, sensor, and receipt, without a change. |
191
+ | `GUIDE` | P E V | Compact guided change. |
192
+ | `GOVERN` | P R E V | Current a2 loop and compatible fallback. |
193
+ | `ASSURE` | P R E V C | Governance with confirmation and handoff. |
194
+
195
+ A corrupt binding never selects `OFF`: with one unambiguous explicit or legacy Vault, Keep Core
196
+ remains active under `GOVERN`, the error stays visible, and mutation guards fail closed. Additional
197
+ roots that FLOW must protect can be declared as project-relative paths under
198
+ `harness.flow.protectedRoots` in `.wendkeep.json`; any change below them requires promotion.
199
+ Invalid local config, marker, or identity never silently falls back to a parent/global Vault.
200
+
201
+ `wendkeep profile status/use` makes the choice observable; `wendkeep flow
202
+ start/finish/promote` handles local adjustments without manufacturing an ADR and fails closed on
203
+ physical escapes, Git metadata/hidden flags, mutating sensors, protected surfaces, or incomplete
204
+ session projection. Bounded no-follow discovery sees empty/ignored protected aliases; Vault writes
205
+ and owner+lease locks validate physical topology. Concurrent promotion elects one owner and supports
206
+ retry through `--change-slug`. Read the complete
207
+ [Operating profiles guide](https://github.com/rogersialves/wendkeep/blob/main/docs/en/commands/operating-profiles.md).
194
208
 
195
209
  ## Shared Project Memory v2
196
210
 
@@ -198,11 +212,17 @@ Hot memory now separates human authorship, operational state, and evidence:
198
212
 
199
213
  - **`CORE.md` is canonical.** It is the short, hand-curated nucleus for durable preferences, active patterns, and open issues; no projector may infer or overwrite it.
200
214
  - **`SHARED_MEMORY.md` is generated operational state.** The `Stop` hook turns the session handoff into sanitized events; the projector deterministically reduces the ledger and publishes a verifiable revision, cursor, and hash. Facts are `verified` only with local evidence; unsupported reports remain `reported`, and disagreements become candidates for human judgment.
201
- - **`MEMORY_EVENTS.jsonl` is the append-only authority.** Producers publish to the outbox with exclusive creation, then the projector serializes append + projection under a lock. Repeating an identical `event_id`/payload is a no-op; reusing the ID with different bytes is observable corruption.
215
+ - **`MEMORY_EVENTS.jsonl` is the append-only authority.** `Stop` makes events durable in the outbox before acknowledging the attempt; the projector runs outside the registry lock and retries reuse the same IDs. Repeating an identical `event_id`/payload is a no-op; reusing the ID with different bytes is observable corruption.
202
216
  - **`MEMORY_CANDIDATES.jsonl` is the curation queue.** Conflicts and legacy content are never silently promoted. `promote` and `reject` record the decision as a new event.
203
217
 
204
218
  Artifacts stay under `.brain/` only. Sanitization strips secrets, tokens, local paths, transcripts, and harness payloads both before persistence and before injection. Events carry a `project_id`, and one vault never accepts another project's events.
205
219
 
220
+ Lifecycle in brief: each `SessionStart` opens an epoch that spans multiple `Stop` events;
221
+ `UserPromptSubmit` advances the native turn and recovers exactly one closed legacy activation.
222
+ Codex uses `session_id`/`turn_id` plus transcript order, with no artificial causal fields. See
223
+ [sessions and hooks](docs/en/commands/sessions-and-import.md) and
224
+ [memory](docs/en/commands/memory.md).
225
+
206
226
  ### Injection and budgets
207
227
 
208
228
  `brain-inject` delivers the same revision/hash on `startup`, `/clear`, and `/compact` `SessionStart` events, always placing CORE and SHARED before change context. The full envelope is capped at 24 KiB; CORE reserves up to 4 KiB, SHARED up to 6 KiB, and each line is capped at 320 characters. Under pressure, lessons are removed first, then non-current changes. CORE and SHARED are never prefix-sliced: a missing, invalid, or over-budget layer becomes a visible, repairable `<wk_memory_error>`.
@@ -217,9 +237,19 @@ wendkeep memory migrate --apply --vault .MyApp-vault # backup + candidates + v2
217
237
 
218
238
  ### Health and recovery
219
239
 
220
- Use `wendkeep memory status --gate --vault <vault>` in CI and before `verify`/`archive`. The critical `memory-health` sensor blocks ledger/outbox/bundle corruption, revision/cursor/hash lag, and active conflicts. A valid pending outbox or ordinary candidate is recoverable and remains a warning rather than blocking.
240
+ Use `wendkeep memory status --gate --vault <vault>` in CI and before `verify`/`archive`. Revision 0
241
+ immediately after valid migration is healthy. The gate correlates `last_memory_attempt`, outbox,
242
+ ledger, SHARED, and checkpoint: `degraded` with a durable outbox is a warning; an ambiguous attempt,
243
+ lost publication, or mismatched checkpoint blocks. See [migration](docs/en/commands/memory-migration.md)
244
+ and [diagnostics](docs/en/commands/maintenance-and-diagnostics.md).
221
245
 
222
- If status blocks, preserve the evidence and run `wendkeep memory repair --vault <vault>` to save a backup of the corrupt ledger, retain valid lines, and re-project. Then run `status --gate` again. Conflicts require explicit curation with `memory promote <id>` or `memory reject <id>`; doctor only diagnoses.
246
+ If status blocks, preserve the evidence and run `wendkeep memory repair --vault <vault>` to back up
247
+ the corrupt ledger, retain valid lines, and re-project. Repair never reclassifies attempts. A
248
+ valid pre-0.59 causal checkpoint is CAS-migrated to the physical boundary with backup/audit. A
249
+ demonstrably superseded ambiguity uses `memory reconcile <session> --by-session <successor>
250
+ --reason <reason>` as a dry run and requires `--apply`; the decision is backed up and audited
251
+ without rewriting ledger, CORE, or notes. Run `status --gate` again afterwards. Conflicts require
252
+ explicit curation with `memory promote <id>` or `memory reject <id>`; doctor only diagnoses.
223
253
 
224
254
  Session notes use one live `## Agentes, tokens e custos` snapshot. Main-agent and subagent hooks recompose it atomically, with costs, token dimensions, reasoning tokens and effort per model/source. Every hook that rewrites a session note takes a per-file lock and writes through a temp file + rename, so the `SubagentStop` fan-out (one hook run per subagent) can never leave a note half-written; a note whose frontmatter reads back damaged is left untouched rather than patched.
225
255
 
@@ -287,7 +317,7 @@ explore → propose → apply (TDD) → verify → archive
287
317
  ```
288
318
 
289
319
  - **Propose** — `wendkeep change new <slug>` scaffolds `08-Mudanças/<slug>/` (`proposta.md`, `design.md`, `tarefas.md`; `--simple` skips the design). It becomes the global *current* change. When the change declares `spec_impact: required`, you author the delta yourself at `specs/<capability>/spec.md` — there is no placeholder to delete. Multiple changes may remain open: `change list`/`status` and the hooks show every pending one, while commands without `--change` act on the current one alone. `change use <slug>` changes focus and `change continue <archived> <new>` creates an auditable continuation.
290
- - **Apply** — implement each `tarefas.md` task. Tag a task that needs machine proof with `[sensor:<id>]` one sensor per task (a task carries a single sensor; split it in two if you need two) and the requirement it satisfies with `[req:<ID>]`, of which a task may declare several.
320
+ - **Apply** — implement each `tarefas.md` task. Mark machine proof with one or more `[sensor:<id>]` tags on the same task: every distinct ID enters the gate once, in declaration order. Also mark satisfied requirements with one or more `[req:<ID>]` tags.
291
321
  - **Verify** — `wendkeep verify` runs the sensors your tasks declared (from `wendkeep.sensors.json` at the project root) and writes `evidencia.json`. A red `critical` fails the gate; a red `warning` is advisory. `verify --deep` builds a self-contained package with complete effective requirements (living contract + this change's delta), so the independent verifier never needs to reconstruct unarchived requirements from `07-Specs`. Every change needs a `verdict.json` to archive; `verify --deep` writes a trivial one automatically when the change declares no `[req:]`.
292
322
  - **Archive** — `wendkeep change archive <slug>` **gates** on the evidence (blocks unless every declared critical sensor is green), promotes each capability's spec delta (`ADDED`/`MODIFIED`/`REMOVED`) into the living `07-Specs/<capability>.md`, moves the change to `_arquivo/`, and mints an ADR in `04-Decisões/`.
293
323