@better-fs-tools/write 0.1.0 → 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.
@@ -1,5 +1,4 @@
1
1
  import { defaultWriteFormatter } from "../formatters/default.js";
2
- import { extensionId } from "./extension-error.js";
3
2
  export function formatResult(deps, call, report) {
4
3
  const ctx = {
5
4
  digest: deps.digest,
@@ -14,20 +13,7 @@ export function formatResult(deps, call, report) {
14
13
  catch { }
15
14
  if (content !== null)
16
15
  return { ...report, content };
17
- const id = extensionId(deps.formatter);
18
- const failed = {
19
- ...report,
20
- notes: [
21
- ...report.notes,
22
- {
23
- code: "extension-failed",
24
- severity: "warning",
25
- message: deps.messages.formatterFailed({ formatter: id ?? "formatter" }),
26
- data: id === null ? { extension: "formatter" } : { extension: "formatter", id },
27
- },
28
- ],
29
- };
30
- return { ...failed, content: toContent(defaultWriteFormatter().format(failed, ctx)) ?? [] };
16
+ return { ...report, content: toContent(defaultWriteFormatter().format(report, ctx)) ?? [] };
31
17
  }
32
18
  function toContent(output) {
33
19
  if (typeof output === "string")
@@ -38,15 +38,8 @@ export async function runWriteHooks(scope, fs, committed) {
38
38
  const rewrote = [];
39
39
  for (const hook of hooks) {
40
40
  const result = await runHook(hook, file.change, ctx);
41
- if (result === null) {
42
- scope.notes.push({
43
- code: "hook-failed",
44
- severity: "warning",
45
- message: messages.hookFailed({ hook: hook.id, path }),
46
- data: { hook: hook.id },
47
- });
41
+ if (result === null)
48
42
  continue;
49
- }
50
43
  scope.notes.push(...result.notes);
51
44
  if (result.rewrote)
52
45
  rewrote.push(hook.id);
package/dist/core/load.js CHANGED
@@ -161,7 +161,7 @@ function classify(scope, sample, requested) {
161
161
  }
162
162
  throw scope.extensionFailure("classifiers", extensionId(classifier));
163
163
  }
164
- throw scope.stop("UNSUPPORTED_BACKEND", messages.unsupportedBackend({ path: requested, detail: "no classifier had an opinion" }));
164
+ throw scope.stop("UNSUPPORTED_BACKEND", messages.unsupportedBackend({ path: requested, detail: "its file type is not supported" }));
165
165
  }
166
166
  function decode(scope, sample, bytes, requested) {
167
167
  const { codecs, messages } = scope.deps;
@@ -12,7 +12,7 @@ function catalogUsingParam(param) {
12
12
  return `${path} was not found. Check the path and its parent directories.`;
13
13
  },
14
14
  notAFile: ({ path, kind }) => `${path} is a ${kindLabel(kind)}. Only regular files can be changed.`,
15
- dangerousPath: ({ path, detail }) => `${path} belongs to a refused policy class${detail === null ? "" : ` (${detail})`}. Choose another path.`,
15
+ dangerousPath: ({ path, detail }) => `${path} is refused by policy${detail === null ? "" : ` (${detail})`}. Choose another path.`,
16
16
  outsideAllowedRoots: ({ path }) => `${path} is outside every configured allowed root. Choose a path inside the workspace.`,
17
17
  permissionDenied: ({ path }) => `Permission was denied for ${path}.`,
18
18
  guardRefused: ({ guard, path }) => `The ${guard} check refused the change to ${path}.`,
@@ -28,7 +28,6 @@ function catalogUsingParam(param) {
28
28
  : `Read ${path} with the read tool before changing it.`,
29
29
  stale: ({ path }) => `${path} changed since it was last read. Read it again, then retry.`,
30
30
  staleRematched: ({ path }) => `${path} changed since it was last read, but every old text still matched exactly once, so the edit was applied.`,
31
- readBeforeWriteOff: () => "Read-before-write is off: this tool has no state store.",
32
31
  tooLarge: ({ path, what, limit, existing }) => {
33
32
  if (what === "patch") {
34
33
  return `The patch is over the limit of ${limit}. Split it into smaller patches.`;
@@ -92,14 +91,8 @@ function catalogUsingParam(param) {
92
91
  `Patch commit failed at ${path} (${code}). Rollback failed, so these files are in a mixed state:`,
93
92
  ...files.map((file) => `${file.state} ${file.path}`),
94
93
  ].join("\n"),
95
- notAtomic: ({ backend }) => `The ${backend} backend does not replace files atomically, so a reader could have seen a partial file.`,
96
- noCompareAndSwap: ({ backend }) => `The ${backend} backend cannot check the file version at the moment of the write. The tool checked it just before.`,
97
- modeNotKept: ({ backend }) => `The ${backend} backend does not keep file modes, so the file's permissions may have changed.`,
98
- directoriesCreated: ({ paths }) => `Created ${paths.length === 1 ? "the directory" : "the directories"} ${paths.join(", ")}.`,
99
94
  userModified: ({ path }) => `The user changed the content before it was written to ${path}. The file holds their version. Read it before changing it again.`,
100
95
  hookRewrote: ({ hook, path }) => `The ${hook} hook rewrote ${path} after the write. Read it again before relying on its text.`,
101
- hookFailed: ({ hook, path }) => `The ${hook} hook failed after ${path} was written. The file is changed.`,
102
- formatterFailed: ({ formatter }) => `The ${formatter} formatter failed, so the default formatter formatted this result.`,
103
96
  };
104
97
  }
105
98
  function kindLabel(kind) {
@@ -1,5 +1,5 @@
1
1
  import { authorizeAccess, authorizeChanges } from "./authorize.js";
2
- import { addCapabilityNotes, fileChange } from "./commit.js";
2
+ import { fileChange } from "./commit.js";
3
3
  import { commitPatch, deleteChange } from "./commit-patch.js";
4
4
  import { encodePlanned } from "./encode.js";
5
5
  import { formatResult } from "./format.js";
@@ -89,7 +89,6 @@ async function patchStages(scope, deps, request) {
89
89
  rewrittenByHook: false,
90
90
  };
91
91
  }
92
- addCapabilityNotes(scope, fs, plannedStep, file);
93
92
  const base = fileChange(scope, plannedStep, step.bytes, file);
94
93
  const change = source === null ? base : { ...base, movedFrom: source.displayPath };
95
94
  return committedFile(scope, plannedStep, change, file);
@@ -40,10 +40,10 @@ export async function runEdit(deps, input, call, misses) {
40
40
  catch (error) {
41
41
  return formatResult(deps, call, invalidInput(deps, "edit", input, error));
42
42
  }
43
- const { matchers } = deps;
43
+ const { matchers, recovery } = deps;
44
44
  const report = await runSingleFile(deps, request, call, {
45
45
  whenMissing: "not-found",
46
- plan: (scope, target, loaded, pre) => planEdit(scope, { request, matchers, misses }, target, loaded, pre),
46
+ plan: (scope, target, loaded, pre) => planEdit(scope, { request, matchers, recovery, misses }, target, loaded, pre),
47
47
  whenSameBytes: "error",
48
48
  });
49
49
  return formatResult(deps, call, report);
@@ -8,6 +8,8 @@ import type { MutationScope } from "./scope.ts";
8
8
  export interface EditPlanInput {
9
9
  readonly request: EditRequest;
10
10
  readonly matchers: readonly Matcher[];
11
+ /** Turns on already-applied, the closest-region hint, and the repeated-miss note. */
12
+ readonly recovery: boolean;
11
13
  readonly misses: MissCounter;
12
14
  }
13
15
  export declare function planEdit<THost>(scope: MutationScope<THost>, input: EditPlanInput, target: ResolvedTarget, loaded: Loaded | null, pre: PreconditionResult): Planned | "no-change";
@@ -129,7 +129,7 @@ function matchPair(scope, input, target, text, pair, index) {
129
129
  maxMatches,
130
130
  });
131
131
  if (chain === null) {
132
- if (isAlreadyApplied(text, pair.newText))
132
+ if (input.recovery && isAlreadyApplied(text, pair.newText))
133
133
  return "applied";
134
134
  throw noMatchFailure(scope, input, target, text, pair, index);
135
135
  }
@@ -197,8 +197,8 @@ function noMatchFailure(scope, input, target, text, pair, index) {
197
197
  const { messages, limits } = scope.deps;
198
198
  const path = target.requestedPath;
199
199
  const newline = trailingNewline(text, pair.oldText);
200
- const closest = closestRegion(text, pair.oldText, limits.maxHintLines);
201
- const misses = input.misses.miss(target.resolvedPath);
200
+ const closest = input.recovery ? closestRegion(text, pair.oldText, limits.maxHintLines) : null;
201
+ const misses = input.recovery ? input.misses.miss(target.resolvedPath) : 0;
202
202
  if (misses >= 3) {
203
203
  scope.notes.push({
204
204
  code: "repeated-miss",
@@ -11,10 +11,8 @@ export async function checkPrecondition(scope, fs, stat, loaded, requested) {
11
11
  return { precondition: { kind: "absent" }, record: null, mustRematch: false };
12
12
  }
13
13
  const version = { kind: "version", version: loaded.version };
14
- if (preconditions.requireRead === "off")
15
- return { precondition: version, record: null, mustRematch: false };
16
- if (store === null) {
17
- addReadBeforeWriteOffNote(scope, tool);
14
+ // With no store, the check is off. The host chose this, so the model is not told.
15
+ if (preconditions.requireRead === "off" || store === null) {
18
16
  return { precondition: version, record: null, mustRematch: false };
19
17
  }
20
18
  const record = await getUsableRecord(scope, store, stat.resolvedPath, digest?.id ?? null);
@@ -65,12 +63,3 @@ function partialAllowed(policy, tool) {
65
63
  return false;
66
64
  return tool === "edit" || tool === "apply_patch";
67
65
  }
68
- function addReadBeforeWriteOffNote(scope, tool) {
69
- if (scope.notes.some((note) => note.code === "read-before-write-off"))
70
- return;
71
- scope.notes.push({
72
- code: "read-before-write-off",
73
- severity: "warning",
74
- message: scope.deps.messages.readBeforeWriteOff({ tool }),
75
- });
76
- }
@@ -2,15 +2,21 @@ import type { Note } from "@better-fs-tools/read";
2
2
  import type { WriteToolName } from "../contract/context.ts";
3
3
  import type { WriteFormatter } from "../contract/format.ts";
4
4
  export interface WriteFormatterOptions {
5
+ /** Add the numbered lines around each edit to the model text. Default false. */
6
+ readonly snippet?: boolean;
5
7
  /** Line-number prefix for edit snippets. Default: `${line}|`, as the read tool shows. */
6
8
  readonly gutter?: (line: number) => string;
7
9
  /** Add each change's diff to the model text. Default false. */
8
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;
9
13
  /** Default: `[${tool}:${note.code}] ${note.message}`. */
10
14
  readonly noteLine?: (note: Note, tool: WriteToolName) => string;
11
15
  }
12
16
  /**
13
17
  * Formats a result as a line for each file, then the notes. An error shows the
14
- * notes only. "view" mode leaves the notes out.
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.
15
21
  */
16
22
  export declare function defaultWriteFormatter(options?: WriteFormatterOptions): WriteFormatter<unknown>;
@@ -1,29 +1,35 @@
1
1
  /**
2
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.
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.
4
6
  */
5
7
  export function defaultWriteFormatter(options = {}) {
6
8
  if (options === null || typeof options !== "object" || Array.isArray(options)) {
7
9
  throw new TypeError("defaultWriteFormatter options must be an object");
8
10
  }
9
- const { gutter = defaultGutter, diff = false, noteLine = defaultNoteLine } = options;
11
+ const { snippet = false, gutter = defaultGutter, diff = false, notes: filter = showNote, noteLine = defaultNoteLine, } = options;
10
12
  if (typeof gutter !== "function") {
11
13
  throw new TypeError("gutter must be a function");
12
14
  }
15
+ if (typeof snippet !== "boolean")
16
+ throw new TypeError("snippet must be a boolean");
13
17
  if (typeof diff !== "boolean")
14
18
  throw new TypeError("diff must be a boolean");
19
+ if (typeof filter !== "function")
20
+ throw new TypeError("notes must be a function");
15
21
  if (typeof noteLine !== "function")
16
22
  throw new TypeError("noteLine must be a function");
17
23
  return Object.freeze({
18
24
  id: "default",
19
25
  format(report, ctx) {
20
26
  const main = [
21
- ...body(report, gutter, ctx.limits.maxListedMatches),
27
+ ...body(report, snippet ? gutter : null, ctx.limits.maxListedMatches),
22
28
  ...(diff ? diffBlocks(report.changes) : []),
23
29
  ];
24
30
  if (ctx.mode === "view")
25
31
  return main.join("\n");
26
- const notes = report.notes.map((note) => noteLine(note, report.tool));
32
+ const notes = noteLines(report.notes, report.tool, filter, noteLine);
27
33
  if (notes.length === 0)
28
34
  return main.join("\n");
29
35
  if (main.length === 0)
@@ -32,6 +38,18 @@ export function defaultWriteFormatter(options = {}) {
32
38
  },
33
39
  });
34
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
+ }
35
53
  function defaultNoteLine(note, tool) {
36
54
  return `[${tool}:${note.code}] ${note.message}`;
37
55
  }
@@ -48,7 +66,7 @@ function body(report, gutter, listed) {
48
66
  if (report.tool === "edit") {
49
67
  return report.changes.flatMap((change) => [
50
68
  editLine(change, listed),
51
- ...snippetLines(change.snippets, gutter),
69
+ ...(gutter === null ? [] : snippetLines(change.snippets, gutter)),
52
70
  ]);
53
71
  }
54
72
  if (report.tool === "apply_patch") {
@@ -6,8 +6,14 @@ export { readPrefixGuard } from "./read-prefix.ts";
6
6
  export { syntaxGuard } from "./syntax.ts";
7
7
  export { truncationNoticeGuard } from "./truncation-notice.ts";
8
8
  /**
9
- * The guards every write tool runs by default, in order: read prefix,
10
- * truncation notice, omission, syntax (JSON), and non-text.
11
- * generatedFileGuard is opt-in.
9
+ * The guards every write tool runs by default: none. Pass guards, for
10
+ * example recommendedGuards(), to turn them on.
12
11
  */
13
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>[];
@@ -10,11 +10,19 @@ export { readPrefixGuard } from "./read-prefix.js";
10
10
  export { syntaxGuard } from "./syntax.js";
11
11
  export { truncationNoticeGuard } from "./truncation-notice.js";
12
12
  /**
13
- * The guards every write tool runs by default, in order: read prefix,
14
- * truncation notice, omission, syntax (JSON), and non-text.
15
- * generatedFileGuard is opt-in.
13
+ * The guards every write tool runs by default: none. Pass guards, for
14
+ * example recommendedGuards(), to turn them on.
16
15
  */
17
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() {
18
26
  return Object.freeze([
19
27
  readPrefixGuard(),
20
28
  truncationNoticeGuard(),
@@ -1,3 +1,7 @@
1
1
  import type { Guard } from "../contract/extensions.ts";
2
- /** Refuses new content that the classifiers find is not text, such as a notebook, NUL bytes, or an image. */
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
+ */
3
7
  export declare function nonTextGuard(): Guard<unknown>;
@@ -1,7 +1,11 @@
1
1
  import { ALLOW, refuse } from "./shared.js";
2
2
  const ENCODER = new TextEncoder();
3
3
  const BOM = Uint8Array.of(0xef, 0xbb, 0xbf);
4
- /** Refuses new content that the classifiers find is not text, such as a notebook, NUL bytes, or an image. */
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
+ */
5
9
  export function nonTextGuard() {
6
10
  return Object.freeze({
7
11
  id: "non-text",
package/dist/index.d.ts CHANGED
@@ -18,13 +18,13 @@ export { defaultPreconditions } from "./contract/preconditions.ts";
18
18
  export { blockAnchorMatcher, defaultEditMatchers, defaultPatchMatchers, escapeMatcher, exactMatcher, indentationMatcher, lineTrimmedMatcher, normalizedMatcher, } from "./matchers/index.ts";
19
19
  export { utf8Codec } from "./codecs/index.ts";
20
20
  export { memoryLocks } from "./locks/index.ts";
21
- export { defaultGuards, generatedFileGuard, nonTextGuard, omissionGuard, readPrefixGuard, syntaxGuard, truncationNoticeGuard, } from "./guards/index.ts";
21
+ export { defaultGuards, recommendedGuards, generatedFileGuard, nonTextGuard, omissionGuard, readPrefixGuard, syntaxGuard, truncationNoticeGuard, } from "./guards/index.ts";
22
22
  export { askBeforeWrite, protectPaths, writeAuthorizers } from "./authorize/index.ts";
23
23
  export { executableShebang, verifyWrite } from "./hooks/index.ts";
24
24
  export { defaultWriteFormatter } from "./formatters/index.ts";
25
25
  export type { WriteFormatterOptions } from "./formatters/index.ts";
26
26
  export { createFsTools } from "./bundle/create-fs-tools.ts";
27
- export type { CreateFsToolsOptions, FsTools, FsToolsBashOptions, FsToolsSharedKey, FsToolsWithBash, } from "./bundle/create-fs-tools.ts";
27
+ export type { CreateFsToolsOptions, FsTools, FsToolsApplyPatchOptions, FsToolsBashOptions, FsToolsSharedKey, FsToolsWithApplyPatch, FsToolsWithBash, } from "./bundle/create-fs-tools.ts";
28
28
  export { createInvalidator } from "./state/index.ts";
29
29
  export type { Invalidate, InvalidateOutcome } from "./state/index.ts";
30
30
  export { textOf } from "@better-fs-tools/read";
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ export { defaultPreconditions } from "./contract/preconditions.js";
6
6
  export { blockAnchorMatcher, defaultEditMatchers, defaultPatchMatchers, escapeMatcher, exactMatcher, indentationMatcher, lineTrimmedMatcher, normalizedMatcher, } from "./matchers/index.js";
7
7
  export { utf8Codec } from "./codecs/index.js";
8
8
  export { memoryLocks } from "./locks/index.js";
9
- export { defaultGuards, generatedFileGuard, nonTextGuard, omissionGuard, readPrefixGuard, syntaxGuard, truncationNoticeGuard, } from "./guards/index.js";
9
+ export { defaultGuards, recommendedGuards, generatedFileGuard, nonTextGuard, omissionGuard, readPrefixGuard, syntaxGuard, truncationNoticeGuard, } from "./guards/index.js";
10
10
  export { askBeforeWrite, protectPaths, writeAuthorizers } from "./authorize/index.js";
11
11
  export { executableShebang, verifyWrite } from "./hooks/index.js";
12
12
  export { defaultWriteFormatter } from "./formatters/index.js";
@@ -5,7 +5,10 @@ export { exactMatcher } from "./exact.ts";
5
5
  export { indentationMatcher } from "./indentation.ts";
6
6
  export { lineTrimmedMatcher } from "./line-trimmed.ts";
7
7
  export { normalizedMatcher } from "./normalized.ts";
8
- /** The matchers the edit tool tries by default, in order: exact, normalized, escape. */
8
+ /**
9
+ * The matchers the edit tool tries by default, in order: exact, normalized.
10
+ * escapeMatcher() and the other matchers are opt-in through `matchers`.
11
+ */
9
12
  export declare function defaultEditMatchers(): readonly Matcher[];
10
13
  /** The matchers the patch tool tries by default, in order: exact, normalized, line-trimmed. */
11
14
  export declare function defaultPatchMatchers(): readonly Matcher[];
@@ -1,4 +1,3 @@
1
- import { escapeMatcher } from "./escape.js";
2
1
  import { exactMatcher } from "./exact.js";
3
2
  import { lineTrimmedMatcher } from "./line-trimmed.js";
4
3
  import { normalizedMatcher } from "./normalized.js";
@@ -8,9 +7,12 @@ export { exactMatcher } from "./exact.js";
8
7
  export { indentationMatcher } from "./indentation.js";
9
8
  export { lineTrimmedMatcher } from "./line-trimmed.js";
10
9
  export { normalizedMatcher } from "./normalized.js";
11
- /** The matchers the edit tool tries by default, in order: exact, normalized, escape. */
10
+ /**
11
+ * The matchers the edit tool tries by default, in order: exact, normalized.
12
+ * escapeMatcher() and the other matchers are opt-in through `matchers`.
13
+ */
12
14
  export function defaultEditMatchers() {
13
- return Object.freeze([exactMatcher(), normalizedMatcher(), escapeMatcher()]);
15
+ return Object.freeze([exactMatcher(), normalizedMatcher()]);
14
16
  }
15
17
  /** The matchers the patch tool tries by default, in order: exact, normalized, line-trimmed. */
16
18
  export function defaultPatchMatchers() {
@@ -75,7 +75,7 @@ Some stages cannot be removed by any dependency: input validation, the type chec
75
75
 
76
76
  A host passes `{ signal?, callId?, host }`, the read tool's `ToolCallContext`. The core passes this object by reference to every stage and every host function, as `ctx.call`. It never reads, copies, freezes, or stores `host`. `host` never appears in the result, a record, a note, or content.
77
77
 
78
- A throw or a malformed return from host code gives `EXTENSION_FAILED` with `data: { extension, phase, id? }`. After the commit, hooks are the exception: the file is already written, so a hook failure is a `hook-failed` warning and the status stays `ok`. A formatter failure is the other exception: a formatter that throws or returns neither a string nor an array gives an `extension-failed` warning with `data: { extension: "formatter", id? }`, and the default formatter formats the report. The status, `changes`, and `commit` stay, so a committed change is never lost.
78
+ A throw or a malformed return from host code gives `EXTENSION_FAILED` with `data: { extension, phase, id? }`. After the commit, hooks are the exception: the file is already written, so a hook failure adds no note and the status stays `ok`. A formatter failure is the other exception: when a formatter throws or returns neither a string nor an array, the default formatter formats the report and no note is added. The status, `changes`, and `commit` stay, so a committed change is never lost.
79
79
 
80
80
  The signal is checked before each stage and raced against each host function and backend call. From the first commit call to the end of the call, the signal is ignored. A started commit finishes or rolls back, and the record is stored. A half-published patch would be worse than a late abort. Hooks after the commit are not raced against the signal either, so a hook that never settles holds the call open.
81
81
 
@@ -115,10 +115,12 @@ The precondition stage reads the record at the real path. A record of another sc
115
115
  | No record | `NOT_READ` | `NOT_READ` | `NOT_READ` |
116
116
  | Partial record, partial not allowed | `NOT_READ` (`wholeFile: true`) | same | same |
117
117
  | Fresh | Go on | Go on | Go on |
118
- | Not fresh, `onStale: "rematch"` | Exact rematch of every pair, or `STALE` | `STALE` | Exact rematch of every hunk, or `STALE`. A Delete gives `STALE` |
119
118
  | Not fresh, `onStale: "reject"` | `STALE` | `STALE` | `STALE` |
119
+ | Not fresh, `onStale: "rematch"` | Exact rematch of every pair, or `STALE` | `STALE` | Exact rematch of every hunk, or `STALE`. A Delete gives `STALE` |
120
+
121
+ `onStale` defaults to `"reject"`. `"rematch"` is opt-in.
120
122
 
121
- The commit carries a precondition: `absent` for a create, and the loaded `version` for a replace or a remove. A backend that reports `compareAndSwap: true` checks it next to the publish. For a backend that does not, the core stats the target again just before the write and gives `STALE` or `EXISTS` itself, and adds a `no-compare-and-swap` note. The window between that stat and the write stays.
123
+ The commit carries a precondition: `absent` for a create, and the loaded `version` for a replace or a remove. A backend that reports `compareAndSwap: true` checks it next to the publish. For a backend that does not, the core stats the target again just before the write and gives `STALE` or `EXISTS` itself. The window between that stat and the write stays.
122
124
 
123
125
  ## Matching
124
126
 
@@ -131,7 +133,7 @@ The core owns the rules on every hit:
131
133
  - Ranges of different pairs must not overlap. Splices apply from the end.
132
134
  - A result equal to the original gives `NO_CHANGE`, unless every pair is already applied.
133
135
 
134
- A miss gets help: an `already-applied` note when the new text is in the file and the old text is not, a trailing-newline hint, the closest region with line numbers, and after three misses in a row on one file a `repeated-miss` note. The miss count lives in the tool instance, not in the store.
136
+ A miss is `NO_MATCH`, with a trailing-newline hint when that is the only difference. With `recovery: true`, a miss gets more help: an `already-applied` note when the new text is in the file and the old text is not, the closest region with line numbers, and after three misses in a row on one file a `repeated-miss` note. The miss count lives in the tool instance, not in the store.
135
137
 
136
138
  ## apply_patch
137
139
 
@@ -201,14 +203,14 @@ A backend keeps the policy. The core never checks roots or symlinks itself. A wr
201
203
  - never replaces a symbolic link: it follows a link inside the roots to its real path, or refuses it;
202
204
  - reports a `version` that changes with every change of the bytes, and the same token from `stat()` and from `open().info.version`;
203
205
  - enforces `absent`, `version`, and `any`, and gives `exists` or `changed`;
204
- - reports `writeCapabilities` honestly. The core turns each `false` into a note for the model.
206
+ - reports `writeCapabilities.compareAndSwap` honestly. When it is false, the core checks the precondition itself just before the write.
205
207
 
206
208
  `runWritableFileSystemConformance(fs, { scratchDirectory })` from `@better-fs-tools/fs` checks these rules. The three virtual adapters show three ways to meet them with weaker backends:
207
209
 
208
210
  | Adapter | Backend calls | How it meets the contract |
209
211
  | -------------------------------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
210
212
  | `cloudflareShellFileSystem()` | `writeFileBytes`, `mkdir`, `rm` | Walks the path with `lstat` first, because `writeFileBytes` creates parents and follows a leaf link. Passes the old mime type back. No modes |
211
- | `cloudflareComputerFileSystem()` | `writeFile`, `mkdir`, `rm` | One transaction, so `atomic`. `exclusive: true` for a create. Passes the old mode back, because `writeFile` resets it |
213
+ | `cloudflareComputerFileSystem()` | `writeFile`, `mkdir`, `rm` | One transaction, so a replace is atomic. `exclusive: true` for a create. Passes the old mode back, because `writeFile` resets it |
212
214
  | `justBashFileSystem()` | `writeFile`, `mkdir`, `rm`, `chmod`, `utimes` | `chmod` after a replace, because `InMemoryFs` resets the mode. Moves `mtime` on by 1 ms when a write left it the same, so the version changes |
213
215
 
214
216
  None of them has `stage()`, so `apply_patch` writes each file in turn and undoes the journal on a failure.
package/docs/hosts.md CHANGED
@@ -4,7 +4,7 @@ This page helps you choose a host package and a filesystem backend. It lists wha
4
4
 
5
5
  ## Choose a bundle
6
6
 
7
- Every bundle builds `read`, `edit`, `write`, and `apply_patch` over one backend. The four tools share one read store, one digest, one lock manager, and one clock, so `edit` and `write` know what the model has read. `createFsTools()` is the portable core. The other three wrap it.
7
+ Every bundle builds `read`, `edit`, and `write` over one backend, and `apply_patch` when the host asks for it. The tools share one digest, one lock manager, and one clock. With `state`, they also share one read store, so `edit` and `write` know what the model has read. `createFsTools()` is the portable core. The other three wrap it.
8
8
 
9
9
  | Bundle | Package | Use it when |
10
10
  | ---------------------- | ------------------------- | ------------------------------------------------------------------------------------------- |
@@ -21,7 +21,8 @@ The just-bash, Cloudflare Shell, and Cloudflare Computer packages are backends,
21
21
  | --------------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------- |
22
22
  | `fs` | required: a backend, or a factory of the call | `nodeFileSystem({ cwd, allowedRoots: [cwd] })`, `cwd` default `process.cwd()` | a `nodeFileSystem` rooted at `ctx.cwd` on each call. `fs`, `cwd`, and `allowedRoots` throw | required, as in `createFsTools()` |
23
23
  | Tool input | canonical | canonical | the Pi signatures below | the AI SDK signatures below, `strict: true` |
24
- | `state` | `memoryStore({ clock })` | `memoryStore({ clock })` | `memoryStore({ clock })` | `memoryStore({ clock })` |
24
+ | `state` | `null`: no read-before-write. `memoryStore({ clock })` turns it on | `null`, as `createFsTools()` | `null`, as `createFsTools()` | `null`, as `createFsTools()` |
25
+ | `applyPatch` | off. `true` or an options object adds `apply_patch` | off, as `createFsTools()` | off, as `createFsTools()`. The `pi.extensions` entry does not register it | off, as `createFsTools()`. When off, `tools` has no `apply_patch` key |
25
26
  | `digest` | `sha256Digest()`, plain JavaScript | `nodeDigest()` | `nodeDigest()` | `sha256Digest()` |
26
27
  | `locks` | `memoryLocks()` | `memoryLocks()` | `memoryLocks()` | `memoryLocks()` |
27
28
  | `clock` | `() => new Date()` | `() => new Date()` | `() => new Date()` | `() => new Date()` |
@@ -90,6 +91,6 @@ Every backend takes the shared `FileSystemRootOptions` from `@better-fs-tools/fs
90
91
 
91
92
  ### Buffered reads and authorization
92
93
 
93
- The read tool calls `authorize` after `fs.open()` and before it reads any content byte. A buffered backend (just-bash and Cloudflare Shell) has already fetched the whole file inside `open()`, so those bytes have left the backend before `authorize` runs. Cloudflare Computer opens the read stream in `open()`: the request reaches the backend, but no chunk is read. In every backend, the core passes no content byte to a classifier, a converter, or the model until `authorize` allows it. A read result from a buffered backend has a `buffered-backend` info note.
94
+ The read tool calls `authorize` after `fs.open()` and before it reads any content byte. A buffered backend (just-bash and Cloudflare Shell) has already fetched the whole file inside `open()`, so those bytes have left the backend before `authorize` runs. Cloudflare Computer opens the read stream in `open()`: the request reaches the backend, but no chunk is read. In every backend, the core passes no content byte to a classifier, a converter, or the model until `authorize` allows it.
94
95
 
95
96
  If a denied read must not reach the backend at all, refuse the path in the backend itself, with `denyRoots` or by leaving it out of `allowedRoots`. The write tools are not affected: they authorize after `stat`, before they open the file.
@@ -98,7 +98,7 @@ interface Snippet {
98
98
  }
99
99
  ```
100
100
 
101
- `matches` is empty for `write`. An already applied pair has no entry. `snippets` is empty for `write` and for a delete. The model text shows the snippets. The full diff is only in `diff`, unless the formatter has `diff: true`.
101
+ `matches` is empty for `write`. An already applied pair has no entry. `snippets` is empty for `write` and for a delete. The model text shows the snippets only when the formatter has `snippet: true`. The full diff is only in `diff`, unless the formatter has `diff: true`.
102
102
 
103
103
  ## `CommitReport`
104
104
 
@@ -162,23 +162,16 @@ Every error result has exactly one warning note whose `code` is the error code i
162
162
 
163
163
  Notes on a successful call:
164
164
 
165
- | `code` | Severity | From | `data` |
166
- | ---------------------------------- | -------- | ---------------------------------------------------- | ------------------------------------------------------------------- |
167
- | `fuzzy-match` | info | a loose match | edit: `{ index, matcher, lines }`. patch: `{ path, hunk, matcher }` |
168
- | `already-applied` | info | `edit` | `{ index }` |
169
- | `stale-rematched` | info | `edit`, `apply_patch` | none |
170
- | `repeated-miss` | info | `edit`, with a `NO_MATCH` | `{ misses }` |
171
- | `read-before-write-off` | warning | no store | none |
172
- | `user-modified` | warning | an authorizer returned `content` | none |
173
- | `directories-created` | info | the commit | `{ paths }` |
174
- | `not-atomic` | warning | `writeCapabilities.atomic` false | none |
175
- | `no-compare-and-swap` | info | `writeCapabilities.compareAndSwap` false | none |
176
- | `mode-not-kept` | info | `writeCapabilities.preserveMode` false, on a replace | none |
177
- | `hook-failed` | warning | a hook threw after the commit | `{ hook }` |
178
- | `extension-failed` | warning | the formatter failed; the default formatter ran | `{ extension: "formatter", id? }` |
179
- | `hook-rewrote` | warning | a hook returned `rewrote: true` | `{ hook }` |
180
- | `executable` | info | `executableShebang()` | `{ mode }` |
181
- | `verify-mismatch`, `verify-failed` | warning | `verifyWrite()` | none |
165
+ | `code` | Severity | From | `data` |
166
+ | ---------------------------------- | -------- | ----------------------------------------------- | ------------------------------------------------------------------- |
167
+ | `fuzzy-match` | info | a loose match | edit: `{ index, matcher, lines }`. patch: `{ path, hunk, matcher }` |
168
+ | `already-applied` | info | `edit` with `recovery: true` | `{ index }` |
169
+ | `stale-rematched` | info | `edit`, `apply_patch` with `onStale: "rematch"` | none |
170
+ | `repeated-miss` | info | `edit` with `recovery: true`, with a `NO_MATCH` | `{ misses }` |
171
+ | `user-modified` | warning | an authorizer returned `content` | none |
172
+ | `hook-rewrote` | warning | a hook returned `rewrote: true` | `{ hook }` |
173
+ | `executable` | info | `executableShebang()` | `{ mode }` |
174
+ | `verify-mismatch`, `verify-failed` | warning | `verifyWrite()` | none |
182
175
 
183
176
  Guards and authorizers may add allow notes of their own.
184
177
 
@@ -186,14 +179,14 @@ Guards and authorizers may add allow notes of their own.
186
179
 
187
180
  The formatter makes `content` once, with `mode: "model"`. A formatter that returns a string gives one text part. `defaultWriteFormatter()` prints a header, a body, then a blank line and the note lines. An error prints the note lines only.
188
181
 
189
- | Tool | Header | Body |
190
- | ------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------- |
191
- | `edit` | `Edited <path>: 1 replacement at line 4.` or `2 replacements at lines 3, 15.` | The snippets, with the read tool's `12\|` gutter, `...` between |
192
- | `write` | `Created <path> (3 lines).` or `Updated <path> (+2 -1 lines).` | none |
193
- | `apply_patch` | `Success. Updated the following files:` | One line for each file: `A`, `M`, or `D` and the path |
194
- | any | `No change to <path>.` for `no-change`. `write` adds the reason | none |
182
+ | Tool | Header | Body |
183
+ | ------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
184
+ | `edit` | `Edited <path>: 1 replacement at line 4.` or `2 replacements at lines 3, 15.` | none. With `snippet: true`, the snippets, with the read tool's `12\|` gutter, `...` between |
185
+ | `write` | `Created <path> (3 lines).` or `Updated <path> (+2 -1 lines).` | none |
186
+ | `apply_patch` | `Success. Updated the following files:` | One line for each file: `A`, `M`, or `D` and the path |
187
+ | any | `No change to <path>.` for `no-change`. `write` adds the reason | none |
195
188
 
196
- `defaultWriteFormatter({ diff: true })` adds each file's diff in a fenced block. `gutter` and `noteLine` change the snippet gutter and the note line.
189
+ `defaultWriteFormatter({ snippet: true })` adds the edit snippets. `defaultWriteFormatter({ diff: true })` adds each file's diff in a fenced block. `gutter` and `noteLine` change the snippet gutter and the note line. `notes(note, tool)` rewrites a note, or returns `null` to hide it from the model text. The read and bash formatters take the same `notes` option. The report keeps every note.
197
190
 
198
191
  ## The stored record
199
192
 
@@ -265,4 +258,4 @@ Each cell is the `error.phase` values of that code, or "no" when the tool never
265
258
  | `SPAWN_FAILED` | no | no | `run` |
266
259
  | `OUTPUT_CAP` | no | no | `run` |
267
260
 
268
- A formatter failure is never an error in any tool. The status stays, and an `extension-failed` warning is added.
261
+ A formatter failure is never an error in any tool. The status stays, and no note is added.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@better-fs-tools/write",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Edit, write, and apply_patch tools for TypeScript agents.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -46,9 +46,9 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@better-fs-tools/fs": "^0.1.0",
50
- "@better-fs-tools/read": "^0.1.0",
51
- "@better-fs-tools/shell": "^0.1.0"
49
+ "@better-fs-tools/fs": "^0.2.0",
50
+ "@better-fs-tools/read": "^0.2.0",
51
+ "@better-fs-tools/shell": "^0.2.0"
52
52
  },
53
53
  "devDependencies": {
54
54
  "typebox": "^1.3.16"