@ryuenn3123/agentic-senior-core 4.0.3 → 4.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.
@@ -1,180 +0,0 @@
1
- // @ts-check
2
-
3
- /**
4
- * Best-effort parser for the legacy v3 rule file format. Extracts:
5
- * - the H1 title
6
- * - an optional intro paragraph (1-3 sentences before the first H2)
7
- * - a list of sections, each with H2 title + ordered content blocks
8
- *
9
- * Each content block is one of:
10
- * { kind: 'paragraph', text }
11
- * { kind: 'bullet-list', items: string[] }
12
- * { kind: 'sub-bullet-list', items: string[] } // legacy nested bullets
13
- *
14
- * The parser intentionally throws on shapes it cannot represent in the new
15
- * format. This forces the human migrator to review unusual sections instead of
16
- * silently losing content.
17
- */
18
-
19
- /**
20
- * @typedef {{ kind: 'paragraph', text: string }} ParagraphBlock
21
- * @typedef {{ kind: 'bullet-list', items: string[] }} BulletListBlock
22
- * @typedef {ParagraphBlock | BulletListBlock} ContentBlock
23
- *
24
- * @typedef {{
25
- * title: string,
26
- * blocks: ContentBlock[],
27
- * }} ParsedSection
28
- *
29
- * @typedef {{
30
- * h1Title: string,
31
- * introParagraph: string | null,
32
- * sections: ParsedSection[],
33
- * warnings: string[],
34
- * }} ParsedRuleFile
35
- */
36
-
37
- /**
38
- * @param {string} sourceText
39
- * @returns {ParsedRuleFile}
40
- */
41
- export function parseLegacyRuleFile(sourceText) {
42
- const lines = sourceText.replace(/\r\n/g, '\n').split('\n');
43
- const warnings = [];
44
- const isH2 = (line) => line.startsWith('## ');
45
- const isH1 = (line) => line.startsWith('# ');
46
- const isColonSectionLabel = (line) => /^[A-Z][^:\n]+:$/.test(line.trim());
47
-
48
- let cursor = 0;
49
- while (cursor < lines.length && lines[cursor].trim() === '') {
50
- cursor += 1;
51
- }
52
-
53
- const h1Match = (lines[cursor] || '').match(/^#\s+(.+)$/);
54
- if (!h1Match) {
55
- throw new Error('Legacy file missing top-level H1 heading at the first non-empty line.');
56
- }
57
- const h1Title = h1Match[1].trim();
58
- cursor += 1;
59
-
60
- while (cursor < lines.length && lines[cursor].trim() === '') {
61
- cursor += 1;
62
- }
63
-
64
- let introParagraph = null;
65
- if (cursor < lines.length && !lines[cursor].startsWith('## ') && !lines[cursor].startsWith('# ')) {
66
- const introLines = [];
67
- while (cursor < lines.length && !lines[cursor].startsWith('## ') && !lines[cursor].startsWith('# ')) {
68
- const line = lines[cursor];
69
- if (line.trim() === '' && introLines.length > 0) {
70
- break;
71
- }
72
- if (line.trim() !== '') {
73
- introLines.push(line.trim());
74
- }
75
- cursor += 1;
76
- }
77
- if (introLines.length > 0) {
78
- introParagraph = introLines.join(' ').trim();
79
- const sentenceCount = (introParagraph.match(/[.!?](?=\s|$)/g) || []).length;
80
- if (sentenceCount > 3) {
81
- warnings.push(`Intro paragraph has ${sentenceCount} sentences (max 3 per format spec). Trim or split during manual review.`);
82
- }
83
- }
84
- }
85
-
86
- while (cursor < lines.length && lines[cursor].trim() === '') {
87
- cursor += 1;
88
- }
89
-
90
- /** @type {ParsedSection[]} */
91
- const sections = [];
92
- while (cursor < lines.length) {
93
- while (cursor < lines.length && lines[cursor].trim() === '') {
94
- cursor += 1;
95
- }
96
- if (cursor >= lines.length) {
97
- break;
98
- }
99
-
100
- let sectionTitle = '';
101
- if (isH2(lines[cursor])) {
102
- sectionTitle = lines[cursor].slice(3).trim();
103
- cursor += 1;
104
- } else if (isColonSectionLabel(lines[cursor])) {
105
- sectionTitle = lines[cursor].trim().replace(/:$/, '');
106
- cursor += 1;
107
- } else if (!isH1(lines[cursor])) {
108
- sectionTitle = sections.length === 0 ? 'General Guidance' : 'Boundary Summary';
109
- } else {
110
- cursor += 1;
111
- continue;
112
- }
113
-
114
- /** @type {ContentBlock[]} */
115
- const blocks = [];
116
- while (cursor < lines.length && !isH2(lines[cursor]) && !isH1(lines[cursor]) && !isColonSectionLabel(lines[cursor])) {
117
- const line = lines[cursor];
118
-
119
- if (line.trim() === '') {
120
- cursor += 1;
121
- continue;
122
- }
123
-
124
- if (/^\s*-\s+/.test(line)) {
125
- const items = [];
126
- let nestedItems = [];
127
- while (cursor < lines.length && (/^\s*-\s+/.test(lines[cursor]) || lines[cursor].trim() === '' || /^\s{2,}\S/.test(lines[cursor]))) {
128
- const bulletLine = lines[cursor];
129
- if (bulletLine.trim() === '') {
130
- cursor += 1;
131
- if (cursor < lines.length && !/^\s*-\s+/.test(lines[cursor])) {
132
- break;
133
- }
134
- continue;
135
- }
136
- const topMatch = bulletLine.match(/^-\s+(.+)$/);
137
- const nestedMatch = bulletLine.match(/^\s{2,}-\s+(.+)$/);
138
- const continuationMatch = bulletLine.match(/^\s{2,}(\S.+)$/);
139
- if (topMatch) {
140
- if (nestedItems.length > 0 && items.length > 0) {
141
- items[items.length - 1] += `\n ${nestedItems.map((nested) => `- ${nested}`).join('\n ')}`;
142
- nestedItems = [];
143
- }
144
- items.push(topMatch[1].trim());
145
- } else if (nestedMatch) {
146
- nestedItems.push(nestedMatch[1].trim());
147
- } else if (continuationMatch && items.length > 0) {
148
- items[items.length - 1] += ` ${continuationMatch[1].trim()}`;
149
- } else {
150
- break;
151
- }
152
- cursor += 1;
153
- }
154
- if (nestedItems.length > 0 && items.length > 0) {
155
- items[items.length - 1] += `\n ${nestedItems.map((nested) => `- ${nested}`).join('\n ')}`;
156
- }
157
- blocks.push({ kind: 'bullet-list', items });
158
- continue;
159
- }
160
-
161
- const paragraphLines = [];
162
- while (
163
- cursor < lines.length
164
- && lines[cursor].trim() !== ''
165
- && !isH2(lines[cursor])
166
- && !isH1(lines[cursor])
167
- && !isColonSectionLabel(lines[cursor])
168
- && !/^\s*-\s+/.test(lines[cursor])
169
- ) {
170
- paragraphLines.push(lines[cursor].trim());
171
- cursor += 1;
172
- }
173
- blocks.push({ kind: 'paragraph', text: paragraphLines.join(' ').trim() });
174
- }
175
-
176
- sections.push({ title: sectionTitle, blocks });
177
- }
178
-
179
- return { h1Title, introParagraph, sections, warnings };
180
- }
@@ -1,169 +0,0 @@
1
- // @ts-check
2
-
3
- /**
4
- * Renders a parsed legacy rule file plus a prefix-table entry into the v4
5
- * canonical format defined in `docs/architecture/format-spec.md`.
6
- *
7
- * Section IDs auto-assign sequentially starting at 001. The renderer never
8
- * skips integers; humans introduce gaps manually during review by editing
9
- * the produced file (e.g. when expecting later splits).
10
- *
11
- * Each parsed bullet-list becomes one numbered item if it has 1-2 items, or a
12
- * single numbered item with sub-bullets when the list is enumerative (3+
13
- * items that share the same shape).
14
- */
15
-
16
- import { stringify as stringifyYaml } from 'yaml';
17
-
18
- function pickKeywords(parsedRuleFile, prefixEntry) {
19
- // Hand-picked first: the file's id_prefix lowercased and the domain itself
20
- // are always relevant. Additional keywords are drawn from the highest-signal
21
- // kebab-case tokens in the H1 + section titles, capped at 6 total. The
22
- // validate gate snippet checks accept either body presence or this array, so
23
- // we prioritize tokens that appear in section titles (more likely to be
24
- // queried) over tokens buried in paragraphs.
25
- const handPicked = new Set([prefixEntry.domain, prefixEntry.prefix.toLowerCase()]);
26
- const titleSignal = parsedRuleFile.h1Title + ' ' + parsedRuleFile.sections.map((section) => section.title).join(' ');
27
- for (const word of titleSignal.toLowerCase().match(/[a-z][a-z0-9]+(?:-[a-z0-9]+)*/g) ?? []) {
28
- if (word.length >= 4 && word.length <= 32 && handPicked.size < 6) {
29
- handPicked.add(word);
30
- }
31
- }
32
- return [...handPicked];
33
- }
34
-
35
- function renderFrontmatter(prefixEntry, parsedRuleFile) {
36
- // Trimmed v4 frontmatter (per phase-1-format.md GATE B revision):
37
- // - drop `version` for first-time-v1 files (only meaningful when bumped)
38
- // - drop `last_migrated` (git history is the audit trail)
39
- // - cap `keywords` at 6 hand-picked entries instead of 12 auto-extracted
40
- const frontmatterObject = {
41
- id_prefix: prefixEntry.prefix,
42
- domain: prefixEntry.domain,
43
- priority: prefixEntry.priority,
44
- scope: prefixEntry.scope,
45
- applies_to: [...prefixEntry.appliesTo],
46
- keywords: pickKeywords(parsedRuleFile, prefixEntry),
47
- };
48
- const yamlBody = stringifyYaml(frontmatterObject, { lineWidth: 0 }).trimEnd();
49
- return `---\n${yamlBody}\n---\n`;
50
- }
51
-
52
- function renderIntroParagraph(parsedRuleFile) {
53
- if (!parsedRuleFile.introParagraph) return '';
54
- return `${parsedRuleFile.introParagraph}\n\n`;
55
- }
56
-
57
- // Common abbreviations that end with a period but are not sentence endings.
58
- // Mid-sentence occurrences like "etc. The next..." would otherwise be split
59
- // at the abbreviation. Pre-masking is the cheapest fix and is easy to extend.
60
- const NON_SENTENCE_ENDING_ABBREVIATIONS = Object.freeze(['e.g', 'i.e', 'etc', 'vs', 'cf', 'Mr', 'Dr', 'Mrs', 'Inc', 'Ltd']);
61
- const ABBREVIATION_MASK_TOKEN = '\u0001';
62
-
63
- function maskAbbreviationPeriods(paragraphText) {
64
- let masked = paragraphText;
65
- for (const abbreviation of NON_SENTENCE_ENDING_ABBREVIATIONS) {
66
- const escaped = abbreviation.replace(/\./g, '\\.');
67
- masked = masked.replace(new RegExp(`\\b${escaped}\\.`, 'g'), `${abbreviation}${ABBREVIATION_MASK_TOKEN}`);
68
- }
69
- return masked;
70
- }
71
-
72
- function unmaskAbbreviationPeriods(text) {
73
- return text.replace(new RegExp(ABBREVIATION_MASK_TOKEN, 'g'), '.');
74
- }
75
-
76
- export function paragraphSplitsIntoDirectives(paragraphText) {
77
- // A `.` `!` or `?` ends a sentence only when it is followed by whitespace
78
- // and an uppercase letter, a backtick (next clause starts with `code`), or
79
- // an opening parenthesis. This rule recognizes:
80
- // - file paths "docs/DESIGN.md" period + lowercase, no whitespace -> not a boundary
81
- // - dotted versions "v1.5", "2.0.0" period + digit -> not a boundary
82
- // - domain literals "example.com" period + lowercase -> not a boundary
83
- // - abbreviations "e.g.", "i.e.", "etc." pre-masked so their internal periods do not split
84
- // Everything else is treated as sentence-final.
85
- const masked = maskAbbreviationPeriods(paragraphText);
86
- const SENTENCE_BOUNDARY = /([.!?])\s+(?=[A-Z`(])/g;
87
- const sentences = [];
88
- let cursor = 0;
89
- for (const match of masked.matchAll(SENTENCE_BOUNDARY)) {
90
- const sentenceEnd = match.index + match[1].length;
91
- sentences.push(unmaskAbbreviationPeriods(masked.slice(cursor, sentenceEnd)).trim());
92
- cursor = match.index + match[0].length;
93
- }
94
- const tail = unmaskAbbreviationPeriods(masked.slice(cursor)).trim();
95
- if (tail.length > 0) {
96
- sentences.push(tail);
97
- }
98
- return sentences.filter((sentence) => sentence.length > 0);
99
- }
100
-
101
- function renderBlockAsNumberedItem(block) {
102
- if (block.kind === 'paragraph') {
103
- return paragraphSplitsIntoDirectives(block.text);
104
- }
105
-
106
- // Each bullet becomes its own numbered directive. The format spec allows
107
- // sub-bullets only as supporting detail under one parent directive, never
108
- // as a way to compress an enumerative list into a single item. Keeping them
109
- // as numbered items preserves citability (each becomes a sub-ID candidate
110
- // during manual review) and matches the worked example in section 6.2.
111
- return [...block.items];
112
- }
113
-
114
- function buildSectionBody(blocks) {
115
- const numberedDirectives = [];
116
- for (const block of blocks) {
117
- const directives = renderBlockAsNumberedItem(block);
118
- for (const directive of directives) {
119
- numberedDirectives.push(directive);
120
- }
121
- }
122
- return numberedDirectives;
123
- }
124
-
125
- /**
126
- * @param {{ prefix: string, domain: string, priority: string, scope: string, appliesTo: string[] }} prefixEntry
127
- * @param {ReturnType<typeof import('./parse-legacy.mjs').parseLegacyRuleFile>} parsedRuleFile
128
- * @returns {{ rendered: string, sectionAssignments: Array<{ sectionTitle: string, sectionId: string, itemCount: number }>, warnings: string[] }}
129
- */
130
- export function renderNewFormat(prefixEntry, parsedRuleFile) {
131
- const warnings = [...parsedRuleFile.warnings];
132
- const renderedParts = [];
133
- renderedParts.push(renderFrontmatter(prefixEntry, parsedRuleFile));
134
- renderedParts.push('\n');
135
- renderedParts.push(`# ${parsedRuleFile.h1Title}\n\n`);
136
- renderedParts.push(renderIntroParagraph(parsedRuleFile));
137
-
138
- const sectionAssignments = [];
139
- parsedRuleFile.sections.forEach((section, sectionIndex) => {
140
- const sectionId = `${prefixEntry.prefix}-${String(sectionIndex + 1).padStart(3, '0')}`;
141
- const numberedItems = buildSectionBody(section.blocks);
142
- if (numberedItems.length > 12) {
143
- warnings.push(
144
- `Section "${section.title}" has ${numberedItems.length} numbered items. Format spec caps at 12; split into two sections during manual review.`,
145
- );
146
- }
147
- if (numberedItems.length === 0) {
148
- warnings.push(`Section "${section.title}" produced no numbered items. Manual review required.`);
149
- }
150
-
151
- renderedParts.push(`## ${sectionId}: ${section.title}\n\n`);
152
- numberedItems.forEach((directive, itemIndex) => {
153
- renderedParts.push(`${itemIndex + 1}. ${directive}\n`);
154
- });
155
- renderedParts.push('\n');
156
-
157
- sectionAssignments.push({
158
- sectionTitle: section.title,
159
- sectionId,
160
- itemCount: numberedItems.length,
161
- });
162
- });
163
-
164
- return {
165
- rendered: renderedParts.join('').replace(/\n{3,}/g, '\n\n').trimEnd() + '\n',
166
- sectionAssignments,
167
- warnings,
168
- };
169
- }
@@ -1,89 +0,0 @@
1
- // @ts-check
2
-
3
- /**
4
- * Roundtrip substance validator.
5
- *
6
- * After rendering the new format, we extract the substantial-word set from
7
- * both the original v3 file and the rendered v4 file, then compute set overlap.
8
- * Drop in overlap below the threshold means the migration almost certainly
9
- * lost real content; the helper surfaces the lost words so the human migrator
10
- * can decide whether the loss is intentional (renamed terms) or a bug.
11
- */
12
-
13
- const STOPWORD_SET = new Set([
14
- 'the', 'and', 'for', 'with', 'that', 'this', 'from', 'into', 'are', 'was',
15
- 'were', 'has', 'have', 'had', 'not', 'but', 'can', 'will', 'must', 'use',
16
- 'used', 'using', 'when', 'then', 'than', 'they', 'their', 'them', 'who',
17
- 'what', 'why', 'how', 'all', 'any', 'one', 'two', 'three', 'four', 'five',
18
- 'six', 'seven', 'eight', 'nine', 'ten', 'each', 'such', 'some', 'most',
19
- 'more', 'less', 'only', 'also', 'just', 'over', 'under', 'between', 'across',
20
- 'before', 'after', 'because', 'while', 'until', 'unless', 'within',
21
- 'without', 'inside', 'outside', 'about', 'around', 'against', 'through',
22
- 'throughout', 'during', 'including', 'include', 'includes', 'see', 'note',
23
- 'rule', 'rules', 'agent', 'agents', 'project', 'repo', 'code', 'file',
24
- 'files', 'item', 'items', 'list', 'lists', 'thing', 'things', 'value',
25
- 'values', 'should', 'shall', 'may', 'might', 'could', 'would', 'does',
26
- 'doing', 'done', 'make', 'makes', 'making', 'made', 'set', 'sets',
27
- ]);
28
-
29
- function tokenize(text) {
30
- const lowered = text.toLowerCase();
31
- // Strip fenced code blocks first (multi-line ``` ... ``` spans).
32
- const noFenced = lowered.replace(/```[\s\S]*?```/g, ' ');
33
- // Strip inline code spans, but only within a single line so that an
34
- // unmatched backtick on a code-heavy line cannot eat the rest of the file.
35
- const noInline = noFenced.replace(/`[^`\n]+`/g, ' ');
36
- const words = noInline.match(/[a-z][a-z0-9]+(?:-[a-z0-9]+)*/g) ?? [];
37
- return words.filter((word) => word.length >= 4 && !STOPWORD_SET.has(word));
38
- }
39
-
40
- /**
41
- * @param {string} originalSourceText
42
- * @param {string} renderedSourceText
43
- * @param {{ minimumOverlapPercent?: number }} [options]
44
- * @returns {{
45
- * passed: boolean,
46
- * originalSubstantialWordCount: number,
47
- * renderedSubstantialWordCount: number,
48
- * overlapPercent: number,
49
- * lostWords: string[],
50
- * newWords: string[],
51
- * minimumRequired: number,
52
- * }}
53
- */
54
- export function roundtripSubstanceCheck(originalSourceText, renderedSourceText, options = {}) {
55
- const minimumOverlapPercent = options.minimumOverlapPercent ?? 95;
56
- const originalWordCounts = new Map();
57
- for (const word of tokenize(originalSourceText)) {
58
- originalWordCounts.set(word, (originalWordCounts.get(word) || 0) + 1);
59
- }
60
- const renderedWordSet = new Set(tokenize(renderedSourceText));
61
-
62
- const lostWords = [];
63
- let preservedDistinctWordCount = 0;
64
- for (const [word, count] of originalWordCounts.entries()) {
65
- if (renderedWordSet.has(word)) {
66
- preservedDistinctWordCount += 1;
67
- } else {
68
- lostWords.push(`${word} (x${count})`);
69
- }
70
- }
71
-
72
- const originalDistinctCount = originalWordCounts.size;
73
- const overlapPercent = originalDistinctCount > 0
74
- ? (preservedDistinctWordCount / originalDistinctCount) * 100
75
- : 100;
76
-
77
- const originalWordSet = new Set(originalWordCounts.keys());
78
- const newWords = [...renderedWordSet].filter((word) => !originalWordSet.has(word));
79
-
80
- return {
81
- passed: overlapPercent >= minimumOverlapPercent,
82
- originalSubstantialWordCount: originalDistinctCount,
83
- renderedSubstantialWordCount: renderedWordSet.size,
84
- overlapPercent: Math.round(overlapPercent * 100) / 100,
85
- lostWords: lostWords.sort().slice(0, 50),
86
- newWords: newWords.sort().slice(0, 50),
87
- minimumRequired: minimumOverlapPercent,
88
- };
89
- }
@@ -1,192 +0,0 @@
1
- #!/usr/bin/env node
2
- // @ts-check
3
-
4
- /**
5
- * scripts/migrate-rule-format.mjs
6
- *
7
- * Phase 1 Task 1.2 migration helper. Converts a legacy v3 rule file into the
8
- * canonical v4 format defined in docs/architecture/format-spec.md. Output is written
9
- * to a `.candidate.md` sibling so the human migrator can review the diff
10
- * before replacing the original.
11
- *
12
- * Usage:
13
- * node scripts/migrate-rule-format.mjs <path-to-rule-file>
14
- * node scripts/migrate-rule-format.mjs <path> --json
15
- * node scripts/migrate-rule-format.mjs <path> --apply
16
- *
17
- * Flags:
18
- * --json Print the structured report to stdout (JSON only, no human prose).
19
- * --apply Overwrite the source file with the rendered v4 content. Default
20
- * behavior writes a .candidate.md file and leaves the source alone.
21
- *
22
- * The helper does not commit, does not stage, and does not call any network.
23
- *
24
- * Exit codes:
25
- * 0 — rendered cleanly + roundtrip overlap >= 95%
26
- * 1 — roundtrip overlap below threshold OR parser warnings present
27
- * 2 — input path missing or filename not in the locked prefix table
28
- */
29
-
30
- import { readFileSync, writeFileSync } from 'node:fs';
31
- import { basename, dirname, resolve } from 'node:path';
32
- import { fileURLToPath } from 'node:url';
33
-
34
- import { countTokens } from '../benchmarks/token-usage/lib/token-counter.mjs';
35
- import { getPrefixEntry } from './migrate-rule-format/id-prefix-table.mjs';
36
- import { parseLegacyRuleFile } from './migrate-rule-format/parse-legacy.mjs';
37
- import { renderNewFormat } from './migrate-rule-format/render-new.mjs';
38
- import { roundtripSubstanceCheck } from './migrate-rule-format/roundtrip-validate.mjs';
39
-
40
- const SCRIPT_FILE_PATH = fileURLToPath(import.meta.url);
41
- const REPOSITORY_ROOT = resolve(dirname(SCRIPT_FILE_PATH), '..');
42
-
43
- /**
44
- * @param {string} ruleFileAbsolutePath
45
- * @returns {Promise<{
46
- * sourcePath: string,
47
- * filename: string,
48
- * prefix: string,
49
- * sectionAssignments: Array<{ sectionTitle: string, sectionId: string, itemCount: number }>,
50
- * warnings: string[],
51
- * roundtrip: ReturnType<typeof roundtripSubstanceCheck>,
52
- * tokenSavings: { original: number, rendered: number, deltaPercent: number },
53
- * candidatePath: string,
54
- * rendered: string,
55
- * }>}
56
- */
57
- export async function migrateOneRuleFile(ruleFileAbsolutePath) {
58
- const filename = basename(ruleFileAbsolutePath);
59
- const prefixEntry = getPrefixEntry(filename);
60
- const originalSource = readFileSync(ruleFileAbsolutePath, 'utf8');
61
- const parsed = parseLegacyRuleFile(originalSource);
62
- const { rendered, sectionAssignments, warnings } = renderNewFormat(prefixEntry, parsed);
63
- const roundtrip = roundtripSubstanceCheck(originalSource, rendered);
64
-
65
- const originalTokenCount = await countTokens(originalSource, 'openai', 'gpt-4o-2024-08-06');
66
- const renderedTokenCount = await countTokens(rendered, 'openai', 'gpt-4o-2024-08-06');
67
- const tokenSavings = {
68
- original: originalTokenCount.token_count,
69
- rendered: renderedTokenCount.token_count,
70
- deltaPercent: Math.round(
71
- ((renderedTokenCount.token_count - originalTokenCount.token_count) / originalTokenCount.token_count) * 10000,
72
- ) / 100,
73
- };
74
-
75
- const candidatePath = ruleFileAbsolutePath.replace(/\.md$/, '.candidate.md');
76
-
77
- return {
78
- sourcePath: ruleFileAbsolutePath,
79
- filename,
80
- prefix: prefixEntry.prefix,
81
- sectionAssignments,
82
- warnings,
83
- roundtrip,
84
- tokenSavings,
85
- candidatePath,
86
- rendered,
87
- };
88
- }
89
-
90
- function formatHumanReport(report) {
91
- const lines = [];
92
- lines.push('=================================================');
93
- lines.push(` migrate-rule-format: ${report.filename}`);
94
- lines.push('=================================================');
95
- lines.push(` Prefix : ${report.prefix}`);
96
- lines.push(` Section count : ${report.sectionAssignments.length}`);
97
- lines.push(` Token (orig) : ${report.tokenSavings.original}`);
98
- lines.push(` Token (new) : ${report.tokenSavings.rendered}`);
99
- const sign = report.tokenSavings.deltaPercent <= 0 ? '' : '+';
100
- lines.push(` Token delta : ${sign}${report.tokenSavings.deltaPercent}%`);
101
- lines.push(` Roundtrip : ${report.roundtrip.passed ? 'PASS' : 'FAIL'} (${report.roundtrip.overlapPercent}% overlap, min ${report.roundtrip.minimumRequired}%)`);
102
- lines.push('');
103
-
104
- lines.push(' Sections assigned:');
105
- for (const assignment of report.sectionAssignments) {
106
- lines.push(` ${assignment.sectionId.padEnd(12)} ${assignment.itemCount} items ${assignment.sectionTitle}`);
107
- }
108
- lines.push('');
109
-
110
- if (report.warnings.length > 0) {
111
- lines.push(' Warnings:');
112
- for (const warning of report.warnings) {
113
- lines.push(` ! ${warning}`);
114
- }
115
- lines.push('');
116
- }
117
-
118
- if (report.roundtrip.lostWords.length > 0) {
119
- lines.push(` Substantial words present in original, missing in rendered (${report.roundtrip.lostWords.length} of distinct):`);
120
- for (const word of report.roundtrip.lostWords.slice(0, 30)) {
121
- lines.push(` - ${word}`);
122
- }
123
- if (report.roundtrip.lostWords.length > 30) {
124
- lines.push(` ... ${report.roundtrip.lostWords.length - 30} more (see JSON report)`);
125
- }
126
- lines.push('');
127
- }
128
-
129
- return lines.join('\n');
130
- }
131
-
132
- async function runCli() {
133
- const argv = process.argv.slice(2);
134
- if (argv.length === 0) {
135
- console.error('usage: node scripts/migrate-rule-format.mjs <path-to-rule-file> [--json] [--apply]');
136
- process.exit(2);
137
- }
138
-
139
- const inputPath = argv[0];
140
- const jsonMode = argv.includes('--json');
141
- const applyMode = argv.includes('--apply');
142
- const ruleFileAbsolutePath = resolve(REPOSITORY_ROOT, inputPath);
143
-
144
- let report;
145
- try {
146
- report = await migrateOneRuleFile(ruleFileAbsolutePath);
147
- } catch (migrationError) {
148
- if (jsonMode) {
149
- process.stdout.write(`${JSON.stringify({ passed: false, error: migrationError.message }, null, 2)}\n`);
150
- } else {
151
- console.error(`migrate-rule-format failed: ${migrationError.message}`);
152
- }
153
- process.exit(2);
154
- }
155
-
156
- if (applyMode) {
157
- writeFileSync(ruleFileAbsolutePath, report.rendered, 'utf8');
158
- } else {
159
- writeFileSync(report.candidatePath, report.rendered, 'utf8');
160
- }
161
-
162
- const exitCode = report.roundtrip.passed && report.warnings.length === 0 ? 0 : 1;
163
-
164
- if (jsonMode) {
165
- process.stdout.write(`${JSON.stringify({
166
- passed: report.roundtrip.passed,
167
- filename: report.filename,
168
- prefix: report.prefix,
169
- sectionCount: report.sectionAssignments.length,
170
- sectionAssignments: report.sectionAssignments,
171
- warnings: report.warnings,
172
- roundtrip: report.roundtrip,
173
- tokenSavings: report.tokenSavings,
174
- candidatePath: applyMode ? report.sourcePath : report.candidatePath,
175
- mode: applyMode ? 'apply' : 'candidate',
176
- }, null, 2)}\n`);
177
- process.exit(exitCode);
178
- }
179
-
180
- console.log(formatHumanReport(report));
181
- if (applyMode) {
182
- console.log(` APPLIED in place: ${report.sourcePath}`);
183
- } else {
184
- console.log(` Candidate written: ${report.candidatePath}`);
185
- console.log(' Review the diff, then re-run with --apply when satisfied.');
186
- }
187
- process.exit(exitCode);
188
- }
189
-
190
- if (import.meta.url === `file://${process.argv[1].replace(/\\/g, '/')}` || process.argv[1].endsWith('migrate-rule-format.mjs')) {
191
- runCli();
192
- }