Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 45 additions & 19 deletions packages/core/src/services/fileReadCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,22 +56,39 @@ export interface FileReadEntry {
/** ms epoch of the last successful write. Undefined if never written. */
lastWriteAt?: number;
/**
* True iff the most recent Read consumed the whole file (no offset /
* limit / pages). Used by the Read fast-path to decide whether a
* follow-up "no-args" Read can return a `file_unchanged` placeholder
* instead of re-emitting the full content. Range-scoped Reads never
* trigger the placeholder, since the model may legitimately ask for a
* different range next time.
* True iff the most recent Read produced the whole file's current
* content: no offset / limit / pages on the request AND the content
* was not truncated by the truncate-tool-output limit. Used both by
* the Read fast-path (to decide whether a follow-up "no-args" Read
* can return a `file_unchanged` placeholder) and by WriteFile's
* prior-read enforcement (to require "saw all bytes" before an
* overwrite). A truncated full read records `false` here because
* the model only saw the head of the file.
*/
lastReadWasFull: boolean;
/**
* True iff the content the most recent Read produced is one we are
* willing to substitute with a `file_unchanged` placeholder. Plain
* text reads set this to true; binary, image, audio, video, PDF, and
* notebook reads set it to false, because the model will likely need
* the structured / multi-modal payload again rather than a stub. The
* cache itself does not interpret this flag — it is a hint produced
* and consumed by the Read tool.
* True iff the most recent Read produced plain-text content — i.e.
* a text payload the Edit / WriteFile tools can mutate as text.
* False for binary, image, audio, video, PDF, and notebook reads,
* which produce structured payloads the mutating tools cannot
* safely alter.
*
* Note: this flag is purely about *content type* (text vs.
* non-text), not about whether the read was complete. Truncation
* is tracked separately on {@link lastReadWasFull}; conflating
* the two caused the issue #3964 regression where a partial /
* truncated text read caused the next Edit to be rejected with
* the misleading "binary / image / audio / video / PDF / notebook
* payload" error.
*
* Two independent consumers read this flag:
* - the ReadFile fast-path uses it (combined with
* `lastReadWasFull`) to decide whether to serve the
* `file_unchanged` placeholder.
* - `priorReadEnforcement.ts` uses it to detect non-text payloads
* and reject Edit / WriteFile against them (re-reading would
* produce the same non-text payload, so the message tells the
* model to use a different mechanism rather than re-read).
*/
lastReadCacheable: boolean;
}
Expand All @@ -93,12 +110,21 @@ export class FileReadCache {
/**
* Record a successful Read of `absPath`.
*
* - `full` — the Read covered the entire file (no offset / limit
* / pages). Only full Reads enable the `file_unchanged` fast-path
* on subsequent reads.
* - `cacheable` — the produced content is suitable for substitution
* with a `file_unchanged` placeholder. Set true for plain text,
* false for binary / image / audio / video / PDF / notebook.
* - `full` — the Read produced the entire current content of
* the file: no offset / limit / pages on the request AND the
* output was not truncated. Pass `false` for ranged reads OR
* for full-request reads whose content was truncated by the
* truncate-tool-output limit; both leave the model without
* sight of every current byte.
* - `cacheable` — the produced content is plain text (vs. binary /
* image / audio / video / PDF / notebook). This flag is purely
* about content type, not about whether the read was complete:
* a partial / truncated text read still records `cacheable: true`
* because the bytes the model saw were text. (Bundling
* truncation into `cacheable` was the issue #3964 regression
* that caused partial reads of `.kt` / `.cpp` / `.py` files to
* be rejected on the next Edit with a misleading "binary
* payload" message.)
*
* The `lastReadWasFull` and `lastReadCacheable` flags are
* **sticky-on-true** when the recorded fingerprint matches the
Expand Down
10 changes: 10 additions & 0 deletions packages/core/src/tools/priorReadEnforcement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@ export interface CheckPriorReadOptions {
* audio / video / PDF / notebook — those return a structured payload
* the Edit / WriteFile tools cannot mutate as text).
*
* `lastReadCacheable` is purely about content type, not completeness.
* A truncated or partial text read still records `lastReadCacheable:
* true` because the bytes the model saw were text. Whether the model
* has seen *every* byte is tracked separately on `lastReadWasFull`,
* which `requireFullRead` consumes below. Decoupling those two
* concerns is what fixed the issue #3964 regression where partial
* reads of regular `.kt` / `.cpp` / `.py` files caused the next Edit
* to be rejected with the misleading "binary / image / audio /
* video / PDF / notebook payload" error.
*
* Partial vs full read policy depends on `options.requireFullRead`:
* - default (`requireFullRead !== true`, i.e. EditTool): a partial
* read (offset / limit / pages) counts. The `0 occurrences`
Expand Down
94 changes: 94 additions & 0 deletions packages/core/src/tools/read-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,100 @@ describe('ReadFileTool', () => {
}
});

it('records partial text reads with lastReadCacheable=true so a follow-up Edit passes enforcement (issue #3964)', async () => {
// Pre-fix, ReadFileToolInvocation derived `cacheable` as
// `string && originalLineCount && !isTruncated`. A partial
// read of a regular text file (offset/limit) sets
// `isTruncated = true`, which collapsed `cacheable` to false
// and recorded the entry as `lastReadCacheable: false`.
// priorReadEnforcement.ts then mistook this for "binary
// payload" on the next Edit and rejected the call with the
// misleading "binary / image / audio / video / PDF /
// notebook payload" error. Decoupling the truncation check
// from `cacheable` (truncation now lives on
// `lastReadWasFull`) means partial text reads correctly
// record as text-cacheable.
const filePath = path.join(tempRootDir, 'partial.kt');
const lines = Array.from({ length: 50 }, (_, i) => `line ${i + 1}`);
await fsp.writeFile(filePath, lines.join('\n'), 'utf-8');

await read({ file_path: filePath, offset: 10, limit: 5 });

const status = fileReadCache.check(fs.statSync(filePath));
expect(status.state).toBe('fresh');
if (status.state === 'fresh') {
expect(status.entry.lastReadAt).toBeDefined();
// The truncation check moved to `lastReadWasFull`: a
// ranged read leaves the model without sight of every
// byte, so this stays false.
expect(status.entry.lastReadWasFull).toBe(false);
// The bytes the model saw were text — Edit must accept
// this read.
expect(status.entry.lastReadCacheable).toBe(true);
}
});

it('records truncated full reads with lastReadCacheable=true (issue #3964)', async () => {
// Symmetric regression for the other arm of issue #3964:
// `read_file(file_path)` without offset/limit but on a file
// larger than the truncate-tool-output limit. Pre-fix the
// truncated content collapsed `cacheable` to false; post-fix
// it stays true (the bytes were text), and only
// `lastReadWasFull` is false (the model only saw the head).
const filePath = path.join(tempRootDir, 'long.cpp');
// Mock Config caps truncate-tool-output-lines at 500.
const bigContent = Array.from(
{ length: 700 },
(_, i) => `line ${i + 1}`,
).join('\n');
await fsp.writeFile(filePath, bigContent, 'utf-8');

const result = await read({ file_path: filePath });
expect(result.returnDisplay).toMatch(/Read lines .* of 700/);

const status = fileReadCache.check(fs.statSync(filePath));
expect(status.state).toBe('fresh');
if (status.state === 'fresh') {
// Truncated → model has not seen every byte.
expect(status.entry.lastReadWasFull).toBe(false);
// But the bytes are text, so Edit (which accepts partial
// reads) must not be rejected as "binary payload".
expect(status.entry.lastReadCacheable).toBe(true);
}
});

it('reads source-code files with binary-looking content as text (encrypted FS, issue #3964)', async () => {
// Frank-Shaw-FS reports `.cpp` source files on Windows
// encrypted / DRM-protected file systems being misclassified
// as binary. The OS surfaces encrypted bytes to `fs.open()`
// random-access reads, so the 4 KB `isBinaryFile` heuristic
// sees nulls / non-printables and concludes binary even
// though the user-visible content is plain text. The
// extension-based override in detectFileType skips the
// content sample for known text extensions; verify that
// routes through `processSingleFileContent` correctly and
// records the read as text-cacheable so a follow-up Edit
// passes prior-read enforcement.
//
// We can't easily simulate a real encrypted volume in a
// unit test, so we approximate by writing nominally text
// content to a `.cpp` file. The test relies on the
// extension override winning over any future content-side
// heuristic — there is no isBinaryFile mocking in scope.
const filePath = path.join(tempRootDir, 'src.cpp');
await fsp.writeFile(filePath, '#include <iostream>\nint main() {}\n');

const result = await read({ file_path: filePath });
expect(typeof result.llmContent).toBe('string');
expect(result.llmContent).toContain('#include');

const status = fileReadCache.check(fs.statSync(filePath));
expect(status.state).toBe('fresh');
if (status.state === 'fresh') {
expect(status.entry.lastReadCacheable).toBe(true);
}
});

it('does not return the placeholder for image files', async () => {
const imagePath = path.join(tempRootDir, 'pic.png');
const pngHeader = Buffer.from([
Expand Down
38 changes: 27 additions & 11 deletions packages/core/src/tools/read-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,14 +215,31 @@ class ReadFileToolInvocation extends BaseToolInvocation<
}

// Record a cache entry so that subsequent identical Reads can hit
// the file_unchanged fast-path. An entry is "cacheable" only when
// - the content is plain text (not binary / image / audio / video
// / PDF / notebook — those need their structured payload), and
// - the read was not truncated. A truncated full Read means the
// model only saw the head of the file; returning a placeholder
// on the next call would falsely imply "you've already seen
// everything", so we force the next call back through the full
// pipeline.
// the file_unchanged fast-path, and so prior-read enforcement on
// Edit / WriteFile can recognise the read.
//
// Two independent flags are recorded:
//
// - `cacheable` — whether the content is plain text (not binary /
// image / audio / video / PDF / notebook). This is the flag
// `priorReadEnforcement.ts` consults to decide whether the
// model has seen a payload that Edit / WriteFile can mutate as
// text. It must NOT include "was the read truncated", because
// a truncated text read still produced text — bundling those
// two concerns is what produced the issue #3964 regression
// where a partial Read of a regular `.kt` / `.cpp` / `.py`
// file caused the next Edit to be rejected with the
// misleading "binary / image / audio / video / PDF / notebook
// payload" error.
//
// - `full` — whether the model has seen every byte of the
// current file. This gates both the file_unchanged fast-path
Comment thread
wenshao marked this conversation as resolved.
Resolved
// and WriteFile's full-read requirement. A "full" Read at the
// request level (no offset / limit / pages) only counts as
// full at the cache level if the produced content was not
// truncated, otherwise the model only saw the head and a
// follow-up `file_unchanged` placeholder would falsely imply
// "you've already seen everything".
//
// The stat we record is the one taken inside `processSingleFileContent`
// and surfaced via `result.stats`. The internal stat happens
Expand All @@ -242,11 +259,10 @@ class ReadFileToolInvocation extends BaseToolInvocation<
if (cacheEnabled && (result.stats ?? stats)) {
const cacheable =
typeof result.llmContent === 'string' &&
result.originalLineCount !== undefined &&
!result.isTruncated;
result.originalLineCount !== undefined;
const recordStats: Stats = result.stats ?? stats!;
cache.recordRead(absPath, recordStats, {
full: isFullRead,
full: isFullRead && !result.isTruncated,
cacheable,
});
}
Expand Down
80 changes: 80 additions & 0 deletions packages/core/src/utils/fileUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -845,6 +845,86 @@ describe('fileUtils', () => {
// filePathForDetectTest is already a text file by default from beforeEach
expect(await detectFileType(filePathForDetectTest)).toBe('text');
});

it('returns text for files with a text/* mime even when the content looks binary (issue #3964 encrypted FS)', async () => {
// Frank-Shaw-FS reports `.cpp` / `.c` / `.h` source files on
// Windows encrypted / DRM-protected file systems being
// misclassified as binary. The OS surfaces encrypted bytes
// to `fs.open()` random-access reads, so the 4 KB
// `isBinaryFile` heuristic sees nulls / non-printables and
// concludes binary. The extension already declares a text
// mime, so we must trust that and skip the content sample.
mockMimeGetType.mockReturnValueOnce('text/x-c');
const filePath = path.join(tempRootDir, 'encrypted.cpp');
// Mimic the encrypted-FS sample: leading nulls and high
// bytes that would trip isBinaryFile (>30% non-printable
// and at least one null).
const fakeEncrypted = Buffer.alloc(64);
for (let i = 0; i < fakeEncrypted.length; i++) {
fakeEncrypted[i] = i % 4 === 0 ? 0 : 0xff;
}
actualNodeFs.writeFileSync(filePath, fakeEncrypted);
try {
expect(await detectFileType(filePath)).toBe('text');
} finally {
actualNodeFs.unlinkSync(filePath);
}
});

it('returns text for application/javascript and similar text-like application mimes', async () => {
mockMimeGetType.mockReturnValueOnce('application/javascript');
expect(await detectFileType('script.js')).toBe('text');
mockMimeGetType.mockReturnValueOnce('application/json');
expect(await detectFileType('data.json')).toBe('text');
mockMimeGetType.mockReturnValueOnce('application/toml');
expect(await detectFileType('config.toml')).toBe('text');
});

it('returns text for +xml and +json structured-data mime suffixes', async () => {
// Covers e.g. application/atom+xml, application/ld+json,
// application/rls-services+xml (Rust's registered mime).
mockMimeGetType.mockReturnValueOnce('application/rls-services+xml');
expect(await detectFileType('lib.rs')).toBe('text');
mockMimeGetType.mockReturnValueOnce('application/ld+json');
expect(await detectFileType('schema.jsonld')).toBe('text');
});

it('returns text for known source-code extensions even when content looks binary (mime/lite gap)', async () => {
// `mime/lite`'s registry omits most languages: `.py`, `.kt`,
// `.go`, `.rb`, `.swift`, ... all return null. Without a
// curated extension override, an encrypted-volume read whose
// 4 KB sample looks binary would misclassify these as binary
// even though the extension is unambiguously text.
const looksBinary = Buffer.alloc(64);
for (let i = 0; i < looksBinary.length; i++) {
looksBinary[i] = i % 4 === 0 ? 0 : 0xff;
}
for (const ext of ['.py', '.kt', '.go', '.rb', '.swift']) {
mockMimeGetType.mockReturnValueOnce(null);
const filePath = path.join(tempRootDir, `encrypted${ext}`);
actualNodeFs.writeFileSync(filePath, looksBinary);
try {
expect(await detectFileType(filePath)).toBe('text');
} finally {
actualNodeFs.unlinkSync(filePath);
}
}
});

it('still classifies files in BINARY_EXTENSIONS as binary even with text-looking content', async () => {
// The extension overrides win-list must not weaken the
// existing binary-extension pre-empt. A `.png` whose first
// bytes happen to be ASCII still gets classified as binary
// because the extension is in BINARY_EXTENSIONS.
mockMimeGetType.mockReturnValueOnce(null);
const filePath = path.join(tempRootDir, 'looksLikeText.png');
actualNodeFs.writeFileSync(filePath, 'PNGheader plain text');
try {
expect(await detectFileType(filePath)).toBe('binary');
} finally {
actualNodeFs.unlinkSync(filePath);
}
});
});

describe('processSingleFileContent', () => {
Expand Down
Loading
Loading