@leonardo-marziali/ad-lfl-kit 5.1.0 → 5.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/README.md CHANGED
@@ -426,8 +426,60 @@ Claude every pre-existing violation in it. See
426
426
  pre-existing violations would quietly "fix" lines that match the ref.
427
427
  - **`mergeRanges(ranges)`** / **`widenRanges(ranges, context)`** — the range
428
428
  arithmetic, exposed for testing and for callers with their own ranges.
429
+ - **`parseHunkHeader(header)`** — both sides of one `@@ -a,b +c,d @@`
430
+ header as `{ oldStart, oldCount, newStart, newCount }`, or `null`.
429
431
  - **`DEFAULT_CONTEXT_LINES`** — `2`.
430
432
 
433
+ ### Scoped formatting (`format-scope.js`)
434
+
435
+ A linter's findings can be filtered after the fact; a formatter's output
436
+ can't, because the formatter rewrites the whole file. `formatInScope`
437
+ narrows it instead: it formats the text in memory, diffs the result against
438
+ the original, and writes back only the changes that touch the file's
439
+ changed lines (the same scope, and the same ±2-line margin, as
440
+ `scopesFor`).
441
+
442
+ ```js
443
+ const { formatInScope, runBin } = require('@leonardo-marziali/ad-lfl-kit');
444
+
445
+ const result = formatInScope({
446
+ file,
447
+ bases: readSessionBases(sessionDir),
448
+ formatStdin: (text) => {
449
+ const run = runBin('npx', ['-y', 'prettier', '--stdin-filepath', file], {
450
+ input: text,
451
+ encoding: 'utf8',
452
+ });
453
+ return { ok: run.status === 0, stdout: run.stdout, stderr: run.stderr };
454
+ },
455
+ });
456
+ // result.status: 'whole' | 'narrowed' | 'unchanged' | 'skipped'
457
+ ```
458
+
459
+ - **`formatInScope({ file, formatStdin, bases, context })`** — formats
460
+ `file` in place. `formatStdin(text)` runs the formatter on `text` as if it
461
+ were the file's content and returns `{ ok, stdout, stderr }`. `bases` and
462
+ `context` mean what they do for `scopesFor`. The result is
463
+ `{ status, reason? }`:
464
+ - `whole`: the whole file was in scope (no repository, an untracked
465
+ file, a diff that couldn't be read), and the formatter's full output
466
+ was written, as a plain `--write` would have done.
467
+ - `narrowed`: only the formatter's changes near the changed lines were
468
+ applied.
469
+ - `unchanged`: nothing in scope needed formatting; the file wasn't
470
+ written.
471
+ - `skipped`: the formatter failed, and `reason` carries its message. The
472
+ file wasn't written.
473
+
474
+ Formatter changes are matched against the changed lines one hunk at a time.
475
+ A hunk that replaces N lines with N lines is split into N one-line hunks,
476
+ so reformatting an already-messy file doesn't collapse into one hunk that
477
+ overlaps every edit. A hunk that changes the line count can't be split
478
+ safely, so it is applied whole or not at all. Because applying only some
479
+ hunks could in principle leave text the formatter can't parse, the partial
480
+ result goes through `formatStdin` once more and is written only if that
481
+ succeeds.
482
+
431
483
  ### The loop (`loop.js`)
432
484
 
433
485
  - **`runFixLoop({ input, dir, stateFiles, attemptsFile, maxAttempts, files,
@@ -0,0 +1,180 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Runs a formatter over a file but keeps only the changes it makes near the
5
+ * lines the working tree changed — scope.js's notion of "changed", the same
6
+ * one the narrowed linters use.
7
+ *
8
+ * Formatters work on whole files, and the range options some of them have
9
+ * (`ruff format --range`, Prettier's `--range-start`/`--range-end`) take one
10
+ * range per run, widen it to the enclosing node, and work only for some
11
+ * languages. So instead: format the whole text in memory, diff it against
12
+ * the original, and apply only the hunks whose original lines overlap the
13
+ * changed ranges (widened by the usual context margin). That works the same
14
+ * for every formatter that can read stdin.
15
+ *
16
+ * Wherever scope.js would scope the whole file — no repository, an untracked
17
+ * file, a diff it couldn't read — the whole formatted text is written, which
18
+ * is what a plain `--write` would have done.
19
+ *
20
+ * Applying some hunks and not others can, in principle, leave text the
21
+ * formatter can't parse. The partial result is fed back through the
22
+ * formatter once, and written only if that succeeds: a file is never left
23
+ * in a state its own formatter rejects.
24
+ */
25
+
26
+ const fs = require('node:fs');
27
+ const os = require('node:os');
28
+ const path = require('node:path');
29
+ const { runBin } = require('./exec');
30
+ const {
31
+ DEFAULT_CONTEXT_LINES,
32
+ changedRangesByFile,
33
+ parseHunkHeader,
34
+ widenRanges,
35
+ } = require('./scope');
36
+
37
+ const MAX_BUFFER = 64 * 1024 * 1024;
38
+
39
+ /*
40
+ * Lines with their terminators kept, so CRLF and a missing final newline
41
+ * survive a round trip: joining the chunks gives back the exact text.
42
+ */
43
+ function splitLines(text) {
44
+ const lines = [];
45
+ let start = 0;
46
+ for (let end = text.indexOf('\n'); end !== -1; end = text.indexOf('\n', start)) {
47
+ lines.push(text.slice(start, end + 1));
48
+ start = end + 1;
49
+ }
50
+ if (start < text.length) lines.push(text.slice(start));
51
+ return lines;
52
+ }
53
+
54
+ /*
55
+ * The hunks between `before` and `after`, as git sees them with no context.
56
+ * `git diff --no-index` exits 1 when the files differ, so 0 and 1 are both
57
+ * answers; anything else is a failure and returns null.
58
+ */
59
+ function diffHunks(before, after) {
60
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ad-lfl-kit-format-'));
61
+ try {
62
+ const a = path.join(dir, 'a');
63
+ const b = path.join(dir, 'b');
64
+ fs.writeFileSync(a, before);
65
+ fs.writeFileSync(b, after);
66
+ const result = runBin(
67
+ 'git',
68
+ ['diff', '--no-index', '--no-color', '--no-ext-diff', '--unified=0', '--', a, b],
69
+ { encoding: 'utf8', maxBuffer: MAX_BUFFER },
70
+ );
71
+ if (!result || result.error || (result.status !== 0 && result.status !== 1)) return null;
72
+ return (result.stdout || '')
73
+ .split('\n')
74
+ .filter((line) => line.startsWith('@@'))
75
+ .map(parseHunkHeader)
76
+ .filter(Boolean);
77
+ } finally {
78
+ fs.rmSync(dir, { recursive: true, force: true });
79
+ }
80
+ }
81
+
82
+ /*
83
+ * The lines of the ORIGINAL a hunk touches. A pure insertion (`-a,0`) sits
84
+ * after line a, so both neighbours count — the same rule scope.js applies
85
+ * to pure deletions on the other side of its diff.
86
+ */
87
+ function oldRange({ oldStart, oldCount }) {
88
+ if (oldCount > 0) return [oldStart, oldStart + oldCount - 1];
89
+ const at = Math.max(oldStart, 1);
90
+ return [at, at + 1];
91
+ }
92
+
93
+ /*
94
+ * git merges adjacent changed lines into one hunk, so a formatter that
95
+ * touches every line of a messy file would produce a single hunk that
96
+ * overlaps any edit. A hunk that replaces N lines with N lines is really N
97
+ * independent line replacements, and is split into them; one that changes
98
+ * the line count can't be split safely and stays whole.
99
+ */
100
+ function splitOneToOne(hunk) {
101
+ const { oldStart, oldCount, newStart, newCount } = hunk;
102
+ if (oldCount <= 1 || oldCount !== newCount) return [hunk];
103
+ return Array.from({ length: oldCount }, (_, i) => ({
104
+ oldStart: oldStart + i,
105
+ oldCount: 1,
106
+ newStart: newStart + i,
107
+ newCount: 1,
108
+ }));
109
+ }
110
+
111
+ function overlaps([start, end], ranges) {
112
+ return ranges.some(([from, to]) => start <= to && end >= from);
113
+ }
114
+
115
+ /*
116
+ * Replaces each kept hunk's original lines with the formatter's lines,
117
+ * bottom-up so the line numbers of hunks above stay valid.
118
+ */
119
+ function applyHunks(original, formatted, hunks) {
120
+ const lines = splitLines(original);
121
+ const formattedLines = splitLines(formatted);
122
+ const sorted = [...hunks].sort((x, y) => y.oldStart - x.oldStart);
123
+
124
+ for (const { oldStart, oldCount, newStart, newCount } of sorted) {
125
+ const at = oldCount > 0 ? oldStart - 1 : oldStart;
126
+ const replacement =
127
+ newCount > 0 ? formattedLines.slice(newStart - 1, newStart - 1 + newCount) : [];
128
+ lines.splice(at, oldCount, ...replacement);
129
+ }
130
+ return lines.join('');
131
+ }
132
+
133
+ function failureReason(result) {
134
+ return (result.stderr || result.stdout || 'formatter failed').trim();
135
+ }
136
+
137
+ /*
138
+ * Formats `file` in place, limited to its changed lines.
139
+ *
140
+ * - `formatStdin(text) → { ok, stdout, stderr }` runs the formatter on text
141
+ * as if it were `file`'s content (e.g. `prettier --stdin-filepath file`).
142
+ * - `bases` is scopesFor's option: session bases per repository root.
143
+ * - `context` widens each changed range, DEFAULT_CONTEXT_LINES by default.
144
+ *
145
+ * Returns `{ status, reason? }`: `whole` (the whole file was in scope and
146
+ * got formatted), `narrowed` (only some of the formatter's changes were
147
+ * applied), `unchanged` (nothing in scope to change), or `skipped` (the
148
+ * formatter failed; the file was not touched).
149
+ */
150
+ function formatInScope({ file, formatStdin, bases, context = DEFAULT_CONTEXT_LINES }) {
151
+ const absPath = path.resolve(file);
152
+ const original = fs.readFileSync(absPath, 'utf8');
153
+
154
+ const first = formatStdin(original);
155
+ if (!first.ok) return { status: 'skipped', reason: failureReason(first) };
156
+ const formatted = first.stdout;
157
+ if (formatted === original) return { status: 'unchanged' };
158
+
159
+ const changed = changedRangesByFile([absPath], { bases }).get(absPath);
160
+ if (!changed || changed.all) {
161
+ fs.writeFileSync(absPath, formatted);
162
+ return { status: 'whole' };
163
+ }
164
+
165
+ const ranges = widenRanges(changed.ranges, context);
166
+ const hunks = diffHunks(original, formatted);
167
+ if (!hunks) return { status: 'skipped', reason: 'could not diff the formatted output' };
168
+
169
+ const kept = hunks.flatMap(splitOneToOne).filter((hunk) => overlaps(oldRange(hunk), ranges));
170
+ if (kept.length === 0) return { status: 'unchanged' };
171
+
172
+ const partial = applyHunks(original, formatted, kept);
173
+ const recheck = formatStdin(partial);
174
+ if (!recheck.ok) return { status: 'skipped', reason: failureReason(recheck) };
175
+
176
+ fs.writeFileSync(absPath, partial);
177
+ return { status: 'narrowed' };
178
+ }
179
+
180
+ module.exports = { formatInScope };
package/index.js CHANGED
@@ -14,6 +14,7 @@ module.exports = {
14
14
  ...require('./track'),
15
15
  ...require('./base'),
16
16
  ...require('./scope'),
17
+ ...require('./format-scope'),
17
18
  ...require('./guard'),
18
19
  ...require('./loop'),
19
20
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leonardo-marziali/ad-lfl-kit",
3
- "version": "5.1.0",
3
+ "version": "5.2.0",
4
4
  "description": "Agentic development lint-fix-loop kit: session-scoped file tracking and a capped Stop-hook fix loop for Claude Code plugins.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -31,6 +31,7 @@
31
31
  "track.js",
32
32
  "base.js",
33
33
  "scope.js",
34
+ "format-scope.js",
34
35
  "guard.js",
35
36
  "loop.js"
36
37
  ],
package/scope.js CHANGED
@@ -38,7 +38,7 @@ const DEFAULT_CONTEXT_LINES = 2;
38
38
  */
39
39
  const MAX_BUFFER = 64 * 1024 * 1024;
40
40
 
41
- const HUNK_HEADER = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;
41
+ const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
42
42
 
43
43
  function git(args, cwd) {
44
44
  return runBin('git', args, { cwd, encoding: 'utf8', maxBuffer: MAX_BUFFER });
@@ -103,12 +103,27 @@ function readPathSet(result, root) {
103
103
  * blank line under a heading, say) is reported against whatever now sits
104
104
  * there.
105
105
  */
106
- function rangeFromHunk(header) {
106
+ /*
107
+ * Both sides of one `@@ -a,b +c,d @@` header. An omitted count means 1, as
108
+ * in git's own output. Null for anything that isn't a hunk header.
109
+ */
110
+ function parseHunkHeader(header) {
107
111
  const match = HUNK_HEADER.exec(header);
108
112
  if (!match) return null;
113
+ const count = (raw) => (raw === undefined ? 1 : Number(raw));
114
+ return {
115
+ oldStart: Number(match[1]),
116
+ oldCount: count(match[2]),
117
+ newStart: Number(match[3]),
118
+ newCount: count(match[4]),
119
+ };
120
+ }
121
+
122
+ function rangeFromHunk(header) {
123
+ const hunk = parseHunkHeader(header);
124
+ if (!hunk) return null;
109
125
 
110
- const start = Number(match[1]);
111
- const count = match[2] === undefined ? 1 : Number(match[2]);
126
+ const { newStart: start, newCount: count } = hunk;
112
127
  if (count > 0) return [start, start + count - 1];
113
128
 
114
129
  const at = Math.max(start, 1);
@@ -350,4 +365,5 @@ module.exports = {
350
365
  fixableFiles,
351
366
  mergeRanges,
352
367
  widenRanges,
368
+ parseHunkHeader,
353
369
  };