Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
B
buvard
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
PLN
buvard
Commits
d2af3b0b
Commit
d2af3b0b
authored
Nov 11, 2026
by
PLN (Algolia)
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
fix engine: prompt, local endpoint call, data and score guards, 3-round loop, line diff
parent
78edea35
Show whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
295 additions
and
2 deletions
+295
-2
fix.mjs
lib/fix.mjs
+282
-0
index.mjs
lib/index.mjs
+13
-2
No files found.
lib/fix.mjs
0 → 100644
View file @
d2af3b0b
/**
* buvard fix — the loop that turns flags into fixes, via a LOCAL model.
*
* The endpoint is local only: LM Studio's OpenAI-compatible server at
* http://127.0.0.1:1234/v1 by default (BUVARD_FIX_URL for another local
* endpoint, that is all). Text never leaves the machine.
*
* The catalog's iron rules carry over: hits are review candidates, never
* verdicts — the model proposes, the guards dispose. A suggestion survives
* only if the data guard keeps every number and name verbatim, the excerpt
* matches exactly once, and the linter itself confirms the gain (score up,
* or hits down). The loop runs at most three rounds; nothing is written by
* the engine — the CLI owns the file, and only with --write.
*/
import { lint, bodyOf } from './lint.mjs';
import { RATIONALES } from './catalog.mjs';
export const DEFAULT_URL = 'http://127.0.0.1:1234/v1';
export const DEFAULT_MODEL = 'local-model';
/** Une erreur propre pour l'humain au clavier — jamais une pile. */
export class FixError extends Error {}
const VOICE_RULE =
'Règle de voix : ces fragments sont des candidats à relecture, jamais des ' +
'verdicts — la voix de l\'auteur gagne toujours. Propose l\'édition minimale ' +
'qui préserve la voix de l\'auteur et chaque chiffre, nom et affirmation. ' +
'Si un fragment est correct tel quel, réponds KEEP pour ce fragment.';
/** Les hits budgétaires s'appellent « budget tiret cadratin (>1/600 mots) » ; on veut l'id de base. */
const baseId = (id) => (id.startsWith('budget ') ? id.slice(7).replace(/ \(.*/, '') : id);
/** Le prompt de feedback : les flags, le pourquoi de chaque règle, la règle de voix, le format. */
export function buildPrompt(text, result) {
const rules = [...new Set(result.hits.map((h) => baseId(h.id)))]
.map((id) => `- ${id} : ${RATIONALES[id] ?? 'motif de style repéré par le catalogue.'}`)
.join('\n');
const flags = result.hits.map((h) => `- [${baseId(h.id)}] ${h.at}`).join('\n');
return [
'Un texte a passé le linter buvard ; voici ce qu\'il a signalé.',
'',
'Règles touchées, et pourquoi elles existent :',
rules,
'',
'Texte :',
'<<<',
text,
'>>>',
'',
'Fragments signalés (les extraits … affichés sont du contexte, pas la chaîne exacte) :',
flags,
'',
VOICE_RULE,
'',
'Ne touche pas au frontmatter (le bloc entre --- au début, s\'il existe).',
'Réponds STRICTEMENT un tableau JSON, rien d\'autre. Chaque entrée :',
'{"excerpt": "<chaîne exacte, mot pour mot, du texte>", "suggestion": "<remplacement, ou KEEP>", "rule": "<id de règle>", "why": "<une ligne>"}',
].join('\n');
}
async function chat(url, model, prompt, timeoutMs) {
let res;
try {
res = await fetch(`${url.replace(/\/+$/, '')}/chat/completions`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
model,
messages: [
{ role: 'system', content: 'Tu es un éditeur littéraire. Tu réponds strictement le JSON demandé, sans un mot autour.' },
{ role: 'user', content: prompt },
],
temperature: 0.2,
stream: false,
}),
signal: AbortSignal.timeout(timeoutMs),
});
} catch (e) {
if (e?.name === 'TimeoutError' || e?.cause?.code === 'UND_ERR_CONNECT_TIMEOUT')
throw new FixError(`délai dépassé (${Math.round(timeoutMs / 1000)} s) — le modèle local charge peut-être`);
throw new FixError(
`le serveur local ne répond pas sur ${url} — démarre LM Studio (Developer → Start Server) ou règle BUVARD_FIX_URL`,
{ cause: e },
);
}
if (!res.ok) throw new FixError(`le serveur local a répondu ${res.status} ${res.statusText}`);
const data = await res.json().catch(() => null);
const content = data?.choices?.[0]?.message?.content;
if (typeof content !== 'string' || !content.trim())
throw new FixError('le modèle local n\'a renvoyé aucun contenu');
return content;
}
/** Le modèle encadre parfois son JSON de fences ou de politesses ; on récupère le tableau. */
export function parseSuggestions(content) {
const body = content.replace(/```[a-z]*\n?/gi, '').trim();
const start = body.indexOf('[');
const end = body.lastIndexOf(']');
if (start === -1 || end < start)
throw new FixError('le modèle local n\'a pas répondu au format demandé (tableau JSON attendu)');
let parsed;
try {
parsed = JSON.parse(body.slice(start, end + 1));
} catch {
throw new FixError('le modèle local n\'a pas répondu du JSON valide');
}
if (!Array.isArray(parsed))
throw new FixError('le modèle local n\'a pas répondu un tableau JSON');
return parsed
.filter((s) => s && typeof s.excerpt === 'string' && s.excerpt.length > 0)
.map((s) => ({
excerpt: s.excerpt,
suggestion: typeof s.suggestion === 'string' ? s.suggestion : 'KEEP',
rule: typeof s.rule === 'string' ? s.rule : '?',
why: typeof s.why === 'string' ? s.why : '',
}));
}
/** Chiffres : jetons numériques exacts, ni plus ni moins — une donnée ne change pas. */
const numbersOf = (s) => s.match(/\d+(?:[.,]\d+)*/g) ?? [];
/**
* Noms : mots capitalisés hors début de phrase. Le premier mot d'un fragment
* peut n'être qu'une initiale de phrase, on ne peut pas le savoir — le reste, si.
*/
function namesOf(s) {
const out = [];
for (const m of s.matchAll(/[A-ZÉÈÀÂÊÎÔÛËÜÇ][\p{L}'’-]*/gu)) {
const before = s.slice(Math.max(0, m.index - 2), m.index);
if (m.index === 0 || /[.!?…]\s$/.test(before) || /\n\s*$/.test(before)) continue;
out.push(m[0]);
}
return out;
}
const multisetEqual = (a, b) => {
if (a.length !== b.length) return false;
const rest = [...b];
for (const x of a) {
const i = rest.indexOf(x);
if (i === -1) return false;
rest.splice(i, 1);
}
return true;
};
/** Garde-fou données : une suggestion qui altère un chiffre ou un nom est jetée. */
export function dataLost(excerpt, suggestion) {
return (
!multisetEqual(numbersOf(excerpt), numbersOf(suggestion)) ||
!multisetEqual(namesOf(excerpt), namesOf(suggestion))
);
}
const occurrences = (haystack, needle) => haystack.split(needle).length - 1;
/**
* Vérifie chaque suggestion et applique les survivantes, une par une :
* données intactes, fragment unique dans le texte, et le linter répond
* présent — score qui monte, ou hits qui baissent. Sinon, à la poubelle,
* avec la raison. KEEP passe à travers, c'est la règle de voix.
*/
export function verifyAndApply(text, suggestions) {
const base = lint(bodyOf(text));
const applied = [];
const dropped = [];
let current = text;
for (const s of suggestions) {
if (s.suggestion === 'KEEP') {
applied.push({ ...s, status: 'KEEP' });
continue;
}
if (dataLost(s.excerpt, s.suggestion)) {
dropped.push({ ...s, status: 'abandonnée', reason: 'chiffre ou nom modifié' });
continue;
}
if (occurrences(current, s.excerpt) !== 1) {
dropped.push({ ...s, status: 'abandonnée', reason: 'fragment introuvable ou ambigu' });
continue;
}
const after = lint(bodyOf(current.replace(s.excerpt, s.suggestion)));
const better =
after.score > base.score || (after.score === base.score && after.hits.length < base.hits.length);
if (!better) {
dropped.push({ ...s, status: 'abandonnée', reason: 'sans effet sur le score' });
continue;
}
current = current.replace(s.excerpt, s.suggestion);
applied.push({ ...s, status: 'appliquée' });
}
return { applied, dropped, text: current };
}
/**
* La boucle : flags → prompt → modèle local → suggestions vérifiées, au plus
* `maxRounds` fois, et seulement tant que le score s'améliore. Jette FixError
* si le serveur local ne répond pas — l'appelant décide de l'affichage.
*/
export async function fixText(text, opts = {}) {
const url = opts.url ?? process.env.BUVARD_FIX_URL ?? DEFAULT_URL;
const model = opts.model ?? process.env.BUVARD_FIX_MODEL ?? DEFAULT_MODEL;
const timeoutMs = opts.timeoutMs ?? Number(process.env.BUVARD_FIX_TIMEOUT_MS ?? 120000);
const maxRounds = opts.maxRounds ?? 3;
const before = lint(bodyOf(text));
const rounds = [];
let current = text;
let improved = before.hits.length > 0;
for (let round = 1; improved && round <= maxRounds; round++) {
const here = lint(bodyOf(current));
const content = await chat(url, model, buildPrompt(current, here), timeoutMs);
const suggestions = parseSuggestions(content);
const { applied, dropped, text: next } = verifyAndApply(current, suggestions);
const after = lint(bodyOf(next));
const kept = applied.filter((s) => s.status === 'appliquée').length;
rounds.push({
round,
flags: here.hits.length,
score: here.score,
afterScore: after.score,
suggestions: [...applied, ...dropped],
summary: `round ${round} : ${here.hits.length} flags, ${kept} appliquée${kept > 1 ? 's' : ''}, score ${here.score} → ${after.score}`,
});
current = next;
improved =
after.score > here.score || (after.score === here.score && after.hits.length < here.hits.length);
}
const final = lint(bodyOf(current));
return {
url,
model,
before: before.score,
after: final.score,
flagsBefore: before.hits.length,
flagsAfter: final.hits.length,
changed: current !== text,
text: current,
rounds,
};
}
/**
* Diff ligne à ligne (LCS, stdlib only) — largement assez pour de la prose.
* Longues plages identiques repliées sur « … » avec `context` lignes autour.
*/
export function diffLines(a, b, context = 3) {
const A = a.split('\n');
const B = b.split('\n');
const dp = Array.from({ length: A.length + 1 }, () => new Uint32Array(B.length + 1));
for (let i = A.length - 1; i >= 0; i--)
for (let j = B.length - 1; j >= 0; j--)
dp[i][j] = A[i] === B[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
const ops = [];
let i = 0;
let j = 0;
while (i < A.length && j < B.length) {
if (A[i] === B[j]) {
ops.push([' ', A[i++]]);
j++;
} else if (dp[i + 1][j] >= dp[i][j + 1]) ops.push(['-', A[i++]]);
else ops.push(['+', B[j++]]);
}
while (i < A.length) ops.push(['-', A[i++]]);
while (j < B.length) ops.push(['+', B[j++]]);
const keep = ops.map(() => false);
ops.forEach(([t], k) => {
if (t === ' ') return;
for (let x = Math.max(0, k - context); x <= Math.min(ops.length - 1, k + context); x++) keep[x] = true;
});
const out = [];
let folded = false;
ops.forEach(([t, line], k) => {
if (keep[k]) {
out.push(`${t} ${line}`);
folded = false;
} else if (!folded) {
out.push(' …');
folded = true;
}
});
return out.join('\n');
}
lib/index.mjs
View file @
d2af3b0b
/** buvard package entry — the catalog, the budgets, the lint core, the measures. */
/** buvard package entry — the catalog, the budgets, the lint core, the measures
, the fix engine
. */
export { CATALOG, CATALOG_VERSION, BUDGETS } from './catalog.mjs';
export { CATALOG, CATALOG_VERSION, BUDGETS
, RATIONALES
} from './catalog.mjs';
export { lint, bodyOf } from './lint.mjs';
export { lint, bodyOf } from './lint.mjs';
export { measuresOf, filterMeasures, MEASURES, MEASURE_GROUP } from './measures.mjs';
export { measuresOf, filterMeasures, MEASURES, MEASURE_GROUP } from './measures.mjs';
export {
fixText,
buildPrompt,
parseSuggestions,
verifyAndApply,
dataLost,
diffLines,
FixError,
DEFAULT_URL,
DEFAULT_MODEL,
} from './fix.mjs';
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment