@better-fs-tools/write 0.0.0-tegami-trusted-publish-setup → 0.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.
Files changed (196) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +449 -6
  3. package/dist/authorize/ask-before-write.d.ts +11 -0
  4. package/dist/authorize/ask-before-write.js +49 -0
  5. package/dist/authorize/index.d.ts +3 -0
  6. package/dist/authorize/index.js +3 -0
  7. package/dist/authorize/protect-paths.d.ts +12 -0
  8. package/dist/authorize/protect-paths.js +74 -0
  9. package/dist/authorize/write-authorizers.d.ts +9 -0
  10. package/dist/authorize/write-authorizers.js +48 -0
  11. package/dist/bundle/create-fs-tools.d.ts +93 -0
  12. package/dist/bundle/create-fs-tools.js +130 -0
  13. package/dist/codecs/index.d.ts +1 -0
  14. package/dist/codecs/index.js +1 -0
  15. package/dist/codecs/utf8.d.ts +7 -0
  16. package/dist/codecs/utf8.js +61 -0
  17. package/dist/contract/codec.d.ts +26 -0
  18. package/dist/contract/codec.js +0 -0
  19. package/dist/contract/context.d.ts +14 -0
  20. package/dist/contract/context.js +0 -0
  21. package/dist/contract/deps.d.ts +63 -0
  22. package/dist/contract/deps.js +0 -0
  23. package/dist/contract/extensions.d.ts +103 -0
  24. package/dist/contract/extensions.js +0 -0
  25. package/dist/contract/format.d.ts +15 -0
  26. package/dist/contract/format.js +0 -0
  27. package/dist/contract/input.d.ts +35 -0
  28. package/dist/contract/input.js +0 -0
  29. package/dist/contract/limits.d.ts +26 -0
  30. package/dist/contract/limits.js +0 -0
  31. package/dist/contract/locks.d.ts +14 -0
  32. package/dist/contract/locks.js +0 -0
  33. package/dist/contract/matcher.d.ts +30 -0
  34. package/dist/contract/matcher.js +0 -0
  35. package/dist/contract/messages.d.ts +188 -0
  36. package/dist/contract/messages.js +0 -0
  37. package/dist/contract/patch.d.ts +50 -0
  38. package/dist/contract/patch.js +0 -0
  39. package/dist/contract/preconditions.d.ts +13 -0
  40. package/dist/contract/preconditions.js +5 -0
  41. package/dist/contract/result.d.ts +102 -0
  42. package/dist/contract/result.js +0 -0
  43. package/dist/core/abort.d.ts +4 -0
  44. package/dist/core/abort.js +23 -0
  45. package/dist/core/authorize.d.ts +9 -0
  46. package/dist/core/authorize.js +87 -0
  47. package/dist/core/bytes.d.ts +3 -0
  48. package/dist/core/bytes.js +14 -0
  49. package/dist/core/commit-patch.d.ts +20 -0
  50. package/dist/core/commit-patch.js +224 -0
  51. package/dist/core/commit.d.ts +8 -0
  52. package/dist/core/commit.js +77 -0
  53. package/dist/core/create-tools.d.ts +23 -0
  54. package/dist/core/create-tools.js +54 -0
  55. package/dist/core/deps.d.ts +11 -0
  56. package/dist/core/deps.js +210 -0
  57. package/dist/core/diff.d.ts +10 -0
  58. package/dist/core/diff.js +221 -0
  59. package/dist/core/encode.d.ts +3 -0
  60. package/dist/core/encode.js +26 -0
  61. package/dist/core/extension-error.d.ts +8 -0
  62. package/dist/core/extension-error.js +17 -0
  63. package/dist/core/format.d.ts +4 -0
  64. package/dist/core/format.js +22 -0
  65. package/dist/core/guards.d.ts +3 -0
  66. package/dist/core/guards.js +45 -0
  67. package/dist/core/hints.d.ts +14 -0
  68. package/dist/core/hints.js +75 -0
  69. package/dist/core/hooks.d.ts +15 -0
  70. package/dist/core/hooks.js +108 -0
  71. package/dist/core/input.d.ts +20 -0
  72. package/dist/core/input.js +91 -0
  73. package/dist/core/limits.d.ts +10 -0
  74. package/dist/core/limits.js +48 -0
  75. package/dist/core/line-index.d.ts +10 -0
  76. package/dist/core/line-index.js +38 -0
  77. package/dist/core/load.d.ts +14 -0
  78. package/dist/core/load.js +221 -0
  79. package/dist/core/lock.d.ts +2 -0
  80. package/dist/core/lock.js +56 -0
  81. package/dist/core/match.d.ts +15 -0
  82. package/dist/core/match.js +66 -0
  83. package/dist/core/messages.d.ts +8 -0
  84. package/dist/core/messages.js +140 -0
  85. package/dist/core/outcomes.d.ts +21 -0
  86. package/dist/core/outcomes.js +127 -0
  87. package/dist/core/parse-patch.d.ts +3 -0
  88. package/dist/core/parse-patch.js +64 -0
  89. package/dist/core/patch-hunks.d.ts +25 -0
  90. package/dist/core/patch-hunks.js +177 -0
  91. package/dist/core/patch-pipeline.d.ts +4 -0
  92. package/dist/core/patch-pipeline.js +284 -0
  93. package/dist/core/pipeline.d.ts +22 -0
  94. package/dist/core/pipeline.js +153 -0
  95. package/dist/core/plan-edit.d.ts +15 -0
  96. package/dist/core/plan-edit.js +215 -0
  97. package/dist/core/plan-patch.d.ts +29 -0
  98. package/dist/core/plan-patch.js +169 -0
  99. package/dist/core/plan-write.d.ts +6 -0
  100. package/dist/core/plan-write.js +27 -0
  101. package/dist/core/planned.d.ts +35 -0
  102. package/dist/core/planned.js +36 -0
  103. package/dist/core/precondition.d.ts +10 -0
  104. package/dist/core/precondition.js +65 -0
  105. package/dist/core/record.d.ts +3 -0
  106. package/dist/core/record.js +58 -0
  107. package/dist/core/resolve.d.ts +3 -0
  108. package/dist/core/resolve.js +65 -0
  109. package/dist/core/scope.d.ts +33 -0
  110. package/dist/core/scope.js +109 -0
  111. package/dist/core/snippet.d.ts +4 -0
  112. package/dist/core/snippet.js +36 -0
  113. package/dist/core/splice.d.ts +10 -0
  114. package/dist/core/splice.js +19 -0
  115. package/dist/core/target.d.ts +10 -0
  116. package/dist/core/target.js +46 -0
  117. package/dist/formatters/default.d.ts +22 -0
  118. package/dist/formatters/default.js +140 -0
  119. package/dist/formatters/index.d.ts +2 -0
  120. package/dist/formatters/index.js +1 -0
  121. package/dist/guards/generated-file.d.ts +10 -0
  122. package/dist/guards/generated-file.js +39 -0
  123. package/dist/guards/index.d.ts +19 -0
  124. package/dist/guards/index.js +33 -0
  125. package/dist/guards/non-text.d.ts +7 -0
  126. package/dist/guards/non-text.js +50 -0
  127. package/dist/guards/omission.d.ts +9 -0
  128. package/dist/guards/omission.js +48 -0
  129. package/dist/guards/read-prefix.d.ts +12 -0
  130. package/dist/guards/read-prefix.js +87 -0
  131. package/dist/guards/shared.d.ts +11 -0
  132. package/dist/guards/shared.js +46 -0
  133. package/dist/guards/syntax.d.ts +10 -0
  134. package/dist/guards/syntax.js +54 -0
  135. package/dist/guards/truncation-notice.d.ts +8 -0
  136. package/dist/guards/truncation-notice.js +32 -0
  137. package/dist/hooks/executable-shebang.d.ts +9 -0
  138. package/dist/hooks/executable-shebang.js +46 -0
  139. package/dist/hooks/index.d.ts +2 -0
  140. package/dist/hooks/index.js +2 -0
  141. package/dist/hooks/verify-write.d.ts +9 -0
  142. package/dist/hooks/verify-write.js +63 -0
  143. package/dist/index.d.ts +30 -0
  144. package/dist/index.js +15 -0
  145. package/dist/locks/index.d.ts +1 -0
  146. package/dist/locks/index.js +1 -0
  147. package/dist/locks/memory-locks.d.ts +9 -0
  148. package/dist/locks/memory-locks.js +94 -0
  149. package/dist/matchers/block-anchor.d.ts +9 -0
  150. package/dist/matchers/block-anchor.js +69 -0
  151. package/dist/matchers/escape.d.ts +6 -0
  152. package/dist/matchers/escape.js +32 -0
  153. package/dist/matchers/exact.d.ts +4 -0
  154. package/dist/matchers/exact.js +29 -0
  155. package/dist/matchers/fold.d.ts +11 -0
  156. package/dist/matchers/fold.js +144 -0
  157. package/dist/matchers/indentation.d.ts +3 -0
  158. package/dist/matchers/indentation.js +81 -0
  159. package/dist/matchers/index.d.ts +14 -0
  160. package/dist/matchers/index.js +20 -0
  161. package/dist/matchers/line-trimmed.d.ts +3 -0
  162. package/dist/matchers/line-trimmed.js +32 -0
  163. package/dist/matchers/lines.d.ts +24 -0
  164. package/dist/matchers/lines.js +74 -0
  165. package/dist/matchers/normalized.d.ts +7 -0
  166. package/dist/matchers/normalized.js +69 -0
  167. package/dist/patch/grammar.d.ts +5 -0
  168. package/dist/patch/grammar.js +24 -0
  169. package/dist/patch/index.d.ts +4 -0
  170. package/dist/patch/index.js +3 -0
  171. package/dist/patch/parse.d.ts +11 -0
  172. package/dist/patch/parse.js +209 -0
  173. package/dist/signature/contract.d.ts +8 -0
  174. package/dist/signature/contract.js +0 -0
  175. package/dist/signature/edit.d.ts +19 -0
  176. package/dist/signature/edit.js +158 -0
  177. package/dist/signature/index.d.ts +6 -0
  178. package/dist/signature/index.js +4 -0
  179. package/dist/signature/matching.d.ts +3 -0
  180. package/dist/signature/matching.js +25 -0
  181. package/dist/signature/messages.d.ts +4 -0
  182. package/dist/signature/messages.js +9 -0
  183. package/dist/signature/patch.d.ts +6 -0
  184. package/dist/signature/patch.js +55 -0
  185. package/dist/signature/schema.d.ts +19 -0
  186. package/dist/signature/schema.js +117 -0
  187. package/dist/signature/write.d.ts +9 -0
  188. package/dist/signature/write.js +52 -0
  189. package/dist/state/index.d.ts +2 -0
  190. package/dist/state/index.js +1 -0
  191. package/dist/state/invalidate.d.ts +29 -0
  192. package/dist/state/invalidate.js +37 -0
  193. package/docs/architecture.md +223 -0
  194. package/docs/hosts.md +96 -0
  195. package/docs/result-schema.md +261 -0
  196. package/package.json +53 -2
@@ -0,0 +1,36 @@
1
+ import { LineIndex } from "./line-index.js";
2
+ const MAX_SNIPPET_LINE_LENGTH = 2_000;
3
+ export function buildSnippets(after, ranges, limits) {
4
+ const index = typeof after === "string" ? new LineIndex(after) : after;
5
+ const total = index.count;
6
+ if (total === 0)
7
+ return [];
8
+ const windows = [];
9
+ for (const [first, last] of [...ranges].sort((a, b) => a[0] - b[0])) {
10
+ const from = Math.max(1, Math.min(first, total) - limits.snippetLines);
11
+ const to = Math.min(total, Math.max(last, first) + limits.snippetLines);
12
+ const previous = windows.at(-1);
13
+ if (previous !== undefined && from <= previous[1] + 1)
14
+ previous[1] = Math.max(previous[1], to);
15
+ else
16
+ windows.push([from, to]);
17
+ }
18
+ const snippets = [];
19
+ let left = limits.maxSnippetLines;
20
+ for (const [from, to] of windows) {
21
+ if (left <= 0)
22
+ break;
23
+ const last = Math.min(to, from + left - 1);
24
+ const lines = [];
25
+ for (let line = from; line <= last; line += 1)
26
+ lines.push(clamp(index.line(line)));
27
+ snippets.push({ startLine: from, lines });
28
+ left -= lines.length;
29
+ }
30
+ return snippets;
31
+ }
32
+ function clamp(line) {
33
+ if (line.length <= MAX_SNIPPET_LINE_LENGTH)
34
+ return line;
35
+ return `${line.slice(0, MAX_SNIPPET_LINE_LENGTH)}… [line truncated at ${MAX_SNIPPET_LINE_LENGTH} chars]`;
36
+ }
@@ -0,0 +1,10 @@
1
+ export interface Splice {
2
+ readonly start: number;
3
+ readonly end: number;
4
+ readonly text: string;
5
+ }
6
+ export declare function spliceAll(text: string, splices: readonly Splice[]): string;
7
+ export declare function placed(splices: readonly Splice[]): {
8
+ start: number;
9
+ end: number;
10
+ }[];
@@ -0,0 +1,19 @@
1
+ export function spliceAll(text, splices) {
2
+ const parts = [];
3
+ let tail = text.length;
4
+ for (let index = splices.length - 1; index >= 0; index -= 1) {
5
+ const splice = splices[index];
6
+ parts.push(text.slice(splice.end, tail), splice.text);
7
+ tail = splice.start;
8
+ }
9
+ parts.push(text.slice(0, tail));
10
+ return parts.reverse().join("");
11
+ }
12
+ export function placed(splices) {
13
+ let shift = 0;
14
+ return splices.map((splice) => {
15
+ const start = splice.start + shift;
16
+ shift += splice.text.length - (splice.end - splice.start);
17
+ return { start, end: start + splice.text.length };
18
+ });
19
+ }
@@ -0,0 +1,10 @@
1
+ import type { FileStat, WritableFileSystem } from "@better-fs-tools/fs";
2
+ import type { WritePhase } from "../contract/result.ts";
3
+ import type { MutationScope } from "./scope.ts";
4
+ export interface Target {
5
+ readonly requestedPath: string;
6
+ readonly path: string;
7
+ }
8
+ export declare function statTarget<THost>(scope: MutationScope<THost>, fs: WritableFileSystem, target: Target, phase?: WritePhase): Promise<FileStat>;
9
+ export declare function statAgain<THost>(scope: MutationScope<THost>, fs: WritableFileSystem, target: Target, first: FileStat): Promise<FileStat>;
10
+ export declare function ioFailure<THost>(scope: MutationScope<THost>, path: string | null, detail: string): import("./outcomes.ts").WriteStop;
@@ -0,0 +1,46 @@
1
+ import { AbortStop } from "./abort.js";
2
+ import { isRecord } from "./input.js";
3
+ import { isBackendError, messageOf } from "./outcomes.js";
4
+ export async function statTarget(scope, fs, target, phase = "stat") {
5
+ scope.enter(phase);
6
+ scope.checkAbort();
7
+ const { signal } = scope;
8
+ let outcome;
9
+ try {
10
+ outcome = await scope.race(() => fs.stat(target.path, signal === undefined ? {} : { signal }));
11
+ }
12
+ catch (error) {
13
+ if (error instanceof AbortStop)
14
+ throw error;
15
+ throw ioFailure(scope, target.requestedPath, messageOf(error));
16
+ }
17
+ if (!isRecord(outcome))
18
+ throw ioFailure(scope, target.requestedPath, "malformed stat outcome");
19
+ if (outcome.ok === false && isBackendError(outcome.error)) {
20
+ throw scope.backendFailure(target.requestedPath, outcome.error);
21
+ }
22
+ if (outcome.ok !== true || !isFileStat(outcome.stat)) {
23
+ throw ioFailure(scope, target.requestedPath, "malformed stat outcome");
24
+ }
25
+ return outcome.stat;
26
+ }
27
+ export async function statAgain(scope, fs, target, first) {
28
+ const second = await statTarget(scope, fs, target);
29
+ if (second.resolvedPath !== first.resolvedPath) {
30
+ const { messages } = scope.deps;
31
+ throw scope.stop("STALE", messages.stale({ tool: scope.tool, path: target.requestedPath }));
32
+ }
33
+ return second;
34
+ }
35
+ export function ioFailure(scope, path, detail) {
36
+ return scope.stop("IO_ERROR", scope.deps.messages.ioError({ path }), { detail });
37
+ }
38
+ function isFileStat(value) {
39
+ if (!isRecord(value) || typeof value.resolvedPath !== "string")
40
+ return false;
41
+ if (typeof value.displayPath !== "string")
42
+ return false;
43
+ if (value.exists === false)
44
+ return Array.isArray(value.missingDirectories);
45
+ return value.exists === true && typeof value.version === "string";
46
+ }
@@ -0,0 +1,22 @@
1
+ import type { Note } from "@better-fs-tools/read";
2
+ import type { WriteToolName } from "../contract/context.ts";
3
+ import type { WriteFormatter } from "../contract/format.ts";
4
+ export interface WriteFormatterOptions {
5
+ /** Add the numbered lines around each edit to the model text. Default false. */
6
+ readonly snippet?: boolean;
7
+ /** Line-number prefix for edit snippets. Default: `${line}|`, as the read tool shows. */
8
+ readonly gutter?: (line: number) => string;
9
+ /** Add each change's diff to the model text. Default false. */
10
+ readonly diff?: boolean;
11
+ /** Filter or rewrite a note for the model text. null hides it. Default: show every note. */
12
+ readonly notes?: (note: Note, tool: WriteToolName) => Note | null;
13
+ /** Default: `[${tool}:${note.code}] ${note.message}`. */
14
+ readonly noteLine?: (note: Note, tool: WriteToolName) => string;
15
+ }
16
+ /**
17
+ * Formats a result as a line for each file, then the notes. An error shows the
18
+ * notes only. "view" mode leaves the notes out. `snippet` adds the lines
19
+ * around each edit, and `diff` adds each diff. The `notes` option hides or
20
+ * rewrites a note, as the read tool's formatters do.
21
+ */
22
+ export declare function defaultWriteFormatter(options?: WriteFormatterOptions): WriteFormatter<unknown>;
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Formats a result as a line for each file, then the notes. An error shows the
3
+ * notes only. "view" mode leaves the notes out. `snippet` adds the lines
4
+ * around each edit, and `diff` adds each diff. The `notes` option hides or
5
+ * rewrites a note, as the read tool's formatters do.
6
+ */
7
+ export function defaultWriteFormatter(options = {}) {
8
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
9
+ throw new TypeError("defaultWriteFormatter options must be an object");
10
+ }
11
+ const { snippet = false, gutter = defaultGutter, diff = false, notes: filter = showNote, noteLine = defaultNoteLine, } = options;
12
+ if (typeof gutter !== "function") {
13
+ throw new TypeError("gutter must be a function");
14
+ }
15
+ if (typeof snippet !== "boolean")
16
+ throw new TypeError("snippet must be a boolean");
17
+ if (typeof diff !== "boolean")
18
+ throw new TypeError("diff must be a boolean");
19
+ if (typeof filter !== "function")
20
+ throw new TypeError("notes must be a function");
21
+ if (typeof noteLine !== "function")
22
+ throw new TypeError("noteLine must be a function");
23
+ return Object.freeze({
24
+ id: "default",
25
+ format(report, ctx) {
26
+ const main = [
27
+ ...body(report, snippet ? gutter : null, ctx.limits.maxListedMatches),
28
+ ...(diff ? diffBlocks(report.changes) : []),
29
+ ];
30
+ if (ctx.mode === "view")
31
+ return main.join("\n");
32
+ const notes = noteLines(report.notes, report.tool, filter, noteLine);
33
+ if (notes.length === 0)
34
+ return main.join("\n");
35
+ if (main.length === 0)
36
+ return notes.join("\n");
37
+ return `${main.join("\n")}\n\n${notes.join("\n")}`;
38
+ },
39
+ });
40
+ }
41
+ function noteLines(notes, tool, filter, line) {
42
+ const lines = [];
43
+ for (const note of notes) {
44
+ const shown = filter(note, tool);
45
+ if (shown !== null)
46
+ lines.push(line(shown, tool));
47
+ }
48
+ return lines;
49
+ }
50
+ function showNote(note) {
51
+ return note;
52
+ }
53
+ function defaultNoteLine(note, tool) {
54
+ return `[${tool}:${note.code}] ${note.message}`;
55
+ }
56
+ function defaultGutter(line) {
57
+ return `${line}|`;
58
+ }
59
+ function body(report, gutter, listed) {
60
+ if (report.status === "error")
61
+ return [];
62
+ if (report.status === "no-change") {
63
+ const reason = report.tool === "write" ? ": the content is the same" : "";
64
+ return report.unchanged.map((path) => `No change to ${path}${reason}.`);
65
+ }
66
+ if (report.tool === "edit") {
67
+ return report.changes.flatMap((change) => [
68
+ editLine(change, listed),
69
+ ...(gutter === null ? [] : snippetLines(change.snippets, gutter)),
70
+ ]);
71
+ }
72
+ if (report.tool === "apply_patch") {
73
+ return ["Success. Updated the following files:", ...report.changes.map(patchLine)];
74
+ }
75
+ return report.changes.map(changeLine);
76
+ }
77
+ // Follows the Codex apply_patch output: `A`, `M`, or `D` and the path.
78
+ function patchLine(change) {
79
+ const letter = change.kind === "create" ? "A" : change.kind === "delete" ? "D" : "M";
80
+ const details = [
81
+ ...(change.movedFrom === null ? [] : [`moved from ${change.movedFrom}`]),
82
+ ...change.matches
83
+ .filter((match) => match.fuzzy)
84
+ .map((match) => `hunk ${match.index + 1} matched by ${match.matcher}`),
85
+ ];
86
+ return `${letter} ${change.path}${details.length === 0 ? "" : ` (${details.join(", ")})`}`;
87
+ }
88
+ function editLine(change, listed) {
89
+ if (change.userModified) {
90
+ return `Edited ${change.path} with the user's changes (+${change.linesAdded} -${change.linesRemoved} lines).`;
91
+ }
92
+ const total = change.matches.reduce((sum, match) => sum + match.count, 0);
93
+ const all = change.matches.some((match) => match.count > 1);
94
+ const ranges = change.matches.flatMap((match) => match.replaced).sort((a, b) => a[0] - b[0]);
95
+ const shown = ranges
96
+ .slice(0, listed)
97
+ .map(([first, last]) => (first === last ? `${first}` : `${first}-${last}`));
98
+ const single = total === 1 && ranges.length === 1 && ranges[0]?.[0] === ranges[0]?.[1];
99
+ const more = total > shown.length ? ", …" : "";
100
+ const counted = `${total} replacement${total === 1 ? "" : "s"}${all ? " (replace all)" : ""}`;
101
+ return `Edited ${change.path}: ${counted} at line${single ? "" : "s"} ${shown.join(", ")}${more}.`;
102
+ }
103
+ function snippetLines(snippets, gutter) {
104
+ return snippets.flatMap((snippet, index) => [
105
+ ...(index === 0 ? [] : ["..."]),
106
+ ...snippet.lines.map((line, offset) => `${gutter(snippet.startLine + offset)}${line}`),
107
+ ]);
108
+ }
109
+ function changeLine(change) {
110
+ const counts = `(+${change.linesAdded} -${change.linesRemoved} lines)`;
111
+ switch (change.kind) {
112
+ case "create": {
113
+ const lines = change.linesAdded;
114
+ return `Created ${change.path} (${lines} line${lines === 1 ? "" : "s"}).`;
115
+ }
116
+ case "update":
117
+ return `Updated ${change.path} ${counts}.`;
118
+ case "delete":
119
+ return `Deleted ${change.path}.`;
120
+ default:
121
+ return `Moved ${change.movedFrom ?? "a file"} to ${change.path} ${counts}.`;
122
+ }
123
+ }
124
+ function diffBlocks(changes) {
125
+ const blocks = [];
126
+ for (const change of changes) {
127
+ if (change.diff === "")
128
+ continue;
129
+ const text = change.diff.endsWith("\n") ? change.diff.slice(0, -1) : change.diff;
130
+ const fence = "`".repeat(Math.max(3, longestRun(text) + 1));
131
+ blocks.push(`${fence}diff`, text, ...(change.diffTruncated ? ["…"] : []), fence);
132
+ }
133
+ return blocks;
134
+ }
135
+ function longestRun(text) {
136
+ let longest = 0;
137
+ for (const match of text.matchAll(/`+/gu))
138
+ longest = Math.max(longest, match[0].length);
139
+ return longest;
140
+ }
@@ -0,0 +1,2 @@
1
+ export { defaultWriteFormatter } from "./default.ts";
2
+ export type { WriteFormatterOptions } from "./default.ts";
@@ -0,0 +1 @@
1
+ export { defaultWriteFormatter } from "./default.js";
@@ -0,0 +1,10 @@
1
+ import type { Guard } from "../contract/extensions.ts";
2
+ /**
3
+ * Opt-in. Refuses an update to a file that looks generated: its name matches
4
+ * one of `names`, or one of `markers` appears in its first 1 024 characters.
5
+ * Creating a file is allowed.
6
+ */
7
+ export declare function generatedFileGuard(options?: {
8
+ readonly markers?: readonly RegExp[];
9
+ readonly names?: readonly RegExp[];
10
+ }): Guard<unknown>;
@@ -0,0 +1,39 @@
1
+ import { ALLOW, refuse, regExpList } from "./shared.js";
2
+ const DEFAULT_NAMES = [/\.min\./u, /\.generated\./u, /_pb2\.py$/u, /\.pb\.go$/u];
3
+ const DEFAULT_MARKERS = [/@generated\b/u, /DO NOT EDIT/u, /auto-generated/iu];
4
+ const MARKER_SEARCH_CHARS = 1_024;
5
+ /**
6
+ * Opt-in. Refuses an update to a file that looks generated: its name matches
7
+ * one of `names`, or one of `markers` appears in its first 1 024 characters.
8
+ * Creating a file is allowed.
9
+ */
10
+ export function generatedFileGuard(options = {}) {
11
+ const markers = options.markers === undefined ? DEFAULT_MARKERS : regExpList(options.markers, "markers");
12
+ const names = options.names === undefined ? DEFAULT_NAMES : regExpList(options.names, "names");
13
+ return Object.freeze({
14
+ id: "generated-file",
15
+ check(change) {
16
+ if (change.before === null)
17
+ return ALLOW;
18
+ const path = change.resolvedPath;
19
+ const reason = nameReason(names, path.slice(path.lastIndexOf("/") + 1)) ??
20
+ markerReason(markers, change.before.text.slice(0, MARKER_SEARCH_CHARS));
21
+ if (reason === null)
22
+ return ALLOW;
23
+ return refuse("generated-file", `${change.displayPath} looks generated: ${reason}. Change its source or generator instead, then regenerate it.`, { reason });
24
+ },
25
+ });
26
+ }
27
+ function nameReason(names, name) {
28
+ return names.some((pattern) => pattern.test(name))
29
+ ? `its name, ${name}, is a generated-file name`
30
+ : null;
31
+ }
32
+ function markerReason(markers, head) {
33
+ for (const pattern of markers) {
34
+ const match = pattern.exec(head);
35
+ if (match !== null)
36
+ return `its first lines hold "${match[0]}"`;
37
+ }
38
+ return null;
39
+ }
@@ -0,0 +1,19 @@
1
+ import type { Guard } from "../contract/extensions.ts";
2
+ export { generatedFileGuard } from "./generated-file.ts";
3
+ export { nonTextGuard } from "./non-text.ts";
4
+ export { omissionGuard } from "./omission.ts";
5
+ export { readPrefixGuard } from "./read-prefix.ts";
6
+ export { syntaxGuard } from "./syntax.ts";
7
+ export { truncationNoticeGuard } from "./truncation-notice.ts";
8
+ /**
9
+ * The guards every write tool runs by default: none. Pass guards, for
10
+ * example recommendedGuards(), to turn them on.
11
+ */
12
+ export declare function defaultGuards(): readonly Guard<unknown>[];
13
+ /**
14
+ * The guards this package recommends, in order: read prefix, truncation
15
+ * notice, omission, syntax (JSON), and non-text. Each can refuse a write.
16
+ * They are off unless a host passes them as `guards`. generatedFileGuard is
17
+ * not in the list.
18
+ */
19
+ export declare function recommendedGuards(): readonly Guard<unknown>[];
@@ -0,0 +1,33 @@
1
+ import { nonTextGuard } from "./non-text.js";
2
+ import { omissionGuard } from "./omission.js";
3
+ import { readPrefixGuard } from "./read-prefix.js";
4
+ import { syntaxGuard } from "./syntax.js";
5
+ import { truncationNoticeGuard } from "./truncation-notice.js";
6
+ export { generatedFileGuard } from "./generated-file.js";
7
+ export { nonTextGuard } from "./non-text.js";
8
+ export { omissionGuard } from "./omission.js";
9
+ export { readPrefixGuard } from "./read-prefix.js";
10
+ export { syntaxGuard } from "./syntax.js";
11
+ export { truncationNoticeGuard } from "./truncation-notice.js";
12
+ /**
13
+ * The guards every write tool runs by default: none. Pass guards, for
14
+ * example recommendedGuards(), to turn them on.
15
+ */
16
+ export function defaultGuards() {
17
+ return Object.freeze([]);
18
+ }
19
+ /**
20
+ * The guards this package recommends, in order: read prefix, truncation
21
+ * notice, omission, syntax (JSON), and non-text. Each can refuse a write.
22
+ * They are off unless a host passes them as `guards`. generatedFileGuard is
23
+ * not in the list.
24
+ */
25
+ export function recommendedGuards() {
26
+ return Object.freeze([
27
+ readPrefixGuard(),
28
+ truncationNoticeGuard(),
29
+ omissionGuard(),
30
+ syntaxGuard(),
31
+ nonTextGuard(),
32
+ ]);
33
+ }
@@ -0,0 +1,7 @@
1
+ import type { Guard } from "../contract/extensions.ts";
2
+ /**
3
+ * Refuses new content that the classifiers find is not text, such as NUL
4
+ * bytes or an image. The default classifiers read a notebook as JSON text.
5
+ * Add notebookClassifier() to the classifiers to refuse notebooks too.
6
+ */
7
+ export declare function nonTextGuard(): Guard<unknown>;
@@ -0,0 +1,50 @@
1
+ import { ALLOW, refuse } from "./shared.js";
2
+ const ENCODER = new TextEncoder();
3
+ const BOM = Uint8Array.of(0xef, 0xbb, 0xbf);
4
+ /**
5
+ * Refuses new content that the classifiers find is not text, such as NUL
6
+ * bytes or an image. The default classifiers read a notebook as JSON text.
7
+ * Add notebookClassifier() to the classifiers to refuse notebooks too.
8
+ */
9
+ export function nonTextGuard() {
10
+ return Object.freeze({
11
+ id: "non-text",
12
+ check(change, ctx) {
13
+ if (change.after === null)
14
+ return ALLOW;
15
+ const sample = sampleOf(change.after, ctx.limits.sampleBytes, change.displayPath);
16
+ const found = unsupported(ctx.classifiers, sample);
17
+ if (found === null)
18
+ return ALLOW;
19
+ return refuse("non-text", `The new content for ${change.displayPath} is not plain text (${found.code}), so this tool will not write it. Send text content, or use a tool made for this kind of file.`, { code: found.code, classifier: found.classifier });
20
+ },
21
+ });
22
+ }
23
+ function sampleOf(after, max, path) {
24
+ const unitsCoveringMaxBytes = max + 1;
25
+ let head = after.text.slice(0, unitsCoveringMaxBytes);
26
+ if (after.style.eol === "crlf")
27
+ head = head.replaceAll("\n", "\r\n");
28
+ const body = ENCODER.encode(head);
29
+ const bytes = new Uint8Array((after.style.bom ? BOM.byteLength : 0) + body.byteLength);
30
+ if (after.style.bom)
31
+ bytes.set(BOM);
32
+ bytes.set(body, bytes.byteLength - body.byteLength);
33
+ return {
34
+ bytes: bytes.subarray(0, max),
35
+ complete: after.text.length <= max && bytes.byteLength <= max,
36
+ path,
37
+ mimeType: null,
38
+ };
39
+ }
40
+ function unsupported(classifiers, sample) {
41
+ for (const classifier of classifiers) {
42
+ const decision = classifier.classify(sample);
43
+ if (decision === null)
44
+ continue;
45
+ if (decision.kind === "text")
46
+ return null;
47
+ return { code: decision.code, classifier: classifier.id };
48
+ }
49
+ return null;
50
+ }
@@ -0,0 +1,9 @@
1
+ import type { Guard } from "../contract/extensions.ts";
2
+ /**
3
+ * Refuses a change that replaces real lines with a placeholder comment such
4
+ * as `// ... rest of code`. Only new text shorter than the old text is
5
+ * checked, and a placeholder already in the old text is allowed.
6
+ */
7
+ export declare function omissionGuard(options?: {
8
+ readonly patterns?: readonly RegExp[];
9
+ }): Guard<unknown>;
@@ -0,0 +1,48 @@
1
+ import { ALLOW, linesOf, newTextParam, quoted, refuse, regExpList } from "./shared.js";
2
+ const OPEN = String.raw `(?:\/\/+|#+|\/\*+|\{\s*\/\*+|\*|<!--|--|;+|%+)`;
3
+ const WORD = String.raw `(?:rest|remaining|existing|unchanged|unmodified|previous|same|omitted|original|other|code)`;
4
+ // Placeholder comments. A bare "..." line is left alone: it is a Python stub.
5
+ const DEFAULT_PATTERNS = [
6
+ new RegExp(String.raw `^\s*${OPEN}\s*[([]?\s*(?:\.{3}|…)\s*.{0,60}\b${WORD}\b.{0,60}$`, "iu"),
7
+ new RegExp(String.raw `^\s*${OPEN}\s*[([]?\s*(?:the\s+)?${WORD}\b.{0,60}(?:\.{3}|…)\s*[)\]]?\s*(?:\*\/\}?|-->)?\s*$`, "iu"),
8
+ new RegExp(String.raw `^\s*${OPEN}\s*[([]?\s*(?:the\s+)?(?:rest\s+of\s+(?:the\s+)?\w+|(?:existing|remaining|previous|original|other)\s+\w+(?:\s+\w+)?)\s+(?:(?:is|are|remains?|stays?)\s+)?(?:unchanged|omitted|(?:the\s+)?same|as\s+before)\.?\s*[)\]]?\s*(?:\*\/\}?|-->)?\s*$`, "iu"),
9
+ ];
10
+ /**
11
+ * Refuses a change that replaces real lines with a placeholder comment such
12
+ * as `// ... rest of code`. Only new text shorter than the old text is
13
+ * checked, and a placeholder already in the old text is allowed.
14
+ */
15
+ export function omissionGuard(options = {}) {
16
+ const patterns = options.patterns === undefined ? DEFAULT_PATTERNS : regExpList(options.patterns, "patterns");
17
+ return Object.freeze({
18
+ id: "omission",
19
+ check(change, ctx) {
20
+ for (const fragment of change.fragments) {
21
+ if (fragment.newText.length >= fragment.oldText.length)
22
+ continue;
23
+ const placeholder = findPlaceholder(fragment, patterns);
24
+ if (placeholder !== null)
25
+ return refusal(change, ctx, placeholder);
26
+ }
27
+ return ALLOW;
28
+ },
29
+ });
30
+ }
31
+ function findPlaceholder(fragment, patterns) {
32
+ let old = null;
33
+ for (const line of linesOf(fragment.newText)) {
34
+ if (!patterns.some((pattern) => pattern.test(line)))
35
+ continue;
36
+ old ??= new Set(linesOf(fragment.oldText).map((entry) => entry.trim()));
37
+ if (!old.has(line.trim()))
38
+ return line;
39
+ }
40
+ return null;
41
+ }
42
+ function refusal(change, ctx, line) {
43
+ const param = newTextParam(change, ctx);
44
+ const next = change.tool === "write"
45
+ ? "Send the complete file content, or use the edit tool to change only part of the file."
46
+ : `Write those lines out in full, or make the ${change.tool === "edit" ? ctx.messages.param("oldText") : "hunk"} smaller so they stay unchanged.`;
47
+ return refuse("omission", `The ${param} for ${change.displayPath} has a placeholder instead of code: "${quoted(line)}". It would delete the lines it stands for. ${next}`, { line: quoted(line) });
48
+ }
@@ -0,0 +1,12 @@
1
+ import type { Guard } from "../contract/extensions.ts";
2
+ /**
3
+ * Refuses new text copied from read output with its line-number prefixes.
4
+ * A change is refused when at least 2, and at least `ratio` (default 0.5), of
5
+ * its new non-empty lines start with consecutive line numbers. Lines already
6
+ * in the file do not count, and a file that already looks like this is not
7
+ * checked.
8
+ */
9
+ export declare function readPrefixGuard(options?: {
10
+ readonly gutter?: RegExp;
11
+ readonly ratio?: number;
12
+ }): Guard<unknown>;
@@ -0,0 +1,87 @@
1
+ import { ALLOW, existingLines, withoutStatefulFlags, linesOf, newTextParam, quoted, refuse, } from "./shared.js";
2
+ // Read output gutters such as "12|", "12:a3|", "12: ", "12→", and " 12\t".
3
+ // Group 2 is the weak ": " form, which YAML keys also match.
4
+ const DEFAULT_GUTTER = /^[ \t]*(\d+)(?::[0-9A-Za-z_-]+)?(?:\||→|(: ))|^ +(\d+)\t/u;
5
+ /**
6
+ * Refuses new text copied from read output with its line-number prefixes.
7
+ * A change is refused when at least 2, and at least `ratio` (default 0.5), of
8
+ * its new non-empty lines start with consecutive line numbers. Lines already
9
+ * in the file do not count, and a file that already looks like this is not
10
+ * checked.
11
+ */
12
+ export function readPrefixGuard(options = {}) {
13
+ const { gutter = DEFAULT_GUTTER, ratio = 0.5 } = options;
14
+ if (!(gutter instanceof RegExp))
15
+ throw new TypeError("gutter must be a regular expression");
16
+ if (typeof ratio !== "number" || !(ratio > 0 && ratio <= 1)) {
17
+ throw new TypeError("ratio must be a number above 0 and at most 1");
18
+ }
19
+ const test = withoutStatefulFlags(gutter);
20
+ const builtIn = gutter === DEFAULT_GUTTER;
21
+ return Object.freeze({
22
+ id: "read-prefix",
23
+ check(change, ctx) {
24
+ if (change.after === null)
25
+ return ALLOW;
26
+ const known = existingLines(change);
27
+ let beforeChecked = false;
28
+ for (const fragment of change.fragments) {
29
+ const lines = linesOf(fragment.newText).filter((line) => line.trim() !== "");
30
+ const hits = consecutiveHits(lines.flatMap((line, index) => hit(test, line, index)));
31
+ if (hits.length < 2)
32
+ continue;
33
+ const fresh = lines.filter((line) => !known(line));
34
+ const counted = hits.filter((entry) => !known(lines[entry.line]));
35
+ if (counted.length < 2 || counted.length < ratio * fresh.length)
36
+ continue;
37
+ if (builtIn && counted.length < 3 && counted.every((entry) => entry.weak))
38
+ continue;
39
+ if (!beforeChecked) {
40
+ beforeChecked = true;
41
+ if (change.before !== null && gutterShare(test, change.before.text) >= ratio) {
42
+ return ALLOW;
43
+ }
44
+ }
45
+ const sample = counted[0].gutter;
46
+ return refuse("read-prefix", `The ${newTextParam(change, ctx)} for ${change.displayPath} starts ${counted.length} of its ${fresh.length} new lines with read tool line numbers, such as "${quoted(sample)}". Send only the file text, without the line-number prefixes.`, { lines: counted.length, gutter: sample });
47
+ }
48
+ return ALLOW;
49
+ },
50
+ });
51
+ }
52
+ function hit(test, text, line) {
53
+ const match = test.exec(text);
54
+ if (match === null)
55
+ return [];
56
+ const digits = match.slice(1).find((group) => group !== undefined && /^\d+$/u.test(group));
57
+ return [
58
+ {
59
+ line,
60
+ number: digits === undefined ? null : Number(digits),
61
+ weak: match[2] !== undefined,
62
+ gutter: match[0],
63
+ },
64
+ ];
65
+ }
66
+ function consecutiveHits(hits) {
67
+ return hits.filter((entry, index) => {
68
+ if (entry.number === null)
69
+ return true;
70
+ const before = hits[index - 1];
71
+ const after = hits[index + 1];
72
+ return ((before?.number !== undefined && before.number === entry.number - 1) ||
73
+ (after?.number !== undefined && after.number === entry.number + 1));
74
+ });
75
+ }
76
+ function gutterShare(test, text) {
77
+ let lines = 0;
78
+ let hits = 0;
79
+ for (const line of linesOf(text)) {
80
+ if (line.trim() === "")
81
+ continue;
82
+ lines += 1;
83
+ if (test.test(line))
84
+ hits += 1;
85
+ }
86
+ return lines === 0 ? 0 : hits / lines;
87
+ }
@@ -0,0 +1,11 @@
1
+ import type { JsonObject } from "@better-fs-tools/read";
2
+ import type { GuardContext, GuardDecision, PlannedChange } from "../contract/extensions.ts";
3
+ export declare const ALLOW: GuardDecision;
4
+ export declare function refuse(code: string, message: string, data?: JsonObject): GuardDecision;
5
+ export declare function linesOf(text: string): string[];
6
+ export declare function newTextParam(change: PlannedChange, ctx: GuardContext<unknown>): string;
7
+ export declare function withoutStatefulFlags(pattern: RegExp): RegExp;
8
+ export declare function regExpList(value: unknown, name: string): readonly RegExp[];
9
+ export declare function extensionOf(path: string): string | null;
10
+ export declare function quoted(line: string): string;
11
+ export declare function existingLines(change: PlannedChange): (line: string) => boolean;