@lincolness/ponte 0.0.0-stage → 0.2.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/src/pack.ts ADDED
@@ -0,0 +1,228 @@
1
+ // Geração do pacote (repo inteiro num arquivo), do delta e do manifesto de hashes.
2
+
3
+ import { createHash } from "node:crypto";
4
+ import { promises as fs } from "node:fs";
5
+ import path from "node:path";
6
+ import { byPath, listFiles, readText, type PonteConfig } from "./files.ts";
7
+ import { deltaHeader, packHeader, partHeader } from "./prompt.ts";
8
+
9
+ export interface PackedFile {
10
+ path: string;
11
+ content: string;
12
+ hash: string;
13
+ }
14
+
15
+ export interface Omitted {
16
+ path: string;
17
+ reason: string;
18
+ }
19
+
20
+ export interface Manifest {
21
+ version: 1;
22
+ createdAt: string;
23
+ filters: string[];
24
+ files: Record<string, string>;
25
+ }
26
+
27
+ export const MANIFEST = "manifest.json";
28
+
29
+ export function hashText(text: string): string {
30
+ return createHash("sha1").update(text).digest("hex");
31
+ }
32
+
33
+ export function approxTokens(chars: number): number {
34
+ return Math.round(chars / 4);
35
+ }
36
+
37
+ export async function collect(
38
+ root: string,
39
+ cfg: PonteConfig,
40
+ filters: string[] = [],
41
+ ): Promise<{ files: PackedFile[]; omitted: Omitted[] }> {
42
+ const paths = await listFiles(root, cfg, { only: filters });
43
+ const files: PackedFile[] = [];
44
+ const omitted: Omitted[] = [];
45
+ for (const p of paths) {
46
+ const r = await readText(path.join(root, p), cfg.maxFileKB * 1024);
47
+ if (r.ok) files.push({ path: p, content: r.text, hash: hashText(r.text) });
48
+ else if (r.reason !== "não encontrado") omitted.push({ path: p, reason: r.reason });
49
+ }
50
+ return { files, omitted };
51
+ }
52
+
53
+ const LANG: Record<string, string> = {
54
+ ts: "ts", tsx: "tsx", js: "js", jsx: "jsx", mjs: "js", cjs: "js",
55
+ py: "python", ipynb: "json", r: "r", R: "r", jl: "julia",
56
+ java: "java", kt: "kotlin", scala: "scala", groovy: "groovy",
57
+ cs: "csharp", fs: "fsharp", vb: "vb", go: "go", rs: "rust", rb: "ruby", php: "php",
58
+ c: "c", h: "c", cpp: "cpp", hpp: "cpp", cc: "cpp", swift: "swift", m: "objc",
59
+ sql: "sql", sh: "bash", bash: "bash", zsh: "bash", ps1: "powershell", bat: "bat", cmd: "bat",
60
+ yml: "yaml", yaml: "yaml", json: "json", toml: "toml", ini: "ini", cfg: "ini", xml: "xml",
61
+ html: "html", htm: "html", css: "css", scss: "scss", less: "less", vue: "vue", svelte: "svelte",
62
+ md: "markdown", rst: "rst", tex: "latex", dockerfile: "dockerfile", tf: "hcl", proto: "proto",
63
+ };
64
+
65
+ export function langFor(p: string): string {
66
+ const base = path.posix.basename(p);
67
+ if (/^dockerfile$/i.test(base)) return "dockerfile";
68
+ if (/^makefile$/i.test(base)) return "makefile";
69
+ const ext = base.includes(".") ? base.slice(base.lastIndexOf(".") + 1) : "";
70
+ return LANG[ext] ?? LANG[ext.toLowerCase()] ?? "";
71
+ }
72
+
73
+ /** Cerca com crases suficientes para o conteúdo não fechar o bloco antes da hora. */
74
+ export function fenceFor(content: string): string {
75
+ let max = 0;
76
+ for (const m of content.matchAll(/`+/g)) max = Math.max(max, m[0].length);
77
+ return "`".repeat(Math.max(3, max + 1));
78
+ }
79
+
80
+ export function renderFileBlock(f: { path: string; content: string }): string {
81
+ const fence = fenceFor(f.content);
82
+ const body = f.content.endsWith("\n") ? f.content : f.content + "\n";
83
+ return `FILE: ${f.path}\n${fence}${langFor(f.path)}\n${body}${fence}\n`;
84
+ }
85
+
86
+ export function renderTree(paths: string[]): string {
87
+ const lines: string[] = [];
88
+ let prev: string[] = [];
89
+ for (const p of [...paths].sort(byPath)) {
90
+ const parts = p.split("/");
91
+ const dirs = parts.slice(0, -1);
92
+ let common = 0;
93
+ while (common < dirs.length && common < prev.length && dirs[common] === prev[common]) common++;
94
+ for (let i = common; i < dirs.length; i++) lines.push(`${" ".repeat(i)}${dirs[i]}/`);
95
+ lines.push(`${" ".repeat(dirs.length)}${parts[parts.length - 1]}`);
96
+ prev = dirs;
97
+ }
98
+ return lines.join("\n");
99
+ }
100
+
101
+ function renderOmitted(omitted: Omitted[]): string {
102
+ if (!omitted.length) return "";
103
+ return `\n## Arquivos omitidos\n\n${omitted.map((o) => `- ${o.path} (${o.reason})`).join("\n")}\n`;
104
+ }
105
+
106
+ export interface RenderPackOptions {
107
+ repoName: string;
108
+ files: PackedFile[];
109
+ omitted: Omitted[];
110
+ filters: string[];
111
+ date: string;
112
+ /** 0 = sem divisão */
113
+ maxPartChars: number;
114
+ }
115
+
116
+ /** Devolve uma ou mais partes de texto. */
117
+ export function renderPack(o: RenderPackOptions): string[] {
118
+ const blocks = o.files.map(renderFileBlock);
119
+ const tree = `## Estrutura\n\n\`\`\`\n${renderTree(o.files.map((f) => f.path))}\n\`\`\`\n${renderOmitted(o.omitted)}\n## Arquivos\n\n`;
120
+ const bodyChars = blocks.reduce((n, b) => n + b.length + 1, 0) + tree.length;
121
+ const header = (part?: { index: number; total: number }) => {
122
+ const make = (tokens: number) =>
123
+ packHeader({
124
+ repoName: o.repoName,
125
+ date: o.date,
126
+ fileCount: o.files.length,
127
+ approxTokens: tokens,
128
+ filters: o.filters,
129
+ part,
130
+ }) + "\n";
131
+ // conta o próprio cabeçalho (instruções) no total
132
+ return make(approxTokens(bodyChars + make(0).length));
133
+ };
134
+
135
+ const single = header() + tree + blocks.join("\n");
136
+ if (!o.maxPartChars || single.length <= o.maxPartChars) return [single];
137
+
138
+ // Agrupa arquivos inteiros em partes; um arquivo maior que o limite fica sozinho numa parte.
139
+ const groups: string[][] = [];
140
+ let current: string[] = [];
141
+ let size = header({ index: 1, total: 9 }).length + tree.length;
142
+ for (const b of blocks) {
143
+ if (current.length && size + b.length > o.maxPartChars) {
144
+ groups.push(current);
145
+ current = [];
146
+ size = partHeader(o.repoName, 9, 9).length;
147
+ }
148
+ current.push(b);
149
+ size += b.length + 1;
150
+ }
151
+ if (current.length) groups.push(current);
152
+ const total = groups.length;
153
+ return groups.map((g, i) =>
154
+ i === 0
155
+ ? header({ index: 1, total }) + tree + g.join("\n")
156
+ : partHeader(o.repoName, i + 1, total) + "\n" + g.join("\n"),
157
+ );
158
+ }
159
+
160
+ export interface Delta {
161
+ changed: PackedFile[];
162
+ added: string[];
163
+ modified: string[];
164
+ deleted: string[];
165
+ }
166
+
167
+ export function computeDelta(manifest: Manifest, files: PackedFile[]): Delta {
168
+ const now = new Map(files.map((f) => [f.path, f]));
169
+ const added: string[] = [];
170
+ const modified: string[] = [];
171
+ const changed: PackedFile[] = [];
172
+ for (const f of files) {
173
+ const before = manifest.files[f.path];
174
+ if (before === undefined) added.push(f.path);
175
+ else if (before !== f.hash) modified.push(f.path);
176
+ else continue;
177
+ changed.push(f);
178
+ }
179
+ const deleted = Object.keys(manifest.files).filter((p) => !now.has(p)).sort();
180
+ return { changed, added, modified, deleted };
181
+ }
182
+
183
+ export function renderDelta(repoName: string, date: string, d: Delta): string {
184
+ return (
185
+ deltaHeader({ repoName, date, changed: d.changed.length, deleted: d.deleted }) +
186
+ "\n" +
187
+ d.changed.map(renderFileBlock).join("\n")
188
+ );
189
+ }
190
+
191
+ export function makeManifest(files: PackedFile[], filters: string[], date: string): Manifest {
192
+ return {
193
+ version: 1,
194
+ createdAt: date,
195
+ filters,
196
+ files: Object.fromEntries(files.map((f) => [f.path, f.hash])),
197
+ };
198
+ }
199
+
200
+ export async function readManifest(outAbs: string): Promise<Manifest | null> {
201
+ try {
202
+ const m = JSON.parse(await fs.readFile(path.join(outAbs, MANIFEST), "utf8")) as Manifest;
203
+ return m && m.files ? m : null;
204
+ } catch {
205
+ return null;
206
+ }
207
+ }
208
+
209
+ export async function writeManifest(outAbs: string, m: Manifest): Promise<void> {
210
+ await ensureOutDir(outAbs);
211
+ await fs.writeFile(path.join(outAbs, MANIFEST), JSON.stringify(m, null, 2), "utf8");
212
+ }
213
+
214
+ /** Cria a pasta de saída com um .gitignore que ignora tudo dentro dela. */
215
+ export async function ensureOutDir(outAbs: string): Promise<void> {
216
+ await fs.mkdir(outAbs, { recursive: true });
217
+ const gi = path.join(outAbs, ".gitignore");
218
+ try {
219
+ await fs.access(gi);
220
+ } catch {
221
+ await fs.writeFile(gi, "*\n", "utf8");
222
+ }
223
+ }
224
+
225
+ export function stamp(d = new Date()): string {
226
+ const pad = (n: number) => String(n).padStart(2, "0");
227
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
228
+ }
package/src/parse.ts ADDED
@@ -0,0 +1,247 @@
1
+ // Leitura da resposta do modelo externo: blocos FILE / EDIT / DELETE / MOVE.
2
+
3
+ export interface EditPair {
4
+ search: string;
5
+ replace: string;
6
+ }
7
+
8
+ export type Op =
9
+ | { kind: "file"; path: string; content: string; line: number }
10
+ | { kind: "edit"; path: string; pairs: EditPair[]; line: number }
11
+ | { kind: "delete"; path: string; line: number }
12
+ | { kind: "move"; from: string; to: string; line: number };
13
+
14
+ export interface ParseIssue {
15
+ line: number;
16
+ message: string;
17
+ }
18
+
19
+ export interface ParseResult {
20
+ ops: Op[];
21
+ issues: ParseIssue[];
22
+ }
23
+
24
+ const KEYWORDS: Record<string, Op["kind"]> = {
25
+ FILE: "file",
26
+ ARQUIVO: "file",
27
+ EDIT: "edit",
28
+ EDITAR: "edit",
29
+ DELETE: "delete",
30
+ APAGAR: "delete",
31
+ REMOVER: "delete",
32
+ MOVE: "move",
33
+ RENAME: "move",
34
+ MOVER: "move",
35
+ };
36
+
37
+ // Aceita enfeites que os chats costumam pôr: "### FILE: x", "**FILE:** `x`", "- FILE: x", "> FILE: x".
38
+ const HEADER = new RegExp(
39
+ String.raw`^[\s>#*_\-]*(` + Object.keys(KEYWORDS).join("|") + String.raw`)\b[*_]*\s*:\s*[*_]*\s*(.+?)\s*$`,
40
+ // sem flag "i": "File: x" em prosa não deve virar operação
41
+ );
42
+ const FENCE_OPEN = /^(\s*)(`{3,}|~{3,})(.*)$/;
43
+ const SEARCH = /^\s*<{5,}\s*SEARCH\b.*$/;
44
+ const DIVIDER = /^\s*={5,}\s*$/;
45
+ const REPLACE = /^\s*>{5,}\s*REPLACE\b.*$/;
46
+
47
+ export function cleanPath(raw: string): string {
48
+ let p = raw.trim();
49
+ // tira enfeites em volta: `x`, **x**, "x", 'x', (x)
50
+ for (let i = 0; i < 3; i++) p = p.replace(/^[`*_"'(]+|[`*_"'):]+$/g, "").trim();
51
+ p = p.replace(/\\/g, "/");
52
+ if (p.startsWith("@")) p = p.slice(1);
53
+ while (p.startsWith("./")) p = p.slice(2);
54
+ return p;
55
+ }
56
+
57
+ function isFenceClose(line: string, fence: string): boolean {
58
+ const ch = fence[0];
59
+ const t = line.trim();
60
+ return t.length >= fence.length && t.split("").every((c) => c === ch);
61
+ }
62
+
63
+ function stripIndent(line: string, indent: string): string {
64
+ return indent && line.startsWith(indent) ? line.slice(indent.length) : line;
65
+ }
66
+
67
+ /** Normaliza o que costuma vir estranho ao copiar do chat. */
68
+ export function normalizeText(text: string): string {
69
+ return text
70
+ .replace(/\r\n?/g, "\n")
71
+ .replace(/ /g, " ")
72
+ .replace(/[​‌‍]/g, "");
73
+ }
74
+
75
+ export function parseResponse(input: string): ParseResult {
76
+ const lines = normalizeText(input).split("\n");
77
+ const ops: Op[] = [];
78
+ const issues: ParseIssue[] = [];
79
+ const looseBlocks: string[] = [];
80
+ let i = 0;
81
+
82
+ const nextNonBlank = (from: number) => {
83
+ let j = from;
84
+ while (j < lines.length && lines[j].trim() === "") j++;
85
+ return j;
86
+ };
87
+
88
+ while (i < lines.length) {
89
+ const line = lines[i];
90
+ const header = HEADER.exec(line);
91
+
92
+ if (!header) {
93
+ // Bloco de código solto (exemplo, comando, explicação): pula inteiro.
94
+ const open = FENCE_OPEN.exec(line);
95
+ if (open) {
96
+ const fence = open[2];
97
+ const inner: string[] = [];
98
+ i++;
99
+ while (i < lines.length && !isFenceClose(lines[i], fence)) inner.push(stripIndent(lines[i++], open[1]));
100
+ looseBlocks.push(inner.join("\n"));
101
+ }
102
+ i++;
103
+ continue;
104
+ }
105
+
106
+ const kind = KEYWORDS[header[1].toUpperCase()];
107
+ const lineNo = i + 1;
108
+ const target = header[2];
109
+ i++;
110
+
111
+ if (kind === "delete") {
112
+ const p = cleanPath(target);
113
+ if (p) ops.push({ kind: "delete", path: p, line: lineNo });
114
+ else issues.push({ line: lineNo, message: "DELETE sem caminho" });
115
+ continue;
116
+ }
117
+
118
+ if (kind === "move") {
119
+ const m = /^(.+?)\s*(?:->|=>|→|\s+to\s+|\s+para\s+)\s*(.+)$/.exec(target);
120
+ if (!m) {
121
+ issues.push({ line: lineNo, message: `MOVE sem "antigo -> novo": ${target}` });
122
+ continue;
123
+ }
124
+ ops.push({ kind: "move", from: cleanPath(m[1]), to: cleanPath(m[2]), line: lineNo });
125
+ continue;
126
+ }
127
+
128
+ const p = cleanPath(target);
129
+ const j = nextNonBlank(i);
130
+ const open = j < lines.length ? FENCE_OPEN.exec(lines[j]) : null;
131
+
132
+ if (kind === "edit") {
133
+ if (!open && j < lines.length && SEARCH.test(lines[j])) {
134
+ // EDIT sem cerca: lê pares até acabar a sequência.
135
+ const r = readPairs(lines, j, null, "");
136
+ i = r.end;
137
+ if (r.error) issues.push({ line: lineNo, message: `EDIT ${p}: ${r.error}` });
138
+ else if (!r.pairs.length) issues.push({ line: lineNo, message: `EDIT ${p}: nenhum par SEARCH/REPLACE` });
139
+ else ops.push({ kind: "edit", path: p, pairs: r.pairs, line: lineNo });
140
+ continue;
141
+ }
142
+ if (!open) {
143
+ issues.push({ line: lineNo, message: `EDIT ${p}: esperava um bloco de código logo depois` });
144
+ continue;
145
+ }
146
+ const r = readPairs(lines, j + 1, open[2], open[1]);
147
+ i = r.end;
148
+ if (r.error) issues.push({ line: lineNo, message: `EDIT ${p}: ${r.error}` });
149
+ else if (!r.pairs.length) issues.push({ line: lineNo, message: `EDIT ${p}: nenhum par SEARCH/REPLACE` });
150
+ else ops.push({ kind: "edit", path: p, pairs: r.pairs, line: lineNo });
151
+ continue;
152
+ }
153
+
154
+ // FILE
155
+ if (!open) {
156
+ issues.push({ line: lineNo, message: `FILE ${p}: esperava um bloco de código logo depois` });
157
+ continue;
158
+ }
159
+ const fence = open[2];
160
+ const indent = open[1];
161
+ const body: string[] = [];
162
+ let k = j + 1;
163
+ while (k < lines.length && !isFenceClose(lines[k], fence)) {
164
+ body.push(stripIndent(lines[k], indent));
165
+ k++;
166
+ }
167
+ if (k >= lines.length) {
168
+ issues.push({ line: lineNo, message: `FILE ${p}: bloco de código não foi fechado` });
169
+ i = k;
170
+ continue;
171
+ }
172
+ i = k + 1;
173
+ if (!p) {
174
+ issues.push({ line: lineNo, message: "FILE sem caminho" });
175
+ continue;
176
+ }
177
+ ops.push({ kind: "file", path: p, content: body.join("\n"), line: lineNo });
178
+ }
179
+
180
+ // Resposta inteira embrulhada num bloco de código (ex.: ````text ... ````): procura dentro.
181
+ if (!ops.length && !issues.length) {
182
+ for (const block of looseBlocks) {
183
+ if (!looksLikePonteResponse(block)) continue;
184
+ const inner = parseResponse(block);
185
+ ops.push(...inner.ops);
186
+ issues.push(...inner.issues);
187
+ }
188
+ }
189
+
190
+ return { ops, issues };
191
+ }
192
+
193
+ /**
194
+ * Lê pares SEARCH/REPLACE. Dentro de um par, uma linha de cerca é conteúdo, não fechamento
195
+ * (assim o bloco sobrevive mesmo se o trecho tiver ```).
196
+ */
197
+ function readPairs(
198
+ lines: string[],
199
+ start: number,
200
+ fence: string | null,
201
+ indent: string,
202
+ ): { pairs: EditPair[]; end: number; error?: string } {
203
+ const pairs: EditPair[] = [];
204
+ let state: "out" | "search" | "replace" = "out";
205
+ let search: string[] = [];
206
+ let replace: string[] = [];
207
+ let k = start;
208
+ for (; k < lines.length; k++) {
209
+ const raw = lines[k];
210
+ const line = stripIndent(raw, indent);
211
+ if (state === "out") {
212
+ if (fence && isFenceClose(raw, fence)) return { pairs, end: k + 1 };
213
+ if (SEARCH.test(line)) {
214
+ state = "search";
215
+ search = [];
216
+ replace = [];
217
+ continue;
218
+ }
219
+ if (!fence) {
220
+ // sem cerca: termina na primeira linha que não seja branca nem início de par
221
+ if (line.trim() === "") continue;
222
+ return { pairs, end: k };
223
+ }
224
+ continue; // texto solto dentro da cerca (ex.: o caminho repetido): ignora
225
+ }
226
+ if (state === "search") {
227
+ if (DIVIDER.test(line)) state = "replace";
228
+ else if (REPLACE.test(line)) return { pairs, end: k + 1, error: `par ${pairs.length + 1} sem a linha =======` };
229
+ else search.push(line);
230
+ continue;
231
+ }
232
+ // replace
233
+ if (REPLACE.test(line)) {
234
+ pairs.push({ search: search.join("\n"), replace: replace.join("\n") });
235
+ state = "out";
236
+ } else {
237
+ replace.push(line);
238
+ }
239
+ }
240
+ if (state !== "out") return { pairs, end: k, error: `par ${pairs.length + 1} sem >>>>>>> REPLACE` };
241
+ if (fence) return { pairs, end: k, error: "bloco de código não foi fechado" };
242
+ return { pairs, end: k };
243
+ }
244
+
245
+ export function looksLikePonteResponse(text: string): boolean {
246
+ return /^[\s>#*_\-]*(FILE|EDIT|DELETE|MOVE)\b[*_]*\s*:/m.test(text);
247
+ }
package/src/prompt.ts ADDED
@@ -0,0 +1,116 @@
1
+ // Textos enviados ao modelo externo (Copilot, ChatGPT etc.).
2
+
3
+ export const FORMAT_INSTRUCTIONS = `## Como responder com alterações de código
4
+
5
+ Uma ferramenta aplica a sua resposta automaticamente no repositório. Para isso, escreva cada alteração num dos quatro tipos de bloco do exemplo abaixo (o exemplo está entre linhas ~~~~~ só para não ser confundido com uma alteração de verdade; na sua resposta, não use as linhas ~~~~~). As palavras-chave FILE, EDIT, DELETE e MOVE ficam em inglês, no início da linha, seguidas do caminho relativo à raiz exatamente como aparece no pacote.
6
+
7
+ ~~~~~text
8
+ FILE: caminho/arquivo-novo-ou-reescrito.ext
9
+ \`\`\`linguagem
10
+ conteúdo completo do arquivo
11
+ \`\`\`
12
+
13
+ EDIT: caminho/arquivo-alterado.ext
14
+ \`\`\`
15
+ <<<<<<< SEARCH
16
+ linhas copiadas exatamente do arquivo atual
17
+ =======
18
+ linhas novas
19
+ >>>>>>> REPLACE
20
+ <<<<<<< SEARCH
21
+ outro trecho do mesmo arquivo
22
+ =======
23
+ substituto
24
+ >>>>>>> REPLACE
25
+ \`\`\`
26
+
27
+ DELETE: caminho/arquivo-removido.ext
28
+
29
+ MOVE: caminho/antigo.ext -> caminho/novo.ext
30
+ ~~~~~
31
+
32
+ - FILE cria um arquivo ou o reescreve por inteiro.
33
+ - EDIT troca trechos; prefira EDIT em arquivos grandes. Um bloco EDIT pode ter vários pares SEARCH/REPLACE.
34
+ - DELETE remove o arquivo.
35
+ - MOVE renomeia ou move mantendo o conteúdo; para mudar também o conteúdo, use FILE ou EDIT no caminho novo depois do MOVE.
36
+
37
+ Regras:
38
+ - O texto de cada SEARCH precisa aparecer uma única vez no arquivo. Copie as linhas como estão, com a mesma indentação, e inclua linhas vizinhas suficientes para não haver ambiguidade.
39
+ - Mantenha os SEARCH curtos: as linhas que mudam e um pouco de contexto. Para apagar um trecho, deixe o REPLACE vazio.
40
+ - Os pares de um mesmo arquivo são aplicados em ordem, de cima para baixo, cada um sobre o resultado do anterior.
41
+ - Se o conteúdo tiver \`\`\`, abra e feche o bloco com mais crases (\`\`\`\`).
42
+ - Dentro de FILE nunca use "...", "resto igual" ou omissões: o arquivo é gravado exatamente como está no bloco.
43
+ - Explicações podem ir fora dos blocos, antes ou depois.
44
+ `;
45
+
46
+ export function packHeader(opts: {
47
+ repoName: string;
48
+ date: string;
49
+ fileCount: number;
50
+ approxTokens: number;
51
+ filters: string[];
52
+ part?: { index: number; total: number };
53
+ }): string {
54
+ const lines = [
55
+ `# Pacote do repositório: ${opts.repoName}`,
56
+ "",
57
+ `Gerado em ${opts.date}. ${opts.fileCount} arquivo(s), cerca de ${formatTokens(opts.approxTokens)} tokens.`,
58
+ ];
59
+ if (opts.filters.length) lines.push(`Recorte: só arquivos que casam com ${opts.filters.join(", ")}.`);
60
+ if (opts.part) {
61
+ lines.push(
62
+ `Este é a PARTE ${opts.part.index} de ${opts.part.total}. Espere receber todas as partes antes de responder.`,
63
+ );
64
+ }
65
+ lines.push(
66
+ "",
67
+ "Abaixo estão a estrutura e o conteúdo completo dos arquivos do repositório. Cada arquivo começa com uma linha `FILE: caminho`, seguida do conteúdo num bloco de código.",
68
+ "Use este pacote como a versão atual do código. Se eu mandar uma ATUALIZAÇÃO depois, ela substitui os arquivos correspondentes.",
69
+ "",
70
+ FORMAT_INSTRUCTIONS,
71
+ );
72
+ return lines.join("\n");
73
+ }
74
+
75
+ export function partHeader(repoName: string, index: number, total: number): string {
76
+ return `# Pacote do repositório: ${repoName} (PARTE ${index} de ${total})\n\nContinuação do pacote. As instruções de resposta estão na parte 1.\n`;
77
+ }
78
+
79
+ export function deltaHeader(opts: {
80
+ repoName: string;
81
+ date: string;
82
+ changed: number;
83
+ deleted: string[];
84
+ }): string {
85
+ const lines = [
86
+ `# ATUALIZAÇÃO do repositório: ${opts.repoName}`,
87
+ "",
88
+ `Gerada em ${opts.date}. Os ${opts.changed} arquivo(s) abaixo mudaram desde o último pacote que você recebeu.`,
89
+ "Considere estas versões como as atuais: elas substituem as anteriores. O resto do repositório continua igual.",
90
+ ];
91
+ if (opts.deleted.length) {
92
+ lines.push("", "Arquivos removidos:", ...opts.deleted.map((d) => `- ${d}`));
93
+ }
94
+ lines.push("", "Continue respondendo no mesmo formato (FILE / EDIT com SEARCH/REPLACE / DELETE / MOVE).", "");
95
+ return lines.join("\n");
96
+ }
97
+
98
+ export function errorReportHeader(applied: string[]): string {
99
+ const lines = [
100
+ "# Algumas alterações não puderam ser aplicadas",
101
+ "",
102
+ ];
103
+ if (applied.length) {
104
+ lines.push("Já foram aplicadas (não reenvie):", ...applied.map((a) => `- ${a}`), "");
105
+ }
106
+ lines.push(
107
+ "Os blocos abaixo falharam. Reenvie SOMENTE as alterações destes arquivos, no mesmo formato, com base no conteúdo atual mostrado aqui.",
108
+ "",
109
+ );
110
+ return lines.join("\n");
111
+ }
112
+
113
+ export function formatTokens(n: number): string {
114
+ if (n >= 1000) return `${(n / 1000).toFixed(n >= 10000 ? 0 : 1)}k`;
115
+ return String(n);
116
+ }