@igor-guari/pi-skill-improve-codebase-architecture 0.0.0-stage → 1.0.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/HTML-REPORT.md ADDED
@@ -0,0 +1,123 @@
1
+ # HTML Report Format
2
+
3
+ The architectural review is rendered as a single self-contained HTML file in the OS temp directory. Tailwind and Mermaid both come from CDNs. Mermaid handles graph-shaped diagrams reliably; hand-built divs and inline SVG handle the more editorial visuals (mass diagrams, cross-sections). Mix the two: don't lean on Mermaid for everything, it'll start to look generic.
4
+
5
+ ## Scaffold
6
+
7
+ ```html
8
+ <!doctype html>
9
+ <html lang="en">
10
+ <head>
11
+ <meta charset="utf-8" />
12
+ <title>Architecture review for {{repo name}}</title>
13
+ <script src="https://cdn.tailwindcss.com"></script>
14
+ <script type="module">
15
+ import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";
16
+ mermaid.initialize({ startOnLoad: true, theme: "neutral", securityLevel: "loose" });
17
+ </script>
18
+ <style>
19
+ /* small custom layer for things Tailwind doesn't cover cleanly:
20
+ dashed seam lines, hand-drawn-feeling arrow heads, etc. */
21
+ .seam { stroke-dasharray: 4 4; }
22
+ .leak { stroke: #dc2626; }
23
+ .deep { background: linear-gradient(135deg, #0f172a, #1e293b); }
24
+ </style>
25
+ </head>
26
+ <body class="bg-stone-50 text-slate-900 font-sans">
27
+ <main class="max-w-5xl mx-auto px-6 py-12 space-y-12">
28
+ <header>...</header>
29
+ <section id="candidates" class="space-y-10">...</section>
30
+ <section id="top-recommendation">...</section>
31
+ </main>
32
+ </body>
33
+ </html>
34
+ ```
35
+
36
+ ## Header
37
+
38
+ Repo name, date, and a compact legend: solid box = module, dashed line = seam, red arrow = leakage, thick dark box = deep module. No introduction paragraph. Straight into the candidates.
39
+
40
+ ## Candidate card
41
+
42
+ The diagrams carry the weight. Prose is sparse, plain, and uses the glossary terms (from the `codebase-design` skill) without ceremony.
43
+
44
+ Each candidate is one `<article>`:
45
+
46
+ - **Title**: short, names the deepening (e.g. "Collapse the Order intake pipeline").
47
+ - **Badge row**: recommendation strength (`Strong` = emerald, `Worth exploring` = amber, `Speculative` = slate), plus a tag for the dependency category (`in-process`, `local-substitutable`, `ports & adapters`, `mock`).
48
+ - **Files**: monospaced list, `font-mono text-sm`.
49
+ - **Before / After diagram**: the centrepiece. Two columns, side by side. See patterns below.
50
+ - **Problem**: one sentence. What hurts.
51
+ - **Solution**: one sentence. What changes.
52
+ - **Wins**: bullets, ≤6 words each. e.g. "Tests hit one interface", "Pricing logic stops leaking", "Delete 4 shallow wrappers".
53
+ - **ADR callout** (if applicable): one line in an amber-tinted box.
54
+
55
+ No paragraphs of explanation. If the diagram needs a paragraph to be understood, redraw the diagram.
56
+
57
+ ## Diagram patterns
58
+
59
+ Pick the pattern that fits the candidate. Mix them. Don't make every diagram look the same. Variety is part of the point.
60
+
61
+ ### Mermaid graph (the workhorse for dependencies / call flow)
62
+
63
+ Use a Mermaid `flowchart` or `graph` when the point is "X calls Y calls Z, and look at the mess." Wrap it in a Tailwind-styled card so it doesn't feel parachuted in. Style with classDef to colour leakage edges red and the deep module dark. Sequence diagrams work well for "before: 6 round-trips; after: 1."
64
+
65
+ ```html
66
+ <div class="rounded-lg border border-slate-200 bg-white p-4">
67
+ <pre class="mermaid">
68
+ flowchart LR
69
+ A[OrderHandler] --> B[OrderValidator]
70
+ B --> C[OrderRepo]
71
+ C -.leak.-> D[PricingClient]
72
+ classDef leak stroke:#dc2626,stroke-width:2px;
73
+ class C,D leak
74
+ </pre>
75
+ </div>
76
+ ```
77
+
78
+ ### Hand-built boxes-and-arrows (when Mermaid's layout fights you)
79
+
80
+ Modules as `<div>`s with borders and labels. Arrows as inline SVG `<line>` or `<path>` elements positioned absolutely over a relative container. Reach for this when you want the "after" diagram to feel like one thick-bordered deep module with greyed-out internals, since Mermaid won't render that with the right weight.
81
+
82
+ ### Cross-section (good for layered shallowness)
83
+
84
+ Stack horizontal bands (`h-12 border-l-4`) to show layers a call passes through. Before: 6 thin layers each doing nothing. After: 1 thick band labelled with the consolidated responsibility.
85
+
86
+ ### Mass diagram (good for "interface as wide as implementation")
87
+
88
+ Two rectangles per module: one for interface surface area, one for implementation. Before: interface rectangle is nearly as tall as the implementation rectangle (shallow). After: interface rectangle is short, implementation rectangle is tall (deep).
89
+
90
+ ### Call-graph collapse
91
+
92
+ Before: a tree of function calls rendered as nested boxes. After: the same tree collapsed into one box, with the now-internal calls shown faded inside it.
93
+
94
+ ## Style guidance
95
+
96
+ - Lean editorial, not corporate-dashboard. Generous whitespace. Serif optional for headings (`font-serif` works well with stone/slate).
97
+ - Colour sparingly: one accent (emerald or indigo) plus red for leakage and amber for warnings.
98
+ - Keep diagrams ~320px tall so before/after sits comfortably side by side without scrolling.
99
+ - Use `text-xs uppercase tracking-wider` for module labels inside diagrams, so they read as schematic, not as UI.
100
+ - The only scripts are the Tailwind CDN and the Mermaid ESM import. The report is otherwise static: no app code, no interactivity beyond Mermaid's own rendering.
101
+
102
+ ## Top recommendation section
103
+
104
+ One larger card. Candidate name, one sentence on why, anchor link to its card. That's it.
105
+
106
+ ## Tone
107
+
108
+ Plain English, concise, but the architectural nouns and verbs come straight from the `codebase-design` skill. Concision is not an excuse to drift.
109
+
110
+ **Use exactly:** module, interface, implementation, depth, deep, shallow, seam, adapter, leverage, locality.
111
+
112
+ **Never substitute:** component, service, unit (for module) · API, signature (for interface) · boundary (for seam) · layer, wrapper (for module, when you mean module).
113
+
114
+ **Phrasings that fit the style:**
115
+
116
+ - "Order intake module is shallow: interface nearly matches the implementation."
117
+ - "Pricing leaks across the seam."
118
+ - "Deepen: one interface, one place to test."
119
+ - "Two adapters justify the seam: HTTP in prod, in-memory in tests."
120
+
121
+ **Wins bullets** name the gain in glossary terms: *"locality: bugs concentrate in one module"*, *"leverage: one interface, N call sites"*, *"interface shrinks; implementation absorbs the wrappers"*. Don't write *"easier to maintain"* or *"cleaner code"*, because those terms aren't in the glossary and don't earn their place.
122
+
123
+ No hedging, no throat-clearing, no "it's worth noting that…". If a sentence could be a bullet, make it a bullet. If a bullet could be cut, cut it. If a term isn't in the `codebase-design` glossary, reach for one that is before inventing a new one.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Matt Pocock
4
+ Copyright (c) 2025 Igor Guariroba
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,53 @@
1
- # Temporary Holding Version
1
+ # pi-skill-improve-codebase-architecture
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![Pi Package](https://img.shields.io/badge/pi--package-skill-blue)](https://github.com/IgorGuariroba/pi-skill-improve-codebase-architecture)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
5
+
6
+ **improve-codebase-architecture** skill for the **[Pi coding agent](https://pi.dev)**, adapted from Matt Pocock's Engineering Skills.
7
+
8
+ > Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick.
9
+
10
+ ---
11
+
12
+ ## Installation
13
+
14
+ Install directly into Pi using `pi install`:
15
+
16
+ ```bash
17
+ pi install git:github.com/IgorGuariroba/pi-skill-improve-codebase-architecture
18
+ ```
19
+
20
+ Or clone into your local/global skills directory:
21
+
22
+ ```bash
23
+ # Global Pi skills directory:
24
+ git clone https://github.com/IgorGuariroba/pi-skill-improve-codebase-architecture.git ~/.pi/agent/skills/improve-codebase-architecture
25
+
26
+ # Or Agent Skills standard path:
27
+ git clone https://github.com/IgorGuariroba/pi-skill-improve-codebase-architecture.git ~/.agents/skills/improve-codebase-architecture
28
+ ```
29
+
30
+ ---
31
+
32
+ ## Usage
33
+
34
+ Trigger it explicitly in your session:
35
+
36
+ ```text
37
+ /skill:improve-codebase-architecture
38
+ ```
39
+
40
+ Or let Pi automatically route to it based on conversation context and need.
41
+
42
+ ---
43
+
44
+ ## Credits
45
+
46
+ - **Original concept & methodology**: [Matt Pocock](https://github.com/mattpocock)
47
+ - **Adapted for Pi Agent**: [Igor Guariroba](https://github.com/IgorGuariroba)
48
+
49
+ ---
50
+
51
+ ## License
52
+
53
+ [MIT](LICENSE)
package/SKILL.md ADDED
@@ -0,0 +1,78 @@
1
+ ---
2
+ name: improve-codebase-architecture
3
+ description: Scan a codebase for deepening opportunities, present them as a visual
4
+ HTML report, then grill through whichever one you pick.
5
+ disable-model-invocation: true
6
+ license: MIT
7
+ metadata:
8
+ author: Matt Pocock
9
+ adapted_by: Igor Guariroba
10
+ version: 1.0.0
11
+ ---
12
+
13
+
14
+ # Improve Codebase Architecture
15
+
16
+ Surface architectural friction and propose **deepening opportunities**: refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability.
17
+
18
+ This command is _informed_ by the project's domain model and built on a shared design vocabulary:
19
+
20
+ - Read `../codebase-design/SKILL.md` (relative to this skill directory) for the architecture vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**, **locality**) and its principles (the deletion test, "the interface is the test surface", "one adapter = hypothetical seam, two = real"). Use these terms exactly in every suggestion, and don't drift into "component," "service," "API," or "boundary."
21
+ - The domain language in `GLOSSARY.md` gives names to good seams; ADRs in `docs/adr/` record decisions this command should not re-litigate.
22
+
23
+ ## Process
24
+
25
+ ### 1. Explore
26
+
27
+ **Scope before you scan: YAGNI.** Deepening a module pays off by making future changes to it easier, so put extra weight on the parts of the codebase that have recently changed. Decide *where* to look before you look:
28
+
29
+ - If the user named a direction (a module, a subsystem, a pain point), take it, and skip the inference below.
30
+ - Otherwise, walk back a good stretch of the commit history (`git log --oneline`) to find the codebase's hot spots, the files and areas that keep coming up, and let those paths pull your attention first. If the changes are scattered with no clear hot spot, widen the net.
31
+
32
+ Read the project's domain glossary (`GLOSSARY.md`) and any ADRs in the area you're touching first.
33
+
34
+ Then explore the scoped codebase directly, or read `references/pi-workers.md` and use a read-only Pi worker for independent exploration. Give it absolute pointers to the scope, vocabulary, glossary and ADRs, and require file-level evidence for each candidate. Exploration is complete when each candidate has evidence of friction and a deletion-test judgement. Explore organically and note where you experience friction:
35
+
36
+ - Where does understanding one concept require bouncing between many small modules?
37
+ - Where are modules **shallow**, with an interface nearly as complex as the implementation?
38
+ - Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)?
39
+ - Where do tightly-coupled modules leak across their seams?
40
+ - Which parts of the codebase are untested, or hard to test through their current interface?
41
+
42
+ Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want.
43
+
44
+ ### 2. Present candidates as an HTML report
45
+
46
+ Write a self-contained HTML file to the OS temp directory so nothing lands in the repo. Resolve the temp dir from `$TMPDIR`, falling back to `/tmp` (or `%TEMP%` on Windows), and write to `<tmpdir>/architecture-review-<timestamp>.html` so each run gets a fresh file. Open it for the user (`xdg-open <path>` on Linux, `open <path>` on macOS, `start <path>` on Windows) and tell them the absolute path.
47
+
48
+ The report uses **Tailwind via CDN** for layout and styling, and **Mermaid via CDN** for diagrams where a graph/flow/sequence reliably communicates the structure. Mix Mermaid with hand-crafted CSS/SVG visuals: use Mermaid when relationships are graph-shaped (call graphs, dependencies, sequences), and hand-built divs/SVG when you want something more editorial (mass diagrams, cross-sections, collapse animations). Each candidate gets a **before/after visualisation**. Be visual.
49
+
50
+ For each candidate, render a card with:
51
+
52
+ - **Files**: which files/modules are involved
53
+ - **Problem**: why the current architecture is causing friction
54
+ - **Solution**: plain English description of what would change
55
+ - **Benefits**: explained in terms of locality and leverage, and how tests would improve
56
+ - **Before / After diagram**: side-by-side, custom-drawn, illustrating the shallowness and the deepening
57
+ - **Recommendation strength**: one of `Strong`, `Worth exploring`, `Speculative`, rendered as a badge
58
+
59
+ End the report with a **Top recommendation** section: which candidate you'd tackle first and why.
60
+
61
+ **Use GLOSSARY.md vocabulary for the domain, and the `codebase-design` vocabulary for the architecture.** If `GLOSSARY.md` defines "Order," talk about "the Order intake module," not "the FooBarHandler," and not "the Order service."
62
+
63
+ **ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly in the card (e.g. a warning callout: _"contradicts ADR-0007, but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids.
64
+
65
+ See [HTML-REPORT.md](HTML-REPORT.md) for the full HTML scaffold, diagram patterns, and styling guidance.
66
+
67
+ Do NOT propose interfaces yet. After the file is written, ask the user: "Which of these would you like to explore?"
68
+
69
+ ### 3. Grilling loop
70
+
71
+ Once the user picks a candidate, read `../grilling/SKILL.md` to walk the decision tree with them: constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive.
72
+
73
+ Side effects happen inline as decisions crystallize; read `../domain-modeling/SKILL.md` to keep the domain model current as you go:
74
+
75
+ - **Naming a deepened module after a concept not in `GLOSSARY.md`?** Add the term to `GLOSSARY.md`. Create the file lazily if it doesn't exist.
76
+ - **Sharpening a fuzzy term during the conversation?** Update `GLOSSARY.md` right there.
77
+ - **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing; skip ephemeral reasons ("not worth it right now") and self-evident ones.
78
+ - **Want to explore alternative interfaces for the deepened module?** Read `../codebase-design/DESIGN-IT-TWICE.md` and use its independent Pi worker pattern.
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@igor-guari/pi-skill-improve-codebase-architecture",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you ",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi-skill",
8
+ "pi",
9
+ "improve-codebase-architecture",
10
+ "engineering-skills"
11
+ ],
12
+ "author": "Igor Guariroba",
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/IgorGuariroba/pi-skill-improve-codebase-architecture.git"
17
+ },
18
+ "homepage": "https://github.com/IgorGuariroba/pi-skill-improve-codebase-architecture#readme",
19
+ "pi": {
20
+ "skills": [
21
+ "."
22
+ ]
23
+ },
24
+ "files": [
25
+ "SKILL.md",
26
+ "*.md",
27
+ "references/"
28
+ ]
29
+ }
@@ -0,0 +1,33 @@
1
+ # Workers no Pi
2
+
3
+ Referência compartilhada para delegação em processos Pi independentes. Um **worker** é outro processo Pi com contexto próprio; o coordenador continua responsável pelo resultado.
4
+
5
+ ## Preparar e executar
6
+
7
+ 1. Confira `pi --help` para as opções da instalação. Crie um diretório de execução fora do repositório (`mktemp -d`) e um prompt por tarefa. Registre papel, cwd absoluto, escopo permitido, referências absolutas à spec/tickets/skills, resultado esperado e critério de conclusão. Compartilhe ponteiros, não o histórico da conversa.
8
+ 2. Execute cada tarefa com cwd explícito e contexto novo. Exemplo de comando para `process_start` (substitua os caminhos):
9
+
10
+ ```bash
11
+ cd /absolute/worktree && pi --print --no-session @/absolute/run/task.md > /absolute/run/result.md 2> /absolute/run/stderr.log
12
+ ```
13
+
14
+ Use o modelo/provider solicitado, se houver; caso contrário, mantenha os defaults configurados. `--no-session` evita persistir/reutilizar a conversa; configurações e instruções do projeto continuam disponíveis. Carregue outras skills lendo seus `SKILL.md` por caminho absoluto no prompt. Pi não precisa de uma ferramenta `Skill` para isso.
15
+ 3. Inicie tarefas independentes com chamadas separadas de `process_start`, cada uma com `watch`: `success: {exitCode: {eq: 0}}`, `failure: {exitCode: {ne: 0}}` e `timeoutMs` finito conforme o trabalho (por exemplo, 600000 para revisão). Após registrar os watches, informe a espera e encerre o turno. Os resultados chegam automaticamente; use `process_logs` para diagnóstico, não polling manual.
16
+ 4. Ao receber a conclusão, leia resultado e stderr e confira os artefatos. Exit code zero comprova execução, não cumprimento da tarefa. Uma resposta sem evidência, com bloqueio ou trabalho parcial é incompleta. Em timeout, inspecione e pare o processo antes de repetir ou liberar seu worktree. Preserve prompts, resultados e logs até entregar o trabalho.
17
+
18
+ Se `process_start`/watch não estiverem disponíveis, escolha o caminho Herdr abaixo quando aplicável; caso contrário, execute tarefas sequencialmente com timeout explícito na ferramenta disponível. Registre a perda de paralelismo. Falha de autenticação ou diálogo que exija interação deve ser reportado ao usuário; não invente aprovações nem transfira segredos em prompts.
19
+
20
+ ## Contratos e isolamento
21
+
22
+ - **Implementação:** um worktree e branch exclusivos por worker escritor. O resultado informa commit(s), critérios atendidos, comandos/testes e resultados, pendências e status Git. Só aceite conclusão após conferir esses itens.
23
+ - **Revisão/exploração:** leitura apenas do código; saída final em stdout, capturada pelo coordenador. Autorize escrita de notas externas apenas quando a tarefa exigir. Com `bash`, uma instrução de leitura não é sandbox: mantenha o escopo explícito e verifique o status Git antes/depois. Para leitura estrita sem shell, a instalação oferece `--tools read,grep,find,ls --no-mcp`; o coordenador pode fornecer diff e commits em arquivos externos.
24
+ - **Integração:** um único escritor na branch de integração. O coordenador serializa merges; workers de tickets não atualizam essa branch. Nenhum reset destrutivo ou limpeza forçada de alterações alheias.
25
+ - **Conclusão:** o coordenador valida commits, testes e critérios de aceitação. Estado de processo/pane não substitui essa validação.
26
+
27
+ ## Herdr: acompanhamento visível
28
+
29
+ Quando o usuário mencionar/pedir Herdr e `HERDR_ENV=1`, leia `../skills/herdr/SKILL.md` (relativo a este arquivo) e consulte a CLI instalada antes de controlar panes. Fora do Herdr, continue com processos Pi; Herdr não é pré-requisito.
30
+
31
+ Use os comandos documentados de pane para executar o mesmo comando `pi --print --no-session` em um shell disponível, preservando foco e cwd explícito. Capture saída, stderr e exit code em arquivos exclusivos fora do repositório. Aguarde via `watch_create` com polling barato do arquivo de exit code, sucesso zero, falha não zero e timeout finito. Publique esse arquivo apenas depois que o Pi terminar. Após registrar o watch, encerre o turno. Em timeout, inspecione o pane antes de repetir.
32
+
33
+ Se preferir um Pi interativo reconhecido por Herdr, confira primeiro se a CLI instalada oferece esse kind e siga a skill Herdr para iniciar, enviar prompt e aguardar. Cada tarefa independente começa em um processo/sessão nova. `idle`/`done` indica estado da interface, não aceitação do trabalho: leia a resposta e valide os artefatos. Crie workspaces/tabs ou outra topologia somente quando o usuário os solicitar; encerre apenas recursos criados para esta execução.