FedCal commited on
Commit
7ec2b7f
·
verified ·
1 Parent(s): b38e2b2

Mirror geo-retrofit-benchmark on HF (Zenodo concept DOI 10.5281/zenodo.21602375)

Browse files
Files changed (1) hide show
  1. src/geo-retrofit.mjs +319 -0
src/geo-retrofit.mjs ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+ /**
3
+ * geo-retrofit.mjs - additive answer-first / FAQ retrofit engine (standalone,
4
+ * sanitized reproduction).
5
+ *
6
+ * This is the mutation half of the two-part engine (paired with
7
+ * ./audit-geo.mjs, the gate half). Given an article's HTML and a
8
+ * (already-generated) answer paragraph and/or FAQ Q&A pairs, it builds the
9
+ * two LOCKED markup fragments and injects them idempotently:
10
+ * - an answer-first "lead" block, prepended as the literal first content
11
+ * - a FAQ accordion block, appended as the literal last content
12
+ *
13
+ * Both fragments are additive-only: the engine never edits or deletes any
14
+ * pre-existing content. Idempotency is enforced two ways: (1) a data
15
+ * attribute marker skips re-injection on a second run, (2) a
16
+ * gate-compliance skip (needsLead/needsFaq re-use the SAME gate functions
17
+ * from ./audit-geo.mjs) so an article that already satisfies the gate on
18
+ * its own body is left untouched too.
19
+ *
20
+ * WHAT THIS REPO DELIBERATELY DOES NOT SHIP: the production version of this
21
+ * engine calls an on-prem LLM (Ollama) to GENERATE the answer paragraph and
22
+ * FAQ pairs, and reads/writes a project-specific manifest + content-tree
23
+ * layout. Both are stripped here - text generation is a pluggable concern
24
+ * (any LLM, or a human editor, can supply the `answer`/`pairs` inputs), and
25
+ * this repo demonstrates the transform + gate mechanics standalone, with
26
+ * zero project coupling and zero network calls. See RESULTS.md for the real
27
+ * production numbers this exact transform produced.
28
+ *
29
+ * CLI:
30
+ * node src/geo-retrofit.mjs <before.html> --lead "..." --faq pairs.json
31
+ *
32
+ * Usage:
33
+ * node src/geo-retrofit.mjs fixtures/sample-before.html
34
+ */
35
+
36
+ import { readFileSync, writeFileSync } from 'node:fs';
37
+ import { argv, exit } from 'node:process';
38
+
39
+ import { stripPreCode, parseBlocks, checkAnswerFirst, countFaqPairs, wordCount, hasCiteSource, FAQ_MIN, FAQ_MAX, ANSWER_BLOCK_MIN_WORDS, ANSWER_BLOCK_MAX_WORDS } from './audit-geo.mjs';
40
+
41
+ // Re-export the cross-imported gate primitives so a caller can import
42
+ // everything it needs from this single module.
43
+ export { stripPreCode, parseBlocks, checkAnswerFirst, countFaqPairs, wordCount, hasCiteSource };
44
+
45
+ // --- HTML-escape helper (inlined, standalone - no project dependency) -----------
46
+
47
+ /**
48
+ * escapeHtmlText - escapes the 5 XML/HTML special characters. ALWAYS applied
49
+ * to generated text (answer paragraph, FAQ questions/answers) before
50
+ * interpolation into the fragment markup - stored self-XSS mitigation.
51
+ */
52
+ export function escapeHtmlText(value) {
53
+ return String(value ?? '')
54
+ .replace(/&/g, '&amp;')
55
+ .replace(/</g, '&lt;')
56
+ .replace(/>/g, '&gt;')
57
+ .replace(/"/g, '&quot;')
58
+ .replace(/'/g, '&#39;');
59
+ }
60
+
61
+ // --- LOCKED markup constants (do not re-derive) ----------------------------------
62
+
63
+ export const LEAD_HEADING = { it: 'Risposta diretta', en: 'Direct answer' };
64
+ export const FAQ_HEADING = { it: 'Domande frequenti', en: 'Frequently asked questions' };
65
+
66
+ const LEAD_MARKER = 'data-geo-retrofit="lead"';
67
+ const FAQ_MARKER = 'data-geo-retrofit="faq"';
68
+ // A pre-existing bare <section class="faq"> (no marker at all) is also
69
+ // treated as "already has FAQ" - never stack a second block on top of one
70
+ // the article already ships.
71
+ const BARE_FAQ_SECTION_RE = /<section[^>]*\bclass=["'][^"']*\bfaq\b[^"']*["']/i;
72
+
73
+ // --- Markup builders (exact LOCKED shape, escape ALL generated text) ------------
74
+
75
+ /**
76
+ * buildLeadFragment - the answer-first lead block. `headingText` is always
77
+ * the LOCKED literal ("Risposta diretta"/"Direct answer"), never generated.
78
+ * `answerText` is externally-supplied (LLM or human) and MUST be escaped
79
+ * before interpolation.
80
+ */
81
+ export function buildLeadFragment(headingText, answerText) {
82
+ return (
83
+ `<div class="geo-retrofit-lead" data-geo-retrofit="lead">\n` +
84
+ ` <h2>${escapeHtmlText(headingText)}</h2>\n` +
85
+ ` <p>${escapeHtmlText(answerText)}</p>\n` +
86
+ `</div>`
87
+ );
88
+ }
89
+
90
+ /**
91
+ * buildFaqFragment - the FAQ accordion block. `pairs` is an array of
92
+ * `{ question, answer }` - both externally-supplied and MUST be escaped
93
+ * before interpolation. The inner `<h3>` inside `<summary>` is what makes
94
+ * countFaqPairs() (./audit-geo.mjs) register each pair - the gate scans the
95
+ * raw tag sequence, `<details>/<summary>/<div>` wrappers are invisible to it.
96
+ */
97
+ export function buildFaqFragment(headingText, pairs) {
98
+ const items = pairs
99
+ .map(
100
+ (pair) =>
101
+ ` <details class="geo-retrofit-faq-item">\n` +
102
+ ` <summary class="geo-retrofit-faq-question"><h3>${escapeHtmlText(pair.question)}</h3></summary>\n` +
103
+ ` <div class="geo-retrofit-faq-answer">\n` +
104
+ ` <p>${escapeHtmlText(pair.answer)}</p>\n` +
105
+ ` </div>\n` +
106
+ ` </details>`,
107
+ )
108
+ .join('\n');
109
+ return (
110
+ `<section class="faq geo-retrofit-faq" data-geo-retrofit="faq">\n` +
111
+ ` <h2>${escapeHtmlText(headingText)}</h2>\n` +
112
+ `${items}\n` +
113
+ `</section>`
114
+ );
115
+ }
116
+
117
+ // --- Idempotency (marker skip + gate-compliance skip) ----------------------------
118
+
119
+ /**
120
+ * needsLead - false when the article already carries the lead marker, OR
121
+ * when its own pre-mutation body already opens with a valid answer-first
122
+ * structure (checkAnswerFirst present===true) - re-uses the gate's own
123
+ * function so the self-check and the acceptance gate agree by construction.
124
+ */
125
+ export function needsLead(html) {
126
+ if (html.includes(LEAD_MARKER)) return false;
127
+ const blocks = parseBlocks(stripPreCode(html));
128
+ const { present } = checkAnswerFirst(blocks);
129
+ return !present;
130
+ }
131
+
132
+ /**
133
+ * needsFaq - false when the article already carries the FAQ marker, OR has
134
+ * ANY pre-existing bare `<section class="faq">`, OR its own pre-mutation
135
+ * body already has a gate-parseable FAQ pair count in [FAQ_MIN,FAQ_MAX].
136
+ */
137
+ export function needsFaq(html) {
138
+ if (html.includes(FAQ_MARKER)) return false;
139
+ if (BARE_FAQ_SECTION_RE.test(html)) return false;
140
+ const blocks = parseBlocks(stripPreCode(html));
141
+ const count = countFaqPairs(blocks);
142
+ return !(count >= FAQ_MIN && count <= FAQ_MAX);
143
+ }
144
+
145
+ // --- Injection at fixed offsets (no <pre>/<code> collision risk - insertion
146
+ // points are the literal file-start/file-end) ------------------------------------
147
+
148
+ /** injectLead - prepends `leadHtml` as the literal FIRST content. */
149
+ export function injectLead(html, leadHtml) {
150
+ return `${leadHtml}\n${html}`;
151
+ }
152
+
153
+ /** injectFaq - appends `faqHtml` as the literal LAST content. */
154
+ export function injectFaq(html, faqHtml) {
155
+ return `${html}\n${faqHtml}`;
156
+ }
157
+
158
+ /**
159
+ * injectFragments - applies needsLead()/needsFaq() BEFORE injecting either
160
+ * fragment, so an idempotent re-run (or an already-gate-compliant article)
161
+ * yields byte-identical output. Never mutates in place.
162
+ *
163
+ * @param {string} html
164
+ * @param {{lead?: string|null, faq?: string|null}} [fragments]
165
+ * @returns {{html: string, leadInjected: boolean, faqInjected: boolean}}
166
+ */
167
+ export function injectFragments(html, { lead = null, faq = null } = {}) {
168
+ let out = html;
169
+ let leadInjected = false;
170
+ let faqInjected = false;
171
+ if (lead && needsLead(html)) {
172
+ out = injectLead(out, lead);
173
+ leadInjected = true;
174
+ }
175
+ if (faq && needsFaq(html)) {
176
+ out = injectFaq(out, faq);
177
+ faqInjected = true;
178
+ }
179
+ return { html: out, leadInjected, faqInjected };
180
+ }
181
+
182
+ // --- Post-generation guards (defensive habit for ANY externally-supplied
183
+ // text, whether it comes from an LLM or a human editor) --------------------------
184
+
185
+ const CJK_RE = /[一-鿿぀-ヿ가-힣]/;
186
+ const INSTRUCTION_ECHO_RE = /(40-60 word|direct answer|no em-dash)/i;
187
+ const FENCE_RE = /^```[a-zA-Z]*\n?([\s\S]*?)\n?```$/;
188
+ const LEADING_PREAMBLE_RE =
189
+ /^(here(?:'s|\s+is)\s+the\s+(?:answer|direct answer|faq)[:\s]*|sure[,!\s]+here(?:'s|\s+is)?[:\s]*|certainly[,!\s]+here(?:'s|\s+is)?[:\s]*|of\s+course[,!\s]+)/i;
190
+
191
+ /**
192
+ * sanitizeGenerated - strips markdown fences/leading preamble a model
193
+ * sometimes adds despite instructions, THEN normalizes em/en-dash to a
194
+ * plain hyphen, THEN rejects (throws) output polluted with CJK characters
195
+ * or literal instruction-echo phrases. Applied BEFORE word-count/FAQ-count
196
+ * validation so counts are computed on final, cleaned text.
197
+ */
198
+ export function sanitizeGenerated(text) {
199
+ let out = String(text ?? '').trim();
200
+ const fenceMatch = out.match(FENCE_RE);
201
+ if (fenceMatch) out = fenceMatch[1].trim();
202
+ for (let i = 0; i < 3; i++) {
203
+ const stripped = out.replace(LEADING_PREAMBLE_RE, '').trim();
204
+ if (stripped === out) break;
205
+ out = stripped;
206
+ }
207
+ // em-dash (U+2014) and en-dash (U+2013) - no fake polish, plain hyphen only.
208
+ out = out.replace(/[—–]/g, '-');
209
+ if (CJK_RE.test(out)) {
210
+ throw new Error('sanitizeGenerated: rejected CJK-polluted output');
211
+ }
212
+ if (INSTRUCTION_ECHO_RE.test(out)) {
213
+ throw new Error('sanitizeGenerated: rejected instruction-echo in output');
214
+ }
215
+ return out;
216
+ }
217
+
218
+ /** validateLead - lead paragraph word count must be self-counted, never trusted from the source. */
219
+ export function validateLead(text) {
220
+ const count = wordCount(text);
221
+ return count >= ANSWER_BLOCK_MIN_WORDS && count <= ANSWER_BLOCK_MAX_WORDS;
222
+ }
223
+
224
+ /**
225
+ * validateFaq - pair count must be in [FAQ_MIN,FAQ_MAX] AND every question
226
+ * must end in a literal "?" with NOTHING after (a trailing parenthetical or
227
+ * entity after the "?" would silently fail countFaqPairs()).
228
+ */
229
+ export function validateFaq(pairs) {
230
+ if (!Array.isArray(pairs) || pairs.length < FAQ_MIN || pairs.length > FAQ_MAX) return false;
231
+ return pairs.every((pair) => typeof pair?.question === 'string' && pair.question.trim().endsWith('?'));
232
+ }
233
+
234
+ /**
235
+ * assertParity - a bilingual-publishing requirement: every language variant
236
+ * of the same article must produce the SAME number of FAQ pairs. Returns
237
+ * false on mismatch rather than throwing, so callers can retry the shorter
238
+ * side before giving up on the pair.
239
+ */
240
+ export function assertParity(itPairs, enPairs) {
241
+ return Array.isArray(itPairs) && Array.isArray(enPairs) && itPairs.length === enPairs.length;
242
+ }
243
+
244
+ // --- CLI entry point (demonstration only - reads a before.html + JSON lead/faq
245
+ // payload, writes the retrofitted HTML to stdout) --------------------------------
246
+
247
+ function parseArgs(args) {
248
+ const out = {};
249
+ for (let i = 0; i < args.length; i++) {
250
+ const a = args[i];
251
+ if (!a.startsWith('--')) continue;
252
+ const key = a.slice(2);
253
+ const next = args[i + 1];
254
+ if (next !== undefined && !next.startsWith('--')) {
255
+ out[key] = next;
256
+ i += 1;
257
+ } else {
258
+ out[key] = true;
259
+ }
260
+ }
261
+ return out;
262
+ }
263
+
264
+ async function main() {
265
+ const positional = argv.slice(2).filter((a) => !a.startsWith('--'));
266
+ const args = parseArgs(argv.slice(2));
267
+
268
+ if (positional.length === 0) {
269
+ console.log(
270
+ 'Usage: node src/geo-retrofit.mjs <before.html> [--lang it|en] [--payload payload.json] [--out out.html]',
271
+ );
272
+ console.log(' payload.json shape: { "answer": "...", "faqPairs": [{"question":"...","answer":"..."}] }');
273
+ exit(0);
274
+ return;
275
+ }
276
+
277
+ const lang = args.lang || 'en';
278
+ const html = readFileSync(positional[0], 'utf8');
279
+
280
+ let answer = null;
281
+ let faqPairs = null;
282
+ if (args.payload) {
283
+ const payload = JSON.parse(readFileSync(String(args.payload), 'utf8'));
284
+ answer = payload.answer ?? null;
285
+ faqPairs = payload.faqPairs ?? null;
286
+ }
287
+
288
+ let lead = null;
289
+ let faq = null;
290
+ if (answer && needsLead(html)) {
291
+ const cleaned = sanitizeGenerated(answer);
292
+ if (!validateLead(cleaned)) throw new Error(`lead word count ${wordCount(cleaned)} outside the answer-block window`);
293
+ lead = buildLeadFragment(LEAD_HEADING[lang] ?? LEAD_HEADING.en, cleaned);
294
+ }
295
+ if (faqPairs && needsFaq(html)) {
296
+ const cleanedPairs = faqPairs.map((p) => ({ question: sanitizeGenerated(p.question), answer: sanitizeGenerated(p.answer) }));
297
+ if (!validateFaq(cleanedPairs)) throw new Error('FAQ payload failed validation (count or question shape)');
298
+ faq = buildFaqFragment(FAQ_HEADING[lang] ?? FAQ_HEADING.en, cleanedPairs);
299
+ }
300
+
301
+ const { html: out, leadInjected, faqInjected } = injectFragments(html, { lead, faq });
302
+ console.error(`[geo-retrofit] leadInjected=${leadInjected} faqInjected=${faqInjected}`);
303
+
304
+ if (args.out) {
305
+ writeFileSync(String(args.out), out, 'utf8');
306
+ console.error(`[geo-retrofit] wrote ${args.out}`);
307
+ } else {
308
+ console.log(out);
309
+ }
310
+ exit(0);
311
+ }
312
+
313
+ const isDirectRun = argv[1] && import.meta.url === `file://${argv[1]}`;
314
+ if (isDirectRun) {
315
+ main().catch((err) => {
316
+ console.error(`[geo-retrofit] fatal: ${err.stack || err.message}`);
317
+ exit(1);
318
+ });
319
+ }