@lincolness/ponte 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/LICENSE +21 -0
- package/README.md +121 -2
- package/package.json +36 -4
- package/src/apply.ts +417 -0
- package/src/clipboard.ts +88 -0
- package/src/files.ts +297 -0
- package/src/index.ts +517 -0
- package/src/pack.ts +228 -0
- package/src/parse.ts +247 -0
- package/src/prompt.ts +116 -0
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 lincolness
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,122 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-ponte
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Extensão do [pi](https://github.com/earendil-works/pi) que faz a ponte entre o repositório e um chat externo mais forte (Copilot, ChatGPT, Claude.ai...), sem depender do modelo local para copiar código de um lado para o outro.
|
|
4
|
+
|
|
5
|
+
- **Ida:** `/ponte pack` gera o repositório inteiro num único `.txt`, com estrutura, conteúdo e instruções de como o modelo externo deve responder.
|
|
6
|
+
- **Volta:** `/ponte apply` lê a resposta do chat e aplica as alterações nos arquivos. Quem aplica é a extensão, não o modelo do pi.
|
|
7
|
+
- **Manter atualizado:** `/ponte delta` gera só o que mudou desde o último envio, para continuar a mesma conversa sem reenviar tudo.
|
|
8
|
+
|
|
9
|
+
## Instalação
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pi install npm:@lincolness/ponte
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Para testar sem instalar: `pi -e npm:@lincolness/ponte`.
|
|
16
|
+
|
|
17
|
+
Sem acesso ao npm, copie a pasta para `~/.pi/agent/extensions/ponte`.
|
|
18
|
+
|
|
19
|
+
Não há dependências para instalar. Funciona em Windows, macOS e Linux.
|
|
20
|
+
|
|
21
|
+
## Fluxo de uso
|
|
22
|
+
|
|
23
|
+
1. No pi: `/ponte pack` e depois `/ponte copy`. O arquivo vai para a área de transferência; cole com Ctrl+V no Copilot como anexo. Outra opção é `/ponte abrir` e arrastar `.pi/ponte/repo.txt` para o chat.
|
|
24
|
+
2. No Copilot: peça o que quiser ("corrija o bug X", "adicione testes para Y"). As instruções no topo do pacote já dizem como ele deve responder.
|
|
25
|
+
3. Copie a resposta inteira pelo botão de copiar da mensagem.
|
|
26
|
+
4. No pi, escolha uma das formas:
|
|
27
|
+
- `/ponte apply`: lê da área de transferência. Se não achar nada, abre um editor para você colar.
|
|
28
|
+
- Ou cole a resposta direto no prompt do pi. A extensão detecta os blocos e pergunta se deve aplicar. Se você responder "Não", o texto vai para o modelo como uma mensagem normal.
|
|
29
|
+
- Ou salve a resposta em `.pi/ponte/resposta.txt` e rode `/ponte apply .pi/ponte/resposta.txt`. Essa pasta fica fora do pacote.
|
|
30
|
+
5. Aparece um resumo (`+` criar, `~` alterar, `-` apagar) e você confirma.
|
|
31
|
+
- Se algum trecho não casar, só os arquivos sem erro são aplicados. Um relatório com o erro e o conteúdo atual do arquivo vai para a área de transferência. Cole no Copilot e ele corrige.
|
|
32
|
+
6. Rode testes e ajuste com o pi normalmente. Para o Copilot ver o estado novo, rode `/ponte delta` e `/ponte copy`.
|
|
33
|
+
|
|
34
|
+
O rodapé do pi mostra `ponte: N mudança(s) para enviar` quando o repositório mudou desde o último envio.
|
|
35
|
+
|
|
36
|
+
## Comandos
|
|
37
|
+
|
|
38
|
+
| Comando | O que faz |
|
|
39
|
+
|---|---|
|
|
40
|
+
| `/ponte pack [filtros...]` | Gera `.pi/ponte/repo.txt`. Filtros no estilo .gitignore limitam o recorte: `/ponte pack src/api "*.sql"` |
|
|
41
|
+
| `/ponte delta` | Gera `.pi/ponte/delta-NNN.txt` só com os arquivos novos ou alterados e a lista dos removidos |
|
|
42
|
+
| `/ponte apply [arquivo]` | Aplica a resposta. Sem argumento, lê da área de transferência ou abre o editor para colar |
|
|
43
|
+
| `/ponte undo` | Desfaz a última aplicação. Pode repetir para voltar mais aplicações |
|
|
44
|
+
| `/ponte status` | Lista o que mudou desde o último envio |
|
|
45
|
+
| `/ponte copy` / `/ponte copy texto` | Copia o último pacote ou delta como arquivo (para anexar) ou como texto |
|
|
46
|
+
| `/ponte abrir` | Abre a pasta `.pi/ponte` no Explorer ou Finder |
|
|
47
|
+
| `/ponte formato` | Copia só as instruções de formato, útil para colar num chat já aberto |
|
|
48
|
+
|
|
49
|
+
O modelo do pi também ganha duas ferramentas: `ponte_pack` ("gera o pacote só da pasta src") e `ponte_apply` ("aplica a resposta que salvei em resposta.txt"). Assim ele chama a extensão em vez de redigitar o código.
|
|
50
|
+
|
|
51
|
+
## Formato da resposta
|
|
52
|
+
|
|
53
|
+
Este é o formato que o pacote pede ao modelo externo:
|
|
54
|
+
|
|
55
|
+
````text
|
|
56
|
+
FILE: caminho/novo.py
|
|
57
|
+
```python
|
|
58
|
+
conteúdo completo
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
EDIT: caminho/existente.ts
|
|
62
|
+
```
|
|
63
|
+
<<<<<<< SEARCH
|
|
64
|
+
linhas atuais, exatas
|
|
65
|
+
=======
|
|
66
|
+
linhas novas
|
|
67
|
+
>>>>>>> REPLACE
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
DELETE: caminho/velho.txt
|
|
71
|
+
MOVE: antigo.ts -> novo.ts
|
|
72
|
+
````
|
|
73
|
+
|
|
74
|
+
A aplicação aceita as variações que costumam aparecer quando se copia de um chat:
|
|
75
|
+
|
|
76
|
+
- cabeçalho com markdown em volta (`### **FILE:** \`x\``);
|
|
77
|
+
- CRLF e espaços não separáveis;
|
|
78
|
+
- SEARCH com espaços sobrando no fim da linha;
|
|
79
|
+
- SEARCH com a indentação errada (o REPLACE é reindentado);
|
|
80
|
+
- resposta inteira embrulhada num bloco de código.
|
|
81
|
+
|
|
82
|
+
Ela mantém o fim de linha (CRLF/LF) e o BOM de cada arquivo. Antes de gravar, simula tudo em memória, então um arquivo nunca fica com parte das alterações aplicada.
|
|
83
|
+
|
|
84
|
+
## O que entra no pacote
|
|
85
|
+
|
|
86
|
+
- Num repositório git, entra o que o git conhece (versionado ou novo, respeitando o .gitignore). Fora de git, a pasta é percorrida ignorando o .gitignore da raiz e as pastas comuns de build e dependências.
|
|
87
|
+
- Ficam sempre de fora: `.git`, `.pi`, lockfiles, arquivos minificados, binários, arquivos que não estão em UTF-8 e arquivos acima de 256 KB.
|
|
88
|
+
- **Segredos ficam de fora:** `.env`, `.env.*`, `*.pem`, `*.key`, `.npmrc`, `secrets.*` etc. O `.env.example` entra. Mesmo assim, confira o pacote antes de mandar para um serviço externo.
|
|
89
|
+
- Arquivos binários e os que não estão em UTF-8 são listados em "Arquivos omitidos" no próprio pacote. Arquivos em Latin-1/Windows-1252 caem aqui; converta para UTF-8 se precisar editá-los pela ponte.
|
|
90
|
+
|
|
91
|
+
## Configuração (opcional)
|
|
92
|
+
|
|
93
|
+
Crie o arquivo `.pi/ponte.json` no projeto:
|
|
94
|
+
|
|
95
|
+
```json
|
|
96
|
+
{
|
|
97
|
+
"exclude": ["docs/legado/", "*.csv"],
|
|
98
|
+
"include": [],
|
|
99
|
+
"maxFileKB": 256,
|
|
100
|
+
"maxPartKB": 0,
|
|
101
|
+
"outDir": ".pi/ponte",
|
|
102
|
+
"ext": "txt"
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
- `maxPartKB`: divide o pacote em `repo.parte1.txt`, `repo.parte2.txt`... quando o chat tem limite de tamanho por anexo. Arquivos nunca são cortados ao meio.
|
|
107
|
+
- `ext`: use `md` se o chat aceitar e você preferir.
|
|
108
|
+
|
|
109
|
+
A pasta `.pi/ponte/` cria o próprio `.gitignore`, então nada dela vai para o git.
|
|
110
|
+
|
|
111
|
+
## Desenvolvimento
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
npm test # node --test (Node >= 22.18, que roda TypeScript direto)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
- `src/files.ts`: listagem e filtros
|
|
118
|
+
- `src/pack.ts`: pacote, delta e manifesto
|
|
119
|
+
- `src/parse.ts`: leitura da resposta
|
|
120
|
+
- `src/apply.ts`: plano, gravação e undo
|
|
121
|
+
- `src/clipboard.ts`: área de transferência
|
|
122
|
+
- `src/index.ts`: ligação com o pi
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincolness/ponte",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Extensão do pi: empacota o repositório num arquivo para um chat externo (Copilot, ChatGPT) e aplica a resposta de volta",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"pi-package",
|
|
9
|
+
"pi",
|
|
10
|
+
"copilot",
|
|
11
|
+
"repo-pack",
|
|
12
|
+
"search-replace"
|
|
13
|
+
],
|
|
14
|
+
"pi": {
|
|
15
|
+
"extensions": [
|
|
16
|
+
"./src/index.ts"
|
|
17
|
+
]
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"src/",
|
|
21
|
+
"README.md",
|
|
22
|
+
"CHANGELOG.md",
|
|
23
|
+
"LICENSE"
|
|
24
|
+
],
|
|
25
|
+
"peerDependencies": {
|
|
26
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
27
|
+
"typebox": "*"
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"test": "node --test tests/"
|
|
31
|
+
},
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=20"
|
|
34
|
+
},
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
}
|
|
38
|
+
}
|
package/src/apply.ts
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
// Aplicação das operações: primeiro simula tudo em memória, depois grava (com backup para desfazer).
|
|
2
|
+
|
|
3
|
+
import { promises as fs } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { byPath, readText, toPosix } from "./files.ts";
|
|
6
|
+
import { fenceFor, langFor } from "./pack.ts";
|
|
7
|
+
import type { EditPair, Op } from "./parse.ts";
|
|
8
|
+
import { errorReportHeader } from "./prompt.ts";
|
|
9
|
+
|
|
10
|
+
// ---------------------------------------------------------------- SEARCH/REPLACE
|
|
11
|
+
|
|
12
|
+
export type ReplaceResult =
|
|
13
|
+
| { ok: true; content: string; mode: "exato" | "espaços no fim" | "indentação" }
|
|
14
|
+
| { ok: false; reason: string };
|
|
15
|
+
|
|
16
|
+
function countOccurrences(hay: string, needle: string): number[] {
|
|
17
|
+
const at: number[] = [];
|
|
18
|
+
let from = 0;
|
|
19
|
+
for (;;) {
|
|
20
|
+
const k = hay.indexOf(needle, from);
|
|
21
|
+
if (k < 0) return at;
|
|
22
|
+
at.push(k);
|
|
23
|
+
from = k + 1;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function leading(s: string): string {
|
|
28
|
+
return /^[ \t]*/.exec(s)![0];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function reindent(lines: string[], fromIndent: string, toIndent: string): string[] {
|
|
32
|
+
if (fromIndent === toIndent) return lines;
|
|
33
|
+
return lines.map((l) => {
|
|
34
|
+
if (l.trim() === "") return l;
|
|
35
|
+
if (l.startsWith(fromIndent)) return toIndent + l.slice(fromIndent.length);
|
|
36
|
+
// linha menos indentada que a referência: ajusta pela diferença, se der
|
|
37
|
+
if (toIndent.startsWith(fromIndent)) return toIndent.slice(fromIndent.length) + l;
|
|
38
|
+
return l;
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function findLineMatches(lines: string[], search: string[], eq: (a: string, b: string) => boolean): number[] {
|
|
43
|
+
const out: number[] = [];
|
|
44
|
+
for (let i = 0; i + search.length <= lines.length; i++) {
|
|
45
|
+
let ok = true;
|
|
46
|
+
for (let j = 0; j < search.length; j++) {
|
|
47
|
+
if (!eq(lines[i + j], search[j])) {
|
|
48
|
+
ok = false;
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (ok) out.push(i);
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Quantas linhas em branco há em cada ponta (os modelos costumam colocá-las no SEARCH). */
|
|
58
|
+
function blankEdges(lines: string[]): [number, number] {
|
|
59
|
+
let a = 0;
|
|
60
|
+
let b = 0;
|
|
61
|
+
while (a < lines.length && lines[a].trim() === "") a++;
|
|
62
|
+
while (b < lines.length - a && lines[lines.length - 1 - b].trim() === "") b++;
|
|
63
|
+
return [a, b];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const AMBIGUOUS = (n: number) => `o trecho do SEARCH aparece ${n} vezes; inclua mais linhas de contexto`;
|
|
67
|
+
|
|
68
|
+
export function applySearchReplace(content: string, pair: EditPair): ReplaceResult {
|
|
69
|
+
const { search, replace } = pair;
|
|
70
|
+
if (search.trim() === "") {
|
|
71
|
+
return { ok: false, reason: "SEARCH vazio (para criar ou reescrever o arquivo, use FILE)" };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const lines = content.split("\n");
|
|
75
|
+
const rawS = search.split("\n");
|
|
76
|
+
const [sa, sb] = blankEdges(rawS);
|
|
77
|
+
const s = rawS.slice(sa, rawS.length - sb);
|
|
78
|
+
// linhas em branco nas pontas do REPLACE que correspondem às do SEARCH também saem
|
|
79
|
+
let r = replace === "" ? [] : replace.split("\n");
|
|
80
|
+
let ra = 0;
|
|
81
|
+
while (ra < sa && ra < r.length && r[ra].trim() === "") ra++;
|
|
82
|
+
let rb = 0;
|
|
83
|
+
while (rb < sb && rb < r.length - ra && r[r.length - 1 - rb].trim() === "") rb++;
|
|
84
|
+
r = r.slice(ra, r.length - rb);
|
|
85
|
+
|
|
86
|
+
const replaceLines = (i: number, newLines: string[]) =>
|
|
87
|
+
[...lines.slice(0, i), ...newLines, ...lines.slice(i + s.length)].join("\n");
|
|
88
|
+
|
|
89
|
+
// 1) linhas inteiras (tolerando espaços no fim)
|
|
90
|
+
const byLine = findLineMatches(lines, s, (a, b) => a.trimEnd() === b.trimEnd());
|
|
91
|
+
if (byLine.length > 1) return { ok: false, reason: AMBIGUOUS(byLine.length) };
|
|
92
|
+
if (byLine.length === 1) {
|
|
93
|
+
const i = byLine[0];
|
|
94
|
+
const exact = s.every((l, j) => lines[i + j] === l);
|
|
95
|
+
return { ok: true, content: replaceLines(i, r), mode: exact ? "exato" : "espaços no fim" };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// 2) trecho no meio de uma linha: substring exata
|
|
99
|
+
const at = countOccurrences(content, search);
|
|
100
|
+
if (at.length > 1) return { ok: false, reason: AMBIGUOUS(at.length) };
|
|
101
|
+
if (at.length === 1) {
|
|
102
|
+
return { ok: true, content: content.slice(0, at[0]) + replace + content.slice(at[0] + search.length), mode: "exato" };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// 3) ignorando indentação, e reindentando o REPLACE para o nível encontrado
|
|
106
|
+
const loose = findLineMatches(lines, s, (a, b) => a.trim() === b.trim());
|
|
107
|
+
if (loose.length > 1) return { ok: false, reason: AMBIGUOUS(loose.length) };
|
|
108
|
+
if (loose.length === 1) {
|
|
109
|
+
const i = loose[0];
|
|
110
|
+
const k = s.findIndex((l) => l.trim() !== "");
|
|
111
|
+
return { ok: true, content: replaceLines(i, reindent(r, leading(s[k]), leading(lines[i + k]))), mode: "indentação" };
|
|
112
|
+
}
|
|
113
|
+
return { ok: false, reason: "o trecho do SEARCH não foi encontrado no arquivo atual" };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ---------------------------------------------------------------- caminhos
|
|
117
|
+
|
|
118
|
+
export function checkPath(rel: string, protectedDirs: string[]): string | null {
|
|
119
|
+
const p = toPosix(rel);
|
|
120
|
+
if (!p) return "caminho vazio";
|
|
121
|
+
if (p.startsWith("/") || /^[a-zA-Z]:/.test(p)) return "caminho absoluto não é permitido";
|
|
122
|
+
const norm = path.posix.normalize(p);
|
|
123
|
+
if (norm === ".." || norm.startsWith("../")) return "caminho sai da raiz do repositório";
|
|
124
|
+
const parts = norm.split("/");
|
|
125
|
+
if (parts.includes(".git")) return "não mexo dentro de .git";
|
|
126
|
+
for (const d of protectedDirs) {
|
|
127
|
+
if (norm === d || norm.startsWith(d + "/")) return `não mexo dentro de ${d}`;
|
|
128
|
+
}
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// ---------------------------------------------------------------- plano
|
|
133
|
+
|
|
134
|
+
interface FileState {
|
|
135
|
+
/** conteúdo atual na simulação (LF); null = não existe */
|
|
136
|
+
content: string | null;
|
|
137
|
+
original: string | null;
|
|
138
|
+
eol: "\n" | "\r\n";
|
|
139
|
+
bom: boolean;
|
|
140
|
+
/** a última escrita veio de um FILE/EDIT do modelo externo (ele conhece este conteúdo) */
|
|
141
|
+
touched: boolean;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface OpFailure {
|
|
145
|
+
op: Op;
|
|
146
|
+
path: string;
|
|
147
|
+
message: string;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface Change {
|
|
151
|
+
path: string;
|
|
152
|
+
kind: "criar" | "alterar" | "apagar";
|
|
153
|
+
before: string | null;
|
|
154
|
+
after: string | null;
|
|
155
|
+
eol: "\n" | "\r\n";
|
|
156
|
+
bom: boolean;
|
|
157
|
+
/** descrição curta para o resumo (ex.: "2 trechos", "reescrito") */
|
|
158
|
+
note: string;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export interface Plan {
|
|
162
|
+
changes: Change[];
|
|
163
|
+
failures: OpFailure[];
|
|
164
|
+
/** caminhos com alguma falha: nada deles é gravado no modo parcial */
|
|
165
|
+
failedPaths: Set<string>;
|
|
166
|
+
/** observações não fatais (ex.: casou ignorando indentação) */
|
|
167
|
+
notes: string[];
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function describeOp(op: Op): string {
|
|
171
|
+
switch (op.kind) {
|
|
172
|
+
case "file":
|
|
173
|
+
return `FILE ${op.path}`;
|
|
174
|
+
case "edit":
|
|
175
|
+
return `EDIT ${op.path}`;
|
|
176
|
+
case "delete":
|
|
177
|
+
return `DELETE ${op.path}`;
|
|
178
|
+
case "move":
|
|
179
|
+
return `MOVE ${op.from} -> ${op.to}`;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export async function planOps(root: string, ops: Op[], protectedDirs: string[] = []): Promise<Plan> {
|
|
184
|
+
const state = new Map<string, FileState>();
|
|
185
|
+
const failures: OpFailure[] = [];
|
|
186
|
+
const failedPaths = new Set<string>();
|
|
187
|
+
const notes: string[] = [];
|
|
188
|
+
const editCount = new Map<string, number>();
|
|
189
|
+
const rewritten = new Set<string>();
|
|
190
|
+
|
|
191
|
+
async function get(rel: string): Promise<FileState | { error: string }> {
|
|
192
|
+
const cached = state.get(rel);
|
|
193
|
+
if (cached) return cached;
|
|
194
|
+
const r = await readText(path.join(root, rel));
|
|
195
|
+
let st: FileState;
|
|
196
|
+
if (r.ok) st = { content: r.text, original: r.text, eol: r.eol, bom: r.bom, touched: false };
|
|
197
|
+
else if (r.reason === "não encontrado") st = { content: null, original: null, eol: "\n", bom: false, touched: false };
|
|
198
|
+
else return { error: `não consigo editar este arquivo (${r.reason})` };
|
|
199
|
+
state.set(rel, st);
|
|
200
|
+
return st;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const fail = (op: Op, p: string, message: string) => {
|
|
204
|
+
failures.push({ op, path: p, message });
|
|
205
|
+
failedPaths.add(p);
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
for (const op of ops) {
|
|
209
|
+
const paths = op.kind === "move" ? [op.from, op.to] : [op.path];
|
|
210
|
+
const bad = paths.map((p) => [p, checkPath(p, protectedDirs)] as const).find(([, e]) => e);
|
|
211
|
+
if (bad) {
|
|
212
|
+
fail(op, bad[0], bad[1]!);
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const norm = paths.map((p) => path.posix.normalize(toPosix(p)));
|
|
216
|
+
const blocked = norm.find((p) => failedPaths.has(p));
|
|
217
|
+
if (blocked) {
|
|
218
|
+
fail(op, blocked, "ignorado porque uma alteração anterior neste arquivo falhou");
|
|
219
|
+
for (const p of norm) failedPaths.add(p);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (op.kind === "move") {
|
|
224
|
+
const [from, to] = norm;
|
|
225
|
+
const a = await get(from);
|
|
226
|
+
const b = await get(to);
|
|
227
|
+
if ("error" in a) { fail(op, from, a.error); continue; }
|
|
228
|
+
if ("error" in b) { fail(op, to, b.error); continue; }
|
|
229
|
+
if (a.content === null) { fail(op, from, "arquivo de origem não existe"); failedPaths.add(to); continue; }
|
|
230
|
+
if (b.content !== null) { fail(op, to, "o destino já existe"); failedPaths.add(from); continue; }
|
|
231
|
+
b.content = a.content;
|
|
232
|
+
b.eol = a.eol;
|
|
233
|
+
b.bom = a.bom;
|
|
234
|
+
b.touched = a.touched;
|
|
235
|
+
a.content = null;
|
|
236
|
+
a.touched = false;
|
|
237
|
+
notes.push(`${from} → ${to}`);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const p = norm[0];
|
|
242
|
+
const st = await get(p);
|
|
243
|
+
if ("error" in st) { fail(op, p, st.error); continue; }
|
|
244
|
+
|
|
245
|
+
if (op.kind === "delete") {
|
|
246
|
+
if (st.content === null) { fail(op, p, "arquivo não existe"); continue; }
|
|
247
|
+
st.content = null;
|
|
248
|
+
st.touched = false;
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (op.kind === "file") {
|
|
253
|
+
st.content = op.content === "" || op.content.endsWith("\n") ? op.content : op.content + "\n";
|
|
254
|
+
st.touched = true;
|
|
255
|
+
rewritten.add(p);
|
|
256
|
+
if (/^\s*(\/\/|#|<!--|\/\*)?\s*\.\.\.\s*(resto|rest|restante|existing|código|code)/im.test(op.content)) {
|
|
257
|
+
notes.push(`${p}: o conteúdo parece ter um trecho omitido ("..."). Confira antes de seguir.`);
|
|
258
|
+
}
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// edit
|
|
263
|
+
if (st.content === null) { fail(op, p, "arquivo não existe (para criar, use FILE)"); continue; }
|
|
264
|
+
let current = st.content;
|
|
265
|
+
let failed = false;
|
|
266
|
+
for (let k = 0; k < op.pairs.length; k++) {
|
|
267
|
+
const res = applySearchReplace(current, op.pairs[k]);
|
|
268
|
+
if (!res.ok) {
|
|
269
|
+
fail(op, p, `par ${k + 1} de ${op.pairs.length}: ${res.reason}`);
|
|
270
|
+
failed = true;
|
|
271
|
+
break;
|
|
272
|
+
}
|
|
273
|
+
if (res.mode !== "exato") notes.push(`${p}, par ${k + 1}: casou ignorando ${res.mode}`);
|
|
274
|
+
current = res.content;
|
|
275
|
+
}
|
|
276
|
+
if (failed) continue;
|
|
277
|
+
st.content = current;
|
|
278
|
+
st.touched = true;
|
|
279
|
+
editCount.set(p, (editCount.get(p) ?? 0) + op.pairs.length);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const changes: Change[] = [];
|
|
283
|
+
for (const [p, st] of [...state.entries()].sort(([a], [b]) => byPath(a, b))) {
|
|
284
|
+
if (st.content === st.original) continue;
|
|
285
|
+
const kind = st.original === null ? "criar" : st.content === null ? "apagar" : "alterar";
|
|
286
|
+
const n = editCount.get(p);
|
|
287
|
+
const note =
|
|
288
|
+
kind === "apagar" ? "" : rewritten.has(p) ? (kind === "criar" ? "novo" : "reescrito") : n ? `${n} trecho(s)` : "movido";
|
|
289
|
+
changes.push({ path: p, kind, before: st.original, after: st.content, eol: st.eol, bom: st.bom, note });
|
|
290
|
+
}
|
|
291
|
+
return { changes, failures, failedPaths, notes };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// ---------------------------------------------------------------- gravação e desfazer
|
|
295
|
+
|
|
296
|
+
export interface BackupInfo {
|
|
297
|
+
dir: string;
|
|
298
|
+
created: string[];
|
|
299
|
+
modified: string[];
|
|
300
|
+
deleted: string[];
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function encode(content: string, eol: "\n" | "\r\n", bom: boolean): string {
|
|
304
|
+
const body = eol === "\r\n" ? content.replace(/\n/g, "\r\n") : content;
|
|
305
|
+
return bom ? "" + body : body;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export async function writeChanges(root: string, backupsAbs: string, changes: Change[]): Promise<BackupInfo> {
|
|
309
|
+
const id = new Date().toISOString().replace(/[:.]/g, "-");
|
|
310
|
+
const dir = path.join(backupsAbs, id);
|
|
311
|
+
const info: BackupInfo = { dir, created: [], modified: [], deleted: [] };
|
|
312
|
+
await fs.mkdir(path.join(dir, "files"), { recursive: true });
|
|
313
|
+
|
|
314
|
+
// backup primeiro, de tudo; só depois escreve
|
|
315
|
+
for (const c of changes) {
|
|
316
|
+
if (c.before === null) continue;
|
|
317
|
+
const dest = path.join(dir, "files", c.path);
|
|
318
|
+
await fs.mkdir(path.dirname(dest), { recursive: true });
|
|
319
|
+
await fs.copyFile(path.join(root, c.path), dest);
|
|
320
|
+
}
|
|
321
|
+
for (const c of changes) {
|
|
322
|
+
const abs = path.join(root, c.path);
|
|
323
|
+
if (c.after === null) {
|
|
324
|
+
await fs.rm(abs, { force: true });
|
|
325
|
+
info.deleted.push(c.path);
|
|
326
|
+
} else {
|
|
327
|
+
await fs.mkdir(path.dirname(abs), { recursive: true });
|
|
328
|
+
await fs.writeFile(abs, encode(c.after, c.eol, c.bom), "utf8");
|
|
329
|
+
(c.before === null ? info.created : info.modified).push(c.path);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
await fs.writeFile(
|
|
333
|
+
path.join(dir, "backup.json"),
|
|
334
|
+
JSON.stringify({ created: info.created, modified: info.modified, deleted: info.deleted }, null, 2),
|
|
335
|
+
);
|
|
336
|
+
return info;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Desfaz a última aplicação. Devolve null se não houver backup. */
|
|
340
|
+
export async function undoLast(root: string, backupsAbs: string): Promise<BackupInfo | null> {
|
|
341
|
+
let entries: string[];
|
|
342
|
+
try {
|
|
343
|
+
entries = (await fs.readdir(backupsAbs)).sort();
|
|
344
|
+
} catch {
|
|
345
|
+
return null;
|
|
346
|
+
}
|
|
347
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
348
|
+
const dir = path.join(backupsAbs, entries[i]);
|
|
349
|
+
let meta: { created: string[]; modified: string[]; deleted: string[] };
|
|
350
|
+
try {
|
|
351
|
+
meta = JSON.parse(await fs.readFile(path.join(dir, "backup.json"), "utf8"));
|
|
352
|
+
} catch {
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
for (const p of meta.created) await fs.rm(path.join(root, p), { force: true });
|
|
356
|
+
for (const p of [...meta.modified, ...meta.deleted]) {
|
|
357
|
+
const dest = path.join(root, p);
|
|
358
|
+
await fs.mkdir(path.dirname(dest), { recursive: true });
|
|
359
|
+
await fs.copyFile(path.join(dir, "files", p), dest);
|
|
360
|
+
}
|
|
361
|
+
await fs.rm(dir, { recursive: true, force: true });
|
|
362
|
+
return { dir, ...meta };
|
|
363
|
+
}
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// ---------------------------------------------------------------- relatórios
|
|
368
|
+
|
|
369
|
+
export function summarize(plan: Plan, onlyOk = false): string {
|
|
370
|
+
const lines: string[] = [];
|
|
371
|
+
const sign = { criar: "+", alterar: "~", apagar: "-" } as const;
|
|
372
|
+
for (const c of plan.changes) {
|
|
373
|
+
if (onlyOk && plan.failedPaths.has(c.path)) continue;
|
|
374
|
+
lines.push(`${sign[c.kind]} ${c.path}${c.note ? ` (${c.note})` : ""}`);
|
|
375
|
+
}
|
|
376
|
+
if (plan.failures.length) {
|
|
377
|
+
lines.push("", "Falhas:");
|
|
378
|
+
for (const f of plan.failures) lines.push(`✗ ${describeOp(f.op)}: ${f.message}`);
|
|
379
|
+
}
|
|
380
|
+
if (plan.notes.length) {
|
|
381
|
+
lines.push("", "Observações:");
|
|
382
|
+
for (const n of plan.notes) lines.push(`• ${n}`);
|
|
383
|
+
}
|
|
384
|
+
return lines.join("\n");
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Texto para colar de volta no chat externo quando algo falha. */
|
|
388
|
+
export async function errorReport(
|
|
389
|
+
root: string,
|
|
390
|
+
plan: Plan,
|
|
391
|
+
applied: string[],
|
|
392
|
+
parseIssues: string[] = [],
|
|
393
|
+
maxFileChars = 60_000,
|
|
394
|
+
): Promise<string> {
|
|
395
|
+
const out = [errorReportHeader(applied)];
|
|
396
|
+
for (const f of plan.failures) out.push(`- ${describeOp(f.op)} (linha ${f.op.line} da resposta): ${f.message}`);
|
|
397
|
+
for (const issue of parseIssues) out.push(`- ${issue}`);
|
|
398
|
+
if (!plan.failures.length) return out.join("\n");
|
|
399
|
+
out.push("", "## Conteúdo atual dos arquivos envolvidos", "");
|
|
400
|
+
const seen = new Set<string>();
|
|
401
|
+
for (const f of plan.failures) {
|
|
402
|
+
if (seen.has(f.path)) continue;
|
|
403
|
+
seen.add(f.path);
|
|
404
|
+
const r = await readText(path.join(root, f.path));
|
|
405
|
+
if (!r.ok) {
|
|
406
|
+
out.push(`${f.path}: ${r.reason}`, "");
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
if (r.text.length > maxFileChars) {
|
|
410
|
+
out.push(`${f.path}: arquivo grande (${r.text.length} caracteres); conteúdo não incluído.`, "");
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
const fence = fenceFor(r.text);
|
|
414
|
+
out.push(`FILE: ${f.path}`, `${fence}${langFor(f.path)}`, r.text.replace(/\n$/, ""), fence, "");
|
|
415
|
+
}
|
|
416
|
+
return out.join("\n");
|
|
417
|
+
}
|