@osovv/vv-opencode 2.5.0 → 2.6.1

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/CHANGELOG.md CHANGED
@@ -1,3 +1,19 @@
1
+ ## <small>2.6.1 (2026-11-22)</small>
2
+
3
+ ### Summary
4
+
5
+ Version 2.6.1 fixes runtime session handling so that session-created reconciliation, family-settings resolution and birth, and auxiliary work only act on sessions whose location directory matches the plugin runtime. Role application is now location-owned, family roots keep their native model, and creation reconciliation compares the freshly read session model instead of the creation event. This prevents cross-location interference and keeps sessions outside the runtime's location read-only, which matters for users running multiple locations who need predictable model selection and isolation between them; foreign-location and family-root coverage was added to lock in the behavior.
6
+
7
+ * fix(runtime): isolate session mutation to the owning location ([613510f](https://github.com/osovv/vv-opencode/commit/613510f))
8
+
9
+ ## 2.6.0 (2026-11-10)
10
+
11
+ ### Summary
12
+
13
+ Version 2.6.0 fixes a data-corruption bug in the str_replace_editor tool used by the Hashline Edit plugin. Concurrent edits to the same file could previously collide and leave contents corrupted; the plugin now serializes complete read, check, write, and cache cycles per canonical target across sessions in one process, and publishes byte-verified staged UTF-8 writes atomically while preserving file mode and symlinks. As a result, users and agents can safely edit the same files from multiple sessions without producing mangled or truncated content, and failed or cancelled operations recover cleanly instead of leaving stale output behind.
14
+
15
+ * fix(editor): prevent concurrent str_replace_editor corruption ([a991c13](https://github.com/osovv/vv-opencode/commit/a991c13))
16
+
1
17
  ## 2.5.0 (2026-11-08)
2
18
 
3
19
  ### Summary
package/README.md CHANGED
@@ -578,6 +578,8 @@ Routing changes require an OpenCode restart, like other runtime plugin settings.
578
578
 
579
579
  `hashline_edit` and `str_replace_editor` publish closed input contracts and reject conflicting or malformed fields before touching a file, without changing literal edit behavior: `replace` keeps its optional inclusive `end` (the `replace_range` alias still works), `lines` accepts a string, a string array, or `null` (an empty array or `null` deletes the range), `append`/`prepend` perform boundary insertion, `new_str` may be intentionally empty to delete, and `view_range` may end at `-1` to view to end of file. Supplying conflicting anchors, an unknown field, or a malformed range is a structural error that leaves file content, paths, freshness metadata, and the metadata sink unchanged, and the existing current-file and stale-anchor checks stay authoritative before any mutation.
580
580
 
581
+ Native `str_replace_editor` calls targeting the same canonical path are serialized across sessions in one process, including the read, freshness check, mutation, and cache update; calls for different files remain independent. Native reads and editor views share session-isolated canonical freshness records, so aliases cannot bypass an existing observation. Writes stage and verify the complete UTF-8 payload before atomic publication instead of truncating the destination, preserving ordinary file modes, POSIX ownership, and existing symlink targets. Multi-hardlink targets and files with setuid, setgid, or sticky mode bits are refused; inability to preserve uid/gid also fails without changing the original file. Publication requires a writable parent directory and does not preserve extended ACLs or xattrs. Removing a restrictive ACL can widen effective access: use a metadata-preserving editor for files with extended ACLs. Separate calls are not an all-or-nothing batch: a rejected replacement does not undo earlier successful calls. This coordination does not lock out other editing tools or external processes, and it does not add support for arbitrary text encodings.
582
+
581
583
  ### Tool history compaction
582
584
 
583
585
  `ToolHistoryCompactionPlugin` shrinks the context replayed to the model on every turn without touching on-disk storage. It rewrites only the in-memory provider-context copy the model is about to receive, through the native session `context` hook and gated per bound session family by its captured policy, and only the `output` of old completed tool parts — `input` and part structure (callID/type/order) are never changed, so provider tool_use/tool_result stitching stays intact.
@@ -0,0 +1,49 @@
1
+ export interface AtomicWriteStat {
2
+ mode: number;
3
+ nlink: number;
4
+ uid: number;
5
+ gid: number;
6
+ }
7
+ /** Injectable filesystem surface; production uses the node:fs/promises-backed default. */
8
+ export interface AtomicWriteIo {
9
+ realpath(path: string): Promise<string>;
10
+ stat(path: string): Promise<AtomicWriteStat>;
11
+ access(path: string, mode: number): Promise<void>;
12
+ readFile(path: string): Promise<Buffer>;
13
+ writeFile(path: string, data: Uint8Array, options: {
14
+ flag: "wx";
15
+ mode: number;
16
+ signal?: AbortSignal;
17
+ }): Promise<void>;
18
+ chmod(path: string, mode: number): Promise<void>;
19
+ chown(path: string, uid: number, gid: number): Promise<void>;
20
+ rename(from: string, to: string): Promise<void>;
21
+ link(existingPath: string, newPath: string): Promise<void>;
22
+ unlink(path: string): Promise<void>;
23
+ }
24
+ export declare const nodeAtomicWriteIo: AtomicWriteIo;
25
+ /**
26
+ * Replace `path` through a verified staging file. The canonical target (after
27
+ * resolving symlinks) is replaced so a symlink itself is never turned into a
28
+ * regular file. Ordinary modes and POSIX ownership are preserved; read-only targets and targets
29
+ * with special mode bits or multiple hard links are refused rather than silently
30
+ * changing their semantics or restoring privilege bits cleared by an in-place write.
31
+ *
32
+ * `expectedText` is the content the editor read for this command. Checking it
33
+ * immediately before publication detects an external change cheaply; it is not
34
+ * a universal compare-and-swap against other processes.
35
+ */
36
+ export declare function writeUtf8FileAtomically(path: string, content: string, options?: {
37
+ expectedText?: string;
38
+ signal?: AbortSignal;
39
+ io?: AtomicWriteIo;
40
+ }): Promise<void>;
41
+ /**
42
+ * Create `path` through a verified staging file and publish with a no-replace
43
+ * hard link. Returns false when any creator (including a racing one) already
44
+ * owns the directory entry, without overwriting it.
45
+ */
46
+ export declare function createUtf8FileExclusively(path: string, content: string, options?: {
47
+ signal?: AbortSignal;
48
+ io?: AtomicWriteIo;
49
+ }): Promise<boolean>;
@@ -0,0 +1,198 @@
1
+ // FILE: src/plugins/hashline-edit/atomic-write.ts
2
+ // VERSION: 0.1.0
3
+ // START_MODULE_CONTRACT
4
+ // PURPOSE: Publish str_replace_editor UTF-8 writes through a unique staging file in the target directory instead of truncating and rewriting the destination in place.
5
+ // SCOPE: Symlink-resolving atomic replacement with ordinary mode and POSIX ownership preservation, read-only, special-mode and multi-hardlink refusal, actionable ownership errors, pre-publication change and cancellation checks, byte-verified staged payloads, exclusive create publication, and cleanup after partial staging failures. No cross-process compare-and-swap or crash-durability guarantee.
6
+ // DEPENDS: [node:crypto, node:fs, node:fs/promises, node:path, src/plugins/hashline-edit/target-lock.ts]
7
+ // LINKS: [M-PLUGIN-HASHLINE-EDIT, V-M-PLUGIN-HASHLINE-EDIT]
8
+ // ROLE: RUNTIME
9
+ // MAP_MODE: EXPORTS
10
+ // END_MODULE_CONTRACT
11
+ //
12
+ // START_MODULE_MAP
13
+ // AtomicWriteIo - Injectable filesystem operations used by the staging publisher.
14
+ // AtomicWriteStat - Minimal target metadata required for safe publication.
15
+ // nodeAtomicWriteIo - Default node:fs/promises-backed operation set; tests may wrap it for fault injection.
16
+ // writeUtf8FileAtomically - Replace an existing file through a verified staging file and atomic rename.
17
+ // createUtf8FileExclusively - Create a new file through a verified staging file without overwriting a racing creator.
18
+ // END_MODULE_MAP
19
+ //
20
+ // START_CHANGE_SUMMARY
21
+ // LAST_CHANGE: [Direct fix - Publish byte-verified UTF-8 atomically with metadata preservation, pre-commit cancellation and change checks, partial-write cleanup, and exclusive create.]
22
+ // END_CHANGE_SUMMARY
23
+ import { randomBytes } from "node:crypto";
24
+ import { constants } from "node:fs";
25
+ import { access, chmod, chown, link, readFile, realpath, rename, stat, unlink, writeFile, } from "node:fs/promises";
26
+ import { basename, dirname, join } from "node:path";
27
+ import { throwIfAborted } from "./target-lock.js";
28
+ // END_BLOCK_TYPES
29
+ // START_BLOCK_DEFAULT_IO
30
+ export const nodeAtomicWriteIo = {
31
+ realpath: (path) => realpath(path),
32
+ async stat(path) {
33
+ const info = await stat(path);
34
+ return { mode: info.mode, nlink: info.nlink, uid: info.uid, gid: info.gid };
35
+ },
36
+ access: (path, mode) => access(path, mode),
37
+ readFile: (path) => readFile(path),
38
+ async writeFile(path, data, options) {
39
+ await writeFile(path, data, options);
40
+ },
41
+ chmod: (path, mode) => chmod(path, mode),
42
+ async chown(path, uid, gid) {
43
+ // Windows has no POSIX uid/gid; native ACL preservation is not implemented here.
44
+ if (process.platform !== "win32")
45
+ await chown(path, uid, gid);
46
+ },
47
+ rename: (from, to) => rename(from, to),
48
+ link: (existingPath, newPath) => link(existingPath, newPath),
49
+ unlink: (path) => unlink(path),
50
+ };
51
+ // END_BLOCK_DEFAULT_IO
52
+ // START_BLOCK_HELPERS
53
+ function ioFailure(message, code, cause) {
54
+ const error = new Error(message, { cause });
55
+ error.code = code;
56
+ return error;
57
+ }
58
+ function isErrno(error, code) {
59
+ return (typeof error === "object" && error !== null && error.code === code);
60
+ }
61
+ async function removeQuietly(io, path) {
62
+ try {
63
+ await io.unlink(path);
64
+ }
65
+ catch {
66
+ // The staging file may already be published or never created.
67
+ }
68
+ }
69
+ function stagingPath(target) {
70
+ const suffix = `${process.pid}-${randomBytes(6).toString("hex")}`;
71
+ return join(dirname(target), `.${basename(target)}.vvoc-${suffix}.tmp`);
72
+ }
73
+ /**
74
+ * Write the exact UTF-8 bytes to a unique staging file and read them back
75
+ * before publication. The caller owns cleanup of the returned path.
76
+ */
77
+ async function stageVerifiedBytes(io, target, bytes, createMode, chmodTo, owner, signal) {
78
+ for (let attempt = 0; attempt < 3; attempt += 1) {
79
+ throwIfAborted(signal);
80
+ const temp = stagingPath(target);
81
+ try {
82
+ await io.writeFile(temp, bytes, { flag: "wx", mode: createMode, signal });
83
+ }
84
+ catch (error) {
85
+ if (isErrno(error, "EEXIST"))
86
+ continue;
87
+ await removeQuietly(io, temp);
88
+ throw error;
89
+ }
90
+ try {
91
+ throwIfAborted(signal);
92
+ if (owner !== undefined) {
93
+ try {
94
+ await io.chown(temp, owner.uid, owner.gid);
95
+ }
96
+ catch (error) {
97
+ throw ioFailure(`Refusing to atomically replace ${target}: cannot preserve POSIX ownership (uid ${owner.uid}, gid ${owner.gid}). The original file is unchanged.`, "EOWNERSHIP", error);
98
+ }
99
+ }
100
+ if (chmodTo !== undefined) {
101
+ await io.chmod(temp, chmodTo);
102
+ }
103
+ const staged = await io.readFile(temp);
104
+ if (Buffer.compare(staged, bytes) !== 0) {
105
+ throw ioFailure(`Refusing to publish ${target}: the staged UTF-8 bytes did not verify.`, "EIO");
106
+ }
107
+ return temp;
108
+ }
109
+ catch (error) {
110
+ await removeQuietly(io, temp);
111
+ throw error;
112
+ }
113
+ }
114
+ throw ioFailure(`Could not allocate a unique staging file for ${target}.`, "EEXIST");
115
+ }
116
+ async function resolveParentRealpath(io, path) {
117
+ const parent = dirname(path);
118
+ try {
119
+ return await io.realpath(parent);
120
+ }
121
+ catch {
122
+ return parent;
123
+ }
124
+ }
125
+ // END_BLOCK_HELPERS
126
+ // START_BLOCK_PUBLICATION
127
+ /**
128
+ * Replace `path` through a verified staging file. The canonical target (after
129
+ * resolving symlinks) is replaced so a symlink itself is never turned into a
130
+ * regular file. Ordinary modes and POSIX ownership are preserved; read-only targets and targets
131
+ * with special mode bits or multiple hard links are refused rather than silently
132
+ * changing their semantics or restoring privilege bits cleared by an in-place write.
133
+ *
134
+ * `expectedText` is the content the editor read for this command. Checking it
135
+ * immediately before publication detects an external change cheaply; it is not
136
+ * a universal compare-and-swap against other processes.
137
+ */
138
+ export async function writeUtf8FileAtomically(path, content, options = {}) {
139
+ throwIfAborted(options.signal);
140
+ const io = options.io ?? nodeAtomicWriteIo;
141
+ const bytes = Buffer.from(content, "utf8");
142
+ const target = await io.realpath(path);
143
+ const info = await io.stat(target);
144
+ if ((info.mode & 0o222) === 0) {
145
+ throw ioFailure(`Refusing to write ${path}: the file is not writable.`, "EACCES");
146
+ }
147
+ await io.access(target, constants.W_OK);
148
+ if ((info.mode & 0o7000) !== 0) {
149
+ throw ioFailure(`Refusing to atomically replace ${path}: setuid, setgid, or sticky mode bits require an ownership-preserving in-place editor.`, "ESPECIALMODE");
150
+ }
151
+ if (info.nlink > 1) {
152
+ throw ioFailure(`Refusing to atomically replace ${path}: the file has ${info.nlink} hard links.`, "EHARDLINK");
153
+ }
154
+ const mode = info.mode & 0o777;
155
+ const temp = await stageVerifiedBytes(io, target, bytes, 0o600, mode, info, options.signal);
156
+ try {
157
+ if (options.expectedText !== undefined) {
158
+ const current = await io.readFile(target);
159
+ if (!current.equals(Buffer.from(options.expectedText, "utf8"))) {
160
+ throw ioFailure(`Refusing to edit ${path}: the file changed after it was read. Run view again before editing.`, "ECONCURRENT");
161
+ }
162
+ }
163
+ throwIfAborted(options.signal);
164
+ await io.rename(temp, target);
165
+ }
166
+ catch (error) {
167
+ await removeQuietly(io, temp);
168
+ throw error;
169
+ }
170
+ }
171
+ /**
172
+ * Create `path` through a verified staging file and publish with a no-replace
173
+ * hard link. Returns false when any creator (including a racing one) already
174
+ * owns the directory entry, without overwriting it.
175
+ */
176
+ export async function createUtf8FileExclusively(path, content, options = {}) {
177
+ throwIfAborted(options.signal);
178
+ const io = options.io ?? nodeAtomicWriteIo;
179
+ const bytes = Buffer.from(content, "utf8");
180
+ const target = join(await resolveParentRealpath(io, path), basename(path));
181
+ const temp = await stageVerifiedBytes(io, target, bytes, 0o666, undefined, undefined, options.signal);
182
+ try {
183
+ throwIfAborted(options.signal);
184
+ await io.link(temp, target);
185
+ return true;
186
+ }
187
+ catch (error) {
188
+ if (isErrno(error, "EEXIST")) {
189
+ return false;
190
+ }
191
+ throw error;
192
+ }
193
+ finally {
194
+ await removeQuietly(io, temp);
195
+ }
196
+ }
197
+ // END_BLOCK_PUBLICATION
198
+ //# sourceMappingURL=atomic-write.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"atomic-write.js","sourceRoot":"","sources":["../../../src/plugins/hashline-edit/atomic-write.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAClD,iBAAiB;AACjB,wBAAwB;AACxB,yKAAyK;AACzK,gZAAgZ;AAChZ,2GAA2G;AAC3G,8DAA8D;AAC9D,kBAAkB;AAClB,sBAAsB;AACtB,sBAAsB;AACtB,EAAE;AACF,mBAAmB;AACnB,oFAAoF;AACpF,6EAA6E;AAC7E,8GAA8G;AAC9G,0GAA0G;AAC1G,wHAAwH;AACxH,iBAAiB;AACjB,EAAE;AACF,uBAAuB;AACvB,2LAA2L;AAC3L,qBAAqB;AAErB,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EACL,MAAM,EACN,KAAK,EACL,KAAK,EACL,IAAI,EACJ,QAAQ,EACR,QAAQ,EACR,MAAM,EACN,I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C;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,IAAY,EACZ,OAAe,EACf,UAAwD,EAAE;IAE1D,cAAc,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAC/B,MAAM,EAAE,GAAG,OAAO,CAAC,EAAE,IAAI,iBAAiB,CAAC;IAC3C,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IAC3C,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,qBAAqB,CAAC,EAAE,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;IAC3E,MAAM,IAAI,GAAG,MAAM,kBAAkB,CACnC,EAAE,EACF,MAAM,EACN,KAAK,EACL,KAAK,EACL,SAAS,EACT,SAAS,EACT,OAAO,CAAC,MAAM,CACf,CAAC;IACF,IAAI,CAAC;QACH,cAAc,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAC/B,MAAM,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QAC5B,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,OAAO,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;YAC7B,OAAO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;YAAS,CAAC;QACT,MAAM,aAAa,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;AACH,CAAC;AACD,wBAAwB"}
@@ -1,9 +1,9 @@
1
1
  // FILE: src/plugins/hashline-edit/index.ts
2
- // VERSION: 2.0.0
2
+ // VERSION: 2.1.0
3
3
  // START_MODULE_CONTRACT
4
4
  // PURPOSE: Route per-model native edit tooling: register hashline_edit and str_replace_editor as native OpenCode 2.0.18 tools, resolve the session edit mode from the captured vvoc routing config, expose exactly one plugin edit tool per actual session model (never touching the host edit/patch contracts), require a native resource permission before any write, transform native read results with true line anchors and freshness tracking, and honor an explicit host permission denial while restoring plugin-owned versus captured host tool definitions by ownership.
5
- // SCOPE: Native Plugin.define entry, per-bound-family captured routing resolution, session model capture from native context/model.request hooks, deny-safe native session context tool-list visibility enforcement with plugin-owned versus captured host definition ownership, execute.before visibility/structural guards, execute.after read-anchor transformation and freshness recording, native tool execution with awaited permission before mutation and respected caller abort, bounded post-edit metadata reporting, and editMode telemetry. Pure edit algorithms, anchors, encoding, normalization, and error semantics are unchanged. No V1 chat.message/tool.execute hooks, no V1 tool()/ToolContext.
6
- // DEPENDS: [@opencode/plugin, @opencode/plugin/promise/tool, effect (Schema.toJsonSchemaDocument; direct dep T009), zod, zod/v4/core, node:fs/promises, node:path, src/lib/agent-tool-contract.ts, src/plugins/hashline-edit/diff-summary.ts, src/plugins/hashline-edit/edit-operations.ts, src/plugins/hashline-edit/file-text-canonicalization.ts, src/plugins/hashline-edit/hash-computation.ts, src/plugins/hashline-edit/normalize-edits.ts, src/plugins/hashline-edit/routing.ts, src/plugins/hashline-edit/schemas.ts, src/plugins/hashline-edit/session-state.ts, src/plugins/hashline-edit/str-replace-editor.ts, src/plugins/hashline-edit/validation.ts, src/runtime/context.ts]
5
+ // SCOPE: Native Plugin.define entry, per-bound-family captured routing resolution, session model capture from native context/model.request hooks, deny-safe native session context tool-list visibility enforcement with plugin-owned versus captured host definition ownership, execute.before visibility/structural guards, execute.after read-anchor transformation and freshness recording, native tool execution with awaited permission before mutation and respected caller abort, process-wide canonical-target serialization and session-isolated canonical freshness shared by live handler instances, atomic staged UTF-8 publication for str_replace_editor mutations, bounded post-edit metadata reporting, and editMode telemetry. Pure edit algorithms, anchors, and literal matching are unchanged. No V1 chat.message/tool.execute hooks, no V1 tool()/ToolContext.
6
+ // DEPENDS: [@opencode/plugin, @opencode/plugin/promise/tool, effect (Schema.toJsonSchemaDocument; direct dep T009), zod, zod/v4/core, node:fs/promises, node:path, src/lib/agent-tool-contract.ts, src/plugins/hashline-edit/atomic-write.ts, src/plugins/hashline-edit/diff-summary.ts, src/plugins/hashline-edit/edit-operations.ts, src/plugins/hashline-edit/file-text-canonicalization.ts, src/plugins/hashline-edit/hash-computation.ts, src/plugins/hashline-edit/normalize-edits.ts, src/plugins/hashline-edit/routing.ts, src/plugins/hashline-edit/schemas.ts, src/plugins/hashline-edit/session-state.ts, src/plugins/hashline-edit/str-replace-editor.ts, src/plugins/hashline-edit/validation.ts, src/runtime/context.ts]
7
7
  // LINKS: [M-PLUGIN-HASHLINE-EDIT, M-AGENT-TOOL-CONTRACT, M-NATIVE-RUNTIME, V-M-PLUGIN-HASHLINE-EDIT]
8
8
  // ROLE: RUNTIME
9
9
  // MAP_MODE: EXPORTS
@@ -24,18 +24,19 @@
24
24
  // END_MODULE_MAP
25
25
  //
26
26
  // START_CHANGE_SUMMARY
27
- // LAST_CHANGE: [C-HASHLINE-DENY-SAFETY T-001 - Honor explicit permission denial and split plugin-owned versus captured host tool definitions in session visibility enforcement.]
27
+ // LAST_CHANGE: [Direct fix - Serialize str_replace_editor target cycles, share canonical freshness across live handlers and aliases, and publish staged UTF-8 writes atomically with pre-commit cancellation.]
28
28
  // END_CHANGE_SUMMARY
29
29
  import { Plugin } from "@opencode/plugin";
30
30
  import { Schema } from "effect";
31
31
  import { z } from "zod";
32
32
  import { $ZodType, toJSONSchema } from "zod/v4/core";
33
- import { dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
33
+ import { dirname, basename, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
34
34
  import { existsSync } from "node:fs";
35
35
  import { homedir } from "node:os";
36
- import { readFile, readdir, stat, writeFile } from "node:fs/promises";
36
+ import { readFile, readdir, realpath, stat } from "node:fs/promises";
37
37
  import { acquireNativeSnapshotRuntime, } from "../../runtime/context.js";
38
38
  import { ContractInputError, formatContractIssues } from "../../lib/agent-tool-contract.js";
39
+ import { createUtf8FileExclusively, writeUtf8FileAtomically } from "./atomic-write.js";
39
40
  import { findFirstChangedLine, summarizeEditDiff } from "./diff-summary.js";
40
41
  import { applyHashlineEditsWithReport } from "./edit-operations.js";
41
42
  import { canonicalizeFileText, restoreFileText } from "./file-text-canonicalization.js";
@@ -252,6 +253,11 @@ function locateResource(locationDir, projectRoot, target, kind) {
252
253
  };
253
254
  }
254
255
  // START_BLOCK_FS_HELPERS
256
+ // Like the target lock, freshness must have one process-wide owner. Canonical
257
+ // keys keep native reads and editor views authoritative through path aliases;
258
+ // session keys still isolate observations made by different agents.
259
+ const sharedFileCache = new SessionFileCache();
260
+ let fileCacheOwners = 0;
255
261
  async function statSnapshot(filePath) {
256
262
  try {
257
263
  const info = await stat(filePath);
@@ -273,7 +279,21 @@ async function inferTargetKind(target) {
273
279
  return "file";
274
280
  }
275
281
  }
276
- function createNodeStrReplaceFs() {
282
+ /** Resolve symlink aliases for coordination; missing targets resolve through their parent. */
283
+ async function canonicalizeExistingPath(path) {
284
+ try {
285
+ return await realpath(path);
286
+ }
287
+ catch {
288
+ try {
289
+ return join(await realpath(dirname(path)), basename(path));
290
+ }
291
+ catch {
292
+ return resolve(path);
293
+ }
294
+ }
295
+ }
296
+ function createNodeStrReplaceFs(signal) {
277
297
  return {
278
298
  async exists(path) {
279
299
  try {
@@ -295,8 +315,14 @@ function createNodeStrReplaceFs() {
295
315
  async readText(path) {
296
316
  return readFile(path, "utf8");
297
317
  },
298
- async writeText(path, content) {
299
- await writeFile(path, content, "utf8");
318
+ async writeText(path, content, options) {
319
+ await writeUtf8FileAtomically(path, content, { expectedText: options?.expectedText, signal });
320
+ },
321
+ async createText(path, content) {
322
+ return createUtf8FileExclusively(path, content, { signal });
323
+ },
324
+ async canonicalize(path) {
325
+ return canonicalizeExistingPath(path);
300
326
  },
301
327
  async listDir(path) {
302
328
  const entries = await readdir(path, { withFileTypes: true });
@@ -615,17 +641,19 @@ async function executeHashlineEdit(args, telemetry, publish, baseDir, hostHome)
615
641
  return `Error: ${message}`;
616
642
  }
617
643
  }
618
- async function executeStrReplaceEditor(args, sessionID, fileCache, telemetry, publish, baseDir, hostHome) {
644
+ async function executeStrReplaceEditor(args, sessionID, fileCache, telemetry, publish, baseDir, hostHome, signal) {
619
645
  const requestedPath = requireNonEmptyPath(args.path);
620
646
  if (requestedPath === undefined) {
621
647
  return "Error: path must be a non-empty path";
622
648
  }
623
649
  const targetPath = normalizeTargetPath(baseDir, requestedPath, hostHome);
650
+ const freshnessPath = await canonicalizeExistingPath(targetPath);
624
651
  const resolvedArgs = { ...args, path: targetPath };
625
652
  const editor = new StrReplaceEditor({
626
- fs: createNodeStrReplaceFs(),
627
- onViewed: (path, snapshot) => fileCache.record(sessionID, path, snapshot),
628
- checkFreshness: (path, current) => fileCache.check(sessionID, path, current),
653
+ fs: createNodeStrReplaceFs(signal),
654
+ signal,
655
+ onViewed: (_path, snapshot) => fileCache.record(sessionID, freshnessPath, snapshot),
656
+ checkFreshness: (_path, current) => fileCache.check(sessionID, freshnessPath, current),
629
657
  });
630
658
  const result = await editor.execute(resolvedArgs);
631
659
  if (!result.ok) {
@@ -663,7 +691,9 @@ function modelOf(model) {
663
691
  /** Build routing state, native hook handlers and the two native tool infos. */
664
692
  export function createHashlineEditHandlers(deps, options = {}) {
665
693
  const modelCache = new SessionModelCache();
666
- const fileCache = new SessionFileCache();
694
+ const fileCache = sharedFileCache;
695
+ fileCacheOwners += 1;
696
+ let disposed = false;
667
697
  const nativeDefinitions = options.nativeDefinitions ?? new Map();
668
698
  const resolveMode = (sessionID, settings) => resolveEditMode(settings.routing, modelCache.get(sessionID));
669
699
  const requireLocation = async (sessionID) => {
@@ -810,7 +840,7 @@ export function createHashlineEditHandlers(deps, options = {}) {
810
840
  const projectRoot = await deps.projectRootFor(context.sessionID);
811
841
  const targetPath = normalizeTargetPath(baseDir, requestedPath, hostHome);
812
842
  const telemetry = await telemetryFor(context.sessionID);
813
- const run = () => executeStrReplaceEditor(validation.data, context.sessionID, fileCache, telemetry, (u) => context.progress(u), baseDir, hostHome);
843
+ const run = () => executeStrReplaceEditor(validation.data, context.sessionID, fileCache, telemetry, (u) => context.progress(u), baseDir, hostHome, context.signal);
814
844
  const output = await requestFileEffect(context, baseDir, projectRoot, validation.data.command === "view" ? "read" : "edit", [targetPath], "str_replace_editor", run);
815
845
  return nativeResult(output);
816
846
  },
@@ -919,9 +949,10 @@ export function createHashlineEditHandlers(deps, options = {}) {
919
949
  // A successful native read always establishes freshness (needed by the
920
950
  // str_replace editor); anchoring additionally requires hashline mode.
921
951
  if (targetPath !== undefined) {
922
- const snapshot = await statSnapshot(targetPath);
952
+ const freshnessPath = await canonicalizeExistingPath(targetPath);
953
+ const snapshot = await statSnapshot(freshnessPath);
923
954
  if (snapshot)
924
- fileCache.record(event.sessionID, targetPath, snapshot);
955
+ fileCache.record(event.sessionID, freshnessPath, snapshot);
925
956
  }
926
957
  const settings = await deps.settingsFor(event.sessionID);
927
958
  if (settings === undefined || !settings.enabled)
@@ -958,8 +989,13 @@ export function createHashlineEditHandlers(deps, options = {}) {
958
989
  return {
959
990
  handlers,
960
991
  dispose() {
992
+ if (disposed)
993
+ return;
994
+ disposed = true;
961
995
  modelCache.clear();
962
- fileCache.clear();
996
+ fileCacheOwners -= 1;
997
+ if (fileCacheOwners === 0)
998
+ fileCache.clear();
963
999
  },
964
1000
  };
965
1001
  }