@jaimevalasek/aioson 1.20.0 → 1.21.3

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 (34) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/docs/pt/living-memory/reflexao-in-harness.md +2 -0
  3. package/package.json +1 -1
  4. package/src/cli.js +5 -0
  5. package/src/commands/context-health.js +35 -2
  6. package/src/commands/feature-close.js +36 -0
  7. package/src/commands/install.js +5 -0
  8. package/src/commands/memory-archive.js +193 -193
  9. package/src/commands/memory-reflect-commit.js +28 -4
  10. package/src/commands/memory-restore.js +177 -177
  11. package/src/commands/memory-search.js +135 -135
  12. package/src/commands/memory-trim.js +191 -0
  13. package/src/constants.js +1 -0
  14. package/src/current-state-trim.js +170 -0
  15. package/src/doctor.js +17 -0
  16. package/src/i18n/messages/en.js +16 -0
  17. package/src/i18n/messages/es.js +16 -0
  18. package/src/i18n/messages/fr.js +16 -0
  19. package/src/i18n/messages/pt-BR.js +16 -0
  20. package/src/install-wizard.js +3 -2
  21. package/src/lib/tool-capabilities.js +67 -64
  22. package/src/memory-reflect-engine.js +10 -4
  23. package/src/permissions-generator.js +3 -0
  24. package/template/.aioson/agents/architect.md +3 -0
  25. package/template/.aioson/agents/committer.md +1 -1
  26. package/template/.aioson/agents/dev.md +2 -2
  27. package/template/.aioson/agents/deyvin.md +2 -1
  28. package/template/.aioson/agents/pentester.md +1 -0
  29. package/template/.aioson/agents/qa.md +4 -0
  30. package/template/.aioson/agents/sheldon.md +1 -0
  31. package/template/.aioson/agents/tester.md +2 -0
  32. package/template/.aioson/config/autonomy-protocol.json +1 -0
  33. package/template/.aioson/design-docs/agent-loading-contract.md +138 -0
  34. package/template/.aioson/docs/quality/code-health-analysis.md +79 -0
@@ -0,0 +1,138 @@
1
+ ---
2
+ description: "Contrato de carga de memória/contexto dos agentes AIOSON — tiers de loading (sempre / por-gatilho / sob-justificativa), política de retenção+arquivamento de memória append-style (current-state.md), matriz por agente e enforcement. Complementa agent-structural-contract."
3
+ scope: "governance"
4
+ agents: []
5
+ status: partially-implemented
6
+ implemented: "P0 (rollup), P1 (archive-awareness), tagging, tooling — shipped 2026-05 (v1.21.1)"
7
+ deferred: "P2 (mandatory slug-resolve pre-code), P3 (reflect-prompt hash+path), per-tier budget line in context:health"
8
+ ---
9
+
10
+ # Agent Loading Contract
11
+
12
+ > Governança transversal de **quando** cada agente carrega **qual** camada de memória.
13
+ > Complementa `agent-structural-contract.md` (que cobre seções/observabilidade/handoff).
14
+ > Loaded por todos os agentes na seção "Project rules, docs & design governance".
15
+
16
+ ## Por que existe
17
+
18
+ A doutrina lazy-load já está nos prompts ("never preload all at once", "cost discipline"),
19
+ mas **nunca foi estendida à bootstrap**. Resultado medido (2026-05-28, modo inception):
20
+
21
+ - `bootstrap/current-state.md` = **81 KB / ~33k tokens** = **84% da bootstrap**, log append-only de
22
+ 172 entradas. Lido **na ativação** por `@dev`, `@qa`, `@architect`, `@deyvin` — os agentes mais usados.
23
+ - `@product`/`@analyst`/`@neo` já leem só os arquivos pequenos (`what-is`/`what-it-does`) — disciplinados.
24
+ - Como `current-state` > cap de leitura (~25k tokens), quem "lê" recebe fatia **truncada e arbitrária**:
25
+ paga caro **e** vê incompleto.
26
+ - `aioson context:health` mede `.aioson/context/*.md` mas **ignora `bootstrap/`** — subreporta o maior custo.
27
+
28
+ Dois modos de falha a corrigir:
29
+ - **Over-load:** leitura eager+completa de memória pesada independente da tarefa (desperdício).
30
+ - **Under-load:** contexto específico (dossier/spec da feature) só carrega se o agente *decidir* — gatilho
31
+ heurístico, não forçado → trabalho sub-informado ("buraco no processo").
32
+
33
+ ## Princípio
34
+
35
+ Toda camada de memória tem um **tier de carga** e um **gatilho**. Nada caro entra na ativação por padrão.
36
+ Memória que cresce por append tem **política de retenção** — não acumula para sempre no caminho quente.
37
+
38
+ ## Os três tiers de carga
39
+
40
+ ### Tier 0 — Sempre (orçamento ≤ ~2k tokens)
41
+ Orientação imediata e barata; responde "o que é + o que está acontecendo + o que falta":
42
+ - `bootstrap/what-is.md` — identidade do sistema
43
+ - `context/project-pulse.md` — último agente, feature ativa, blockers, próximo passo
44
+ - `context/dev-state.md` — estado da feature em desenvolvimento (o que está sendo feito / o que falta)
45
+
46
+ (O `.md` do próprio agente e `CLAUDE.md` são sempre carregados pelo harness — fora do orçamento.)
47
+
48
+ ### Tier 1 — Por gatilho (carregar SÓ quando o gatilho dispara)
49
+
50
+ | Gatilho na tarefa | Carregar |
51
+ |---|---|
52
+ | Precisa de capacidades recém-shipadas (review, não re-descobrir) | `current-state.md` **só a seção HOT**; cold/archive por keyword |
53
+ | Raciocínio arquitetural/estrutural | `bootstrap/how-it-works.md` |
54
+ | Request nomeia/implica uma feature (slug) | `features/{slug}/dossier.md` + `spec-{slug}.md` (+ prd/requirements) |
55
+ | Implementação toca fronteiras de módulo/naming/reuse | `design-docs/*.md` (por relevância) |
56
+ | Rule cujo `agents:` inclui o agente ou é `[]` | aquela rule |
57
+ | Tarefa casa com um processo (SDD, secure-tdd, decision-presentation) | o SKILL correspondente |
58
+
59
+ ### Tier 2 — Sob justificativa explícita (caro)
60
+ - `brain:query` (memória procedural) — antes de recomendações arquiteturais
61
+ - `git diff/log` — só quando memória+runtime são insuficientes ou o user pede histórico de commit
62
+ - **`current-state.md` completo + `current-state-archive.md`** — só quando um survey precisa do histórico inteiro
63
+ - scan artifacts (`scan-*.md`) — deep-dive brownfield
64
+
65
+ ## Política de retenção de memória append-style (o coração)
66
+
67
+ > Responde diretamente: *"dá pra ir arquivando as partes do current-state.md que não são necessárias?"* — **sim.**
68
+
69
+ `current-state.md` (e qualquer arquivo de estado que cresce por append) tem **ciclo de vida por entrada**.
70
+ Uma entrada "Slice 3 da feature X shipou…" é HOT enquanto X está ativa; depois que X **fecha**, vira histórico —
71
+ valiosa para arqueologia, **desnecessária em toda ativação**.
72
+
73
+ **Estrutura HOT/COLD:**
74
+ - `bootstrap/current-state.md` (**HOT**) — apenas: features ativas (`in_progress`) + entradas dentro da
75
+ janela recente (≥ último minor publicado **ou** ~últimos 45 dias). Alvo: **≤ ~10 KB**.
76
+ - `bootstrap/current-state-archive.md` (**COLD**) — todo o resto. Nunca carregado na ativação (Tier-2);
77
+ permanece pesquisável via `memory:search` / grep.
78
+
79
+ **Gatilhos de rollup (mover HOT → COLD, nunca apagar):**
80
+ 1. **Event-driven** — `feature:close` move as entradas daquela feature para o archive. Requer tag de slug
81
+ por entrada (ver abaixo).
82
+ 2. **Window-based** — verbo `memory:trim` (ou a etapa de reflexão da Living Memory, que já manda
83
+ *"remove obsolete entries"* — hoje não honrado) aplica a janela de retenção a entradas legadas/sem tag.
84
+
85
+ **Tag de entrada (going-forward):** quem faz append (`@dev`, `@committer`, reflexão) prefixa a entrada com
86
+ `[{slug} · {YYYY-MM-DD}]` para tornar o rollup determinístico. Entradas legadas sem tag caem na regra de janela.
87
+
88
+ **Leitura:** Tier-1 lê só o HOT; o archive é Tier-2 (arqueologia/keyword).
89
+
90
+ > Generaliza: **toda memória que cresce por append precisa de política de retenção, não append infinito.**
91
+ > Pastas de feature, plans e dossiers já são arquivados em `done/` no `feature:close`; `current-state.md`
92
+ > é o único log *global* que ainda não tem rollup — esta política fecha essa lacuna.
93
+
94
+ ## Matriz de loading por agente (sob o contrato)
95
+
96
+ | Agente | Tier-0 | Gatilhos Tier-1 típicos | Lê `current-state` completo? |
97
+ |---|---|---|---|
98
+ | @product, @analyst | what-is + (what-it-does) | dossier/spec se feature nomeada | ❌ nunca |
99
+ | @neo | what-is | — (roteador) | ❌ nunca |
100
+ | @deyvin | Tier-0 | HOT + dossier/spec por slug; pair-exec/debug docs por gatilho | só HOT (full = Tier-2) |
101
+ | @dev | Tier-0 + how-it-works | HOT + dossier/spec + rules(dev) + design-docs por toque | só HOT |
102
+ | @qa | Tier-0 | HOT (evitar re-flag de shipado) + área sob review | só HOT |
103
+ | @architect | Tier-0 + how-it-works | HOT + design-docs governança | só HOT |
104
+
105
+ ## Gatilhos determinísticos (fecha o under-load)
106
+
107
+ Quando a request **nomeia ou implica** uma feature, o agente **DEVE** resolver o slug
108
+ (via `features.md` / `project-pulse.md`) e carregar `dossier` + `spec` **antes** de editar código.
109
+ Converte o gatilho de heurístico ("o agente decide") em contrato ("tem que resolver + carregar").
110
+ Usar `aioson context:pack . --agent=<a> --goal="<request>"` para obter o conjunto exato de arquivos.
111
+
112
+ ## Enforcement & medição
113
+
114
+ - `aioson context:health` **DEVE** incluir `bootstrap/*.md` (hoje cego) + uma linha de **orçamento por tier**.
115
+ - Orçamentos: Tier-0 ≤ ~2k tokens; ativação (Tier-0 + prompt do agente) alvo ≤ ~8k tokens.
116
+ - `@qa` (Gate D) e `@sheldon` (enrichment) checam os prompts contra este contrato, como já fazem com
117
+ `agent-structural-contract` — violação = finding Medium `recommended_owner: dev`, nunca bloqueia feature sozinha.
118
+
119
+ ## Sequência de implementação (@dev — inception-mirror src/ + template/)
120
+
121
+ 1. ✅ **P0 (maior retorno) — shipped v1.21.1:** `memory:trim` (engine + comando, split HOT/COLD) +
122
+ hook de rollup no `feature:close` (keep=25, best-effort). Derrubou `current-state.md` 81KB→21KB.
123
+ 2. ✅ **P1 — shipped v1.21.1:** seção "Bootstrap context" de @dev/@qa/@architect/@deyvin agora aponta
124
+ pro `current-state-archive.md` (grep/`memory:search` on-demand). A reescrita pesada "ler parcial + grep
125
+ head" foi dispensada — pós-trim o arquivo HOT já é pequeno.
126
+ 3. ✅ **Tagging — shipped v1.21.1:** reflect-engine + @dev invariant #8 + @committer prefixam
127
+ entradas com `[{slug} · {YYYY-MM-DD}]`.
128
+ 4. ✅ **Tooling — shipped v1.21.1:** `context:health` mede `bootstrap/` e exclui o archive frio.
129
+ (⬜ linha de orçamento por tier ainda não.)
130
+ 5. ⬜ **P2 (adiado):** tornar a resolução de slug + load de dossier/spec obrigatória no pré-código.
131
+ 6. ⬜ **P3 (adiado):** `reflect-prompt.json` guardar hash+path em vez do snapshot completo.
132
+
133
+ ## Não-objetivos / adiado
134
+
135
+ - Mudar o **conteúdo** ou schema da memória (só a política de carga/retenção).
136
+ - Memória cross-project; seleção de contexto por LLM; file-watcher.
137
+ - Tocar @product/@analyst/@neo (já disciplinados) além do alinhamento de referência a este doc.
138
+ - **Apagar** histórico — arquivamento move, nunca deleta (arqueologia preservada e pesquisável).
@@ -0,0 +1,79 @@
1
+ ---
2
+ description: "Code-health / improvement analysis playbook — coverage gaps, test sufficiency, regression need, execution-chain tracing, performance hotspots, componentization/maintainability. Shared on-demand lens for @tester/@qa/@pentester/@architect/@sheldon/@deyvin. Load only when the trigger fires; do not inline."
3
+ agents: [tester, qa, pentester, architect, sheldon, deyvin]
4
+ ---
5
+
6
+ # Code-Health Analysis
7
+
8
+ > Shared, **on-demand** lens. Load when assessing where a codebase needs better tests,
9
+ > regression guards, performance, or refactoring — never inline by default.
10
+ > Scale depth to classification: **MICRO** → coverage + regression only; **SMALL** → add
11
+ > execution-chain + perf; **MEDIUM** → all six facets. Respect the loading discipline in
12
+ > `.aioson/design-docs/agent-loading-contract.md` — read only the files a facet points to.
13
+
14
+ ## The loop
15
+
16
+ Run as a cycle, not a one-shot. Each pass narrows scope and produces concrete, verifiable changes.
17
+
18
+ ### 1. Plan
19
+ State the goal and bound the scope: which modules/files, which classification, which facets apply.
20
+ Prefer the smallest target that answers the question. Write down what "better" means here
21
+ (e.g. "critical-path branch coverage ≥ 80%", "no N+1 in the list endpoint").
22
+
23
+ ### 2. Investigate — the six facets
24
+ - **Coverage gaps** — find files/paths with weak coverage and **read them**. Critical paths
25
+ (auth, money, ownership, data integrity) first. Signal: no test file, line coverage high but
26
+ branches untested, error paths uncovered.
27
+ - **Test sufficiency** — does it test more than happy path? Look for missing edge cases (zero/empty,
28
+ boundary, concurrent), failure paths (invalid input, conflict, unauthorized, not found), and
29
+ business-rule violations. High line coverage + weak assertions = false confidence.
30
+ - **Regression need** — has this area broken before (devlogs / git / `current-state-archive.md`)?
31
+ Is it a recurring hotspot? If yes, a regression test pinning the exact prior failure is worth more
32
+ than broad coverage. Pin the bug, not the function.
33
+ - **Execution chain** — trace the runtime flow: entry → call chain → side effects → exit. Map
34
+ dependencies and where state mutates. For >5 files, dispatch a read-only scout instead of
35
+ inline-reading (see `@deyvin` sub-task scout) — preserve context.
36
+ - **Performance hotspots** — N+1 queries in lists, sync external calls in the request cycle,
37
+ unbounded/unpaginated queries, repeated work in loops, missing indexes on WHERE/ORDER/JOIN,
38
+ O(n²) over growing collections. Flag with the trigger condition, not a micro-benchmark guess.
39
+ - **Componentization / maintainability** — duplicated blocks (extract), oversized files/functions
40
+ (split — see `.aioson/design-docs/file-size.md`), tight coupling / mixed concerns (separate),
41
+ god-objects, primitive obsession. Only propose extraction when it lowers real maintenance cost,
42
+ not for symmetry.
43
+
44
+ ### 3. Refine (lapida)
45
+ Dedupe findings; prioritize by **risk × effort**. Separate **must-fix** (correctness, security,
46
+ critical-path coverage) from **nice-to-have** (cosmetic refactors). Drop speculative findings.
47
+
48
+ ### 4. Operate (opera)
49
+ Produce the concrete change, not a description: **write the test**, propose the extraction with the
50
+ target shape, or the specific perf fix. Stay within the active agent's scope — analysis agents
51
+ recommend + write tests; structural changes route to `@dev`/`@architect`.
52
+
53
+ ### 5. Test
54
+ Add/run the test or verification command. Confirm the change does what it claims. For a regression
55
+ finding, prove the test fails before the fix and passes after.
56
+
57
+ ### 6. Adjust
58
+ Re-measure against the goal from step 1. If not improved, iterate or revert. Record the decision
59
+ (spec / dossier Agent Trail) so the next session does not re-derive it.
60
+
61
+ ## Per-agent emphasis
62
+
63
+ | Agent | Leans on | Output |
64
+ |---|---|---|
65
+ | @tester | coverage, test sufficiency, regression | writes the missing tests (line/branch/property) |
66
+ | @qa | risk-first triage; routes coverage→@tester, perf/structure→@architect | findings in the QA report |
67
+ | @pentester | execution-chain, attack surface (perf/componentization light) | threat-surface + chain findings |
68
+ | @architect | componentization, maintainability, performance (structural) | structural recommendations / design-doc |
69
+ | @sheldon | all six facets (deep technical analysis) | enrichment / analysis report |
70
+ | @deyvin | quick lens on a slice during a pair session | inline suggestions; escalate if broad |
71
+
72
+ ## Trigger (when to load this doc)
73
+ Load when the task is: "is this well-tested / does it need more tests?", "should we add a regression
74
+ test?", "trace how this runs / where it's slow", or "is this worth refactoring/extracting?".
75
+ Do **not** load for routine happy-path implementation or a bounded bug fix with a known reproducer.
76
+
77
+ ## Output discipline
78
+ Report each finding as: **facet · location (file:line) · what · risk×effort · proposed action**.
79
+ Never invent findings to look thorough; never omit a critical one. Scale verbosity to classification.