@better-fs-tools/write 0.3.0 → 0.4.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 +6 -4
- package/dist/contract/messages.d.ts +24 -2
- package/dist/core/messages.js +42 -4
- package/dist/core/patch-hunks.d.ts +7 -0
- package/dist/core/patch-hunks.js +58 -16
- package/dist/core/plan-edit.js +7 -2
- package/dist/core/plan-patch.js +9 -2
- package/dist/index.d.ts +1 -1
- package/dist/matchers/keep-bytes.d.ts +9 -0
- package/dist/matchers/keep-bytes.js +25 -0
- package/docs/architecture.md +3 -2
- package/docs/hosts.md +1 -1
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
<a href="https://betterfs.dev"><img src="https://betterfs.dev/brand/D-wordmark-auto.svg" alt="Better FS Tools" height="64"></a>
|
|
2
|
+
|
|
1
3
|
# @better-fs-tools/write
|
|
2
4
|
|
|
3
5
|
Edit, write, and apply_patch tools for TypeScript agents. They share one mutation core with the read tool in [`@better-fs-tools/read`](https://www.npmjs.com/package/@better-fs-tools/read): the same filesystem contract, the same read store, and the same resolvers and authorizers.
|
|
@@ -80,7 +82,7 @@ Every integration takes the options of the core factories, with the same default
|
|
|
80
82
|
|
|
81
83
|
`createEditTool({ fs })`. The input is a path and one or more `{ oldText, newText, replaceAll? }` pairs, all matched against one snapshot of the file. Each old text must match once, unless `replaceAll` is set. Pairs must not overlap. The replacement is a literal splice: `$&` and `$1` in the new text stay as written.
|
|
82
84
|
|
|
83
|
-
Matching tries `exactMatcher()` first, then `normalizedMatcher()` (trailing whitespace, Unicode normalization, curly quotes, dashes, and special spaces). A loose match gives a `fuzzy-match` note that names the lines. After a loose match with `normalizedMatcher()` or `lineTrimmedMatcher()`, the leading and trailing lines that the new text leaves as they were keep the file's bytes, and each replaced line keeps the CR of the file line it replaces. When the old text and the new text are the same, the edit can only change the characters that the matcher folded, so the new text is written as given. `escapeMatcher()` (escape sequences written out), `lineTrimmedMatcher()`, `indentationMatcher()`, and `blockAnchorMatcher()` are opt-in through the `matchers` option, for example `matchers: [...defaultEditMatchers(), escapeMatcher()]`.
|
|
85
|
+
Matching tries `exactMatcher()` first, then `normalizedMatcher()` (trailing whitespace, Unicode normalization, curly quotes, dashes, and special spaces). A loose match gives a `fuzzy-match` note that names the lines and says what the tool wrote: how many unchanged lines kept the file's characters, how many lines kept the file's CRLF line ends, or that the new lines were written as given. The note does not ask the model to check the result, because a model then often undid a correct edit. The `fuzzyMatch` and `patchFuzzyMatch` messages get these counts in an optional `written` argument. After a loose match with `normalizedMatcher()` or `lineTrimmedMatcher()`, the leading and trailing lines that the new text leaves as they were keep the file's bytes, and each replaced line keeps the CR of the file line it replaces. When the old text and the new text are the same, the edit can only change the characters that the matcher folded, so the new text is written as given. `escapeMatcher()` (escape sequences written out), `lineTrimmedMatcher()`, `indentationMatcher()`, and `blockAnchorMatcher()` are opt-in through the `matchers` option, for example `matchers: [...defaultEditMatchers(), escapeMatcher()]`.
|
|
84
86
|
|
|
85
87
|
When a pair does not match, the error is `NO_MATCH`, even when the new text is already in the file. `recovery: true` turns on three extras. The error shows the closest region of the file with line numbers. When the new text is already in the file and the old text is not, the pair is `already-applied` and the status is `no-change`. After three misses in a row on one file, the tool adds a `repeated-miss` note that asks the model to read the file again.
|
|
86
88
|
|
|
@@ -130,7 +132,7 @@ console.log(textOf(result));
|
|
|
130
132
|
// D /src/old.ts
|
|
131
133
|
```
|
|
132
134
|
|
|
133
|
-
Every operation is checked before any file changes. An Add on an existing file, an Update or Delete on a missing file, a move onto an existing file, two operations on one file, and a hunk that does not match all give `PATCH_VERIFY`, with every problem listed. Each hunk matches at the first place after the previous hunk, as Codex does. The chain is `exactMatcher()`, `normalizedMatcher()`, and `lineTrimmedMatcher()` on whole lines. Context lines keep the file's own bytes. So does a `-` line that comes back unchanged as a `+` line. Each other `+` line keeps the CR of the file line it replaces, so a CRLF line in a mixed-EOL file stays CRLF. When the old and new lines of a hunk are the same, the hunk can only change the characters that the matcher folded, so its `+` lines are written as given.
|
|
135
|
+
Every operation is checked before any file changes. An Add on an existing file, an Update or Delete on a missing file, a move onto an existing file, two operations on one file, and a hunk that does not match all give `PATCH_VERIFY`, with every problem listed. Each hunk matches at the first place after the previous hunk, as Codex does. A `@@ <line>` header moves the search to the line below the line it names. When the old lines are not found there, the tool also tries them at the named line itself, and takes that hit only when it starts at that line. This is a change from Codex, which looks only below the line. It lets a model write the line it changes as the `@@` header, for example `@@ target: A−B` followed by `-target: A−B`. A hunk that still does not match says where the search started, for example `failed to find the expected lines at line 2, where the @@ line matched, or from line 3 on`. The chain is `exactMatcher()`, `normalizedMatcher()`, and `lineTrimmedMatcher()` on whole lines. Context lines keep the file's own bytes. So does a `-` line that comes back unchanged as a `+` line. Each other `+` line keeps the CR of the file line it replaces, so a CRLF line in a mixed-EOL file stays CRLF. When the old and new lines of a hunk are the same, the hunk can only change the characters that the matcher folded, so its `+` lines are written as given.
|
|
134
136
|
|
|
135
137
|
The commit stages every new file when the backend has `stage()`, then publishes in patch order. Without `stage()` it writes each file in turn. When a step fails, the steps already done are undone from the end, and `result.commit` says so. When an undo step also fails, the code is `PARTIAL_COMMIT` and `result.commit.files` lists the state of every file. A host can pass its own `patchParser` for another patch format.
|
|
136
138
|
|
|
@@ -450,8 +452,8 @@ export const noGenerated: ToolAuthorizer<unknown> = {
|
|
|
450
452
|
## More
|
|
451
453
|
|
|
452
454
|
- [docs/architecture.md](docs/architecture.md): the pipeline, the stages, and why they are fixed
|
|
453
|
-
- [docs/result-schema.md](docs/result-schema.md): every field of the result, every error code, and every note, plus one table of the statuses and error codes of all five tools. The [write reference](https://
|
|
454
|
-
- [docs/hosts.md](docs/hosts.md): the defaults of every host and bundle, and what each backend can do. [Choose an integration](https://
|
|
455
|
+
- [docs/result-schema.md](docs/result-schema.md): every field of the result, every error code, and every note, plus one table of the statuses and error codes of all five tools. The [write reference](https://betterfs.dev/reference/write) on the docs site has the same facts
|
|
456
|
+
- [docs/hosts.md](docs/hosts.md): the defaults of every host and bundle, and what each backend can do. [Choose an integration](https://betterfs.dev/integrations) and [Filesystems](https://betterfs.dev/filesystems) on the docs site have the same tables
|
|
455
457
|
- [`@better-fs-tools/fs`](https://www.npmjs.com/package/@better-fs-tools/fs): the `WritableFileSystem` contract and its conformance suite
|
|
456
458
|
|
|
457
459
|
## License
|
|
@@ -3,6 +3,18 @@ import type { ToolMessages } from "@better-fs-tools/read";
|
|
|
3
3
|
import type { WriteToolName } from "./context.ts";
|
|
4
4
|
import type { WriteErrorCode, WritePhase } from "./result.ts";
|
|
5
5
|
export type WriteCanonicalParam = "path" | "edits" | "oldText" | "newText" | "replaceAll" | "content" | "patch";
|
|
6
|
+
/**
|
|
7
|
+
* What the tool wrote for one loose hit, compared line by line with the
|
|
8
|
+
* model's new lines. Each count is a number of lines.
|
|
9
|
+
*/
|
|
10
|
+
export interface FuzzyWrite {
|
|
11
|
+
/** Lines written with the file's own characters, not the model's. */
|
|
12
|
+
readonly keptLines: number;
|
|
13
|
+
/** Lines that kept the file's CR, which the model's line did not have. */
|
|
14
|
+
readonly keptLineEnds: number;
|
|
15
|
+
/** Lines that the matcher changed in another way, for example a new indentation. */
|
|
16
|
+
readonly adaptedLines: number;
|
|
17
|
+
}
|
|
6
18
|
/**
|
|
7
19
|
* Wording for every note the write tools produce. Text that names a model
|
|
8
20
|
* parameter gets the name from `param(name)`, which a signature overrides.
|
|
@@ -122,11 +134,13 @@ export interface WriteMessageCatalog extends ToolMessages {
|
|
|
122
134
|
path: string;
|
|
123
135
|
index: number;
|
|
124
136
|
}): string;
|
|
137
|
+
/** `written` is optional, so a host's own message can leave it out. */
|
|
125
138
|
fuzzyMatch(c: {
|
|
126
139
|
path: string;
|
|
127
140
|
index: number;
|
|
128
141
|
matcher: string;
|
|
129
142
|
lines: readonly [number, number];
|
|
143
|
+
written?: FuzzyWrite;
|
|
130
144
|
}): string;
|
|
131
145
|
repeatedMiss(c: {
|
|
132
146
|
path: string;
|
|
@@ -155,18 +169,26 @@ export interface WriteMessageCatalog extends ToolMessages {
|
|
|
155
169
|
hunk: number;
|
|
156
170
|
context: string;
|
|
157
171
|
}): string;
|
|
158
|
-
/**
|
|
172
|
+
/**
|
|
173
|
+
* `hunk` is one-based. `from` is the one-based line where the search
|
|
174
|
+
* started. `context` is the one-based line that the `@@` text matched, or
|
|
175
|
+
* null for a bare `@@`. The tool also tried the old lines at that line.
|
|
176
|
+
* Both are optional, so a host's own message can leave them out.
|
|
177
|
+
*/
|
|
159
178
|
patchLinesNotFound(c: {
|
|
160
179
|
path: string;
|
|
161
180
|
hunk: number;
|
|
162
181
|
lines: readonly string[];
|
|
182
|
+
from?: number;
|
|
183
|
+
context?: number | null;
|
|
163
184
|
}): string;
|
|
164
|
-
/** `hunk` is one-based. */
|
|
185
|
+
/** `hunk` is one-based. `written` is optional, as in fuzzyMatch. */
|
|
165
186
|
patchFuzzyMatch(c: {
|
|
166
187
|
path: string;
|
|
167
188
|
hunk: number;
|
|
168
189
|
matcher: string;
|
|
169
190
|
lines: readonly [number, number];
|
|
191
|
+
written?: FuzzyWrite;
|
|
170
192
|
}): string;
|
|
171
193
|
/** `files` is set when the rollback failed: the state of every file the patch targets. */
|
|
172
194
|
patchCommitFailed(c: {
|
package/dist/core/messages.js
CHANGED
|
@@ -70,7 +70,7 @@ function catalogUsingParam(param) {
|
|
|
70
70
|
overlap: ({ path, first, second }) => `Edits ${first + 1} and ${second + 1} change overlapping text in ${path}. Merge them into one edit.`,
|
|
71
71
|
noChange: ({ path }) => `The edits leave ${path} as it is. Check the ${param("newText")} values, or do not send the edit.`,
|
|
72
72
|
alreadyApplied: ({ path, index }) => `Edit ${index + 1} is already applied: the ${param("newText")} is in ${path} and the ${param("oldText")} is not. Do not send this edit again.`,
|
|
73
|
-
fuzzyMatch: ({ path, index, matcher, lines }) => `Edit ${index + 1} matched ${path} at ${lineSpan(lines)} only with the ${matcher} matcher, not exactly.
|
|
73
|
+
fuzzyMatch: ({ path, index, matcher, lines, written }) => `Edit ${index + 1} matched ${path} at ${lineSpan(lines)} only with the ${matcher} matcher, not exactly. The edit is applied.${wroteWhat(matcher, written)}`,
|
|
74
74
|
repeatedMiss: ({ path, misses }) => `This is miss ${misses} in a row on ${path}. Read the file again, include more surrounding lines, or replace the file with the write tool.`,
|
|
75
75
|
patchParse: ({ line, detail }) => `The patch could not be parsed at line ${line}: ${detail}`,
|
|
76
76
|
patchVerifyHeader: () => "Patch validation failed (no files were modified):",
|
|
@@ -80,11 +80,11 @@ function catalogUsingParam(param) {
|
|
|
80
80
|
: `${path} does not exist, so it cannot be deleted.`,
|
|
81
81
|
patchMoveExists: ({ path, from }) => `${path} already exists, so ${from} cannot move there. Choose another path, or delete ${path} first.`,
|
|
82
82
|
patchContextNotFound: ({ path, hunk, context }) => `${path}: hunk ${hunk}: failed to find the context line ${JSON.stringify(context)}.`,
|
|
83
|
-
patchLinesNotFound: ({ path, hunk, lines }) => [
|
|
84
|
-
`${path}: hunk ${hunk}: failed to find the expected lines:`,
|
|
83
|
+
patchLinesNotFound: ({ path, hunk, lines, from, context }) => [
|
|
84
|
+
`${path}: hunk ${hunk}: failed to find the expected lines${searchedWhere(from, context)}:`,
|
|
85
85
|
...lines.map((line) => ` ${line}`),
|
|
86
86
|
].join("\n"),
|
|
87
|
-
patchFuzzyMatch: ({ path, hunk, matcher, lines }) => `Hunk ${hunk} matched ${path} at ${lineSpan(lines)} only with the ${matcher} matcher, not exactly.
|
|
87
|
+
patchFuzzyMatch: ({ path, hunk, matcher, lines, written }) => `Hunk ${hunk} matched ${path} at ${lineSpan(lines)} only with the ${matcher} matcher, not exactly. The hunk is applied.${wroteWhat(matcher, written)}`,
|
|
88
88
|
patchCommitFailed: ({ path, code, rolledBack, files }) => rolledBack
|
|
89
89
|
? `Patch commit failed at ${path} (${code}). The patch was rolled back. No files are changed.`
|
|
90
90
|
: [
|
|
@@ -95,6 +95,44 @@ function catalogUsingParam(param) {
|
|
|
95
95
|
hookRewrote: ({ hook, path }) => `The ${hook} hook rewrote ${path} after the write. Read it again before relying on its text.`,
|
|
96
96
|
};
|
|
97
97
|
}
|
|
98
|
+
/**
|
|
99
|
+
* Says where a hunk's old lines were sought. Nothing for a search of the
|
|
100
|
+
* whole file, so the text stays the Codex text.
|
|
101
|
+
*/
|
|
102
|
+
function searchedWhere(from, context) {
|
|
103
|
+
if (context !== undefined && context !== null) {
|
|
104
|
+
return ` at line ${context}, where the @@ line matched, or from line ${context + 1} on`;
|
|
105
|
+
}
|
|
106
|
+
if (from === undefined || from <= 1)
|
|
107
|
+
return "";
|
|
108
|
+
return ` from line ${from} on, after the previous hunk`;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Says what the tool wrote after a loose match, so the model does not undo
|
|
112
|
+
* a correct change. Each sentence names only what took place for that hit.
|
|
113
|
+
*/
|
|
114
|
+
function wroteWhat(matcher, written) {
|
|
115
|
+
if (written === undefined)
|
|
116
|
+
return "";
|
|
117
|
+
const { keptLines, keptLineEnds, adaptedLines } = written;
|
|
118
|
+
const said = [];
|
|
119
|
+
if (keptLines > 0) {
|
|
120
|
+
said.push(`${lineCount(keptLines, "unchanged line")} kept the file's characters.`);
|
|
121
|
+
}
|
|
122
|
+
if (keptLineEnds > 0) {
|
|
123
|
+
const ends = keptLineEnds === 1 ? "line end" : "line ends";
|
|
124
|
+
said.push(`${lineCount(keptLineEnds, "line")} kept the file's CRLF ${ends}.`);
|
|
125
|
+
}
|
|
126
|
+
if (adaptedLines > 0) {
|
|
127
|
+
said.push(`The ${matcher} matcher changed ${lineCount(adaptedLines, "line")} to fit the file.`);
|
|
128
|
+
}
|
|
129
|
+
if (said.length === 0)
|
|
130
|
+
said.push("The new lines were written as given.");
|
|
131
|
+
return ` ${said.join(" ")}`;
|
|
132
|
+
}
|
|
133
|
+
function lineCount(count, noun) {
|
|
134
|
+
return `${count} ${noun}${count === 1 ? "" : "s"}`;
|
|
135
|
+
}
|
|
98
136
|
/** Names a span of 1-based lines: "line 4" for one line, "lines 4-6" for more. */
|
|
99
137
|
function lineSpan(lines) {
|
|
100
138
|
return lines[0] === lines[1] ? `line ${lines[0]}` : `lines ${lines[0]}-${lines[1]}`;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ChangeFragment } from "../contract/extensions.ts";
|
|
2
2
|
import type { Matcher } from "../contract/matcher.ts";
|
|
3
3
|
import type { PatchHunk } from "../contract/patch.ts";
|
|
4
|
+
import type { FuzzyWrite } from "../contract/messages.ts";
|
|
4
5
|
import type { MatchInfo } from "../contract/result.ts";
|
|
5
6
|
import type { MutationScope } from "./scope.ts";
|
|
6
7
|
export type HunkProblem = {
|
|
@@ -11,11 +12,17 @@ export type HunkProblem = {
|
|
|
11
12
|
readonly reason: "lines-not-found";
|
|
12
13
|
readonly hunk: number;
|
|
13
14
|
readonly lines: readonly string[];
|
|
15
|
+
/** Zero-based line where the search for the old lines started. */
|
|
16
|
+
readonly from: number;
|
|
17
|
+
/** Zero-based line that the `@@` text matched, or null for a bare `@@`. */
|
|
18
|
+
readonly context: number | null;
|
|
14
19
|
};
|
|
15
20
|
export type HunksOutcome = {
|
|
16
21
|
readonly ok: true;
|
|
17
22
|
readonly text: string;
|
|
18
23
|
readonly matches: readonly MatchInfo[];
|
|
24
|
+
/** For each match, what the tool wrote compared with the hunk's lines. */
|
|
25
|
+
readonly written: readonly FuzzyWrite[];
|
|
19
26
|
readonly changed: readonly (readonly [number, number])[];
|
|
20
27
|
readonly fragments: readonly ChangeFragment[];
|
|
21
28
|
} | {
|
package/dist/core/patch-hunks.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { keepFileLines } from "../matchers/keep-bytes.js";
|
|
1
|
+
import { describeWrite, keepFileLines } from "../matchers/keep-bytes.js";
|
|
2
2
|
import { findWith } from "./match.js";
|
|
3
3
|
export function applyHunks(scope, matchers, text, hunks) {
|
|
4
4
|
const file = new LineFile(text);
|
|
@@ -6,6 +6,7 @@ export function applyHunks(scope, matchers, text, hunks) {
|
|
|
6
6
|
const found = [];
|
|
7
7
|
let cursor = 0;
|
|
8
8
|
for (const [index, hunk] of hunks.entries()) {
|
|
9
|
+
let context = null;
|
|
9
10
|
if (hunk.context !== null) {
|
|
10
11
|
const hit = file.seek(scope, matchers, [hunk.context], cursor, false);
|
|
11
12
|
if (hit === null) {
|
|
@@ -14,27 +15,33 @@ export function applyHunks(scope, matchers, text, hunks) {
|
|
|
14
15
|
problem: { reason: "context-not-found", hunk: index, context: hunk.context },
|
|
15
16
|
};
|
|
16
17
|
}
|
|
18
|
+
context = hit.line;
|
|
17
19
|
cursor = hit.line + 1;
|
|
18
20
|
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
let hit = old.length === 0 ? null : file.seek(scope, matchers, old, cursor, hunk.endOfFile);
|
|
22
|
-
if (hit === null && old.length > 0 && old.at(-1) === "") {
|
|
23
|
-
// A trailing empty old line is often only a blank separator.
|
|
24
|
-
body = withoutLastOldLine(body);
|
|
25
|
-
old = oldLines(body);
|
|
26
|
-
hit = old.length === 0 ? null : file.seek(scope, matchers, old, cursor, hunk.endOfFile);
|
|
27
|
-
}
|
|
28
|
-
if (old.length === 0) {
|
|
21
|
+
const after = findOld(hunk, (old) => file.seek(scope, matchers, old, cursor, hunk.endOfFile));
|
|
22
|
+
if (after.old.length === 0) {
|
|
29
23
|
const insertAt = hunk.context === null ? file.lines.length : cursor;
|
|
30
|
-
replacements.push({ start: insertAt, remove: 0, lines: body.map((line) => line.text) });
|
|
24
|
+
replacements.push({ start: insertAt, remove: 0, lines: after.body.map((line) => line.text) });
|
|
31
25
|
continue;
|
|
32
26
|
}
|
|
27
|
+
// A hunk whose @@ text is its own first old line: the model named the
|
|
28
|
+
// line it changes. Codex looks only below that line; this also tries
|
|
29
|
+
// the line itself, and takes a hit only when it starts there.
|
|
30
|
+
const anchor = context;
|
|
31
|
+
const at = after.hit !== null || anchor === null
|
|
32
|
+
? null
|
|
33
|
+
: findOld(hunk, (old) => file.seekAt(scope, matchers, old, anchor, hunk.endOfFile));
|
|
34
|
+
const { body, old, hit } = at !== null && at.hit !== null ? at : after;
|
|
33
35
|
if (hit === null) {
|
|
34
|
-
return {
|
|
36
|
+
return {
|
|
37
|
+
ok: false,
|
|
38
|
+
problem: { reason: "lines-not-found", hunk: index, lines: old, from: cursor, context },
|
|
39
|
+
};
|
|
35
40
|
}
|
|
36
|
-
|
|
37
|
-
|
|
41
|
+
const lines = newLines(body, file, hit);
|
|
42
|
+
replacements.push({ start: hit.line, remove: old.length, lines });
|
|
43
|
+
const written = describeWrite(file.lines.slice(hit.line, hit.line + old.length), body.filter((line) => line.kind !== "-").map((line) => line.text), lines);
|
|
44
|
+
found.push({ index, hit, size: old.length, written });
|
|
38
45
|
cursor = hit.line + old.length;
|
|
39
46
|
}
|
|
40
47
|
return applyReplacements(file, replacements, found);
|
|
@@ -79,7 +86,22 @@ function applyReplacements(file, replacements, found) {
|
|
|
79
86
|
newText: replacement.lines.join("\n"),
|
|
80
87
|
}));
|
|
81
88
|
const ending = file.finalNewline && result.length > 0 ? "\n" : "";
|
|
82
|
-
|
|
89
|
+
const written = found.map((entry) => entry.written);
|
|
90
|
+
return { ok: true, text: `${result.join("\n")}${ending}`, matches, written, changed, fragments };
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Seeks the old lines of a hunk. When they are not found and the last old
|
|
94
|
+
* line is empty, seeks again without it: it is often only a blank separator.
|
|
95
|
+
*/
|
|
96
|
+
function findOld(hunk, seek) {
|
|
97
|
+
const old = oldLines(hunk.lines);
|
|
98
|
+
const hit = old.length === 0 ? null : seek(old);
|
|
99
|
+
if (hit !== null || old.length === 0 || old.at(-1) !== "") {
|
|
100
|
+
return { body: hunk.lines, old, hit };
|
|
101
|
+
}
|
|
102
|
+
const body = withoutLastOldLine(hunk.lines);
|
|
103
|
+
const shorter = oldLines(body);
|
|
104
|
+
return { body, old: shorter, hit: shorter.length === 0 ? null : seek(shorter) };
|
|
83
105
|
}
|
|
84
106
|
function oldLines(body) {
|
|
85
107
|
return body.filter((line) => line.kind !== "+").map((line) => line.text);
|
|
@@ -184,6 +206,26 @@ class LineFile {
|
|
|
184
206
|
}
|
|
185
207
|
return null;
|
|
186
208
|
}
|
|
209
|
+
/** Like seek(), but takes a hit only when it starts at `line`. */
|
|
210
|
+
seekAt(scope, matchers, wanted, line, endOfFile) {
|
|
211
|
+
const last = this.lines.length - wanted.length;
|
|
212
|
+
if (line > last || (endOfFile && line !== last))
|
|
213
|
+
return null;
|
|
214
|
+
const needle = wanted.map((text) => `${text}\n`).join("");
|
|
215
|
+
for (const matcher of matchers) {
|
|
216
|
+
scope.checkAbort();
|
|
217
|
+
const [range] = findWith(scope, matcher, this.haystack, needle, {
|
|
218
|
+
mode: "lines",
|
|
219
|
+
from: this.lineStartOffsets[line],
|
|
220
|
+
maxMatches: 1,
|
|
221
|
+
});
|
|
222
|
+
if (range === undefined || this.lineAt(range.start) !== line)
|
|
223
|
+
continue;
|
|
224
|
+
if (this.coversWholeLines(range, line, wanted.length))
|
|
225
|
+
return { line, matcher };
|
|
226
|
+
}
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
187
229
|
coversWholeLines(range, line, count) {
|
|
188
230
|
if (range.refused !== undefined)
|
|
189
231
|
return false;
|
package/dist/core/plan-edit.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { exactMatcher } from "../matchers/exact.js";
|
|
2
|
+
import { describeWrite } from "../matchers/keep-bytes.js";
|
|
2
3
|
import { closestRegion, isAlreadyApplied, trailingNewline } from "./hints.js";
|
|
3
4
|
import { LineIndex } from "./line-index.js";
|
|
4
5
|
import { REPLACE_ALL_CAP, adaptFor, escapeDrift, findWith, runChain, tooWide } from "./match.js";
|
|
@@ -82,9 +83,11 @@ export function planEdit(scope, input, target, loaded, pre) {
|
|
|
82
83
|
replaced: byPair.get(pair.index) ?? [],
|
|
83
84
|
};
|
|
84
85
|
});
|
|
85
|
-
for (const match of matches) {
|
|
86
|
+
for (const [at, match] of matches.entries()) {
|
|
86
87
|
if (!match.fuzzy)
|
|
87
88
|
continue;
|
|
89
|
+
const pair = found[at];
|
|
90
|
+
const first = pair.hits[0];
|
|
88
91
|
scope.notes.push({
|
|
89
92
|
code: "fuzzy-match",
|
|
90
93
|
severity: "info",
|
|
@@ -93,6 +96,7 @@ export function planEdit(scope, input, target, loaded, pre) {
|
|
|
93
96
|
index: match.index,
|
|
94
97
|
matcher: match.matcher,
|
|
95
98
|
lines: match.lines,
|
|
99
|
+
written: describeWrite(text.slice(first.start, first.end).split("\n"), pair.newText.split("\n"), first.text.split("\n")),
|
|
96
100
|
}),
|
|
97
101
|
data: { index: match.index, matcher: match.matcher, lines: [...match.lines] },
|
|
98
102
|
});
|
|
@@ -174,7 +178,7 @@ function matchPair(scope, input, target, text, pair, index) {
|
|
|
174
178
|
}
|
|
175
179
|
return { start: range.start, end: range.end, text: replacement };
|
|
176
180
|
});
|
|
177
|
-
return { index, matcher, hits };
|
|
181
|
+
return { index, matcher, hits, newText: pair.newText };
|
|
178
182
|
}
|
|
179
183
|
function rematchAfterStale(scope, text, pair, index, path) {
|
|
180
184
|
const ranges = findWith(scope, STALE_REMATCH_MATCHER, text, pair.oldText, {
|
|
@@ -191,6 +195,7 @@ function rematchAfterStale(scope, text, pair, index, path) {
|
|
|
191
195
|
index,
|
|
192
196
|
matcher: STALE_REMATCH_MATCHER,
|
|
193
197
|
hits: ranges.map((range) => ({ start: range.start, end: range.end, text: pair.newText })),
|
|
198
|
+
newText: pair.newText,
|
|
194
199
|
};
|
|
195
200
|
}
|
|
196
201
|
function noMatchFailure(scope, input, target, text, pair, index) {
|
package/dist/core/plan-patch.js
CHANGED
|
@@ -66,7 +66,7 @@ export function planPatch(scope, matchers, targets, problems) {
|
|
|
66
66
|
message: messages.staleRematched({ path: main.displayPath }),
|
|
67
67
|
});
|
|
68
68
|
}
|
|
69
|
-
for (const match of outcome.matches) {
|
|
69
|
+
for (const [at, match] of outcome.matches.entries()) {
|
|
70
70
|
if (!match.fuzzy)
|
|
71
71
|
continue;
|
|
72
72
|
scope.notes.push({
|
|
@@ -77,6 +77,7 @@ export function planPatch(scope, matchers, targets, problems) {
|
|
|
77
77
|
hunk: match.index + 1,
|
|
78
78
|
matcher: match.matcher,
|
|
79
79
|
lines: match.lines,
|
|
80
|
+
written: outcome.written[at],
|
|
80
81
|
}),
|
|
81
82
|
data: { path: main.displayPath, hunk: match.index, matcher: match.matcher },
|
|
82
83
|
});
|
|
@@ -107,7 +108,13 @@ function hunkProblem(scope, path, line, problem) {
|
|
|
107
108
|
const hunk = problem.hunk + 1;
|
|
108
109
|
const message = problem.reason === "context-not-found"
|
|
109
110
|
? messages.patchContextNotFound({ path, hunk, context: problem.context })
|
|
110
|
-
: messages.patchLinesNotFound({
|
|
111
|
+
: messages.patchLinesNotFound({
|
|
112
|
+
path,
|
|
113
|
+
hunk,
|
|
114
|
+
lines: problem.lines,
|
|
115
|
+
from: problem.from + 1,
|
|
116
|
+
context: problem.context === null ? null : problem.context + 1,
|
|
117
|
+
});
|
|
111
118
|
return { path, line, reason: problem.reason, message, hunk: problem.hunk };
|
|
112
119
|
}
|
|
113
120
|
function planAdd(scope, target, content) {
|
package/dist/index.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export type { LockManager, LockOutcome } from "./contract/locks.ts";
|
|
|
9
9
|
export type { PreconditionPolicy } from "./contract/preconditions.ts";
|
|
10
10
|
export type { WriteFormatContext, WriteFormatter } from "./contract/format.ts";
|
|
11
11
|
export type { WriteLimits } from "./contract/limits.ts";
|
|
12
|
-
export type { WriteCanonicalParam, WriteMessageCatalog } from "./contract/messages.ts";
|
|
12
|
+
export type { FuzzyWrite, WriteCanonicalParam, WriteMessageCatalog } from "./contract/messages.ts";
|
|
13
13
|
export { createApplyPatchTool, createEditTool, createWriteTool } from "./core/create-tools.ts";
|
|
14
14
|
export { parseApplyPatchInput, parseEditInput, parseWriteInput } from "./core/input.ts";
|
|
15
15
|
export { defaultWriteLimits, resolveWriteLimits } from "./core/limits.ts";
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { FuzzyWrite } from "../contract/messages.ts";
|
|
1
2
|
/**
|
|
2
3
|
* Builds the new lines for one loose hit so that text the model did not
|
|
3
4
|
* change keeps the file's bytes.
|
|
@@ -20,3 +21,11 @@ export declare function keepFileLines(file: readonly string[], old: readonly str
|
|
|
20
21
|
* when it did not, the new text is written as given.
|
|
21
22
|
*/
|
|
22
23
|
export declare function adaptKeepingBytes(newText: string, region: string, needle: string, lined: (file: readonly string[], old: readonly string[]) => boolean): string;
|
|
24
|
+
/**
|
|
25
|
+
* Compares what the tool wrote for one loose hit with the model's new lines,
|
|
26
|
+
* position by position. `file` holds the file's own lines of the hit. A
|
|
27
|
+
* written line that differs from the model's line only by a final CR kept the
|
|
28
|
+
* file's line end. One that is a line of `file` kept the file's characters.
|
|
29
|
+
* Any other difference came from the matcher.
|
|
30
|
+
*/
|
|
31
|
+
export declare function describeWrite(file: readonly string[], given: readonly string[], written: readonly string[]): FuzzyWrite;
|
|
@@ -49,3 +49,28 @@ export function adaptKeepingBytes(newText, region, needle, lined) {
|
|
|
49
49
|
return newText;
|
|
50
50
|
return keepFileLines(file, old, newText.split("\n"), newText !== needle).join("\n");
|
|
51
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* Compares what the tool wrote for one loose hit with the model's new lines,
|
|
54
|
+
* position by position. `file` holds the file's own lines of the hit. A
|
|
55
|
+
* written line that differs from the model's line only by a final CR kept the
|
|
56
|
+
* file's line end. One that is a line of `file` kept the file's characters.
|
|
57
|
+
* Any other difference came from the matcher.
|
|
58
|
+
*/
|
|
59
|
+
export function describeWrite(file, given, written) {
|
|
60
|
+
let keptLines = 0;
|
|
61
|
+
let keptLineEnds = 0;
|
|
62
|
+
let adaptedLines = 0;
|
|
63
|
+
for (const [at, line] of written.entries()) {
|
|
64
|
+
const sent = given[at];
|
|
65
|
+
if (line === sent)
|
|
66
|
+
continue;
|
|
67
|
+
if (sent !== undefined && line === `${sent}${CR}`)
|
|
68
|
+
keptLineEnds += 1;
|
|
69
|
+
else if (sent !== undefined && file.includes(line))
|
|
70
|
+
keptLines += 1;
|
|
71
|
+
else
|
|
72
|
+
adaptedLines += 1;
|
|
73
|
+
}
|
|
74
|
+
adaptedLines += Math.max(0, given.length - written.length);
|
|
75
|
+
return { keptLines, keptLineEnds, adaptedLines };
|
|
76
|
+
}
|
package/docs/architecture.md
CHANGED
|
@@ -89,7 +89,7 @@ An allow decision in the change stage may carry `content` for `edit` and `write`
|
|
|
89
89
|
|
|
90
90
|
The lock key is the real path, and only `stat` knows it. So the core stats, authorizes access, locks every real path of the call in sorted order, and stats again. The second stat decides: a file that appeared or vanished between the two stats is judged by it, and a real path that changed gives `STALE`.
|
|
91
91
|
|
|
92
|
-
`memoryLocks()` orders writers inside one process. The read tool takes no lock: it detects a change with `verify()`, and each write replaces the file in one step on a backend that can. `createFsTools()`, and the bundles that wrap it (`
|
|
92
|
+
`memoryLocks()` orders writers inside one process. The read tool takes no lock: it detects a change with `verify()`, and each write replaces the file in one step on a backend that can. `createFsTools()`, and the bundles that wrap it (`createPiFsTools()` and `createAiSdkFsTools()`), share one lock manager across the three write tools.
|
|
93
93
|
|
|
94
94
|
## Load
|
|
95
95
|
|
|
@@ -130,6 +130,7 @@ The core owns the rules on every hit:
|
|
|
130
130
|
|
|
131
131
|
- The splice is literal: `text.slice(0, start) + newText + text.slice(end)`. `String.prototype.replace` is never called, so `$&` and `$1` stay as written.
|
|
132
132
|
- A matcher's `adapt()` can rewrite the new text for its hit before the splice. `normalizedMatcher()` and `lineTrimmedMatcher()` use it so that the leading and trailing lines the new text leaves as they were keep the file's bytes, and each replaced line keeps the CR of the file line it replaces. When the old text and the new text are the same, the new text keeps its characters.
|
|
133
|
+
- Each loose hit gives a `fuzzy-match` note. `describeWrite()` compares the written lines with the model's new lines, line by line, and counts the lines that kept the file's characters, the lines that kept only the file's CR, and the lines that the matcher changed in another way. `fuzzyMatch` and `patchFuzzyMatch` get the counts as `written`, and the default text says only what took place. `apply_patch` makes the same counts in `applyHunks()`.
|
|
133
134
|
- A loose hit much longer than the old text (`span`), a hit that starts or ends inside a folded span (`boundary`), and a loose hit whose new text adds escape sequences the matched text does not have (`escape`) give `MATCH_REFUSED`.
|
|
134
135
|
- Ranges of different pairs must not overlap. Splices apply from the end.
|
|
135
136
|
- A result equal to the original gives `NO_CHANGE`, unless every pair is already applied.
|
|
@@ -140,7 +141,7 @@ A miss is `NO_MATCH`, with a trailing-newline hint when that is the only differe
|
|
|
140
141
|
|
|
141
142
|
The order is parse, resolve, stat, access, lock, stat again, load, preconditions, verify every hunk, plan, guards, change authorize, encode, commit, hooks, record.
|
|
142
143
|
|
|
143
|
-
Verification collects every problem before anything changes: an Add on an existing file, an Update or Delete on a missing file, a move onto an existing file, two operations on one file, a missing `remove()` for a Delete or Move, and each hunk that does not match. Each hunk matches at the first place after the previous hunk (Codex). The chain runs on whole lines. A ` ` context line takes the file's own line, so its bytes stay the same. In each run of `-` and `+` lines, a `-` line that comes back unchanged as a `+` line also takes the file's line, and each other `+` line takes the CR of the file line it replaces. A hunk whose old and new lines are the same writes its `+` lines as given, with those CRs.
|
|
144
|
+
Verification collects every problem before anything changes: an Add on an existing file, an Update or Delete on a missing file, a move onto an existing file, two operations on one file, a missing `remove()` for a Delete or Move, and each hunk that does not match. Each hunk matches at the first place after the previous hunk (Codex). A `@@` header moves the search below the line it matches. When the old lines are not found from there, `applyHunks()` tries them once more at the header's own line with `seekAt()`, which takes a hit only when it starts at that line. This differs from Codex: it accepts a hunk whose first `-` or context line repeats the header. The trailing-blank retry runs in both searches. The `lines-not-found` problem holds the line where the search started and the line the header matched, and `patchLinesNotFound` names them. The chain runs on whole lines. A ` ` context line takes the file's own line, so its bytes stay the same. In each run of `-` and `+` lines, a `-` line that comes back unchanged as a `+` line also takes the file's line, and each other `+` line takes the CR of the file line it replaces. A hunk whose old and new lines are the same writes its `+` lines as given, with those CRs.
|
|
144
145
|
|
|
145
146
|
The commit keeps a journal:
|
|
146
147
|
|
package/docs/hosts.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Hosts and backends
|
|
2
2
|
|
|
3
|
-
This page helps you choose an integration and a filesystem backend. It lists the defaults that every integration shares, the few options that only one host has, a recommended configuration for each host, and what each backend can do. The READMEs of the integration and backend packages link here. The docs site has the same facts on [Choose an integration](https://
|
|
3
|
+
This page helps you choose an integration and a filesystem backend. It lists the defaults that every integration shares, the few options that only one host has, a recommended configuration for each host, and what each backend can do. The READMEs of the integration and backend packages link here. The docs site has the same facts on [Choose an integration](https://betterfs.dev/integrations) and [Filesystems](https://betterfs.dev/filesystems).
|
|
4
4
|
|
|
5
5
|
## One interface in three layers
|
|
6
6
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@better-fs-tools/write",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Edit, write, and apply_patch tools for TypeScript agents.",
|
|
5
|
+
"homepage": "https://betterfs.dev",
|
|
5
6
|
"license": "MIT",
|
|
6
7
|
"repository": {
|
|
7
8
|
"type": "git",
|
|
@@ -46,9 +47,9 @@
|
|
|
46
47
|
"access": "public"
|
|
47
48
|
},
|
|
48
49
|
"dependencies": {
|
|
49
|
-
"@better-fs-tools/fs": "^0.
|
|
50
|
-
"@better-fs-tools/read": "^0.
|
|
51
|
-
"@better-fs-tools/shell": "^0.
|
|
50
|
+
"@better-fs-tools/fs": "^0.4.0",
|
|
51
|
+
"@better-fs-tools/read": "^0.4.0",
|
|
52
|
+
"@better-fs-tools/shell": "^0.4.0"
|
|
52
53
|
},
|
|
53
54
|
"devDependencies": {
|
|
54
55
|
"typebox": "^1.3.16"
|