From 22c663075bdf9926079c69143c7028db88145be9 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Thu, 27 Aug 2026 15:11:34 +0800 Subject: [PATCH 01/79] feat(file-safety): atomic text publish primitive + safeWriteJson refactor (A4, #1375) --- src/eslint-suppressions.json | 1305 ----------------- src/integrations/editor/DiffViewProvider.ts | 3 +- .../editor/__tests__/DiffViewProvider.spec.ts | 28 +- .../__tests__/safeWriteText.spec.ts | 614 ++++++++ src/services/file-safety/safeWriteText.ts | 307 ++++ 5 files changed, 942 insertions(+), 1315 deletions(-) create mode 100644 src/services/file-safety/__tests__/safeWriteText.spec.ts create mode 100644 src/services/file-safety/safeWriteText.ts diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index e07b00bd6a9..185d3a9d6a2 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -1,1307 +1,2 @@ -{ - "api/providers/__tests__/anthropic-vertex.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 31 - } - }, - "api/providers/__tests__/anthropic.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 7 - } - }, - "api/providers/__tests__/base-openai-compatible-provider-timeout.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "api/providers/__tests__/base-openai-compatible-provider.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/providers/__tests__/base-provider.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "api/providers/__tests__/bedrock-custom-arn.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 12 - } - }, - "api/providers/__tests__/bedrock-error-handling.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 7 - } - }, - "api/providers/__tests__/bedrock-inference-profiles.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 27 - } - }, - "api/providers/__tests__/bedrock-native-tools.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 19 - } - }, - "api/providers/__tests__/bedrock-reasoning.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/providers/__tests__/bedrock.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 37 - } - }, - "api/providers/__tests__/deepseek.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 12 - } - }, - "api/providers/__tests__/gemini-handler.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 18 - } - }, - "api/providers/__tests__/gemini.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 33 - } - }, - "api/providers/__tests__/kenari.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/providers/__tests__/kimi-code.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/providers/__tests__/lite-llm.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 26 - } - }, - "api/providers/__tests__/mimo.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 18 - } - }, - "api/providers/__tests__/minimax.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/providers/__tests__/moonshot.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 22 - } - }, - "api/providers/__tests__/native-ollama.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 21 - } - }, - "api/providers/__tests__/openai-codex-native-tool-calls.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 22 - } - }, - "api/providers/__tests__/openai-codex.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 16 - } - }, - "api/providers/__tests__/openai-native-tools.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 14 - } - }, - "api/providers/__tests__/openai-native-usage.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 25 - } - }, - "api/providers/__tests__/openai-native.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 74 - } - }, - "api/providers/__tests__/openai-timeout.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "api/providers/__tests__/openai.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "api/providers/__tests__/opencode-go.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "api/providers/__tests__/openrouter.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 34 - } - }, - "api/providers/__tests__/qwen-code-native-tools.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/providers/__tests__/sambanova.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/providers/__tests__/unbound.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "api/providers/__tests__/vercel-ai-gateway.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/providers/__tests__/vertex.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "api/providers/__tests__/zai.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/providers/anthropic-vertex.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "api/providers/anthropic.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/providers/base-openai-compatible-provider.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 6 - } - }, - "api/providers/base-provider.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "api/providers/bedrock.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 32 - } - }, - "api/providers/deepseek.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/providers/fetchers/__tests__/kenari.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/providers/fetchers/__tests__/kimi-code.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/providers/fetchers/__tests__/lmstudio.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "api/providers/fetchers/__tests__/modelEndpointCache.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 9 - } - }, - "api/providers/fetchers/__tests__/moonshot.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/providers/fetchers/__tests__/ollama.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 9 - } - }, - "api/providers/fetchers/__tests__/opencode-go.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/providers/fetchers/__tests__/openrouter.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/providers/fetchers/__tests__/vercel-ai-gateway.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/providers/fetchers/__tests__/zoo-gateway.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 8 - } - }, - "api/providers/fetchers/litellm.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/providers/gemini.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "api/providers/lite-llm.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 6 - } - }, - "api/providers/mimo.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "api/providers/moonshot.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/providers/native-ollama.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/providers/openai-codex.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 31 - } - }, - "api/providers/openai-native.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 27 - } - }, - "api/providers/openai.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/providers/openrouter.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 6 - } - }, - "api/providers/poe.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/providers/requesty.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "api/providers/unbound.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "api/providers/utils/__tests__/error-handler.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 35 - } - }, - "api/providers/utils/__tests__/image-generation.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 17 - } - }, - "api/providers/utils/__tests__/timeout-config.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/providers/utils/error-handler.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 7 - } - }, - "api/providers/xai.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "api/transform/__tests__/ai-sdk.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "api/transform/__tests__/anthropic-filter.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 6 - } - }, - "api/transform/__tests__/bedrock-converse-format.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "api/transform/__tests__/gemini-format.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "api/transform/__tests__/mistral-format.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/transform/__tests__/model-params.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 8 - } - }, - "api/transform/__tests__/openai-format.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 49 - } - }, - "api/transform/__tests__/r1-format.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 8 - } - }, - "api/transform/__tests__/reasoning.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/transform/__tests__/responses-api-input.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/transform/__tests__/zai-format.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "api/transform/ai-sdk.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/transform/bedrock-converse-format.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "api/transform/cache-strategy/__tests__/cache-strategy.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 17 - } - }, - "api/transform/caching/__tests__/gemini.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/transform/gemini-format.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "api/transform/openai-format.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 7 - } - }, - "api/transform/r1-format.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "api/transform/responses-api-input.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 6 - } - }, - "api/transform/responses-api-stream.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "api/transform/zai-format.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "core/assistant-message/NativeToolCallParser.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/assistant-message/__tests__/presentAssistantMessage-custom-tool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "core/assistant-message/__tests__/presentAssistantMessage-images.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 14 - } - }, - "core/assistant-message/__tests__/presentAssistantMessage-unknown-tool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 8 - } - }, - "core/assistant-message/presentAssistantMessage.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "core/auto-approval/__tests__/AutoApprovalHandler.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/checkpoints/__tests__/checkpoint.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "core/checkpoints/index.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/condense/__tests__/condense.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "core/condense/__tests__/foldedFileContext.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 10 - } - }, - "core/condense/__tests__/index.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 24 - } - }, - "core/config/ContextProxy.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/config/CustomModesManager.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "core/config/ProviderSettingsManager.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "core/config/__tests__/ContextProxy.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "core/config/__tests__/CustomModesManager.exportImportSlugChange.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "core/config/__tests__/CustomModesManager.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 12 - } - }, - "core/config/__tests__/CustomModesManager.yamlEdgeCases.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/context-management/__tests__/context-management.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/context-tracking/__tests__/FileContextTracker.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "core/context/context-management/__tests__/context-error-handling.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/context/context-management/context-error-handling.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/diff/stats.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/environment/__tests__/getEnvironmentDetails.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/ignore/__tests__/RooIgnoreController.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/mentions/index.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/mentions/processUserContentMentions.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/message-manager/index.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 21 - } - }, - "core/message-manager/index.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/prompts/__tests__/add-custom-instructions.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/prompts/__tests__/get-prompt-component.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/prompts/__tests__/responses-rooignore.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 6 - } - }, - "core/prompts/__tests__/system-prompt.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "core/prompts/sections/__tests__/custom-instructions-global.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 18 - } - }, - "core/prompts/sections/__tests__/custom-instructions.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 55 - } - }, - "core/prompts/tools/__tests__/filter-tools-for-mode.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 14 - } - }, - "core/prompts/tools/native-tools/__tests__/converters.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/prompts/tools/native-tools/__tests__/read_file.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "core/task-persistence/__tests__/TaskHistoryStore.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "core/task-persistence/__tests__/importRooTaskHistory.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/task-persistence/__tests__/taskMessages.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/task-persistence/apiMessages.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/task/Task.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 17 - } - }, - "core/task/__tests__/Task.dispose.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "core/task/__tests__/Task.persistence.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 8 - } - }, - "core/task/__tests__/Task.sticky-profile-race.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "core/task/__tests__/Task.throttle.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 24 - } - }, - "core/task/__tests__/apiConversationHistory.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 23 - } - }, - "core/task/__tests__/ask-clear-approval-buttons.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 18 - } - }, - "core/task/__tests__/ask-queued-message-drain.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 17 - } - }, - "core/task/__tests__/flushPendingToolResultsToHistory.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 14 - } - }, - "core/task/__tests__/grace-retry-errors.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "core/task/__tests__/grounding-sources.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "core/task/__tests__/native-tools-filtering.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "core/task/__tests__/new-task-isolation.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/task/__tests__/reasoning-preservation.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 20 - } - }, - "core/task/__tests__/task-tool-history.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "core/task/apiConversationHistory.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 8 - } - }, - "core/tools/BaseTool.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/tools/CodebaseSearchTool.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/tools/GenerateImageTool.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/tools/NewTaskTool.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/tools/ReadFileTool.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "core/tools/ToolRepetitionDetector.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/tools/UpdateTodoListTool.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/tools/UseMcpToolTool.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "core/tools/__tests__/ReadCommandOutputTool.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 16 - } - }, - "core/tools/__tests__/askFollowupQuestionTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 20 - } - }, - "core/tools/__tests__/attemptCompletionTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 11 - } - }, - "core/tools/__tests__/editFileTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "core/tools/__tests__/editTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/tools/__tests__/executeCommand.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 10 - } - }, - "core/tools/__tests__/executeCommandTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 8 - } - }, - "core/tools/__tests__/generateImageTool.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 9 - } - }, - "core/tools/__tests__/listFilesTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 10 - } - }, - "core/tools/__tests__/mcpServerRestriction.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 6 - } - }, - "core/tools/__tests__/newTaskTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 26 - } - }, - "core/tools/__tests__/readFileTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 96 - } - }, - "core/tools/__tests__/runSlashCommandTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/tools/__tests__/searchReplaceTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/tools/__tests__/skillTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "core/tools/__tests__/updateTodoListTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/tools/__tests__/useMcpToolTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 21 - } - }, - "core/tools/__tests__/validateToolUse.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/tools/__tests__/writeToFileTool.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "core/tools/helpers/toolResultFormatting.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/tools/validateToolUse.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "core/webview/ClineProvider.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 7 - } - }, - "core/webview/__tests__/ClineProvider.apiHandlerRebuild.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 34 - } - }, - "core/webview/__tests__/ClineProvider.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 195 - } - }, - "core/webview/__tests__/ClineProvider.sticky-mode.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 27 - } - }, - "core/webview/__tests__/ClineProvider.sticky-profile.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 15 - } - }, - "core/webview/__tests__/ClineProvider.taskHistory.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 12 - } - }, - "core/webview/__tests__/diagnosticsHandler.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 7 - } - }, - "core/webview/__tests__/messageEnhancer.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 8 - } - }, - "core/webview/__tests__/skillsMessageHandler.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/webview/__tests__/telemetrySettingsTracking.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "core/webview/__tests__/webviewMessageHandler.cloudAuth.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "core/webview/__tests__/webviewMessageHandler.delete.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 9 - } - }, - "core/webview/__tests__/webviewMessageHandler.edit.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/webview/__tests__/webviewMessageHandler.importRooHistory.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 13 - } - }, - "core/webview/__tests__/webviewMessageHandler.readFileContent.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 56 - } - }, - "core/webview/__tests__/webviewMessageHandler.searchFiles.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "core/webview/__tests__/webviewMessageHandler.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 35 - } - }, - "core/webview/messageEnhancer.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "core/webview/webviewMessageHandler.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "services/__tests__/zoo-code-auth.test.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "services/checkpoints/__tests__/ShadowCheckpointService.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "services/code-index/__tests__/config-manager.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "services/code-index/__tests__/manager.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 84 - } - }, - "services/code-index/__tests__/orchestrator.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 23 - } - }, - "services/code-index/__tests__/service-factory.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 43 - } - }, - "services/code-index/embedders/__tests__/bedrock.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 7 - } - }, - "services/code-index/embedders/__tests__/gemini.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "services/code-index/embedders/__tests__/mistral.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "services/code-index/embedders/__tests__/ollama.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "services/code-index/embedders/__tests__/openai-compatible-rate-limit.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 15 - } - }, - "services/code-index/embedders/__tests__/openai-compatible.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 28 - } - }, - "services/code-index/embedders/__tests__/openai.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 10 - } - }, - "services/code-index/embedders/__tests__/openrouter.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "services/code-index/embedders/__tests__/vercel-ai-gateway.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "services/code-index/embedders/bedrock.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "services/code-index/embedders/ollama.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "services/code-index/embedders/openai-compatible.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "services/code-index/embedders/openai.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "services/code-index/embedders/openrouter.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "services/code-index/interfaces/vector-store.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "services/code-index/orchestrator.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "services/code-index/processors/__tests__/file-watcher.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 24 - } - }, - "services/code-index/processors/__tests__/parser.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 22 - } - }, - "services/code-index/processors/__tests__/scanner.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 26 - } - }, - "services/code-index/processors/file-watcher.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "services/code-index/processors/scanner.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "services/code-index/semble/__tests__/provider.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 12 - } - }, - "services/code-index/semble/__tests__/semble-cli.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "services/code-index/semble/__tests__/semble-downloader.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 61 - } - }, - "services/code-index/semble/provider.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "services/code-index/semble/semble-cli.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "services/code-index/shared/__tests__/validation-helpers.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "services/code-index/shared/validation-helpers.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "services/code-index/vector-store/__tests__/qdrant-client.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 87 - } - }, - "services/code-index/vector-store/qdrant-client.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "services/glob/__tests__/gitignore-integration.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "services/glob/__tests__/gitignore-test.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "services/glob/__tests__/list-files-limit.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 6 - } - }, - "services/glob/__tests__/list-files.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 22 - } - }, - "services/marketplace/MarketplaceManager.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "services/marketplace/SimpleInstaller.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 7 - } - }, - "services/marketplace/__tests__/MarketplaceManager.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "services/marketplace/__tests__/SimpleInstaller.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 17 - } - }, - "services/marketplace/__tests__/marketplace-setting-check.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "services/mcp/McpHub.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 7 - } - }, - "services/mcp/McpOAuthClientProvider.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "services/mcp/McpServerManager.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "services/mcp/__tests__/McpHub.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 150 - } - }, - "services/mcp/__tests__/McpOAuthClientProvider.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 18 - } - }, - "services/mcp/__tests__/SecretStorageService.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "services/mcp/utils/__tests__/oauth.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 9 - } - }, - "services/mcp/utils/callbackServer.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "services/mcp/utils/oauth.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "services/mdm/__tests__/MdmService.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 5 - } - }, - "services/ripgrep/__tests__/diagnostic.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 1 - } - }, - "services/roo-config/__tests__/index.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 20 - } - }, - "services/roo-config/index.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "services/rules/__tests__/rules.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "services/search/__tests__/file-search.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 3 - } - }, - "services/skills/__tests__/SkillsManager.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } - }, - "services/tree-sitter/__tests__/helpers.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 4 - } - }, - "services/tree-sitter/__tests__/markdownParser.spec.ts": { - "@typescript-eslint/no-explicit-any": { - "count": 2 - } } } diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 3c1d33ae283..2f29ca3ab15 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -18,6 +18,7 @@ import { arePathsEqual, getReadablePath } from "../../utils/path" import { formatResponse } from "../../core/prompts/responses" import { diagnosticsToProblemsString, getNewDiagnostics } from "../diagnostics" import { Task } from "../../core/task/Task" +import { safeWriteText } from "../../services/file-safety/safeWriteText" import { DecorationController } from "./DecorationController" @@ -1157,7 +1158,7 @@ export class DiffViewProvider { // Write the content directly to the file await createDirectoriesForFile(absolutePath) - await fs.writeFile(absolutePath, content, "utf-8") + await safeWriteText(absolutePath, content) // Open the document to ensure diagnostics are loaded // When openFile is false (PREVENT_FOCUS_DISRUPTION enabled), we only open in memory diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index e94a66e1db2..594725d2f30 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -18,6 +18,14 @@ vi.mock("fs/promises", () => ({ readFile: vi.fn().mockResolvedValue("file content"), writeFile: vi.fn().mockResolvedValue(undefined), access: vi.fn().mockResolvedValue(undefined), + mkdir: vi.fn().mockResolvedValue(undefined), + rename: vi.fn().mockResolvedValue(undefined), + unlink: vi.fn().mockResolvedValue(undefined), +})) + +// Mock safeWriteText (used by saveDirectly) +vi.mock("../../../services/file-safety/safeWriteText", () => ({ + safeWriteText: vi.fn().mockResolvedValue(undefined), })) // Mock utils @@ -29,6 +37,8 @@ vi.mock("../../../utils/fs", () => ({ vi.mock("path", () => ({ resolve: vi.fn((cwd, relPath) => `${cwd}/${relPath}`), basename: vi.fn((path) => path.split("/").pop()), + dirname: vi.fn((path) => path.split("/").slice(0, -1).join("/") || "/"), + join: (...args: string[]) => args.join("/"), })) // Mock vscode @@ -782,9 +792,9 @@ describe("DiffViewProvider", () => { const result = await diffViewProvider.saveDirectly("test.ts", "new content", true, true, 2000) - // Verify file was written - const fs = await import("fs/promises") - expect(fs.writeFile).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", "utf-8") + // Verify file was written via safeWriteText + const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content") // Verify file was opened without focus expect(vscode.window.showTextDocument).toHaveBeenCalledWith( @@ -805,9 +815,9 @@ describe("DiffViewProvider", () => { it("should not open file when openWithoutFocus is false", async () => { await diffViewProvider.saveDirectly("test.ts", "new content", false, true, 1000) - // Verify file was written - const fs = await import("fs/promises") - expect(fs.writeFile).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", "utf-8") + // Verify file was written via safeWriteText + const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content") // Verify file was NOT opened expect(vscode.window.showTextDocument).not.toHaveBeenCalled() @@ -820,9 +830,9 @@ describe("DiffViewProvider", () => { await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 1000) - // Verify file was written - const fs = await import("fs/promises") - expect(fs.writeFile).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", "utf-8") + // Verify file was written via safeWriteText + const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content") // Verify delay was NOT called expect(mockDelay).not.toHaveBeenCalled() diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts new file mode 100644 index 00000000000..4accc2b71e0 --- /dev/null +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -0,0 +1,614 @@ +import * as fs from "fs/promises" +import * as fsSync from "fs" +import { execFile } from "child_process" +import type { ChildProcess } from "child_process" +import * as path from "path" + +import { safeWriteText, type SafeWriteTextOptions } from "../safeWriteText" + +// Full mock for fs/promises — all methods are vi.fn() stubs +vi.mock("fs/promises", () => ({ + mkdir: vi.fn(), + access: vi.fn(), + rename: vi.fn(), + unlink: vi.fn(), + realpath: vi.fn(), +})) + +// Full mock for fs — all sync methods are vi.fn() stubs. Stats is a bare +// class stub so tests can build minimal Stats stand-ins via its prototype. +vi.mock("fs", () => ({ + openSync: vi.fn(), + writeSync: vi.fn(), + closeSync: vi.fn(), + mkdirSync: vi.fn(), + fsyncSync: vi.fn(), + chmodSync: vi.fn(), + fchmodSync: vi.fn(), + statSync: vi.fn(), + Stats: class Stats {}, +})) + +// Mock child_process.execFile (callback-based — must invoke callback to resolve) +vi.mock("child_process", () => ({ + execFile: vi.fn((cmd, args, opts, cb) => { + if (typeof cb === "function") cb(null) + }), +})) + +// Minimal stand-in for the ChildProcess that callback-form execFile returns. +const fakeChild = { kill: () => true } as unknown as ChildProcess + +// Helper that mirrors safeWriteText's path resolution exactly +function _resolvedTarget(filePath: string): string { + return path.resolve(filePath) +} +function _dirPath(filePath: string): string { + return path.dirname(_resolvedTarget(filePath)) +} +function _stagingDir(dir: string): string { + return path.join(dir, ".file-safety-staging") +} + +// Minimal Stats stand-in: the SUT only reads `.mode` from it. +function _stats(mode: number): fsSync.Stats { + const s = Object.create(fsSync.Stats.prototype) as fsSync.Stats + Object.assign(s, { mode }) + return s +} + +// ── Test 1: staging file created then cleaned after success ──────────────── + +describe("safeWriteText", () => { + beforeEach(() => { + vi.resetAllMocks() + // After resetAllMocks, vi.fn() returns undefined — restore promise defaults. + vi.mocked(fs.mkdir).mockResolvedValue(undefined) + vi.mocked(fs.access).mockResolvedValue(undefined) + vi.mocked(fs.rename).mockResolvedValue(undefined) + vi.mocked(fs.unlink).mockResolvedValue(undefined) + // Existing-target default: a regular 0o644 file. + vi.mocked(fsSync.statSync).mockReturnValue(_stats(0o644)) + // Default sync-write behaviour: report that all requested bytes were + // written. The Buffer overload passes (fd, buffer, offset, length), + // so the fourth argument is the requested length. + vi.mocked(fsSync.writeSync).mockImplementation((...args: unknown[]) => + typeof args[3] === "number" ? args[3] : 0, + ) + }) + + describe("staging and cleanup", () => { + it("creates a temp file in the staging dir, fsyncs it, renames to target, and cleans up on success", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) // fd=1 + vi.mocked(fsSync.closeSync).mockReturnValue(undefined) + + await safeWriteText(targetPath, "hello world", { platform: "linux" }) + + // staging dir was created with private permissions — use + // stringContaining to handle Windows path resolution + expect(fsSync.mkdirSync).toHaveBeenCalledWith(expect.stringContaining(".file-safety-staging"), { + recursive: true, + mode: 0o700, + }) + // a pre-existing staging dir is repaired to private permissions too + expect(fsSync.chmodSync).toHaveBeenCalledWith(expect.stringContaining(".file-safety-staging"), 0o700) + + // temp file was opened for writing with the existing target's mode + // (default 0o644 from the statSync default mock) + expect(fsSync.openSync).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), "w", 0o644) + + // content was written as a buffer (partial-write loop, full write) + expect(fsSync.writeSync).toHaveBeenCalledWith(1, Buffer.from("hello world", "utf8"), 0, 11) + + // fsync (sync form) was called on the fd + expect(fsSync.fsyncSync).toHaveBeenCalledWith(1) + + // file was closed + expect(fsSync.closeSync).toHaveBeenCalledWith(1) + + // atomic rename happened — realpath mock returns targetPath, so that's the dest + expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath) + + // no unlink of temp (it's now the committed file; DACL skipped via platform:linux) + expect(fs.unlink).not.toHaveBeenCalled() + }) + }) + + // ── Test 2: fsync ordering ─────────────────────────────────────────────── + + describe("fsync ordering", () => { + it("calls fsync on the fd before close, and rename after close", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + await safeWriteText(targetPath, "data", { platform: "linux" }) + + // Verify call order: openSync(temp) → writeSync → fsyncSync(temp) + // → closeSync(temp) → rename. On POSIX the parent directory is then + // opened and fsynced after the commit rename, so openSync/fsyncSync/ + // closeSync each have a second (directory) call. + expect(vi.mocked(fsSync.openSync).mock.calls.length).toBe(2) + expect(vi.mocked(fsSync.writeSync).mock.calls.length).toBe(1) + expect(vi.mocked(fsSync.fsyncSync).mock.calls.length).toBe(2) + expect(vi.mocked(fsSync.closeSync).mock.calls.length).toBe(2) + + // the temp file was fully closed before the commit rename + expect(vi.mocked(fsSync.closeSync).mock.calls[0][0]).toBe(1) + expect(fs.rename).toHaveBeenCalled() + }) + }) + + // ── Test 3: simulated failure between write and rename leaves target intact ── + + describe("crash/torn-write safety", () => { + it("simulated failure between fsync and rename leaves the target byte-identical and no temp left behind", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + vi.mocked(fs.rename).mockRejectedValue(new Error("ENOSPC")) + + await expect(safeWriteText(targetPath, "new data", { platform: "linux" })).rejects.toThrow("ENOSPC") + + // rename was attempted (the failure point) + expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath) + + // temp file was cleaned up on failure + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_")) + + // backup was NOT created (backup:false by default), so target is untouched + // The only rename call was temp→target, not a rollback rename + expect(fs.rename).toHaveBeenCalledTimes(1) + }) + + it("a post-commit backup cleanup failure is non-fatal: the target stays committed and no temp is left behind", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + // The post-commit backup unlink (SUT step 6) fails — the write must + // still succeed; an orphaned backup is the documented acceptable + // outcome, so the failure is swallowed instead of rolling back. + vi.mocked(fs.unlink).mockRejectedValueOnce(new Error("EPERM")) + + await safeWriteText(targetPath, "data", { backup: true, platform: "linux" }) + + // the commit rename (temp -> target) still happened + expect(fs.rename).toHaveBeenNthCalledWith(2, expect.stringContaining("safeWriteText_"), targetPath) + + // the failing cleanup was the post-commit backup unlink + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.bak_")) + + // no rollback rename: the committed target is not restored from the backup + expect(fs.rename).toHaveBeenCalledTimes(2) + + // the staging temp was already committed by the rename; nothing + // temp-shaped is unlinked afterwards + expect(fs.unlink).not.toHaveBeenCalledWith(expect.stringContaining("safeWriteText_")) + }) + }) + + // ── Test 4: backup:true keeps old safeWriteJson semantics incl. rollback ── + + describe("backup:true", () => { + it("renames target -> backup before commit, deletes backup on success", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + await safeWriteText(targetPath, "new data", { backup: true }) + + // target was accessed (exists check) + expect(fs.access).toHaveBeenCalledWith(targetPath) + + // first rename: target -> backup + expect(fs.rename).toHaveBeenNthCalledWith(1, targetPath, expect.stringContaining("safeWriteText.bak_")) + + // second rename: temp -> target (realpath mock returns targetPath) + expect(fs.rename).toHaveBeenNthCalledWith(2, expect.stringContaining("safeWriteText_"), targetPath) + + // backup was deleted on success + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.bak_")) + }) + + it("rollback: on failure after rename target->backup, restores backup to target", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + // first rename (target->backup) succeeds, second fails + let callCount = 0 + vi.mocked(fs.rename).mockImplementation(async () => { + callCount++ + if (callCount === 1) return // target -> backup + throw new Error("ENOSPC") // temp -> target fails + }) + + await expect(safeWriteText(targetPath, "new data", { backup: true })).rejects.toThrow("ENOSPC") + + // rollback rename is the 3rd call (after target->backup and temp->target failure) + expect(fs.rename).toHaveBeenNthCalledWith(3, expect.stringContaining("safeWriteText.bak_"), targetPath) + + // temp was cleaned up on failure + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_")) + }) + + it("backup:true when target does not exist: no backup created, just commit", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + // fs.access resolves for dirPath check, but rejects for target check (backup path) + vi.mocked(fs.access).mockImplementation(async (p) => { + if (typeof p === "string" && p.endsWith("target.txt")) throw { code: "ENOENT" } + }) + + await safeWriteText(targetPath, "new data", { backup: true, platform: "linux" }) + + // no backup rename (target didn't exist) + expect(fs.access).toHaveBeenCalledWith(targetPath) + + // only one rename: temp -> target + expect(fs.rename).toHaveBeenCalledTimes(1) + expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath) + + // no unlink (no backup to delete; DACL skipped via platform:linux) + expect(fs.unlink).not.toHaveBeenCalled() + }) + }) + + // ── Test 5: win32 DACL path ────────────────────────────────────────────── + + describe("win32 DACL", () => { + it.skipIf(process.platform !== "win32")( + "copies target DACL onto staging file via icacls before rename on Windows", + async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + await safeWriteText(targetPath, "data", { platform: "win32" }) + + // icacls dump + restore were called (execFile is callback-based mock) + expect(execFile).toHaveBeenCalledTimes(2) + }, + ) + + it("non-win32: DACL path is unreachable when platform is not win32", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + await safeWriteText(targetPath, "data", { platform: "linux" }) + + // icacls was NOT called on non-win32 + expect(execFile).not.toHaveBeenCalled() + }) + + it("win32 DACL failure falls back to plain rename (never fails the write)", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + // icacls dump fails — the callback-based mock must invoke cb with an error. + vi.mocked(execFile).mockImplementation((_cmd, _args, _opts, cb) => { + if (typeof cb === "function") cb(new Error("icacls error"), "", "") + return fakeChild + }) + + await safeWriteText(targetPath, "data", { platform: "win32" }) + + // write succeeded despite icacls failure (fallback to plain rename) + expect(fs.rename).toHaveBeenCalled() + }) + + it("win32 DACL save args are [targetPath, /save, dumpPath, /T] before backup rename", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + await safeWriteText(targetPath, "data", { backup: true, platform: "win32" }) + + // icacls was called twice (save + restore) + expect(execFile).toHaveBeenCalledTimes(2) + + // First call: save DACL from target before backup rename + const firstCall = vi.mocked(execFile).mock.calls[0] + expect(firstCall[0]).toBe("icacls") + expect(firstCall[1]).toEqual([targetPath, "/save", expect.stringContaining(".acl.tmp"), "/T"]) + + // Second call: restore DACL onto directory after commit rename + const secondCall = vi.mocked(execFile).mock.calls[1] + expect(secondCall[0]).toBe("icacls") + expect(secondCall[1]).toEqual([ + expect.stringContaining("/tmp/test-dir"), + "/restore", + expect.stringContaining(".acl.tmp"), + ]) + + // dump file was unlinked after restore + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining(".acl.tmp")) + }) + + it("win32 DACL: dump is unlinked even when restore fails", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + // icacls save succeeds, restore fails + let callCount = 0 + vi.mocked(execFile).mockImplementation((_cmd, _args, _opts, cb) => { + callCount++ + if (typeof cb === "function") { + cb(callCount === 1 ? null : new Error("icacls restore error"), "", "") + } + return fakeChild + }) + + await safeWriteText(targetPath, "data", { platform: "win32" }) + + // write succeeded despite restore failure (best-effort) + expect(fs.rename).toHaveBeenCalled() + + // dump file was still unlinked in finally + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining(".acl.tmp")) + }) + + it("win32 DACL: when target does not exist, no save/restore/dump", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + // fs.access rejects for targetPath (ENOENT), but resolves for dirPath + vi.mocked(fs.access).mockImplementation(async (p) => { + if (typeof p === "string" && p.endsWith("target.txt")) throw { code: "ENOENT" } + return undefined + }) + + await safeWriteText(targetPath, "data", { platform: "win32" }) + + // icacls was NOT called (target absent → skip DACL entirely) + expect(execFile).not.toHaveBeenCalled() + + // no dump file created or unlinked + expect(fs.unlink).not.toHaveBeenCalled() + }) + }) + + // ── Test 6: pre-written temp path (tempPath option) ────────────────────── + + describe("pre-written temp path", () => { + it("uses the provided tempPath, fsyncs it, and renames to target", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + const customTempPath = "/tmp/custom-temp.tmp" + + // platform:linux skips DACL entirely so this test focuses on tempPath only + await safeWriteText(targetPath, "", { tempPath: customTempPath, platform: "linux" }) + + // openSync was called on the custom temp path (r+ mode for fsync) + expect(fsSync.openSync).toHaveBeenCalledWith(customTempPath, "r+") + + // fsync was called + expect(fsSync.fsyncSync).toHaveBeenCalledWith(1) + + // rename happened — realpath mock returns targetPath + expect(fs.rename).toHaveBeenCalledWith(customTempPath, targetPath) + + // no unlink of custom temp (caller's concern; DACL skipped via platform:linux) + expect(fs.unlink).not.toHaveBeenCalled() + + // a caller-supplied tempPath must not create the staging directory + expect(fsSync.mkdirSync).not.toHaveBeenCalled() + }) + + it("applies the existing target's mode to a caller-supplied tempPath before publishing", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.statSync).mockReturnValue(_stats(0o600)) + vi.mocked(fsSync.openSync).mockReturnValue(2) + + const customTempPath = "/tmp/custom-temp.tmp" + + await safeWriteText(targetPath, "", { tempPath: customTempPath, platform: "linux" }) + + // the caller-staged temp is fchmod'd to the restrictive target mode so + // the atomic rename cannot widen a 0o600 target (CWE-732 regression) + expect(fsSync.fchmodSync).toHaveBeenCalledWith(2, 0o600) + expect(fsSync.openSync).toHaveBeenCalledWith(customTempPath, "r+") + expect(fs.rename).toHaveBeenCalledWith(customTempPath, targetPath) + }) + + it("keeps the temp's default mode when the target does not exist yet (ENOENT)", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + const enoent = Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) + vi.mocked(fsSync.statSync).mockImplementation(() => { + throw enoent + }) + vi.mocked(fsSync.openSync).mockReturnValue(2) + + const customTempPath = "/tmp/custom-temp.tmp" + + await safeWriteText(targetPath, "", { tempPath: customTempPath, platform: "linux" }) + + // no existing target, so nothing to preserve and no fchmod on the temp + expect(fsSync.fchmodSync).not.toHaveBeenCalled() + expect(fs.rename).toHaveBeenCalledWith(customTempPath, targetPath) + }) + + it("opens the temp before applying a read-only target's mode (0o444 does not block the open)", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.statSync).mockReturnValue(_stats(0o444)) + vi.mocked(fsSync.openSync).mockReturnValue(3) + + const customTempPath = "/tmp/custom-temp.tmp" + + await safeWriteText(targetPath, "", { tempPath: customTempPath, platform: "linux" }) + + // a 0o444 target must not make openSync(tempPath, "r+") fail: the mode + // is applied with fchmodSync on the already-open fd, after the open + expect(fsSync.openSync).toHaveBeenCalledWith(customTempPath, "r+") + expect(fsSync.fchmodSync).toHaveBeenCalledWith(3, 0o444) + const openIdx = vi.mocked(fsSync.openSync).mock.invocationCallOrder[0] + const fchmodIdx = vi.mocked(fsSync.fchmodSync).mock.invocationCallOrder[0] + expect(openIdx).toBeLessThan(fchmodIdx) + expect(fs.rename).toHaveBeenCalledWith(customTempPath, targetPath) + }) + }) + + // ── Test 7: symlink handling (Finding 4 regression test) ───────────────── + + describe("symlink handling", () => { + it("a write through a symlink commits onto the resolved referent, never the link path", async () => { + const linkPath = "/tmp/links/link.txt" + const referentPath = "/tmp/targets/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(referentPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + await safeWriteText(linkPath, "new-content", { platform: "linux" }) + + // The commit rename must target the realpath result (the referent), never the link itself — + // that is what guarantees a write through a symlink replaces the referent's content + // and preserves the link. + expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), referentPath) + expect(fs.rename).not.toHaveBeenCalledWith(expect.anything(), linkPath) + }) + + it("when realpath reports ENOENT (target absent), uses the given path as-is", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockRejectedValue(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + await safeWriteText(targetPath, "data", { platform: "linux" }) + + // rename still happened with the fallback path (path.resolve on /tmp → C:\tmp) + const resolvedFallback = _resolvedTarget(targetPath) + expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), resolvedFallback) + }) + }) + + // ── Test 8: review fixes (permissions, partial writes, resolution, durability) ── + + describe("review fixes", () => { + it("preserves the target's restrictive mode and tolerates a failed staging-dir permission repair", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + vi.mocked(fsSync.statSync).mockReturnValue(_stats(0o600)) + // a pre-existing staging dir may fail its best-effort permission repair + vi.mocked(fsSync.chmodSync).mockImplementationOnce(() => { + throw new Error("EACCES") + }) + + await safeWriteText(targetPath, "secret", { platform: "linux" }) + + // the staging file inherits the target's 0o600 mode and the write commits + expect(fsSync.openSync).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), "w", 0o600) + expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath) + }) + + it("falls back to the 0o644 default when the target does not exist yet", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + vi.mocked(fsSync.statSync).mockImplementation(() => { + throw Object.assign(new Error("ENOENT"), { code: "ENOENT" }) + }) + + await safeWriteText(targetPath, "fresh", { platform: "linux" }) + + expect(fsSync.openSync).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), "w", 0o644) + }) + + it("loops on short writes until the full content is durable before fsync", async () => { + const targetPath = "/tmp/test-dir/target.txt" + const content = "0123456789" // 10 bytes + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + const buffer = Buffer.from(content, "utf8") + // first write (offset 0) reports 4 bytes (short write); the loop continues + vi.mocked(fsSync.writeSync).mockImplementation((...args: unknown[]) => + args[2] === 0 ? 4 : typeof args[3] === "number" ? args[3] : 0, + ) + + await safeWriteText(targetPath, content, { platform: "linux" }) + + // [0,10) reports 4 bytes, then [4,10) writes the remaining 6 + expect(fsSync.writeSync).toHaveBeenCalledTimes(2) + expect(fsSync.writeSync).toHaveBeenNthCalledWith(1, 1, buffer, 0, 10) + expect(fsSync.writeSync).toHaveBeenNthCalledWith(2, 1, buffer, 4, 6) + expect(fsSync.fsyncSync).toHaveBeenCalledWith(1) + expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath) + }) + + it("fsyncs the parent directory after the commit rename on POSIX", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + // temp fd=1 then parent-dir fd=2 - distinct fds prove the ordering + vi.mocked(fsSync.openSync).mockReturnValueOnce(1).mockReturnValue(2) + + await safeWriteText(targetPath, "data", { platform: "linux" }) + + // the directory fsync (fd 2) happens only after the file fsync (fd 1); + // the dir path assertion is path-agnostic (stringContaining) because + // path.dirname renders the same input differently on Windows + expect(fsSync.openSync).toHaveBeenCalledWith(expect.stringContaining("test-dir"), "r") + expect(fsSync.fsyncSync).toHaveBeenNthCalledWith(1, 1) + expect(fsSync.fsyncSync).toHaveBeenNthCalledWith(2, 2) + expect(fsSync.closeSync).toHaveBeenCalledWith(2) + }) + + it("treats a failed parent-directory fsync as best-effort", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync) + .mockReturnValueOnce(1) + .mockImplementationOnce(() => { + throw new Error("EBADF") + }) + + // the content rename already committed; a missing directory fsync is not fatal + await safeWriteText(targetPath, "data", { platform: "linux" }) + + expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath) + }) + + it("propagates realpath errors (EACCES and code-less) instead of the fallback path", async () => { + const targetPath = "/tmp/test-dir/target.txt" + const eacces = Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }) + vi.mocked(fs.realpath).mockRejectedValueOnce(eacces) + await expect(safeWriteText(targetPath, "data", { platform: "linux" })).rejects.toBe(eacces) + expect(fs.rename).not.toHaveBeenCalled() + + const plain = new Error("resolution failed") + vi.mocked(fs.realpath).mockRejectedValueOnce(plain) + await expect(safeWriteText(targetPath, "data", { platform: "linux" })).rejects.toBe(plain) + expect(fs.rename).not.toHaveBeenCalled() + }) + + it("backup:true propagates access errors (EACCES and code-less) instead of skipping the backup", async () => { + const targetPath = "/tmp/test-dir/target.txt" + const eacces = Object.assign(new Error("EACCES"), { code: "EACCES" }) + const plain = new Error("access failed") + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + // each write accesses dirPath then target; only the target access rejects + const rejectTarget = (error: Error) => async (p: unknown) => { + if (typeof p === "string" && p.endsWith("target.txt")) throw error + } + vi.mocked(fs.access) + .mockImplementationOnce(rejectTarget(eacces)) + .mockImplementationOnce(rejectTarget(eacces)) + .mockImplementationOnce(rejectTarget(plain)) + .mockImplementationOnce(rejectTarget(plain)) + + await expect(safeWriteText(targetPath, "data", { backup: true, platform: "linux" })).rejects.toEqual( + expect.objectContaining({ code: "EACCES" }), + ) + await expect(safeWriteText(targetPath, "data", { backup: true, platform: "linux" })).rejects.toThrow( + "access failed", + ) + expect(fs.rename).not.toHaveBeenCalled() + }) + }) +}) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts new file mode 100644 index 00000000000..71871032e55 --- /dev/null +++ b/src/services/file-safety/safeWriteText.ts @@ -0,0 +1,307 @@ +import * as fs from "fs/promises" +import * as fsSync from "fs" +import * as path from "path" +import { execFile } from "child_process" + +/** + * Options for safeWriteText atomic text publish primitive. + */ +export interface SafeWriteTextOptions { + /** + * When true, preserve the old-file semantics: rename target -> backup first, + * after commit rename delete the backup; on failure roll the backup back to + * the target path. When false (default) the atomic rename simply replaces + * the target -- crash-safe window is zero. + */ + backup?: boolean + + /** + * Platform override for testing. When omitted the real process.platform + * value is used. Set to "win32" or "linux" / "darwin" from tests so that + * both branches are reachable without needing a real Windows runner. + */ + platform?: string + + /** + * Custom execFile runner for testing (e.g. vi.fn). When omitted the real + * child_process.execFile is used. + */ + execFileRunner?: typeof execFile + + /** + * Pre-written temp path to use for the commit phase. When provided, + * safeWriteText skips creating its own staging file and uses this path + * instead (it still fsyncs before rename). Useful when a caller has + * already written data to a temp file via a custom stream. + */ + tempPath?: string +} + +// -- helpers --------------------------------------------------------------- + +/** Generate a unique temp file name in the given directory. */ +function _tempName(dir: string, prefix: string): string { + return path.join(dir, "." + prefix + "_" + Date.now() + "_" + Math.random().toString(36).substring(2) + ".tmp") +} + +/** Create a private staging sub-directory inside *dir* so that multiple + * concurrent writes never collide on their temp names. */ +function _stagingDir(dir: string): string { + const sd = path.join(dir, ".file-safety-staging") + // mode:0o700 protects a freshly created staging dir; the best-effort chmod + // repairs a pre-existing one (mkdirSync with recursive:true never chmods an + // existing directory), so staged temp files are never group/world readable. + fsSync.mkdirSync(sd, { recursive: true, mode: 0o700 }) + try { + fsSync.chmodSync(sd, 0o700) + } catch { + // best-effort: chmod denied or unavailable; a fresh dir was still + // created with the requested mode + } + return sd +} + +/** + * fsync a file descriptor so its data is durable before the atomic rename. + * Uses the sync form because this repo's @types/node does not declare + * fs.promises.fsync; the staging file is small, so the blocking window is bounded. + */ +function _fsyncFile(fd: number): void { + fsSync.fsyncSync(fd) +} + +/** Save the DACL of *srcPath* to a dump file on Windows. + * Returns true when the dump was written successfully; false otherwise. + * Never throws — callers treat failure as "skip DACL handling". */ +async function _saveDaclWindows(srcPath: string, dumpPath: string, execFileRunner?: typeof execFile): Promise { + const runner = execFileRunner ?? execFile + try { + await new Promise((resolve, reject) => { + runner("icacls", [srcPath, "/save", dumpPath, "/T"], { windowsHide: true }, (err) => + err ? reject(err) : resolve(), + ) + }) + return true + } catch { + return false + } +} + +/** Restore a DACL dump onto *dirPath* on Windows. + * Best-effort: content is already committed, so failure is non-fatal. */ +async function _restoreDaclWindows(dirPath: string, dumpPath: string, execFileRunner?: typeof execFile): Promise { + const runner = execFileRunner ?? execFile + try { + await new Promise((resolve, reject) => { + runner("icacls", [dirPath, "/restore", dumpPath], { windowsHide: true }, (err) => + err ? reject(err) : resolve(), + ) + }) + } catch { + // best-effort; content already committed + } +} + +// -- public API ------------------------------------------------------------ + +/** + * Atomic text publish primitive. + * + * 1. Write content to a temp file in a private per-write staging subdir + * (same volume -> atomic rename guaranteed). + * 2. fsync the temp file, then close it. + * 3. win32 only: if target exists save its DACL dump BEFORE backup rename. + * 4. Optionally rename target -> backup (when backup:true). + * 5. Atomic rename temp -> target. + * 6. win32 only: restore DACL onto the directory AFTER commit rename. + * 7. On success: delete backup (if any) and unlink DACL dump. + * 8. On failure: rollback backup to target path; clean up temp + dump. + */ + +/** + * Resolve the publish target: the symlink referent when the given path is an + * existing symlink, the path itself otherwise. Only ENOENT (target absent yet) + * may fall back to the given path; any other resolution error (EACCES, EIO, ...) + * propagates so a broken or unreadable symlink is never written through its + * link path. Callers that stage a temp file themselves must stage it beside + * the resolved path: the commit is a rename onto the referent, and a rename + * across filesystems fails with EXDEV. + */ +export async function resolvePublishTarget(absoluteFilePath: string): Promise { + return fs.realpath(absoluteFilePath).catch((error: unknown) => { + const code = + typeof error === "object" && error !== null && "code" in error + ? (error as { code?: string }).code + : undefined + if (code !== "ENOENT") throw error + return absoluteFilePath + }) +} + +export async function safeWriteText(filePath: string, content: string, options?: SafeWriteTextOptions): Promise { + const absoluteFilePath = path.resolve(filePath) + + // Resolve the symlink referent (see resolvePublishTarget). + const targetPath = await resolvePublishTarget(absoluteFilePath) + const dirPath = path.dirname(targetPath) + + // Ensure parent directory exists (mirrors safeWriteJson behaviour). + await fs.mkdir(dirPath, { recursive: true }) + await fs.access(dirPath) + + // Create the staging directory only when we generate the temp file there; + // callers supplying their own tempPath (e.g. safeWriteJson) must not be left + // with an empty .file-safety-staging directory behind. + const tempPath = options?.tempPath ?? _tempName(_stagingDir(dirPath), "safeWriteText") + + let backupPath: string | null = null + let releaseBackupOnSuccess = false + let daclDumpPath: string | null = null // tracked for cleanup in finally + + try { + // -- Step 1: write content to staging temp file ------------------- + if (!options?.tempPath) { + // Preserve the existing target's permissions: the staging file must + // not be published wider than the file it replaces (a 0o600 target + // must not become 0o644 through the atomic rename). + let targetMode = 0o644 // default for a fresh target + try { + targetMode = fsSync.statSync(targetPath).mode & 0o777 + } catch { + // target does not exist yet - keep the default + } + const fd = fsSync.openSync(tempPath, "w", targetMode) + try { + // Loop until every byte is written: writeSync can report a short + // (partial) write, and publishing a truncated staging file would + // commit corrupt content. + const buffer = Buffer.from(content, "utf8") + let offset = 0 + while (offset < buffer.length) { + offset += fsSync.writeSync(fd, buffer, offset, buffer.length - offset) + } + _fsyncFile(fd) + } finally { + fsSync.closeSync(fd) + } + } else { + // Preserve the existing target's mode (CWE-732): the caller-staged + // temp carries its own creation mode, and publishing it as-is would + // widen a restrictive target (e.g. 0o600 -> 0o644) through rename. + // The mode is applied with fchmodSync on the open fd (AFTER openSync): + // chmodSync on the path before the open would make a read-only target + // (0o400/0o444) fail openSync(tempPath, "r+") with EACCES. + let targetMode: number | null = null + try { + targetMode = fsSync.statSync(targetPath).mode & 0o777 + } catch { + // target does not exist yet - keep the temp's default mode + } + const fd = fsSync.openSync(tempPath, "r+") + try { + if (targetMode !== null) { + fsSync.fchmodSync(fd, targetMode) + } + _fsyncFile(fd) + } finally { + fsSync.closeSync(fd) + } + } + + // -- Step 2 (win32): save DACL BEFORE backup rename --------------- + const platform = options?.platform ?? process.platform + if (platform === "win32") { + try { + await fs.access(targetPath) // target exists? + daclDumpPath = targetPath + ".acl.tmp" + const saved = await _saveDaclWindows(targetPath, daclDumpPath, options?.execFileRunner) + if (!saved) { + daclDumpPath = null // skip DACL handling entirely + } + } catch { + // target does not exist or access failed — no DACL handling + daclDumpPath = null + } + } + + try { + // -- Step 3 (backup:true): rename target -> backup -------------- + if (options?.backup) { + try { + await fs.access(targetPath) + backupPath = _tempName(dirPath, "safeWriteText.bak") + await fs.rename(targetPath, backupPath) + releaseBackupOnSuccess = true + } catch (err: unknown) { + const code = + typeof err === "object" && err !== null && "code" in err + ? (err as { code?: string }).code + : undefined + if (code !== "ENOENT") throw err + } + } + + // -- Step 4: atomic rename temp -> target --------------------- + await fs.rename(tempPath, targetPath) + + // -- Step 4b (POSIX): fsync the parent directory so the directory entry + // changed by the commit rename is durable, not just the file content. + if (platform !== "win32") { + try { + const dirFd = fsSync.openSync(dirPath, "r") + try { + _fsyncFile(dirFd) + } finally { + fsSync.closeSync(dirFd) + } + } catch { + // best-effort: the content rename already committed + } + } + + // -- Step 5 (win32): restore DACL AFTER commit rename --------- + if (platform === "win32" && daclDumpPath !== null) { + const restoredDir = path.dirname(targetPath) + await _restoreDaclWindows(restoredDir, daclDumpPath, options?.execFileRunner) + } + + // -- Step 6 (backup:true): delete backup on success ----------- + if (releaseBackupOnSuccess && backupPath) { + try { + await fs.unlink(backupPath) + } catch { + // non-fatal — orphaned backup is acceptable + } + } + } finally { + // Unlink DACL dump regardless of success/failure in this span. + if (daclDumpPath !== null) { + await fs.unlink(daclDumpPath).catch(() => {}) + } + } + + // tempPath is now the committed file; no cleanup needed. + } catch (originalError: unknown) { + // -- Rollback / cleanup on failure ---------------------------------- + if (backupPath && releaseBackupOnSuccess) { + try { + await fs.rename(backupPath, targetPath) + } catch { + // rollback failed — do not mask original error + } + } + + // Always clean up the staging temp file on failure. + try { + await fs.unlink(tempPath).catch(() => {}) + } catch { + // cleanup failure is non-fatal + } + + if (daclDumpPath !== null) { + await fs.unlink(daclDumpPath).catch(() => {}) + } + + throw originalError + } +} From 81a3173a1a93c1a3014365682459225cd42ea46b Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Thu, 27 Aug 2026 14:52:58 +0800 Subject: [PATCH 02/79] feat(task): per-task file observation registry (A2, #1375) --- src/core/task/Task.ts | 2 + src/core/tools/ReadFileTool.ts | 12 ++ src/core/tools/__tests__/readFileTool.spec.ts | 116 +++++++++++++++++- 3 files changed, 127 insertions(+), 3 deletions(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index e2e25ef93da..1a71726d641 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -108,6 +108,7 @@ import { restoreTodoListForTask } from "../tools/UpdateTodoListTool" import { FileContextTracker } from "../context-tracking/FileContextTracker" import { ObservationRegistry } from "./observationRegistry" import { RooIgnoreController } from "../ignore/RooIgnoreController" +import { ObservationRegistry } from "./observationRegistry" import { RooProtectedController } from "../protect/RooProtectedController" import { type AssistantMessageContent, presentAssistantMessage } from "../assistant-message" import { DispatchState, type PendingWork } from "./dispatchState" @@ -313,6 +314,7 @@ export class Task extends EventEmitter implements TaskLike { readonly parentTask: Task | undefined = undefined readonly taskNumber: number readonly workspacePath: string + readonly observationRegistry = new ObservationRegistry() /** * The mode associated with this task. Persisted across sessions diff --git a/src/core/tools/ReadFileTool.ts b/src/core/tools/ReadFileTool.ts index 5f1754b11a6..e939e68bfca 100644 --- a/src/core/tools/ReadFileTool.ts +++ b/src/core/tools/ReadFileTool.ts @@ -17,6 +17,7 @@ import type { ReadFileParams, ReadFileMode, ReadFileToolParams, FileEntry, LineR import { isLegacyReadFileParams, type ClineSayTool } from "@roo-code/types" import { Task } from "../task/Task" +import { computeVersionToken } from "../../utils/versionToken" import { formatResponse } from "../prompts/responses" import { RecordSource } from "../context-tracking/FileContextTrackerTypes" import { isPathOutsideWorkspace } from "../../utils/pathUtils" @@ -222,6 +223,11 @@ export class ReadFileTool extends BaseTool<"read_file"> { await task.fileContextTracker.trackFileContext(relPath, "read_tool" as RecordSource) + // A2 (plan #33 / epic #1375): record the observed on-disk version for the future write guard. + // A stat failure leaves the target unobserved and never fails the read. + const version = await computeVersionToken(fullPath).catch(() => undefined) + if (version) task.observationRegistry.observe(fullPath, version) + updateFileResult(relPath, { nativeContent: `File: ${relPath}\n${result}`, }) @@ -806,6 +812,12 @@ export class ReadFileTool extends BaseTool<"read_file"> { // Track file in context await task.fileContextTracker.trackFileContext(relPath, "read_tool") + + // A2 (plan #33 / epic #1375): mirror the native path — record the observed + // on-disk version so legacy-format reads also feed the future write guard. + // A stat failure leaves the target unobserved and never fails the read. + const version = await computeVersionToken(fullPath).catch(() => undefined) + if (version) task.observationRegistry.observe(fullPath, version) } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error) results.push(`File: ${relPath}\nError: ${errorMsg}`) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index cce5928ce9e..8804834dfb6 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -15,13 +15,16 @@ import os from "os" import path from "path" import * as vscode from "vscode" - import type { ToolUse } from "../../../shared/tools" import type { Task, ToolExecutionContext } from "../../task/Task" - import { isBinaryFile } from "isbinaryfile" - import { readFileTool } from "../ReadFileTool" +import type { Stats } from "fs" +import type { LegacyReadFileParams } from "@roo-code/types" +import { readFileTool, ReadFileTool } from "../ReadFileTool" +import type { Task } from "../../task/Task" +import { ObservationRegistry } from "../../task/observationRegistry" +import { computeVersionToken } from "../../../utils/versionToken" import { formatResponse } from "../../prompts/responses" import { validateImageForProcessing, processImageFile, isSupportedImageFormat } from "../helpers/imageHelpers" import { extractTextFromFile, getSupportedBinaryFormats } from "../../../integrations/misc/extract-text" @@ -136,6 +139,7 @@ interface MockTaskOptions { rooIgnoreAllowed?: boolean maxImageFileSize?: number maxTotalImageSize?: number + observationRegistry?: ObservationRegistry } function createMockTask(options: MockTaskOptions = {}) { @@ -143,6 +147,9 @@ function createMockTask(options: MockTaskOptions = {}) { return { cwd: "/test/workspace", + // Mirror Task: every task always owns an observation registry (A2, #1375). + // Tests asserting on observations pass their own instance via options. + observationRegistry: options.observationRegistry ?? new ObservationRegistry(), api: { getModel: vi.fn().mockReturnValue({ info: { supportsImages }, @@ -1750,5 +1757,108 @@ describe("ReadFileTool", () => { expect(mockTask.didToolFailInCurrentTurn).toBe(true) }) + + describe("observation registry", () => { + it("records an observation on successful read of an existing file", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + // Override the beforeEach default stat mock with proper BigIntStats. + mockedFsStat.mockResolvedValue({ + isDirectory: () => false, + dev: BigInt(1), + ino: BigInt(2), + size: BigInt(300), + mtimeNs: BigInt(4_000_000_000n), + ctimeNs: BigInt(5_000_000_000n), + // Cast: the mock only implements the members the tool and versionToken read. + } as unknown as Stats) + mockedIsBinaryFile.mockResolvedValue(false) + + // Spy on observe to capture the exact key used (Windows path.resolve may use backslashes). + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) + + // Verify the tool called observe exactly once with a valid token. + expect(observeSpy).toHaveBeenCalledTimes(1) + const [calledPath, calledVersion] = observeSpy.mock.calls[0] + expect(calledPath).toContain("existing.ts") + expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/) + + // Verify get() returns the same data using the spy-captured key. + const obs = reg.get(calledPath) + expect(obs).toBeDefined() + expect(obs!.version).toBe(calledVersion) + }) + + it("a failed read (absent path) leaves the registry size 0 and does not throw", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + mockedFsReadFile.mockRejectedValue(new Error("ENOENT")) + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute({ path: "missing.ts" }, mockTask as unknown as Task, callbacks) + + // observationRegistry is guaranteed present because we passed it in createMockTask. + const reg = mockTask.observationRegistry + expect(reg).toBeDefined() + expect(reg!.size).toBe(0) + }) + + it("records an observation for legacy-format reads of existing files", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + mockedFsStat.mockResolvedValue({ + isDirectory: () => false, + dev: BigInt(1), + ino: BigInt(2), + size: BigInt(300), + mtimeNs: BigInt(4_000_000_000n), + ctimeNs: BigInt(5_000_000_000n), + // Cast: the mock only implements the members the tool and versionToken read. + } as unknown as Stats) + mockedIsBinaryFile.mockResolvedValue(false) + + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + // Typed legacy (pre-refactor) params: the multi-file format with the + // _legacyFormat discriminant (see LegacyReadFileParams). + const legacyParams: LegacyReadFileParams = { + files: [{ path: "legacy.ts" }], + _legacyFormat: true, + } + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + expect(observeSpy).toHaveBeenCalledTimes(1) + const [calledPath, calledVersion] = observeSpy.mock.calls[0] + expect(calledPath).toContain("legacy.ts") + expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/) + }) + + it("two separate Task-owned registries are independent", async () => { + const regA = new ObservationRegistry() + const regB = new ObservationRegistry() + regA.observe("/shared.ts", "v1") + expect(regA.get("/shared.ts")!.version).toBe("v1") + expect(regB.get("/shared.ts")).toBeUndefined() + regB.observe("/shared.ts", "v2") + expect(regA.get("/shared.ts")!.version).toBe("v1") + expect(regB.get("/shared.ts")!.version).toBe("v2") + }) + }) }) }) From 06dea5b0bcf081961cc08b1dbb8eda060e88038a Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Thu, 27 Aug 2026 22:09:22 +0800 Subject: [PATCH 03/79] feat(tools): guarded write CAS core with per-path FIFO chain (S4a, #1375) --- src/core/tools/ReadFileTool.ts | 36 +- src/core/tools/__tests__/guardedWrite.spec.ts | 454 ++++++++++++++++++ src/core/tools/__tests__/readFileTool.spec.ts | 211 +++++++- src/core/tools/guardedWrite.ts | 260 ++++++++++ 4 files changed, 953 insertions(+), 8 deletions(-) create mode 100644 src/core/tools/__tests__/guardedWrite.spec.ts create mode 100644 src/core/tools/guardedWrite.ts diff --git a/src/core/tools/ReadFileTool.ts b/src/core/tools/ReadFileTool.ts index e939e68bfca..1a89b42c08e 100644 --- a/src/core/tools/ReadFileTool.ts +++ b/src/core/tools/ReadFileTool.ts @@ -17,7 +17,7 @@ import type { ReadFileParams, ReadFileMode, ReadFileToolParams, FileEntry, LineR import { isLegacyReadFileParams, type ClineSayTool } from "@roo-code/types" import { Task } from "../task/Task" -import { computeVersionToken } from "../../utils/versionToken" +import { versionTokenOfStat } from "../../utils/versionToken" import { formatResponse } from "../prompts/responses" import { RecordSource } from "../context-tracking/FileContextTrackerTypes" import { isPathOutsideWorkspace } from "../../utils/pathUtils" @@ -217,6 +217,9 @@ export class ReadFileTool extends BaseTool<"read_file"> { // Read text file content with lossy UTF-8 conversion // Reading as Buffer first allows graceful handling of non-UTF8 bytes // (they become U+FFFD replacement characters instead of throwing) + // A2 (epic #1375): capture the on-disk token before the read so a mutation + // landing mid-read is detected by the post-read stat below. + const preReadStats = await fs.stat(fullPath, { bigint: true }).catch(() => undefined) const buffer = await fs.readFile(fullPath) const fileContent = buffer.toString("utf-8") const result = this.processTextFile(fileContent, entry) @@ -224,9 +227,18 @@ export class ReadFileTool extends BaseTool<"read_file"> { await task.fileContextTracker.trackFileContext(relPath, "read_tool" as RecordSource) // A2 (plan #33 / epic #1375): record the observed on-disk version for the future write guard. - // A stat failure leaves the target unobserved and never fails the read. - const version = await computeVersionToken(fullPath).catch(() => undefined) - if (version) task.observationRegistry.observe(fullPath, version) + // The token is captured before AND after the read; the target is observed only + // when both match — a mutation between the two stats means the content the model + // received is not the on-disk state, and observing it would let a later write + // match a token the model never saw. A stat failure leaves the target + // unobserved and never fails the read. + const postReadStats = await fs.stat(fullPath, { bigint: true }).catch(() => undefined) + if (preReadStats && postReadStats) { + const preReadToken = versionTokenOfStat(preReadStats) + if (preReadToken === versionTokenOfStat(postReadStats)) { + task.observationRegistry.observe(fullPath, preReadToken) + } + } updateFileResult(relPath, { nativeContent: `File: ${relPath}\n${result}`, @@ -781,6 +793,9 @@ export class ReadFileTool extends BaseTool<"read_file"> { } // Read text file + // A2 (epic #1375): capture the on-disk token before the read so a mutation + // landing mid-read is detected by the post-read stat below. + const preReadStats = await fs.stat(fullPath, { bigint: true }).catch(() => undefined) const rawContent = await fs.readFile(fullPath, "utf8") // Handle line ranges if specified @@ -815,9 +830,16 @@ export class ReadFileTool extends BaseTool<"read_file"> { // A2 (plan #33 / epic #1375): mirror the native path — record the observed // on-disk version so legacy-format reads also feed the future write guard. - // A stat failure leaves the target unobserved and never fails the read. - const version = await computeVersionToken(fullPath).catch(() => undefined) - if (version) task.observationRegistry.observe(fullPath, version) + // Observe only when the pre-read and post-read tokens match (a mutation between + // them means the returned content is not the on-disk state). A stat failure + // leaves the target unobserved and never fails the read. + const postReadStats = await fs.stat(fullPath, { bigint: true }).catch(() => undefined) + if (preReadStats && postReadStats) { + const preReadToken = versionTokenOfStat(preReadStats) + if (preReadToken === versionTokenOfStat(postReadStats)) { + task.observationRegistry.observe(fullPath, preReadToken) + } + } } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error) results.push(`File: ${relPath}\nError: ${errorMsg}`) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts new file mode 100644 index 00000000000..122c1c6d9bc --- /dev/null +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -0,0 +1,454 @@ +/** + * Tests for the guarded-write compare-and-swap core (upstream epic #1375, + * phase A4a). + * + * Covers guard selection through the S2 observation registry, version-token + * CAS, remediation messages, and the per-absolute-path FIFO chain: FIFO + * ordering, exactly-one winner under concurrency, no wedge after a rejected + * link, and independence across paths. + */ + +import * as fs from "fs/promises" +import * as path from "path" + +import { describe, expect, it, beforeEach, vi } from "vitest" + +import { createIfAbsent, guardedWrite, replaceIfVersion, resetChain } from "../guardedWrite" +import { safeWriteText } from "../../../services/file-safety/safeWriteText" +import { computeVersionToken } from "../../../utils/versionToken" +import { ObservationRegistry } from "../../task/observationRegistry" +import type { Task } from "../../task/Task" + +// -- Mocks ------------------------------------------------------------------- + +vi.mock("fs/promises", () => ({ + access: vi.fn(), + stat: vi.fn(), +})) + +vi.mock("../../../utils/versionToken", () => ({ + computeVersionToken: vi.fn(), +})) + +vi.mock("../../../services/file-safety/safeWriteText", () => ({ + safeWriteText: vi.fn(), +})) + +const mockedFsAccess = vi.mocked(fs.access) +const mockedComputeVersionToken = vi.mocked(computeVersionToken) +const mockedSafeWriteText = vi.mocked(safeWriteText) + +// -- Fixtures ---------------------------------------------------------------- + +const WORKSPACE = "/test/workspace" + +/** Resolve a fixture path the same way guardedWrite resolves task.cwd-relative paths. */ +const abs = (relPath: string): string => path.resolve(WORKSPACE, relPath) + +interface MockTaskOptions { + cwd?: string + observationRegistry?: ObservationRegistry +} + +/** + * Minimal structural Task: guardedWrite only reads task.cwd and + * task.observationRegistry. The real Task constructor needs the full provider + * machinery, so a single documented double cast stands in for the class. + */ +function createMockTask(options: MockTaskOptions = {}): Task { + const task = { + cwd: options.cwd ?? WORKSPACE, + observationRegistry: options.observationRegistry ?? new ObservationRegistry(), + } + return task as unknown as Task +} + +// -- Tests ------------------------------------------------------------------- + +describe("guardedWrite (S4a, epic #1375)", () => { + beforeEach(() => { + vi.resetAllMocks() + resetChain() + }) + + describe("unobserved create", () => { + it("succeeds when the file is absent and publishes via safeWriteText", async () => { + mockedFsAccess.mockRejectedValue({ code: "ENOENT" }) + const task = createMockTask() + + await guardedWrite(task, "new-file.txt", "hello", "create") + + expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("new-file.txt"), "hello") + }) + + it("fails with the read-first remediation when the file exists - nothing published", async () => { + mockedFsAccess.mockResolvedValue(undefined) + const task = createMockTask() + + await expect(guardedWrite(task, "existing.txt", "hello", "create")).rejects.toThrow( + "File already exists at " + + abs("existing.txt") + + " and was not read before this write -- read the file first, then retry.", + ) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) + + it("rethrows I/O errors that are not ENOENT verbatim (no guard verdict on access failure)", async () => { + const failures = [{ code: "EACCES" }, null, "volume offline", new Error("EIO-ish failure")] + for (const failure of failures) { + mockedFsAccess.mockRejectedValueOnce(failure) + await expect(createIfAbsent(abs("io-error.txt"), "x")).rejects.toBe(failure) + } + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) + }) + + describe("deleted-after-read target", () => { + it("normalizes an ENOENT from the version token into the re-read remediation", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("vanished.txt"), "v1") + const task = createMockTask({ observationRegistry: reg }) + + // The file was deleted after the read: the token computation fails + // with a raw ENOENT, which the guard must convert into the standard + // re-read-then-retry contract. + mockedComputeVersionToken.mockRejectedValue({ code: "ENOENT" }) + + await expect(guardedWrite(task, "vanished.txt", "next", "update")).rejects.toThrow( + "File was deleted after it was read", + ) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) + + it("rethrows non-ENOENT token failures verbatim from replaceIfVersion", async () => { + const failure = { code: "EACCES" } + mockedComputeVersionToken.mockRejectedValueOnce(failure) + + await expect(replaceIfVersion(abs("locked.txt"), "v1", "next")).rejects.toBe(failure) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) + }) + describe("unobserved update", () => { + it("succeeds when the file is absent (same create guard)", async () => { + mockedFsAccess.mockRejectedValue({ code: "ENOENT" }) + const task = createMockTask() + + await guardedWrite(task, "new-file.txt", "hello", "update") + + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("new-file.txt"), "hello") + }) + + it("fails with the read-first remediation when the file exists - nothing published", async () => { + mockedFsAccess.mockResolvedValue(undefined) + const task = createMockTask() + + await expect(guardedWrite(task, "existing.txt", "hello", "update")).rejects.toThrow( + "File already exists at " + + abs("existing.txt") + + " and was not read before this write -- read the file first, then retry.", + ) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) + }) + + describe("observed create", () => { + it("recreates a file that vanished after the read", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("gone.txt"), "v1") + mockedFsAccess.mockRejectedValue({ code: "ENOENT" }) + const task = createMockTask({ observationRegistry: reg }) + + await guardedWrite(task, "gone.txt", "back", "create") + + expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("gone.txt"), "back") + }) + + it("goes through the version guard when the file still exists", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("kept.txt"), "v1") + mockedFsAccess.mockResolvedValue(undefined) + mockedComputeVersionToken.mockResolvedValue("v1") + const task = createMockTask({ observationRegistry: reg }) + + await guardedWrite(task, "kept.txt", "rewritten", "create") + + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("kept.txt"), "rewritten") + }) + + it("fails with the stale remediation suffix when the version moved", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("kept.txt"), "v1") + mockedFsAccess.mockResolvedValue(undefined) + mockedComputeVersionToken.mockResolvedValue("v2") + const task = createMockTask({ observationRegistry: reg }) + + await expect(guardedWrite(task, "kept.txt", "rewritten", "create")).rejects.toThrow( + "Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.", + ) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) + + it("defers to the version guard when the access check is denied (not ENOENT)", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("locked.txt"), "v1") + mockedFsAccess.mockRejectedValue({ code: "EACCES" }) + mockedComputeVersionToken.mockResolvedValue("v2") + const task = createMockTask({ observationRegistry: reg }) + + await expect(guardedWrite(task, "locked.txt", "rewritten", "create")).rejects.toThrow( + "Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.", + ) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) + }) + + describe("observed update (version CAS)", () => { + it("publishes when the on-disk version matches the observation", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("doc.txt"), "v1") + mockedComputeVersionToken.mockResolvedValue("v1") + const task = createMockTask({ observationRegistry: reg }) + + await guardedWrite(task, "doc.txt", "new content", "update") + + expect(mockedComputeVersionToken).toHaveBeenCalledWith(abs("doc.txt")) + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "new content") + }) + + it("fails with the stale remediation suffix when the version moved - nothing published", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("doc.txt"), "v1") + mockedComputeVersionToken.mockResolvedValue("v2") + const task = createMockTask({ observationRegistry: reg }) + + await expect(guardedWrite(task, "doc.txt", "new content", "update")).rejects.toThrow( + "Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.", + ) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) + }) + + describe("edit", () => { + it("fails read-first when the file was never observed - nothing published, no I/O", async () => { + const task = createMockTask() + + await expect(guardedWrite(task, "any.txt", "patched", "edit")).rejects.toThrow( + "File not read yet -- read the file, then retry.", + ) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + expect(mockedComputeVersionToken).not.toHaveBeenCalled() + expect(mockedFsAccess).not.toHaveBeenCalled() + }) + + it("publishes when the version matches the observation", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("doc.txt"), "v1") + mockedComputeVersionToken.mockResolvedValue("v1") + const task = createMockTask({ observationRegistry: reg }) + + await guardedWrite(task, "doc.txt", "patched", "edit") + + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "patched") + }) + + it("fails with the stale remediation suffix when the version moved", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("doc.txt"), "v1") + mockedComputeVersionToken.mockResolvedValue("v3") + const task = createMockTask({ observationRegistry: reg }) + + await expect(guardedWrite(task, "doc.txt", "patched", "edit")).rejects.toThrow( + "Stale version -- the file changed since you read it (expected v1, current v3); re-read the file, then retry.", + ) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) + }) + + describe("concurrency: per-path FIFO chain", () => { + it("two concurrent updates on one path - exactly one publishes, the other fails stale", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("shared.txt"), "v1") + mockedComputeVersionToken.mockResolvedValue("v1") + const task = createMockTask({ observationRegistry: reg }) + + // The first publish changes the on-disk state (new token). + mockedSafeWriteText.mockImplementation(async () => { + mockedComputeVersionToken.mockResolvedValue("v2") + }) + + const p1 = guardedWrite(task, "shared.txt", "first", "update") + const p2 = guardedWrite(task, "shared.txt", "second", "update") + const [r1, r2] = await Promise.allSettled([p1, p2]) + + if (r1.status !== "fulfilled" || r2.status !== "rejected") { + throw new Error("expected exactly one publish, got " + r1.status + " / " + r2.status) + } + expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) + expect(r2.reason.message).toBe( + "Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.", + ) + }) + + it("observed-absent then two concurrent creates - the second fails stale", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("absent.txt"), "v1") // read before, file later vanished + mockedFsAccess.mockRejectedValue({ code: "ENOENT" }) + const task = createMockTask({ observationRegistry: reg }) + + let publishes = 0 + mockedSafeWriteText.mockImplementation(async () => { + publishes += 1 + if (publishes === 1) { + // After the first publish the file exists again under a new token. + mockedFsAccess.mockResolvedValue(undefined) + mockedComputeVersionToken.mockResolvedValue("v2") + } + }) + + const p1 = guardedWrite(task, "absent.txt", "first", "create") + const p2 = guardedWrite(task, "absent.txt", "second", "create") + const [r1, r2] = await Promise.allSettled([p1, p2]) + + if (r1.status !== "fulfilled" || r2.status !== "rejected") { + throw new Error("expected exactly one publish, got " + r1.status + " / " + r2.status) + } + expect(publishes).toBe(1) + expect(r2.reason.message).toContain("Stale version") + expect(r2.reason.message).toContain("re-read the file, then retry.") + }) + + it("the chain settles after a rejection - a later matching write still runs", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("settle.txt"), "v1") + mockedComputeVersionToken.mockResolvedValue("v2") // already stale at v1 + const task = createMockTask({ observationRegistry: reg }) + + const p1 = guardedWrite(task, "settle.txt", "first", "update") + await expect(p1).rejects.toThrow("Stale version") + + // No resetChain: the rejected link must not wedge the chain. The + // caller re-reads the file (observation refreshed to v2) and retries. + reg.observe(abs("settle.txt"), "v2") + const p2 = guardedWrite(task, "settle.txt", "second", "update") + await expect(p2).resolves.toBeUndefined() + + expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("settle.txt"), "second") + }) + + it("evicts settled chain entries - a later write still serializes in order", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("evict.txt"), "v1") + mockedComputeVersionToken.mockResolvedValue("v1") + const task = createMockTask({ observationRegistry: reg }) + + // A first write settles; its chain entry is evicted with it. + const p1 = guardedWrite(task, "evict.txt", "first", "update") + await expect(p1).resolves.toBeUndefined() + + // Two rapid writes submitted after the eviction must still run one + // at a time in submission order (the eviction must not drop the + // chain for in-flight or just-enqueued links). + const order: string[] = [] + mockedSafeWriteText.mockImplementation(async (_path: string, content: string) => { + order.push(content) + }) + const p2 = guardedWrite(task, "evict.txt", "second", "update") + const p3 = guardedWrite(task, "evict.txt", "third", "update") + await Promise.all([p2, p3]) + + expect(order).toEqual(["second", "third"]) + // Three publishes in total: the settled first write plus the two + // serialized rapid writes. + expect(mockedSafeWriteText).toHaveBeenCalledTimes(3) + }) + + it("writes on different paths are independent (no cross-path serialization)", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("a.txt"), "v1") + reg.observe(abs("b.txt"), "v1") + mockedComputeVersionToken.mockResolvedValue("v1") + const task = createMockTask({ observationRegistry: reg }) + + const p1 = guardedWrite(task, "a.txt", "a", "update") + const p2 = guardedWrite(task, "b.txt", "b", "update") + await Promise.all([p1, p2]) + + expect(mockedSafeWriteText).toHaveBeenCalledTimes(2) + }) + }) + + describe("path resolution", () => { + it("resolves a relative path against task.cwd", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("sub/dir.txt"), "v1") + mockedComputeVersionToken.mockResolvedValue("v1") + const task = createMockTask({ observationRegistry: reg }) + + await guardedWrite(task, "sub/dir.txt", "content", "update") + + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("sub/dir.txt"), "content") + }) + + it("normalizes an already-absolute input (trailing separator) to the observation key", async () => { + const reg = new ObservationRegistry() + const canonical = abs("sub/dir.txt") + // ReadFileTool observes under path.resolve(task.cwd, relPath) — the + // canonical spelling. A write addressed with a trailing separator used + // to bypass the observation (isAbsolute passthrough) and fail + // "File already exists" / "File not read yet" for a file that was read. + reg.observe(canonical, "v1") + mockedComputeVersionToken.mockResolvedValue("v1") + const task = createMockTask({ observationRegistry: reg }) + + await guardedWrite(task, canonical + "/", "content", "update") + + expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) + expect(mockedSafeWriteText).toHaveBeenCalledWith(canonical, "content") + }) + + it("serializes two spellings of one file through a single chain key", async () => { + const reg = new ObservationRegistry() + const canonical = abs("shared2.txt") + reg.observe(canonical, "v1") + mockedComputeVersionToken.mockResolvedValue("v1") + const task = createMockTask({ observationRegistry: reg }) + + // The first publish changes the on-disk state (new token). + mockedSafeWriteText.mockImplementation(async () => { + mockedComputeVersionToken.mockResolvedValue("v2") + }) + + // Plain spelling vs the trailing-separator spelling: with one chain key + // they are strictly ordered (first matches v1, second sees v2). + const p1 = guardedWrite(task, canonical, "first", "update") + const p2 = guardedWrite(task, canonical + "/", "second", "update") + const [r1, r2] = await Promise.allSettled([p1, p2]) + + if (r1.status !== "fulfilled" || r2.status !== "rejected") { + throw new Error("expected exactly one publish, got " + r1.status + " / " + r2.status) + } + expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) + expect(r2.reason.message).toBe( + "Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.", + ) + }) + }) + + describe("resetChain", () => { + it("detaches pending links so later writes start a fresh chain", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("x.txt"), "v1") + mockedComputeVersionToken.mockResolvedValue("v1") + const task = createMockTask({ observationRegistry: reg }) + + await guardedWrite(task, "x.txt", "a", "update") + resetChain() + await guardedWrite(task, "x.txt", "b", "update") + + expect(mockedSafeWriteText).toHaveBeenLastCalledWith(abs("x.txt"), "b") + }) + }) +}) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 8804834dfb6..4d9a7103f65 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -211,7 +211,18 @@ describe("ReadFileTool", () => { vi.clearAllMocks() // Default mock implementations - mockedFsStat.mockResolvedValue({ isDirectory: () => false } as any) + // The stat default carries BigIntStats fields (A2, epic #1375): reads now + // token-ize the pre/post stats, so the default must look like a real bigint stat. + // Tests overriding it do so per-call with mockResolvedValue(Once). + mockedFsStat.mockResolvedValue({ + isDirectory: () => false, + dev: BigInt(1), + ino: BigInt(2), + size: BigInt(300), + mtimeNs: BigInt(4_000_000_000n), + ctimeNs: BigInt(5_000_000_000n), + // Cast: the mock only implements the members the tool and versionToken read. + } as unknown as Stats) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("test content")) mockedReadWithSlice.mockReturnValue({ @@ -1849,6 +1860,204 @@ describe("ReadFileTool", () => { expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/) }) + it("does not observe when the file mutates between the pre-read and post-read stats", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + const preStats = { + isDirectory: () => false, + dev: BigInt(1), + ino: BigInt(2), + size: BigInt(300), + mtimeNs: BigInt(4_000_000_000n), + ctimeNs: BigInt(5_000_000_000n), + } + // A mutation lands mid-read: the post-read stat differs. + const postStats = { ...preStats, size: BigInt(301) } + + // Call order: directory check, pre-read stat, post-read stat. + mockedFsStat + .mockResolvedValueOnce({ isDirectory: () => false } as unknown as Stats) + .mockResolvedValueOnce(preStats as unknown as Stats) + .mockResolvedValueOnce(postStats as unknown as Stats) + mockedIsBinaryFile.mockResolvedValue(false) + + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute({ path: "mutated.ts" }, mockTask as unknown as Task, callbacks) + + // The read itself succeeded, but the target stays unobserved: the content the + // model received is not the on-disk state, so observing it would let a later + // write match a token the model never saw. + expect(observeSpy).not.toHaveBeenCalled() + expect(reg.size).toBe(0) + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + }) + + it("leaves the target unobserved without failing the read when the pre-read stat fails", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + // Directory check OK; the pre-read stat fails (caught, target unobserved). + mockedFsStat + .mockResolvedValueOnce({ isDirectory: () => false } as unknown as Stats) + .mockRejectedValueOnce(new Error("EACCES")) + mockedIsBinaryFile.mockResolvedValue(false) + + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute({ path: "stat-fail.ts" }, mockTask as unknown as Task, callbacks) + + expect(observeSpy).not.toHaveBeenCalled() + expect(reg.size).toBe(0) + // The read still succeeds — a stat failure never fails the read. + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalled() + }) + + it("leaves the target unobserved without failing the read when the post-read stat fails", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + const okStats = { + isDirectory: () => false, + dev: BigInt(1), + ino: BigInt(2), + size: BigInt(300), + mtimeNs: BigInt(4_000_000_000n), + ctimeNs: BigInt(5_000_000_000n), + } + // Directory check and pre-read stat OK; the post-read stat fails. + mockedFsStat + .mockResolvedValueOnce({ isDirectory: () => false } as unknown as Stats) + .mockResolvedValueOnce(okStats as unknown as Stats) + .mockRejectedValueOnce(new Error("EACCES")) + mockedIsBinaryFile.mockResolvedValue(false) + + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute({ path: "post-stat-fail.ts" }, mockTask as unknown as Task, callbacks) + + expect(observeSpy).not.toHaveBeenCalled() + expect(reg.size).toBe(0) + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalled() + }) + + it("legacy format: does not observe when the file mutates between the pre-read and post-read stats", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + const preStats = { + isDirectory: () => false, + dev: BigInt(1), + ino: BigInt(2), + size: BigInt(300), + mtimeNs: BigInt(4_000_000_000n), + ctimeNs: BigInt(5_000_000_000n), + } + // Call order: directory check, pre-read stat, post-read stat (mutated). + mockedFsStat + .mockResolvedValueOnce({ isDirectory: () => false } as unknown as Stats) + .mockResolvedValueOnce(preStats as unknown as Stats) + .mockResolvedValueOnce({ ...preStats, size: BigInt(301) } as unknown as Stats) + mockedIsBinaryFile.mockResolvedValue(false) + + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + const legacyParams: LegacyReadFileParams = { + files: [{ path: "legacy-mutated.ts" }], + _legacyFormat: true, + } + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + expect(observeSpy).not.toHaveBeenCalled() + expect(reg.size).toBe(0) + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + }) + + it("legacy format: leaves the target unobserved when a stat fails without failing the read", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + // Directory check OK; the pre-read stat fails (caught, target unobserved). + mockedFsStat + .mockResolvedValueOnce({ isDirectory: () => false } as unknown as Stats) + .mockRejectedValueOnce(new Error("EACCES")) + mockedIsBinaryFile.mockResolvedValue(false) + + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + const legacyParams: LegacyReadFileParams = { + files: [{ path: "legacy-stat-fail.ts" }], + _legacyFormat: true, + } + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + expect(observeSpy).not.toHaveBeenCalled() + expect(reg.size).toBe(0) + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalled() + }) + it("legacy format: leaves the target unobserved when the post-read stat fails", async () => { + const mockTask = createMockTask({ + observationRegistry: new ObservationRegistry(), + }) + const callbacks = createMockCallbacks() + + const okStats = { + isDirectory: () => false, + dev: BigInt(1), + ino: BigInt(2), + size: BigInt(300), + mtimeNs: BigInt(4_000_000_000n), + ctimeNs: BigInt(5_000_000_000n), + } + // Directory check and pre-read stat OK; the post-read stat fails. + mockedFsStat + .mockResolvedValueOnce({ isDirectory: () => false } as unknown as Stats) + .mockResolvedValueOnce(okStats as unknown as Stats) + .mockRejectedValueOnce(new Error("EACCES")) + mockedIsBinaryFile.mockResolvedValue(false) + + const reg = mockTask.observationRegistry! + const observeSpy = vi.spyOn(reg, "observe") + + const legacyParams: LegacyReadFileParams = { + files: [{ path: "legacy-post-stat-fail.ts" }], + _legacyFormat: true, + } + + // Cast: the mock task only implements the members ReadFileTool.execute touches. + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + expect(observeSpy).not.toHaveBeenCalled() + expect(reg.size).toBe(0) + expect(mockTask.didToolFailInCurrentTurn).toBe(false) + expect(callbacks.pushToolResult).toHaveBeenCalled() + }) it("two separate Task-owned registries are independent", async () => { const regA = new ObservationRegistry() const regB = new ObservationRegistry() diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts new file mode 100644 index 00000000000..596cc410350 --- /dev/null +++ b/src/core/tools/guardedWrite.ts @@ -0,0 +1,260 @@ +/** + * Guarded-write compare-and-swap core (upstream epic #1375, phase A4a). + * + * Wraps the S3 safeWriteText publish primitive behind version-token guards so + * that every write is deterministic: + * + * - an unobserved target may only be created when it is absent + * (createIfAbsent); + * - an observed target is published only when the on-disk version token still + * matches the token recorded at read time (replaceIfVersion); + * - an edit-style write requires a prior observation (unobservedEditGuard). + * + * A per-absolute-path FIFO chain of tail promises orders concurrent + * in-process writes to the same path: the first matching write wins, the rest + * fail stale. Observations come from the task's S2 ObservationRegistry. + */ + +import * as fs from "fs/promises" +import * as path from "path" + +import { safeWriteText } from "../../services/file-safety/safeWriteText" +import { computeVersionToken } from "../../utils/versionToken" +import type { Task } from "../task/Task" + +// -- Types ------------------------------------------------------------------ + +/** Write kind that drives guard selection. */ +export type GuardedWriteKind = "create" | "update" | "edit" + +/** Internal error thrown when a guard rejects a write. */ +class GuardRejectedError extends Error { + constructor( + message: string, + readonly path: string, + ) { + super(message) + this.name = "GuardRejectedError" + } +} + +// -- Per-path tail-promise chain -------------------------------------------- + +/** + * Per-absolute-path FIFO chain of pending guarded writes (tail promise per + * path). Every write enqueues onto the current tail for its path, so + * concurrent writes to the same path run one at a time in submission order. + * + * The chain never leaks a rejection through itself: each link settles, a + * rejected link is skipped by the next writer (a failed write must not block + * later writes to the same path), and every caller receives its own link + * promise to handle. + * + * Settled entries are evicted (below), so a long-lived extension does not + * accumulate a map entry per distinct written path. + */ +const pendingChains = new Map>() + +/** + * Enqueue a write operation on the per-path FIFO chain. + * + * Returns the promise for this link; it always settles. A prior link that + * rejected is skipped, not propagated. The map entry for this link is + * deleted once it settles — but only while it is still the current tail for + * the path, so a replacement enqueued in the meantime keeps ownership. + */ +function enqueue(pathKey: string, fn: () => Promise): Promise { + const prev = pendingChains.get(pathKey) ?? Promise.resolve() + const next = prev.then(fn, fn) + pendingChains.set(pathKey, next) + void next.then( + () => { + if (pendingChains.get(pathKey) === next) { + pendingChains.delete(pathKey) + } + }, + () => { + if (pendingChains.get(pathKey) === next) { + pendingChains.delete(pathKey) + } + }, + ) + return next +} + +// -- Guard primitives -------------------------------------------------------- + +/** + * Extract a Node errno code (e.g. "ENOENT") from a thrown value, or + * undefined when the value carries none. + */ +function errorCode(error: unknown): string | undefined { + return typeof error === "object" && error !== null && "code" in error + ? (error as { code?: string }).code + : undefined +} + +/** True when the path is absent on disk (fs.access reports ENOENT). */ +async function fileIsAbsent(absolutePath: string): Promise { + try { + await fs.access(absolutePath) + return false + } catch (error: unknown) { + return errorCode(error) === "ENOENT" + } +} + +/** + * Publish content only if the target file does not exist. + * + * Rejects with a loud remediation error when the file already exists: the + * write was issued for a file that was never read, so the caller must read + * the file first, then retry. + */ +export async function createIfAbsent(absolutePath: string, content: string): Promise { + try { + await fs.access(absolutePath) + } catch (error: unknown) { + if (errorCode(error) !== "ENOENT") { + // A real I/O failure (EACCES, EIO, ...) -- not a guard verdict. + throw error + } + await safeWriteText(absolutePath, content) + return + } + + throw new GuardRejectedError( + "File already exists at " + + absolutePath + + " and was not read before this write -- read the file first, then retry.", + absolutePath, + ) +} + +/** + * Publish content only if the current on-disk version token equals + * expectedVersion (the token observed at read time). + * + * On a match the content is published via the S3 safeWriteText primitive; on + * a mismatch the write is rejected stale with a re-read-then-retry + * remediation suffix. + */ +export async function replaceIfVersion(absolutePath: string, expectedVersion: string, content: string): Promise { + let currentVersion: string + try { + currentVersion = await computeVersionToken(absolutePath) + } catch (error: unknown) { + if (errorCode(error) === "ENOENT") { + // The observed file was deleted after the read: the version recorded + // at read time no longer exists on disk. Normalize the raw ENOENT + // into the guard's re-read-then-retry contract so the caller gets a + // remediation it can act on, not a raw errno. + throw new GuardRejectedError( + "File was deleted after it was read -- the version recorded at read time (" + + expectedVersion + + ") no longer exists; re-read the file, then retry.", + absolutePath, + ) + } + // A real I/O failure (EACCES, EIO, ...) -- not a guard verdict. + throw error + } + + if (currentVersion === expectedVersion) { + await safeWriteText(absolutePath, content) + return + } + + throw new GuardRejectedError( + "Stale version -- the file changed since you read it (expected " + + expectedVersion + + ", current " + + currentVersion + + "); re-read the file, then retry.", + absolutePath, + ) +} + +/** + * Unobserved-edit guard: an edit-style write without a prior observation is + * rejected before any I/O. The literal-match / patch logic stays with the + * tools in S4b; this guard only verifies that a read happened first. + * + * Returns Promise because the rejection is total: this function + * never resolves. + */ +export async function unobservedEditGuard(absolutePath: string): Promise { + throw new GuardRejectedError("File not read yet -- read the file, then retry.", absolutePath) +} + +// -- Public API -------------------------------------------------------------- + +/** + * Resolve a relative or absolute path against task.cwd. + * + * path.resolve also normalizes an already-absolute input (collapsing "." / ".." + * segments and trailing separators), so the key always matches the + * ObservationRegistry key recorded at read time (ReadFileTool observes under + * path.resolve(task.cwd, relPath)) and two spellings of one file share one + * FIFO chain. + */ +function resolveAbsolutePath(task: Task, relPathOrAbsolute: string): string { + return path.resolve(task.cwd, relPathOrAbsolute) +} + +/** + * Guarded write entry point. + * + * 1. Resolves the absolute path against task.cwd. + * 2. Consults the task's S2 observation registry to pick the guard: + * - unobserved + create/update: createIfAbsent (rejects if it exists); + * - observed + create on a file that vanished after the read: recreate; + * - observed otherwise: replaceIfVersion (CAS on the S1 version token); + * - unobserved + edit: unobservedEditGuard. + * 3. Runs the chosen guard on the per-path FIFO chain so concurrent writes to + * the same path are deterministically ordered. + */ +export async function guardedWrite( + task: Task, + relPathOrAbsolute: string, + content: string, + kind: GuardedWriteKind = "update", +): Promise { + const absolutePath = resolveAbsolutePath(task, relPathOrAbsolute) + + return enqueue(absolutePath, async () => { + const obs = task.observationRegistry.get(absolutePath) + + if (obs === undefined) { + // Edit-style writes require a prior read: no observation, no write. + if (kind === "edit") { + await unobservedEditGuard(absolutePath) + } + // Never read: only an absent target may be created. (The edit guard + // above rejects before reaching this line.) + await createIfAbsent(absolutePath, content) + return + } + + if (kind === "edit") { + await replaceIfVersion(absolutePath, obs.version, content) + return + } + + // kind is "create" or "update": a "create" on a file that vanished + // after the read recreates it; otherwise the version recorded at read + // time must still match the on-disk token. + if (kind === "create" && (await fileIsAbsent(absolutePath))) { + await createIfAbsent(absolutePath, content) + } else { + await replaceIfVersion(absolutePath, obs.version, content) + } + }) +} + +/** + * Reset the per-path tail-promise chains (test hook). + */ +export function resetChain(): void { + pendingChains.clear() +} From 6e5a4d86605b74d3a81b9b83c7347717224a4dd6 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Thu, 27 Aug 2026 23:59:02 +0800 Subject: [PATCH 04/79] feat(tools): wire guarded writes into the diff-view save paths (S4b, #1375) --- src/core/tools/ApplyDiffTool.ts | 4 +- src/core/tools/ApplyPatchTool.ts | 24 ++- src/core/tools/EditFileTool.ts | 5 +- src/core/tools/EditTool.ts | 12 +- src/core/tools/SearchReplaceTool.ts | 12 +- src/core/tools/WriteToFileTool.ts | 11 +- .../applyDiffTool.guardedWrite.spec.ts | 157 ++++++++++++++ .../__tests__/applyPatchTool.execute.spec.ts | 198 ++++++++++++++++++ src/core/tools/__tests__/editFileTool.spec.ts | 95 +++++++++ src/core/tools/__tests__/editTool.spec.ts | 46 ++++ .../tools/__tests__/searchReplaceTool.spec.ts | 46 ++++ .../tools/__tests__/writeToFileTool.spec.ts | 73 +++++++ src/integrations/editor/DiffViewProvider.ts | 21 +- .../editor/__tests__/DiffViewProvider.spec.ts | 111 +++++++++- 14 files changed, 794 insertions(+), 21 deletions(-) create mode 100644 src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts diff --git a/src/core/tools/ApplyDiffTool.ts b/src/core/tools/ApplyDiffTool.ts index b08ef9b6e62..59f5765d409 100644 --- a/src/core/tools/ApplyDiffTool.ts +++ b/src/core/tools/ApplyDiffTool.ts @@ -177,7 +177,8 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> { return } - // Save directly without showing diff view or opening the file + // Save directly without showing diff view or opening the file. The diff is + // applied to an existing file, so edit-guard semantics require a prior read. task.diffViewProvider.editType = "modify" task.diffViewProvider.originalContent = originalContent await task.diffViewProvider.saveDirectly( @@ -186,6 +187,7 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> { false, diagnosticsEnabled, writeDelayMs, + "edit", ) } else { // Original behavior with diff view diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 2713e08ffe8..10f3c330229 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -214,7 +214,16 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // Save the changes if (isPreventFocusDisruptionEnabled) { - await task.diffViewProvider.saveDirectly(relPath, newContent, true, diagnosticsEnabled, writeDelayMs) + // Guarded publish: the patch supplies the complete new content, so create-guard + // semantics apply (an unobserved existing target is rejected, not overwritten). + await task.diffViewProvider.saveDirectly( + relPath, + newContent, + true, + diagnosticsEnabled, + writeDelayMs, + "create", + ) } else { await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs) } @@ -408,12 +417,14 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // Save new content to the new path if (isPreventFocusDisruptionEnabled) { + // The move destination is published with the complete new content. await task.diffViewProvider.saveDirectly( change.movePath, newContent, false, diagnosticsEnabled, writeDelayMs, + "create", ) } else { // Write to new path and delete old file @@ -433,7 +444,16 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { } else { // Save changes to the same file if (isPreventFocusDisruptionEnabled) { - await task.diffViewProvider.saveDirectly(relPath, newContent, false, diagnosticsEnabled, writeDelayMs) + // Guarded publish: the patched file content is complete, so create-guard + // semantics apply (stale observed versions are rejected with a re-read hint). + await task.diffViewProvider.saveDirectly( + relPath, + newContent, + false, + diagnosticsEnabled, + writeDelayMs, + "create", + ) } else { await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs) } diff --git a/src/core/tools/EditFileTool.ts b/src/core/tools/EditFileTool.ts index a7301e2ac96..911d4ed85b6 100644 --- a/src/core/tools/EditFileTool.ts +++ b/src/core/tools/EditFileTool.ts @@ -436,13 +436,16 @@ export class EditFileTool extends BaseTool<"edit_file"> { // Save the changes if (isPreventFocusDisruptionEnabled) { - // Direct file write without diff view or opening the file + // Direct file write without diff view or opening the file. In-place edits + // use edit-guard semantics (a prior read is required); new-file creation + // keeps create-guard semantics. await task.diffViewProvider.saveDirectly( relPath, newContent, isNewFile, diagnosticsEnabled, writeDelayMs, + isNewFile ? "create" : "edit", ) } else { // Call saveChanges to update the DiffViewProvider properties diff --git a/src/core/tools/EditTool.ts b/src/core/tools/EditTool.ts index 895b929ed26..be709004e26 100644 --- a/src/core/tools/EditTool.ts +++ b/src/core/tools/EditTool.ts @@ -211,8 +211,16 @@ export class EditTool extends BaseTool<"edit"> { // Save the changes if (isPreventFocusDisruptionEnabled) { - // Direct file write without diff view or opening the file - await task.diffViewProvider.saveDirectly(relPath, newContent, false, diagnosticsEnabled, writeDelayMs) + // Direct file write without diff view or opening the file. This tool only + // edits existing files, so edit-guard semantics require a prior read. + await task.diffViewProvider.saveDirectly( + relPath, + newContent, + false, + diagnosticsEnabled, + writeDelayMs, + "edit", + ) } else { // Call saveChanges to update the DiffViewProvider properties await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs) diff --git a/src/core/tools/SearchReplaceTool.ts b/src/core/tools/SearchReplaceTool.ts index a0f2dadfcc9..18470220fe3 100644 --- a/src/core/tools/SearchReplaceTool.ts +++ b/src/core/tools/SearchReplaceTool.ts @@ -207,8 +207,16 @@ export class SearchReplaceTool extends BaseTool<"search_replace"> { // Save the changes if (isPreventFocusDisruptionEnabled) { - // Direct file write without diff view or opening the file - await task.diffViewProvider.saveDirectly(relPath, newContent, false, diagnosticsEnabled, writeDelayMs) + // Direct file write without diff view or opening the file. This tool only + // edits existing files, so edit-guard semantics require a prior read. + await task.diffViewProvider.saveDirectly( + relPath, + newContent, + false, + diagnosticsEnabled, + writeDelayMs, + "edit", + ) } else { // Call saveChanges to update the DiffViewProvider properties await task.diffViewProvider.saveChanges(diagnosticsEnabled, writeDelayMs) diff --git a/src/core/tools/WriteToFileTool.ts b/src/core/tools/WriteToFileTool.ts index 0c5c80abb91..71bb864c436 100644 --- a/src/core/tools/WriteToFileTool.ts +++ b/src/core/tools/WriteToFileTool.ts @@ -132,7 +132,16 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> { return } - await task.diffViewProvider.saveDirectly(relPath, newContent, false, diagnosticsEnabled, writeDelayMs) + // Guarded publish: this write carries the complete file content, so it uses + // create-guard semantics (unobserved targets may only be created when absent). + await task.diffViewProvider.saveDirectly( + relPath, + newContent, + false, + diagnosticsEnabled, + writeDelayMs, + "create", + ) } else { if (!task.diffViewProvider.isEditing) { const partialMessage = JSON.stringify(sharedMessageProps) diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts new file mode 100644 index 00000000000..2181c989413 --- /dev/null +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -0,0 +1,157 @@ +// npx vitest run core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts + +import type { MockedFunction } from "vitest" + +import { fileExistsAtPath } from "../../../utils/fs" +import type { Task } from "../../task/Task" +import { ApplyDiffTool } from "../ApplyDiffTool" + +vi.mock("fs/promises", () => ({ + default: { + readFile: vi.fn().mockResolvedValue("original file content\n"), + }, +})) + +vi.mock("../../../utils/fs", () => ({ + fileExistsAtPath: vi.fn().mockResolvedValue(true), +})) + +vi.mock("../../prompts/responses", () => ({ + formatResponse: { + toolError: vi.fn((msg: string) => `Error: ${msg}`), + rooIgnoreError: vi.fn((filePath: string) => `Access denied: ${filePath}`), + createPrettyPatch: vi.fn(() => "mock-diff"), + }, +})) + +vi.mock("../../diff/stats", () => ({ + sanitizeUnifiedDiff: vi.fn((diff: string) => diff), + computeDiffStats: vi.fn(() => ({ additions: 1, deletions: 1 })), +})) + +describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { + const mockedFileExistsAtPath = fileExistsAtPath as MockedFunction + + let tool: ApplyDiffTool + let mockTask: Pick< + Task, + | "cwd" + | "consecutiveMistakeCount" + | "consecutiveMistakeCountForApplyDiff" + | "recordToolError" + | "rooIgnoreController" + | "rooProtectedController" + | "say" + | "processQueuedMessages" + | "didEditFile" + | "api" + | "diffStrategy" + | "diffViewProvider" + | "providerRef" + | "fileContextTracker" + > + let mockSaveDirectly: MockedFunction<(...args: unknown[]) => Promise> + let mockAskApproval: MockedFunction<(...args: unknown[]) => Promise> + let mockHandleError: MockedFunction<(...args: unknown[]) => Promise> + let mockPushToolResult: MockedFunction<(...args: unknown[]) => void> + + beforeEach(() => { + vi.clearAllMocks() + + mockedFileExistsAtPath.mockResolvedValue(true) + + mockSaveDirectly = vi.fn().mockResolvedValue({ + newProblemsMessage: "", + userEdits: undefined, + finalContent: "new content", + }) + + // Structural stubs for the guarded-write path: the real DiffViewProvider is + // out of scope here, so vi.fn() doubles stand in for the members the tool + // touches (the saveDirectly double also records the writeKind plumbing). + const diffViewProviderStub = { + editType: undefined as "create" | "modify" | undefined, + originalContent: undefined as string | undefined, + saveDirectly: mockSaveDirectly, + pushToolWriteResult: vi.fn().mockResolvedValue("Saved file"), + reset: vi.fn().mockResolvedValue(undefined), + } + mockTask = { + cwd: "/workspace/project", + consecutiveMistakeCount: 0, + consecutiveMistakeCountForApplyDiff: new Map(), + recordToolError: vi.fn(), + rooIgnoreController: { + validateAccess: vi.fn().mockReturnValue(true), + } as unknown as Task["rooIgnoreController"], + rooProtectedController: { + isWriteProtected: vi.fn().mockReturnValue(false), + } as unknown as Task["rooProtectedController"], + say: vi.fn().mockResolvedValue(undefined), + processQueuedMessages: vi.fn(), + didEditFile: false, + api: { + getModel: () => ({ id: "claude-sonnet-4-5" }), + } as unknown as Task["api"], + diffStrategy: { + applyDiff: vi.fn().mockResolvedValue({ success: true, content: "modified file content\n" }), + } as unknown as Task["diffStrategy"], + diffViewProvider: diffViewProviderStub as unknown as Task["diffViewProvider"], + providerRef: { + deref: vi.fn().mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + diagnosticsEnabled: true, + writeDelayMs: 1000, + // Exercise the focus-disruption (saveDirectly) save path. + experiments: { preventFocusDisruption: true }, + }), + }), + } as unknown as Task["providerRef"], + fileContextTracker: { + trackFileContext: vi.fn().mockResolvedValue(undefined), + } as unknown as Task["fileContextTracker"], + } + + mockAskApproval = vi.fn().mockResolvedValue(true) + mockHandleError = vi.fn().mockResolvedValue(undefined) + mockPushToolResult = vi.fn() + + tool = new ApplyDiffTool() + }) + + it("publishes through the guarded saveDirectly with edit kind", async () => { + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockSaveDirectly).toHaveBeenCalledWith( + "src/thing.ts", + "modified file content\n", + false, + true, + 1000, + "edit", + ) + expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") + expect(mockTask.didEditFile).toBe(true) + expect(mockHandleError).not.toHaveBeenCalled() + }) + + it("surfaces the unobserved edit remediation as a tool error", async () => { + const guardError = new Error("File not read yet -- read the file, then retry.") + mockSaveDirectly.mockRejectedValue(guardError) + + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockHandleError).toHaveBeenCalledWith("applying diff", guardError) + expect(vi.mocked(mockTask.diffViewProvider.reset)).toHaveBeenCalled() + expect(mockTask.didEditFile).toBe(false) + expect(mockPushToolResult).not.toHaveBeenCalledWith("Saved file") + }) +}) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index eb89838cadc..d9ce0a6c7cc 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -95,3 +95,201 @@ describe("ApplyPatchTool.execute - delete file success path", () => { expect(mockTask.recordToolError).not.toHaveBeenCalled() }) }) + +describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { + const mockedFileExistsAtPath = fileExistsAtPath as MockedFunction + + let tool: ApplyPatchTool + let mockTask: Pick< + Task, + | "cwd" + | "consecutiveMistakeCount" + | "recordToolError" + | "rooIgnoreController" + | "rooProtectedController" + | "say" + | "processQueuedMessages" + | "didEditFile" + | "diffViewProvider" + | "providerRef" + | "fileContextTracker" + > + let mockSaveDirectly: MockedFunction<(...args: unknown[]) => Promise> + let mockAskApproval: MockedFunction<(...args: unknown[]) => Promise> + let mockHandleError: MockedFunction<(...args: unknown[]) => Promise> + let mockPushToolResult: MockedFunction<(...args: unknown[]) => void> + + const updatePatch = `*** Begin Patch +*** Update File: src/thing.ts +@@ +-original file content ++modified file content +*** End Patch` + + const addPatch = `*** Begin Patch +*** Add File: src/new.ts ++new line one ++new line two +*** End Patch` + + const movePatch = `*** Begin Patch +*** Update File: src/old.ts +*** Move to: src/new.ts +@@ +-original file content ++modified file content +*** End Patch` + + beforeEach(() => { + vi.clearAllMocks() + + mockedFileExistsAtPath.mockResolvedValue(true) + + mockSaveDirectly = vi.fn().mockResolvedValue({ + newProblemsMessage: "", + userEdits: undefined, + finalContent: "new content", + }) + + // Structural stubs for the guarded-write path: the real DiffViewProvider is + // out of scope here, so vi.fn() doubles stand in for the members the tool + // touches (the saveDirectly double also records the writeKind plumbing). + const diffViewProviderStub = { + editType: undefined as "create" | "modify" | undefined, + originalContent: undefined as string | undefined, + saveDirectly: mockSaveDirectly, + pushToolWriteResult: vi.fn().mockResolvedValue("Saved file"), + reset: vi.fn().mockResolvedValue(undefined), + } + mockTask = { + cwd: "/workspace/project", + consecutiveMistakeCount: 0, + recordToolError: vi.fn(), + rooIgnoreController: { + validateAccess: vi.fn().mockReturnValue(true), + } as unknown as Task["rooIgnoreController"], + rooProtectedController: { + isWriteProtected: vi.fn().mockReturnValue(false), + } as unknown as Task["rooProtectedController"], + say: vi.fn().mockResolvedValue(undefined), + processQueuedMessages: vi.fn(), + didEditFile: false, + diffViewProvider: diffViewProviderStub as unknown as Task["diffViewProvider"], + providerRef: { + deref: vi.fn().mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + diagnosticsEnabled: true, + writeDelayMs: 1000, + // Exercise the focus-disruption (saveDirectly) save path. + experiments: { preventFocusDisruption: true }, + }), + }), + } as unknown as Task["providerRef"], + fileContextTracker: { + trackFileContext: vi.fn().mockResolvedValue(undefined), + } as unknown as Task["fileContextTracker"], + } + + mockAskApproval = vi.fn().mockResolvedValue(true) + mockHandleError = vi.fn().mockResolvedValue(undefined) + mockPushToolResult = vi.fn() + + tool = new ApplyPatchTool() + }) + + it("update: publishes through the guarded saveDirectly with create kind", async () => { + await tool.execute({ patch: updatePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockSaveDirectly).toHaveBeenCalledWith( + "src/thing.ts", + "modified file content\n", + false, + true, + 1000, + "create", + ) + expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") + expect(mockTask.didEditFile).toBe(true) + expect(mockHandleError).not.toHaveBeenCalled() + }) + + it("add: publishes the new file through the guarded saveDirectly with create kind", async () => { + mockedFileExistsAtPath.mockResolvedValueOnce(false) + + await tool.execute({ patch: addPatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockSaveDirectly).toHaveBeenCalledWith( + "src/new.ts", + "new line one\nnew line two\n", + true, + true, + 1000, + "create", + ) + expect(mockPushToolResult).toHaveBeenCalledWith("Saved file") + expect(mockTask.didEditFile).toBe(true) + expect(mockHandleError).not.toHaveBeenCalled() + }) + + it("move: publishes the destination through the guarded saveDirectly with create kind", async () => { + await tool.execute({ patch: movePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockSaveDirectly).toHaveBeenCalledWith( + "src/new.ts", + "modified file content\n", + false, + true, + 1000, + "create", + ) + expect(mockTask.didEditFile).toBe(true) + expect(mockHandleError).not.toHaveBeenCalled() + }) + + it("update: surfaces the unobserved-existing remediation as a tool error", async () => { + const guardError = new Error( + "File already exists at /workspace/project/src/thing.ts and was not read before this write -- read the file first, then retry.", + ) + mockSaveDirectly.mockRejectedValue(guardError) + + await tool.execute({ patch: updatePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockHandleError).toHaveBeenCalledWith("apply patch", guardError) + expect(vi.mocked(mockTask.diffViewProvider.reset)).toHaveBeenCalled() + expect(mockTask.didEditFile).toBe(false) + expect(mockPushToolResult).not.toHaveBeenCalledWith("Saved file") + }) + + it("update: surfaces the stale-version remediation as a tool error", async () => { + const guardError = new Error( + "Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.", + ) + mockSaveDirectly.mockRejectedValue(guardError) + + await tool.execute({ patch: updatePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockHandleError).toHaveBeenCalledWith("apply patch", guardError) + expect(vi.mocked(mockTask.diffViewProvider.reset)).toHaveBeenCalled() + expect(mockTask.didEditFile).toBe(false) + }) +}) diff --git a/src/core/tools/__tests__/editFileTool.spec.ts b/src/core/tools/__tests__/editFileTool.spec.ts index 95a67f04d73..14580accab3 100644 --- a/src/core/tools/__tests__/editFileTool.spec.ts +++ b/src/core/tools/__tests__/editFileTool.spec.ts @@ -168,6 +168,7 @@ describe("editFileTool", () => { fileContent?: string isPartial?: boolean accessAllowed?: boolean + experiments?: Record } = {}, ): Promise { const fileExists = options.fileExists ?? true @@ -178,6 +179,13 @@ describe("editFileTool", () => { mockedFileExistsAtPath.mockResolvedValue(fileExists) mockedFsReadFile.mockResolvedValue(fileContent) mockTask.rooIgnoreController.validateAccess.mockReturnValue(accessAllowed) + mockTask.providerRef.deref.mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + diagnosticsEnabled: true, + writeDelayMs: 1000, + experiments: options.experiments ?? {}, + }), + }) const nativeArgs: Record = { file_path: testFilePath, @@ -690,6 +698,93 @@ describe("editFileTool", () => { }) }) + describe("guarded write (S4b, epic #1375)", () => { + const focusDisruption = { preventFocusDisruption: true } + + it("publishes an existing-file edit through saveDirectly with edit kind", async () => { + const result = await executeEditFileTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileExists: true, fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(mockTask.diffViewProvider.saveDirectly).toHaveBeenCalledWith( + testFilePath, + "Line 1\nModified Line 2\nLine 3", + false, + true, + 1000, + "edit", + ) + expect(mockTask.diffViewProvider.saveChanges).not.toHaveBeenCalled() + expect(mockTask.didEditFile).toBe(true) + expect(result).toContain("Tool result message") + expect(mockHandleError).not.toHaveBeenCalled() + }) + + it("publishes new-file creation through saveDirectly with create kind", async () => { + await executeEditFileTool( + { old_string: "", new_string: "New file content" }, + { fileExists: false, experiments: focusDisruption }, + ) + + expect(mockTask.diffViewProvider.saveDirectly).toHaveBeenCalledWith( + testFilePath, + "New file content", + true, + true, + 1000, + "create", + ) + expect(mockTask.didEditFile).toBe(true) + expect(mockHandleError).not.toHaveBeenCalled() + }) + + it("surfaces the unobserved edit remediation as a tool error and publishes nothing", async () => { + const guardError = new Error("File not read yet -- read the file, then retry.") + mockTask.diffViewProvider.saveDirectly.mockRejectedValue(guardError) + + const result = await executeEditFileTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileExists: true, fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(mockHandleError).toHaveBeenCalledWith("edit_file", guardError) + expect(result).toBeUndefined() + expect(mockTask.diffViewProvider.reset).toHaveBeenCalled() + expect(mockTask.didToolFailInCurrentTurn).toBe(true) + expect(mockTask.didEditFile).toBe(false) + }) + + it("surfaces the stale-version remediation as a tool error and publishes nothing", async () => { + const guardError = new Error( + "Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.", + ) + mockTask.diffViewProvider.saveDirectly.mockRejectedValue(guardError) + + const result = await executeEditFileTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileExists: true, fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(mockHandleError).toHaveBeenCalledWith("edit_file", guardError) + expect(result).toBeUndefined() + expect(mockTask.diffViewProvider.reset).toHaveBeenCalled() + expect(mockTask.didEditFile).toBe(false) + }) + + it("still fails a literal mismatch with the existing message before the guard runs", async () => { + const result = await executeEditFileTool( + { old_string: "NonExistent", new_string: "Whatever" }, + { fileExists: true, fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(result).toContain("No match found") + expect(result).toContain("") + expect(mockTask.diffViewProvider.saveDirectly).not.toHaveBeenCalled() + expect(mockHandleError).not.toHaveBeenCalled() + }) + }) + describe("CRLF normalization", () => { it("preserves CRLF line endings on output", async () => { const contentWithCRLF = "Line 1\r\nLine 2\r\nLine 3" diff --git a/src/core/tools/__tests__/editTool.spec.ts b/src/core/tools/__tests__/editTool.spec.ts index fbb14d7ed24..1315cf8f55c 100644 --- a/src/core/tools/__tests__/editTool.spec.ts +++ b/src/core/tools/__tests__/editTool.spec.ts @@ -169,6 +169,7 @@ describe("editTool", () => { fileContent?: string isPartial?: boolean accessAllowed?: boolean + experiments?: Record } = {}, ): Promise { const fileExists = options.fileExists ?? true @@ -179,6 +180,13 @@ describe("editTool", () => { mockedFileExistsAtPath.mockResolvedValue(fileExists) mockedFsReadFile.mockResolvedValue(fileContent) mockTask.rooIgnoreController.validateAccess.mockReturnValue(accessAllowed) + mockTask.providerRef.deref.mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + diagnosticsEnabled: true, + writeDelayMs: 1000, + experiments: options.experiments ?? {}, + }), + }) const defaultParams = { file_path: testFilePath, @@ -426,4 +434,42 @@ describe("editTool", () => { expect(mockTask.fileContextTracker.trackFileContext).toHaveBeenCalledWith(testFilePath, "roo_edited") }) }) + + describe("guarded write (S4b, epic #1375)", () => { + const focusDisruption = { preventFocusDisruption: true } + + it("publishes through saveDirectly with edit kind", async () => { + const result = await executeEditTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(mockTask.diffViewProvider.saveDirectly).toHaveBeenCalledWith( + testFilePath, + "Line 1\nModified Line 2\nLine 3", + false, + true, + 1000, + "edit", + ) + expect(mockTask.didEditFile).toBe(true) + expect(result).toBe("Tool result message") + expect(mockHandleError).not.toHaveBeenCalled() + }) + + it("surfaces the unobserved edit remediation as a tool error and publishes nothing", async () => { + const guardError = new Error("File not read yet -- read the file, then retry.") + mockTask.diffViewProvider.saveDirectly.mockRejectedValue(guardError) + + const result = await executeEditTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(mockHandleError).toHaveBeenCalledWith("edit", guardError) + expect(result).toBeUndefined() + expect(mockTask.diffViewProvider.reset).toHaveBeenCalled() + expect(mockTask.didEditFile).toBe(false) + }) + }) }) diff --git a/src/core/tools/__tests__/searchReplaceTool.spec.ts b/src/core/tools/__tests__/searchReplaceTool.spec.ts index 65311462cb3..f187b7f237f 100644 --- a/src/core/tools/__tests__/searchReplaceTool.spec.ts +++ b/src/core/tools/__tests__/searchReplaceTool.spec.ts @@ -166,6 +166,7 @@ describe("searchReplaceTool", () => { fileContent?: string isPartial?: boolean accessAllowed?: boolean + experiments?: Record } = {}, ): Promise { const fileExists = options.fileExists ?? true @@ -176,6 +177,13 @@ describe("searchReplaceTool", () => { mockedFileExistsAtPath.mockResolvedValue(fileExists) mockedFsReadFile.mockResolvedValue(fileContent) mockCline.rooIgnoreController.validateAccess.mockReturnValue(accessAllowed) + mockCline.providerRef.deref.mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + diagnosticsEnabled: true, + writeDelayMs: 1000, + experiments: options.experiments ?? {}, + }), + }) const nativeArgs: Record = { file_path: testFilePath, @@ -441,4 +449,42 @@ describe("searchReplaceTool", () => { expect(mockAskApproval).toHaveBeenCalled() }) }) + + describe("guarded write (S4b, epic #1375)", () => { + const focusDisruption = { preventFocusDisruption: true } + + it("publishes through saveDirectly with edit kind", async () => { + const result = await executeSearchReplaceTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(mockCline.diffViewProvider.saveDirectly).toHaveBeenCalledWith( + testFilePath, + "Line 1\nModified Line 2\nLine 3", + false, + true, + 1000, + "edit", + ) + expect(mockCline.didEditFile).toBe(true) + expect(result).toBe("Tool result message") + expect(mockHandleError).not.toHaveBeenCalled() + }) + + it("surfaces the unobserved edit remediation as a tool error and publishes nothing", async () => { + const guardError = new Error("File not read yet -- read the file, then retry.") + mockCline.diffViewProvider.saveDirectly.mockRejectedValue(guardError) + + const result = await executeSearchReplaceTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(mockHandleError).toHaveBeenCalledWith("search and replace", guardError) + expect(result).toBeUndefined() + expect(mockCline.diffViewProvider.reset).toHaveBeenCalled() + expect(mockCline.didEditFile).toBe(false) + }) + }) }) diff --git a/src/core/tools/__tests__/writeToFileTool.spec.ts b/src/core/tools/__tests__/writeToFileTool.spec.ts index 7cb9d015857..0fc4b3c168d 100644 --- a/src/core/tools/__tests__/writeToFileTool.spec.ts +++ b/src/core/tools/__tests__/writeToFileTool.spec.ts @@ -26,6 +26,13 @@ vi.mock("delay", () => ({ default: vi.fn(), })) +// The focus-disruption save path reads the original file content via fs.readFile. +vi.mock("fs/promises", () => ({ + default: { + readFile: vi.fn().mockResolvedValue("original content"), + }, +})) + vi.mock("../../../utils/fs", () => ({ fileExistsAtPath: vi.fn().mockResolvedValue(false), createDirectoriesForFile: vi.fn().mockResolvedValue([]), @@ -156,6 +163,11 @@ describe("writeToFileTool", () => { userEdits: null, finalContent: "final content", }), + saveDirectly: vi.fn().mockResolvedValue({ + newProblemsMessage: "", + userEdits: undefined, + finalContent: "final content", + }), scrollToFirstDiff: vi.fn(), updateDiagnosticSettings: vi.fn(), pushToolWriteResult: vi.fn().mockImplementation(async function ( @@ -187,6 +199,7 @@ describe("writeToFileTool", () => { mockCline.say = vi.fn().mockResolvedValue(undefined) mockCline.ask = vi.fn().mockResolvedValue(undefined) mockCline.recordToolError = vi.fn() + mockCline.processQueuedMessages = vi.fn() mockCline.sayAndCreateMissingParamError = vi.fn().mockResolvedValue("Missing param error") mockAskApproval = vi.fn().mockResolvedValue(true) @@ -204,6 +217,7 @@ describe("writeToFileTool", () => { fileExists?: boolean isPartial?: boolean accessAllowed?: boolean + experiments?: Record } = {}, ): Promise { // Configure mocks based on test scenario @@ -213,6 +227,13 @@ describe("writeToFileTool", () => { mockedFileExistsAtPath.mockResolvedValue(fileExists) mockCline.rooIgnoreController.validateAccess.mockReturnValue(accessAllowed) + mockCline.providerRef.deref.mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + diagnosticsEnabled: true, + writeDelayMs: 1000, + experiments: options.experiments ?? {}, + }), + }) // Create a tool use object const toolUse: ToolUse = { @@ -451,6 +472,58 @@ describe("writeToFileTool", () => { }) }) + describe("guarded write (S4b, epic #1375)", () => { + const focusDisruption = { preventFocusDisruption: true } + + it("publishes through saveDirectly with create kind when the write is approved", async () => { + const result = await executeWriteFileTool({}, { fileExists: true, experiments: focusDisruption }) + + expect(mockCline.diffViewProvider.saveDirectly).toHaveBeenCalledWith( + testFilePath, + testContent, + false, + true, + 1000, + "create", + ) + expect(mockCline.diffViewProvider.saveChanges).not.toHaveBeenCalled() + expect(mockCline.fileContextTracker.trackFileContext).toHaveBeenCalledWith(testFilePath, "roo_edited") + expect(mockCline.didEditFile).toBe(true) + expect(mockCline.consecutiveMistakeCount).toBe(0) + expect(result).toBe("Tool result message") + expect(mockHandleError).not.toHaveBeenCalled() + }) + + it("surfaces the unobserved-existing remediation as a tool error and publishes nothing", async () => { + const guardError = new Error( + `File already exists at ${absoluteFilePath} and was not read before this write -- read the file first, then retry.`, + ) + mockCline.diffViewProvider.saveDirectly.mockRejectedValue(guardError) + + const result = await executeWriteFileTool({}, { fileExists: true, experiments: focusDisruption }) + + expect(mockHandleError).toHaveBeenCalledWith("writing file", guardError) + expect(result).toBeUndefined() + expect(mockCline.diffViewProvider.reset).toHaveBeenCalled() + expect(mockCline.diffViewProvider.saveChanges).not.toHaveBeenCalled() + expect(mockCline.didEditFile).toBe(false) + }) + + it("surfaces the stale-version remediation as a tool error and publishes nothing", async () => { + const guardError = new Error( + "Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.", + ) + mockCline.diffViewProvider.saveDirectly.mockRejectedValue(guardError) + + const result = await executeWriteFileTool({}, { fileExists: true, experiments: focusDisruption }) + + expect(mockHandleError).toHaveBeenCalledWith("writing file", guardError) + expect(result).toBeUndefined() + expect(mockCline.diffViewProvider.reset).toHaveBeenCalled() + expect(mockCline.didEditFile).toBe(false) + }) + }) + describe("error handling", () => { it("handles general file operation errors", async () => { mockCline.diffViewProvider.open.mockRejectedValue(new Error("General error")) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 2f29ca3ab15..f0152108d59 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -18,7 +18,7 @@ import { arePathsEqual, getReadablePath } from "../../utils/path" import { formatResponse } from "../../core/prompts/responses" import { diagnosticsToProblemsString, getNewDiagnostics } from "../diagnostics" import { Task } from "../../core/task/Task" -import { safeWriteText } from "../../services/file-safety/safeWriteText" +import { guardedWrite, type GuardedWriteKind } from "../../core/tools/guardedWrite" import { DecorationController } from "./DecorationController" @@ -1138,6 +1138,10 @@ export class DiffViewProvider { * @param relPath - Relative path to the file * @param content - Content to write to the file * @param openFile - Whether to show the file in editor (false = open in memory only for diagnostics) + * @param writeKind - Guarded-write kind that selects the S4a guard for this publish. + * Defaults to "create" because this method always publishes a complete file + * content: an unobserved target may only be created when absent, and an + * observed target must still carry the version token recorded at read time. * @returns Result of the save operation including any new problems detected */ async saveDirectly( @@ -1146,6 +1150,7 @@ export class DiffViewProvider { openFile: boolean = true, diagnosticsEnabled: boolean = true, writeDelayMs: number = DEFAULT_WRITE_DELAY_MS, + writeKind: GuardedWriteKind = "create", ): Promise<{ newProblemsMessage: string | undefined userEdits: string | undefined @@ -1156,9 +1161,19 @@ export class DiffViewProvider { // Get diagnostics before editing the file this.preDiagnostics = vscode.languages.getDiagnostics() - // Write the content directly to the file + // Publish through the S4 guarded-write API (epic #1375): an unobserved + // write to an existing file and a stale observed version are rejected + // with a re-read-then-retry remediation instead of overwriting the file. + // Concurrent in-process writes to the same path are already ordered by + // the guard's per-path FIFO chain, so no additional locking is added here. + const task = this.taskRef.deref() + if (!task) { + // Fail closed: without the owning task the observation registry is + // unreachable and the write cannot be guarded. + throw new Error("Cannot guard the write: the owning task is no longer available") + } await createDirectoriesForFile(absolutePath) - await safeWriteText(absolutePath, content) + await guardedWrite(task, relPath, content, writeKind) // Open the document to ensure diagnostics are loaded // When openFile is false (PREVENT_FOCUS_DISRUPTION enabled), we only open in memory diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 594725d2f30..2ce234e3bd3 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -8,6 +8,13 @@ import { DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" import { makePosition, makeRange, makeTextDocument, makeTextEditor, makeUri } from "../../../test-utils/vscode" +import * as fs from "fs/promises" + +import { computeVersionToken } from "../../../utils/versionToken" +import { safeWriteText } from "../../../services/file-safety/safeWriteText" +import { ObservationRegistry } from "../../../core/task/observationRegistry" +import type { Task } from "../../../core/task/Task" + // Mock delay vi.mock("delay", () => ({ default: vi.fn().mockResolvedValue(undefined), @@ -28,6 +35,12 @@ vi.mock("../../../services/file-safety/safeWriteText", () => ({ safeWriteText: vi.fn().mockResolvedValue(undefined), })) +// Mock the S1 version token (used by the S4 guarded write); the real +// computeVersionToken needs fs.stat, which is not part of the fs/promises mock above. +vi.mock("../../../utils/versionToken", () => ({ + computeVersionToken: vi.fn(), +})) + // Mock utils vi.mock("../../../utils/fs", () => ({ createDirectoriesForFile: vi.fn().mockResolvedValue([]), @@ -36,6 +49,7 @@ vi.mock("../../../utils/fs", () => ({ // Mock path vi.mock("path", () => ({ resolve: vi.fn((cwd, relPath) => `${cwd}/${relPath}`), + isAbsolute: vi.fn((p: string) => p.startsWith("/")), basename: vi.fn((path) => path.split("/").pop()), dirname: vi.fn((path) => path.split("/").slice(0, -1).join("/") || "/"), join: (...args: string[]) => args.join("/"), @@ -208,15 +222,25 @@ describe("DiffViewProvider", () => { return mockWorkspaceEdit as unknown as vscode.WorkspaceEdit }) - // Create a mock Task instance; the double provides providerRef.deref() -> - // getState() with provider settings (see makeTaskDouble below). - mockTask = makeTaskDouble({ - // Auto-closing edited tabs is opt-in by default; the legacy - // "close/keep behavior" suite below asserts the close path, so - // enable it here. The opt-in default itself is covered by the - // dedicated "auto-close settings decision table" suite. - autoCloseZooOpenedFiles: true, - }) + // Create a mock Task instance. The guarded write (S4b) consults the task's + // S2 observation registry, so the mock carries a real (in-memory) instance. + mockTask = { + cwd: mockCwd, + observationRegistry: new ObservationRegistry(), + providerRef: { + deref: vi.fn().mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + includeDiagnosticMessages: true, + maxDiagnosticMessages: 50, + // Auto-closing edited tabs is opt-in by default; the legacy + // "close/keep behavior" suite below asserts the close path, so + // enable it here. The opt-in default itself is covered by the + // dedicated "auto-close settings decision table" suite. + autoCloseZooOpenedFiles: true, + }), + }), + }, + } diffViewProvider = new DiffViewProvider(mockCwd, mockTask) // Mock the necessary properties and methods @@ -784,6 +808,13 @@ describe("DiffViewProvider", () => { // Mock vscode functions vi.mocked(vscode.window.showTextDocument).mockResolvedValue(makeTextEditor()) vi.mocked(vscode.languages.getDiagnostics).mockReturnValue([]) + + // Baseline for the single-writer flow these tests encode: the file was read + // before the write, so the observation registry holds the version token the + // guarded write recomputes and compares, and the target exists on disk. + mockTask.observationRegistry.observe(`${mockCwd}/test.ts`, "v1") + vi.mocked(computeVersionToken).mockResolvedValue("v1") + vi.mocked(fs.access).mockResolvedValue(undefined) }) it("should write content directly to file without opening diff view", async () => { @@ -859,6 +890,68 @@ describe("DiffViewProvider", () => { expect(diffViewProvider["relPath"]).toBe("test.ts") expect(diffViewProvider["newContent"]).toBe("new content") }) + + describe("guarded write (S4b, epic #1375)", () => { + const enoent = () => Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) + + it("rejects an unobserved write to an existing file with the read-first remediation", async () => { + mockTask.observationRegistry.clear() + + await expect(diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0)).rejects.toThrow( + "File already exists at /mock/cwd/test.ts and was not read before this write -- read the file first, then retry.", + ) + expect(safeWriteText).not.toHaveBeenCalled() + }) + + it("creates an unobserved file when the target is absent", async () => { + mockTask.observationRegistry.clear() + vi.mocked(fs.access).mockRejectedValue(enoent()) + + await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) + + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content") + }) + + it("rejects an observed write whose version token is stale", async () => { + // The file changed on disk after the read that recorded "v1". + vi.mocked(computeVersionToken).mockResolvedValue("v2") + + const result = diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) + + await expect(result).rejects.toThrow("Stale version") + await expect(result).rejects.toThrow("re-read the file, then retry.") + expect(safeWriteText).not.toHaveBeenCalled() + }) + + it("rejects an unobserved edit-kind write before any I/O", async () => { + mockTask.observationRegistry.clear() + + await expect( + diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0, "edit"), + ).rejects.toThrow("File not read yet -- read the file, then retry.") + expect(safeWriteText).not.toHaveBeenCalled() + expect(fs.access).not.toHaveBeenCalled() + }) + + it("recreates an observed file that vanished after the read", async () => { + vi.mocked(fs.access).mockRejectedValue(enoent()) + + await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) + + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content") + }) + + it("fails closed when the owning task has been collected", async () => { + // A real WeakRef cannot be forced to deref to undefined deterministically + // (GC timing), so a structural stub stands in for the collected reference. + diffViewProvider["taskRef"] = { deref: () => undefined } as unknown as WeakRef + + await expect(diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0)).rejects.toThrow( + "Cannot guard the write: the owning task is no longer available", + ) + expect(safeWriteText).not.toHaveBeenCalled() + }) + }) }) describe("saveChanges method with diagnostic settings", () => { From fe49781911442d43bf41f24333b6308b2446cd4c Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Fri, 28 Aug 2026 10:14:23 +0800 Subject: [PATCH 05/79] fix(fws): observe the apply_patch hunk read for the guarded publish The hunk reader now doubles as the S2 observation (ReadFileTool contract): stat before and after the read and record the version token when the on-disk version is unchanged, so the in-place modify publish is not rejected as an unobserved write even though this tool just read the exact content the patch was applied to. Regressions: a stable read records the observation; a mid-read change does not, and the publish surfaces the unobserved-existing remediation. (CodeRabbit finding on trial #1413). --- src/core/tools/ApplyPatchTool.ts | 20 +++++- .../__tests__/applyPatchTool.execute.spec.ts | 65 +++++++++++++++++++ 2 files changed, 83 insertions(+), 2 deletions(-) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 10f3c330229..9ea6620b067 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -11,6 +11,7 @@ import { RecordSource } from "../context-tracking/FileContextTrackerTypes" import { fileExistsAtPath } from "../../utils/fs" import { EXPERIMENT_IDS, experiments } from "../../shared/experiments" import { sanitizeUnifiedDiff, computeDiffStats } from "../diff/stats" +import { versionTokenOfStat } from "../../utils/versionToken" import { BaseTool, ToolCallbacks } from "./BaseTool" import type { ToolUse } from "../../shared/tools" import { parsePatch, ParseError, processAllHunks } from "./apply-patch" @@ -85,10 +86,25 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { return } - // Process each hunk + // Process each hunk. The read doubles as the S2 observation for the + // guarded publish (ReadFileTool contract: stat before and after the + // read, observe only when the on-disk version is unchanged between the + // two stats). Without it, the in-place modify publish is an unobserved + // write and the composed chat-diff default rejects it ("File already + // exists ... and was not read before this write") even though this tool + // just read the exact content the patch was applied to. const readFile = async (filePath: string): Promise => { const absolutePath = path.resolve(task.cwd, filePath) - return await fs.readFile(absolutePath, "utf8") + const preReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) + const content: string = await fs.readFile(absolutePath, "utf8") + const postReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) + if (preReadStats && postReadStats) { + const preReadToken = versionTokenOfStat(preReadStats) + if (preReadToken === versionTokenOfStat(postReadStats)) { + task.observationRegistry.observe(absolutePath, preReadToken) + } + } + return content } let changes: ApplyPatchFileChange[] diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index d9ce0a6c7cc..378be79b610 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -4,12 +4,36 @@ import type { MockedFunction } from "vitest" import { fileExistsAtPath } from "../../../utils/fs" import { isPathOutsideWorkspace } from "../../../utils/pathUtils" +import path from "path" +import * as fsPromises from "fs/promises" import type { Task } from "../../task/Task" +import { ObservationRegistry } from "../../task/observationRegistry" import { ApplyPatchTool } from "../ApplyPatchTool" +// The vi.mock factory exposes the fs/promises functions under a `default` +// property (matching the SUT's default import), which the static module type +// does not declare; cast once at this boundary rather than at each call site. +const mockedFsPromises = vi.mocked( + fsPromises as unknown as { + default: { + stat: ReturnType + unlink: MockedFunction + } + }, +) + vi.mock("fs/promises", () => ({ default: { readFile: vi.fn().mockResolvedValue("original file content\n"), + // Stable on-disk version for the S2 self-read observation (the hunk + // read now stats before and after; equal tokens record the observe). + stat: vi.fn().mockResolvedValue({ + dev: 7n, + ino: 4242n, + size: 1234n, + mtimeNs: 1_700_000_000_123_456_789n, + ctimeNs: 1_700_000_000_789_999_999n, + }), unlink: vi.fn().mockResolvedValue(undefined), }, })) @@ -38,6 +62,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { | "say" | "processQueuedMessages" | "didEditFile" + | "observationRegistry" > let mockAskApproval: MockedFunction<(...args: unknown[]) => Promise> let mockHandleError: MockedFunction<(...args: unknown[]) => Promise> @@ -52,6 +77,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => { mockTask = { cwd: "/workspace/project", consecutiveMistakeCount: 0, + observationRegistry: new ObservationRegistry(), recordToolUsage: vi.fn(), recordToolError: vi.fn(), rooIgnoreController: { @@ -113,6 +139,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { | "diffViewProvider" | "providerRef" | "fileContextTracker" + | "observationRegistry" > let mockSaveDirectly: MockedFunction<(...args: unknown[]) => Promise> let mockAskApproval: MockedFunction<(...args: unknown[]) => Promise> @@ -164,6 +191,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { mockTask = { cwd: "/workspace/project", consecutiveMistakeCount: 0, + observationRegistry: new ObservationRegistry(), recordToolError: vi.fn(), rooIgnoreController: { validateAccess: vi.fn().mockReturnValue(true), @@ -217,6 +245,43 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { expect(mockHandleError).not.toHaveBeenCalled() }) + it("update: observes the hunk read so the guarded publish is not unobserved", async () => { + await tool.execute({ patch: updatePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + // The hunk read doubles as the S2 observation (ReadFileTool contract): + // stable pre/post stats record the version token, so the in-place modify + // publish is not rejected as an unobserved write. + const observed = mockTask.observationRegistry.get(path.resolve("/workspace/project", "src/thing.ts")) + expect(observed?.version).toBe("7:4242:1234:1700000000123456789:1700000000789999999") + }) + + it("update: does not observe when the pre- and post-read tokens disagree", async () => { + // The file changed mid-read: pre/post stats differ, so no observation is + // recorded and the guarded publish surfaces the unobserved-existing + // remediation instead of publishing against a stale version. + const statMock = mockedFsPromises.default.stat + statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n }) + statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 9999n, mtimeNs: 3n, ctimeNs: 4n }) + + const guardError = new Error( + "File already exists at /workspace/project/src/thing.ts and was not read before this write -- read the file first, then retry.", + ) + mockSaveDirectly.mockRejectedValue(guardError) + + await tool.execute({ patch: updatePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) + expect(mockHandleError).toHaveBeenCalled() + }) + it("add: publishes the new file through the guarded saveDirectly with create kind", async () => { mockedFileExistsAtPath.mockResolvedValueOnce(false) From f8dd6c30bbdc3ff42e7aebbb17ba5922651f8ef3 Mon Sep 17 00:00:00 2001 From: Eason Liang Date: Sun, 30 Aug 2026 12:33:32 +0800 Subject: [PATCH 06/79] =?UTF-8?q?chore(ci):=20empty=20commit=20=E2=80=94?= =?UTF-8?q?=20re-trigger=20CI=20and=20the=20CodeRabbit=20current-head=20re?= =?UTF-8?q?view=20gate=20(no=20code=20change)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From d4833045f04ebb3343110e24f26a0a2bad37ad63 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Tue, 6 Oct 2026 16:42:53 +0800 Subject: [PATCH 07/79] fix(tools): run the guard check and the publish under one lock replaceIfVersion read the version token and then called safeWriteText, so another writer that honours the same advisory lock could publish between the check and the rename: the write looked valid on the check and still overwrote a newer file. createIfAbsent had the same shape with the absence check. Both guards now run check plus publish inside acquireFileLock, the mechanism safeWriteJson already uses. Added tests that record the order acquire -> check -> publish -> release for both guards, and that the lock is released when the guard rejects as stale. Local run: 28 tests pass, eslint clean, no suppression count change. --- src/core/tools/__tests__/guardedWrite.spec.ts | 65 ++++++++++ src/core/tools/guardedWrite.ts | 114 +++++++++++------- 2 files changed, 134 insertions(+), 45 deletions(-) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index 122c1c6d9bc..d5cb770b83d 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -16,6 +16,7 @@ import { describe, expect, it, beforeEach, vi } from "vitest" import { createIfAbsent, guardedWrite, replaceIfVersion, resetChain } from "../guardedWrite" import { safeWriteText } from "../../../services/file-safety/safeWriteText" import { computeVersionToken } from "../../../utils/versionToken" +import { acquireFileLock } from "../../../utils/fileLock" import { ObservationRegistry } from "../../task/observationRegistry" import type { Task } from "../../task/Task" @@ -30,6 +31,10 @@ vi.mock("../../../utils/versionToken", () => ({ computeVersionToken: vi.fn(), })) +vi.mock("../../../utils/fileLock", () => ({ + acquireFileLock: vi.fn(async () => releaseMock), // resolves to the release function +})) + vi.mock("../../../services/file-safety/safeWriteText", () => ({ safeWriteText: vi.fn(), })) @@ -37,6 +42,8 @@ vi.mock("../../../services/file-safety/safeWriteText", () => ({ const mockedFsAccess = vi.mocked(fs.access) const mockedComputeVersionToken = vi.mocked(computeVersionToken) const mockedSafeWriteText = vi.mocked(safeWriteText) +let releaseMock: () => Promise = async () => {} +const mockedAcquireFileLock = vi.mocked(acquireFileLock) // -- Fixtures ---------------------------------------------------------------- @@ -452,3 +459,61 @@ describe("guardedWrite (S4a, epic #1375)", () => { }) }) }) + + describe("atomicity of the guard check and publish", () => { + beforeEach(() => { vi.resetAllMocks(); resetChain() }) + it("holds the lock across the version check and the publish", async () => { + const order: string[] = [] + releaseMock = async () => { order.push("release") } + mockedAcquireFileLock.mockImplementation(async () => { + order.push("acquire") + return releaseMock + }) + mockedComputeVersionToken.mockImplementation(async () => { + order.push("check") + return "v1" + }) + mockedSafeWriteText.mockImplementation(async () => { + order.push("publish") + }) + + await replaceIfVersion(abs("x.txt"), "v1", "new") + + // A writer that honors the same lock cannot slip between the check and the publish. + expect(order).toEqual(["acquire", "check", "publish", "release"]) + }) + + it("releases the lock when the guard rejects as stale", async () => { + const order: string[] = [] + releaseMock = async () => { order.push("release") } + mockedAcquireFileLock.mockImplementation(async () => { + order.push("acquire") + return releaseMock + }) + mockedComputeVersionToken.mockResolvedValue("v2") + + await expect(replaceIfVersion(abs("x.txt"), "v1", "new")).rejects.toThrow(/Stale version/) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + expect(order).toEqual(["acquire", "release"]) + }) + + it("holds the lock across the absence check and the create publish", async () => { + const order: string[] = [] + releaseMock = async () => { order.push("release") } + mockedAcquireFileLock.mockImplementation(async () => { + order.push("acquire") + return releaseMock + }) + mockedFsAccess.mockImplementation(async () => { + order.push("check") + throw { code: "ENOENT" } + }) + mockedSafeWriteText.mockImplementation(async () => { + order.push("publish") + }) + + await createIfAbsent(abs("new.txt"), "hello") + + expect(order).toEqual(["acquire", "check", "publish", "release"]) + }) + }) diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index 596cc410350..7be1d0d3968 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -20,6 +20,7 @@ import * as path from "path" import { safeWriteText } from "../../services/file-safety/safeWriteText" import { computeVersionToken } from "../../utils/versionToken" +import { acquireFileLock } from "../../utils/fileLock" import type { Task } from "../task/Task" // -- Types ------------------------------------------------------------------ @@ -94,6 +95,21 @@ function errorCode(error: unknown): string | undefined { : undefined } +/** + * Run a guard check and its publish as one atomic step with respect to every writer + * that honors the same advisory lock (safeWriteJson acquires it through fileLock). + * Without the lock the version token can change between the check and the rename, so + * a write that looked valid on the check can overwrite a newer file. + */ +async function withWriteLock(absolutePath: string, run: () => Promise): Promise { + const release = await acquireFileLock(absolutePath) + try { + await run() + } finally { + await release() + } +} + /** True when the path is absent on disk (fs.access reports ENOENT). */ async function fileIsAbsent(absolutePath: string): Promise { try { @@ -112,23 +128,27 @@ async function fileIsAbsent(absolutePath: string): Promise { * the file first, then retry. */ export async function createIfAbsent(absolutePath: string, content: string): Promise { - try { - await fs.access(absolutePath) - } catch (error: unknown) { - if (errorCode(error) !== "ENOENT") { - // A real I/O failure (EACCES, EIO, ...) -- not a guard verdict. - throw error + await withWriteLock(absolutePath, async () => { + try { + await fs.access(absolutePath) + } catch (error: unknown) { + if (errorCode(error) !== "ENOENT") { + // A real I/O failure (EACCES, EIO, ...) -- not a guard verdict. + throw error + } + // Absent under the lock: no other lock-honoring writer can create it between + // this check and the publish. + await safeWriteText(absolutePath, content) + return } - await safeWriteText(absolutePath, content) - return - } - throw new GuardRejectedError( - "File already exists at " + - absolutePath + - " and was not read before this write -- read the file first, then retry.", - absolutePath, - ) + throw new GuardRejectedError( + "File already exists at " + + absolutePath + + " and was not read before this write -- read the file first, then retry.", + absolutePath, + ) + }) } /** @@ -140,39 +160,43 @@ export async function createIfAbsent(absolutePath: string, content: string): Pro * remediation suffix. */ export async function replaceIfVersion(absolutePath: string, expectedVersion: string, content: string): Promise { - let currentVersion: string - try { - currentVersion = await computeVersionToken(absolutePath) - } catch (error: unknown) { - if (errorCode(error) === "ENOENT") { - // The observed file was deleted after the read: the version recorded - // at read time no longer exists on disk. Normalize the raw ENOENT - // into the guard's re-read-then-retry contract so the caller gets a - // remediation it can act on, not a raw errno. - throw new GuardRejectedError( - "File was deleted after it was read -- the version recorded at read time (" + - expectedVersion + - ") no longer exists; re-read the file, then retry.", - absolutePath, - ) + await withWriteLock(absolutePath, async () => { + let currentVersion: string + try { + currentVersion = await computeVersionToken(absolutePath) + } catch (error: unknown) { + if (errorCode(error) === "ENOENT") { + // The observed file was deleted after the read: the version recorded + // at read time no longer exists on disk. Normalize the raw ENOENT + // into the guard's re-read-then-retry contract so the caller gets a + // remediation it can act on, not a raw errno. + throw new GuardRejectedError( + "File was deleted after it was read -- the version recorded at read time (" + + expectedVersion + + ") no longer exists; re-read the file, then retry.", + absolutePath, + ) + } + // A real I/O failure (EACCES, EIO, ...) -- not a guard verdict. + throw error } - // A real I/O failure (EACCES, EIO, ...) -- not a guard verdict. - throw error - } - if (currentVersion === expectedVersion) { - await safeWriteText(absolutePath, content) - return - } + if (currentVersion === expectedVersion) { + // The check and the publish run under the same lock, so the token cannot + // change between them for any writer that honors it. + await safeWriteText(absolutePath, content) + return + } - throw new GuardRejectedError( - "Stale version -- the file changed since you read it (expected " + - expectedVersion + - ", current " + - currentVersion + - "); re-read the file, then retry.", - absolutePath, - ) + throw new GuardRejectedError( + "Stale version -- the file changed since you read it (expected " + + expectedVersion + + ", current " + + currentVersion + + "); re-read the file, then retry.", + absolutePath, + ) + }) } /** From dc4fd448c66545d97192f39506693f91e00e97b5 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Tue, 6 Oct 2026 18:28:38 +0800 Subject: [PATCH 08/79] test(editor): mock the advisory lock the guarded write now uses The guard runs its check and publish inside acquireFileLock, so the spec reached the real proper-lockfile against the mocked fs/promises and failed on CI (mkdir '/mock/cwd/test.ts/undefined.lock'). The spec mocks the lock as a no-op and asserts the order acquire -> check -> publish -> release, so the atomicity the guard promises is still covered here rather than only in the guardedWrite spec. Local run: 12 saveDirectly tests pass, eslint clean, no suppression count change. --- .../editor/__tests__/DiffViewProvider.spec.ts | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 2ce234e3bd3..c7c961d0216 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -13,6 +13,7 @@ import * as fs from "fs/promises" import { computeVersionToken } from "../../../utils/versionToken" import { safeWriteText } from "../../../services/file-safety/safeWriteText" import { ObservationRegistry } from "../../../core/task/observationRegistry" +import { acquireFileLock } from "../../../utils/fileLock" import type { Task } from "../../../core/task/Task" // Mock delay @@ -42,6 +43,11 @@ vi.mock("../../../utils/versionToken", () => ({ })) // Mock utils +// Mock the advisory lock the guarded write uses to keep its check and publish atomic. +vi.mock("../../../utils/fileLock", () => ({ + acquireFileLock: vi.fn(async () => async () => {}), +})) + vi.mock("../../../utils/fs", () => ({ createDirectoriesForFile: vi.fn().mockResolvedValue([]), })) @@ -910,6 +916,25 @@ describe("DiffViewProvider", () => { await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content") + + }) + it("holds the lock across the guard check and the publish", async () => { + const order: string[] = [] + vi.mocked(acquireFileLock).mockImplementation(async () => { + order.push("acquire") + return async () => { order.push("release") } + }) + mockTask.observationRegistry.clear() + vi.mocked(fs.access).mockImplementation(async () => { + order.push("check") + throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) + }) + vi.mocked(safeWriteText).mockImplementation(async () => { order.push("publish") }) + + await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) + + // A writer that honours the same lock cannot slip between the check and the publish. + expect(order).toEqual(["acquire", "check", "publish", "release"]) }) it("rejects an observed write whose version token is stale", async () => { From f29cc4e9d7d7c4d3017fec0f72ec422ace91f879 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Tue, 6 Oct 2026 19:33:41 +0800 Subject: [PATCH 09/79] fix(file-safety): remove the staging directory once the commit lands The staging sub-directory exists only to hold this write's temp file, so a successful publish left an empty .file-safety-staging directory in the user's workspace on every guarded write. It is now removed after the commit; rmdir fails when a concurrent write still holds a file there, so that case is left alone rather than deleting another write's staging file. Also made the observation-registry test assert the exact key the guard looks up (path.resolve(cwd, relPath)) and the exact version token, instead of a substring and a shape match. Local run: 27 safeWriteText tests pass, eslint clean, no suppression count change. --- src/core/tools/__tests__/readFileTool.spec.ts | 4 ++-- .../file-safety/__tests__/safeWriteText.spec.ts | 13 +++++++++++++ src/services/file-safety/safeWriteText.ts | 15 ++++++++++++++- 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 4d9a7103f65..0d1f3b5f76f 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -1798,8 +1798,8 @@ describe("ReadFileTool", () => { // Verify the tool called observe exactly once with a valid token. expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, calledVersion] = observeSpy.mock.calls[0] - expect(calledPath).toContain("existing.ts") - expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/) + expect(calledPath).toBe(path.resolve("/test/workspace", "existing.ts")) + expect(calledVersion).toBe("1:2:300:4000000000:5000000000") // Verify get() returns the same data using the spy-captured key. const obs = reg.get(calledPath) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index 4accc2b71e0..f5da97f8d8d 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -13,6 +13,7 @@ vi.mock("fs/promises", () => ({ rename: vi.fn(), unlink: vi.fn(), realpath: vi.fn(), + rmdir: vi.fn(), })) // Full mock for fs — all sync methods are vi.fn() stubs. Stats is a bare @@ -400,6 +401,18 @@ describe("safeWriteText", () => { expect(fsSync.mkdirSync).not.toHaveBeenCalled() }) + it("removes the staging directory after the commit lands", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + await safeWriteText(targetPath, "data", { platform: "linux" }) + + // The directory only exists to hold this write's temp file, so a successful publish + // must not leave it behind in the user's workspace. + expect(fs.rmdir).toHaveBeenCalledWith(expect.stringContaining(".file-safety-staging")) + }) + it("applies the existing target's mode to a caller-supplied tempPath before publishing", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index 71871032e55..b9a45837ea6 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -152,7 +152,8 @@ export async function safeWriteText(filePath: string, content: string, options?: // Create the staging directory only when we generate the temp file there; // callers supplying their own tempPath (e.g. safeWriteJson) must not be left // with an empty .file-safety-staging directory behind. - const tempPath = options?.tempPath ?? _tempName(_stagingDir(dirPath), "safeWriteText") + const stagingDir = options?.tempPath ? null : _stagingDir(dirPath) + const tempPath = options?.tempPath ?? _tempName(stagingDir ?? dirPath, "safeWriteText") let backupPath: string | null = null let releaseBackupOnSuccess = false @@ -273,6 +274,18 @@ export async function safeWriteText(filePath: string, content: string, options?: // non-fatal — orphaned backup is acceptable } } + + // The staging sub-directory only exists to hold this write's temp file. Once the + // commit lands it is empty clutter in the user's workspace, so remove it when nothing + // else is in it; a concurrent write still holding a temp file makes rmdir fail and is + // left alone. + if (stagingDir !== null) { + try { + await fs.rmdir(stagingDir) + } catch { + // best-effort: a concurrent write may still hold a temp file here + } + } } finally { // Unlink DACL dump regardless of success/failure in this span. if (daclDumpPath !== null) { From 89ba355e5d83a5281b9deb08b21851b038e2ae12 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Wed, 7 Oct 2026 01:09:26 +0800 Subject: [PATCH 10/79] fix(guarded-write): refresh the observation after a publish, survive a concurrent staging-dir removal createIfAbsent and replaceIfVersion now recompute the version token under the same write lock and return it, and guardedWrite records it in the task's observation registry. Without that, the registry kept the read-time token after a successful write, so the next edit failed with "Stale version", and a newly created file stayed unobserved so a later write failed with "File not read yet" - both contradicting the result message that says the file need not be re-read. The observation is snapshotted when the write is issued rather than when its chain link runs, so the refresh cannot retroactively validate a second write that was issued against the pre-publish state: two concurrent writes to one path still have exactly one winner. The post-commit rmdir of the shared staging directory could remove it between another writer's _stagingDir() and its openSync, making that write fail with a raw ENOENT. The open now re-creates the directory and retries once; a second ENOENT or any other errno still propagates. Local run: 30 guardedWrite + 29 safeWriteText tests pass, tsc clean for the touched files, eslint clean, no suppression count change. --- src/core/tools/__tests__/guardedWrite.spec.ts | 44 +++++++++++- src/core/tools/guardedWrite.ts | 68 ++++++++++++------- .../__tests__/safeWriteText.spec.ts | 35 ++++++++++ src/services/file-safety/safeWriteText.ts | 17 ++++- 4 files changed, 134 insertions(+), 30 deletions(-) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index d5cb770b83d..81ac949ff5f 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -273,6 +273,42 @@ describe("guardedWrite (S4a, epic #1375)", () => { }) }) + describe("observation refresh after a publish", () => { + it("records the published token so a later write needs no re-read", async () => { + const task = createMockTask() + mockedFsAccess.mockRejectedValue({ code: "ENOENT" }) + mockedComputeVersionToken.mockResolvedValue("v-created") + + await guardedWrite(task, "created.txt", "hello", "create") + + // The created file was never read, so without this the registry stays empty + // and the next write fails with "File not read yet". + expect(task.observationRegistry.get(abs("created.txt"))?.version).toBe("v-created") + + mockedFsAccess.mockResolvedValue(undefined) + mockedComputeVersionToken.mockResolvedValue("v-created") + await guardedWrite(task, "created.txt", "again", "update") + + expect(mockedSafeWriteText).toHaveBeenCalledTimes(2) + expect(mockedSafeWriteText).toHaveBeenLastCalledWith(abs("created.txt"), "again") + }) + + it("replaces the read-time token after a successful update", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("doc.txt"), "v1") + mockedFsAccess.mockResolvedValue(undefined) + // First call: the CAS check. Second call: the token of what was just written. + mockedComputeVersionToken.mockResolvedValueOnce("v1").mockResolvedValueOnce("v2") + const task = createMockTask({ observationRegistry: reg }) + + await guardedWrite(task, "doc.txt", "patched", "edit") + + // Leaving v1 here makes the next edit fail with "Stale version" even though + // nothing else touched the file. + expect(reg.get(abs("doc.txt"))?.version).toBe("v2") + }) + }) + describe("concurrency: per-path FIFO chain", () => { it("two concurrent updates on one path - exactly one publishes, the other fails stale", async () => { const reg = new ObservationRegistry() @@ -477,10 +513,12 @@ describe("guardedWrite (S4a, epic #1375)", () => { order.push("publish") }) - await replaceIfVersion(abs("x.txt"), "v1", "new") + const published = await replaceIfVersion(abs("x.txt"), "v1", "new") - // A writer that honors the same lock cannot slip between the check and the publish. - expect(order).toEqual(["acquire", "check", "publish", "release"]) + // A writer that honors the same lock cannot slip between the check and the publish, + // and the token handed back is recomputed before the lock is released. + expect(order).toEqual(["acquire", "check", "publish", "check", "release"]) + expect(published).toBe("v1") }) it("releases the lock when the guard rejects as stale", async () => { diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index 7be1d0d3968..d6d5b0de9fc 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -54,7 +54,7 @@ class GuardRejectedError extends Error { * Settled entries are evicted (below), so a long-lived extension does not * accumulate a map entry per distinct written path. */ -const pendingChains = new Map>() +const pendingChains = new Map>() /** * Enqueue a write operation on the per-path FIFO chain. @@ -64,7 +64,7 @@ const pendingChains = new Map>() * deleted once it settles — but only while it is still the current tail for * the path, so a replacement enqueued in the meantime keeps ownership. */ -function enqueue(pathKey: string, fn: () => Promise): Promise { +function enqueue(pathKey: string, fn: () => Promise): Promise { const prev = pendingChains.get(pathKey) ?? Promise.resolve() const next = prev.then(fn, fn) pendingChains.set(pathKey, next) @@ -101,10 +101,10 @@ function errorCode(error: unknown): string | undefined { * Without the lock the version token can change between the check and the rename, so * a write that looked valid on the check can overwrite a newer file. */ -async function withWriteLock(absolutePath: string, run: () => Promise): Promise { +async function withWriteLock(absolutePath: string, run: () => Promise): Promise { const release = await acquireFileLock(absolutePath) try { - await run() + return await run() } finally { await release() } @@ -127,8 +127,8 @@ async function fileIsAbsent(absolutePath: string): Promise { * write was issued for a file that was never read, so the caller must read * the file first, then retry. */ -export async function createIfAbsent(absolutePath: string, content: string): Promise { - await withWriteLock(absolutePath, async () => { +export async function createIfAbsent(absolutePath: string, content: string): Promise { + return withWriteLock(absolutePath, async () => { try { await fs.access(absolutePath) } catch (error: unknown) { @@ -139,7 +139,10 @@ export async function createIfAbsent(absolutePath: string, content: string): Pro // Absent under the lock: no other lock-honoring writer can create it between // this check and the publish. await safeWriteText(absolutePath, content) - return + // Recomputed under the same lock: the caller records this as the new + // observation, so a later write is compared against what this publish + // actually wrote rather than against no observation at all. + return computeVersionToken(absolutePath) } throw new GuardRejectedError( @@ -159,8 +162,12 @@ export async function createIfAbsent(absolutePath: string, content: string): Pro * a mismatch the write is rejected stale with a re-read-then-retry * remediation suffix. */ -export async function replaceIfVersion(absolutePath: string, expectedVersion: string, content: string): Promise { - await withWriteLock(absolutePath, async () => { +export async function replaceIfVersion( + absolutePath: string, + expectedVersion: string, + content: string, +): Promise { + return withWriteLock(absolutePath, async () => { let currentVersion: string try { currentVersion = await computeVersionToken(absolutePath) @@ -185,7 +192,9 @@ export async function replaceIfVersion(absolutePath: string, expectedVersion: st // The check and the publish run under the same lock, so the token cannot // change between them for any writer that honors it. await safeWriteText(absolutePath, content) - return + // The publish moved the token; hand the new one back so the caller can + // record it instead of leaving the read-time token in the registry. + return computeVersionToken(absolutePath) } throw new GuardRejectedError( @@ -246,8 +255,14 @@ export async function guardedWrite( ): Promise { const absolutePath = resolveAbsolutePath(task, relPathOrAbsolute) + // Snapshot the observation when the write is issued, not when its link runs. + // A refresh after a publish must not retroactively validate a second write that + // was issued against the pre-publish state: two concurrent writes to one path + // still have exactly one winner. + const obs = task.observationRegistry.get(absolutePath) + return enqueue(absolutePath, async () => { - const obs = task.observationRegistry.get(absolutePath) + let publishedVersion: string if (obs === undefined) { // Edit-style writes require a prior read: no observation, no write. @@ -256,23 +271,24 @@ export async function guardedWrite( } // Never read: only an absent target may be created. (The edit guard // above rejects before reaching this line.) - await createIfAbsent(absolutePath, content) - return - } - - if (kind === "edit") { - await replaceIfVersion(absolutePath, obs.version, content) - return - } - - // kind is "create" or "update": a "create" on a file that vanished - // after the read recreates it; otherwise the version recorded at read - // time must still match the on-disk token. - if (kind === "create" && (await fileIsAbsent(absolutePath))) { - await createIfAbsent(absolutePath, content) + publishedVersion = await createIfAbsent(absolutePath, content) + } else if (kind === "edit") { + publishedVersion = await replaceIfVersion(absolutePath, obs.version, content) + } else if (kind === "create" && (await fileIsAbsent(absolutePath))) { + // kind is "create" or "update": a "create" on a file that vanished + // after the read recreates it. + publishedVersion = await createIfAbsent(absolutePath, content) } else { - await replaceIfVersion(absolutePath, obs.version, content) + // Otherwise the version recorded at read time must still match the + // on-disk token. + publishedVersion = await replaceIfVersion(absolutePath, obs.version, content) } + + // The file on disk is now what this write published. Record that token: a + // later guarded write must compare against it rather than the read-time (or, + // for a created file, missing) token, which is what the result message + // "you do not need to re-read the file" promises. + task.observationRegistry.observe(absolutePath, publishedVersion) }) } diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index f5da97f8d8d..7ff90de9650 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -413,6 +413,41 @@ describe("safeWriteText", () => { expect(fs.rmdir).toHaveBeenCalledWith(expect.stringContaining(".file-safety-staging")) }) + it("re-creates the staging directory when a concurrent write removes it mid-write", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync) + .mockImplementationOnce(() => { + // Another writer committed and rmdir'd the shared staging directory + // between _stagingDir() and this open. + throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) + }) + .mockReturnValue(1) + + await safeWriteText(targetPath, "data", { platform: "linux" }) + + // Once for the original staging call, once for the recovery. + expect(fsSync.mkdirSync).toHaveBeenCalledTimes(2) + expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath) + }) + + it("gives up after one recovery when the staging open keeps failing with ENOENT", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + const enoent = Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) + vi.mocked(fsSync.openSync).mockImplementation(() => { + throw enoent + }) + + await expect(safeWriteText(targetPath, "data", { platform: "linux" })).rejects.toBe(enoent) + + // One staging create plus one recovery attempt, then the error surfaces + // instead of looping. + expect(fsSync.mkdirSync).toHaveBeenCalledTimes(2) + expect(fsSync.openSync).toHaveBeenCalledTimes(2) + expect(fs.rename).not.toHaveBeenCalled() + }) + it("applies the existing target's mode to a caller-supplied tempPath before publishing", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index b9a45837ea6..7e5a94700ae 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -171,7 +171,22 @@ export async function safeWriteText(filePath: string, content: string, options?: } catch { // target does not exist yet - keep the default } - const fd = fsSync.openSync(tempPath, "w", targetMode) + let fd: number + try { + fd = fsSync.openSync(tempPath, "w", targetMode) + } catch (error: unknown) { + // Every write to one directory shares the staging dir, and a write that finishes + // removes it when empty. A concurrent writer can therefore remove it between + // _stagingDir() and this open. Re-create it and try once; any other errno, or + // a second ENOENT, is a real failure. + const code = + typeof error === "object" && error !== null && "code" in error + ? (error as { code?: string }).code + : undefined + if (code !== "ENOENT" || stagingDir === null) throw error + _stagingDir(dirPath) + fd = fsSync.openSync(tempPath, "w", targetMode) + } try { // Loop until every byte is written: writeSync can report a short // (partial) write, and publishing a truncated staging file would From 1144375e35ace08abd7d1e661c68e3d2626f6c4e Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Wed, 7 Oct 2026 05:40:32 +0800 Subject: [PATCH 11/79] test(tools): nest the atomicity suite, tighten the legacy observation assertions, fix the registry docstring - guardedWrite.spec.ts: the atomicity describe sat outside the top-level suite (which closed at line 497) and re-declared the same beforeEach. It is now nested inside the suite, the duplicated beforeEach is gone, and the single-line arrow bodies were expanded to match the repository format. - readFileTool.spec.ts: the legacy-format test asserted the observation key with toContain and the token with a regex, so a key mismatch between the read side and the guard's lookup would still pass. It now asserts the exact resolved path and the exact token, and reads the observation back through reg.get under that key - the same shape the native-format test already uses. - observationRegistry.ts: the module docstring still claimed observations are 'recorded but not consulted' with 'no behavior change'; guardedWrite consults the registry on every guarded publish. Local: guardedWrite.spec.ts 30 passed, readFileTool.spec.ts 81 passed, eslint clean on all three files with --prune-suppressions (no suppression change), package tsc clean. --- src/core/tools/__tests__/guardedWrite.spec.ts | 15 ++++++++++----- src/core/tools/__tests__/readFileTool.spec.ts | 11 +++++++++-- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index 81ac949ff5f..2a8806fa2a2 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -494,13 +494,13 @@ describe("guardedWrite (S4a, epic #1375)", () => { expect(mockedSafeWriteText).toHaveBeenLastCalledWith(abs("x.txt"), "b") }) }) -}) describe("atomicity of the guard check and publish", () => { - beforeEach(() => { vi.resetAllMocks(); resetChain() }) it("holds the lock across the version check and the publish", async () => { const order: string[] = [] - releaseMock = async () => { order.push("release") } + releaseMock = async () => { + order.push("release") + } mockedAcquireFileLock.mockImplementation(async () => { order.push("acquire") return releaseMock @@ -523,7 +523,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { it("releases the lock when the guard rejects as stale", async () => { const order: string[] = [] - releaseMock = async () => { order.push("release") } + releaseMock = async () => { + order.push("release") + } mockedAcquireFileLock.mockImplementation(async () => { order.push("acquire") return releaseMock @@ -537,7 +539,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { it("holds the lock across the absence check and the create publish", async () => { const order: string[] = [] - releaseMock = async () => { order.push("release") } + releaseMock = async () => { + order.push("release") + } mockedAcquireFileLock.mockImplementation(async () => { order.push("acquire") return releaseMock @@ -555,3 +559,4 @@ describe("guardedWrite (S4a, epic #1375)", () => { expect(order).toEqual(["acquire", "check", "publish", "release"]) }) }) +}) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 0d1f3b5f76f..2877cbda1d8 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -1856,8 +1856,15 @@ describe("ReadFileTool", () => { expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, calledVersion] = observeSpy.mock.calls[0] - expect(calledPath).toContain("legacy.ts") - expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/) + // Exact key and token, mirroring the native-format test: a mismatch between the + // key the read side records under and the key the guard looks up would otherwise + // still pass a substring/regex assertion. + expect(calledPath).toBe(path.resolve("/test/workspace", "legacy.ts")) + expect(calledVersion).toBe("1:2:300:4000000000:5000000000") + // The observation is retrievable under that exact key. + const obs = reg.get(calledPath) + expect(obs).toBeDefined() + expect(obs!.version).toBe(calledVersion) }) it("does not observe when the file mutates between the pre-read and post-read stats", async () => { From 38532fcae4bd2b692b72bd9b4ce45abee0af54f5 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Wed, 7 Oct 2026 08:11:16 +0800 Subject: [PATCH 12/79] fix(tools): lock the canonical publish target for guarded writes guardedWrite took its advisory lock on path.resolve(task.cwd, ...) while safeWriteJson locks the path it publishes to after resolving the publish target. acquireFileLock runs with realpath:false, so an alias and its referent produce different lock files: a guarded write through one spelling did not serialize with a safeWriteJson publish through the other, which is the cross-writer window the guard exists to close. withWriteLock now resolves the publish target first and locks that canonical path across the absence/version check and the publish. The publish itself still receives the caller's path, so safeWriteText's own resolution and the ObservationRegistry key are unchanged. Test: resolvePublishTarget maps alias.txt -> target.txt for one call; the lock is taken on target.txt, never on alias.txt, and safeWriteText still receives alias.txt. Proven sensitive: reverting the source gives 1 failed / 30 passed; with it 31 passed. eslint clean; package tsc reports nothing in the touched files. --- src/core/tools/__tests__/guardedWrite.spec.ts | 23 ++++++++++++++++++- src/core/tools/guardedWrite.ts | 10 ++++++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index 2a8806fa2a2..8da4ea08026 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -14,7 +14,7 @@ import * as path from "path" import { describe, expect, it, beforeEach, vi } from "vitest" import { createIfAbsent, guardedWrite, replaceIfVersion, resetChain } from "../guardedWrite" -import { safeWriteText } from "../../../services/file-safety/safeWriteText" +import { resolvePublishTarget, safeWriteText } from "../../../services/file-safety/safeWriteText" import { computeVersionToken } from "../../../utils/versionToken" import { acquireFileLock } from "../../../utils/fileLock" import { ObservationRegistry } from "../../task/observationRegistry" @@ -37,11 +37,13 @@ vi.mock("../../../utils/fileLock", () => ({ vi.mock("../../../services/file-safety/safeWriteText", () => ({ safeWriteText: vi.fn(), + resolvePublishTarget: vi.fn(async (p: string) => p), })) const mockedFsAccess = vi.mocked(fs.access) const mockedComputeVersionToken = vi.mocked(computeVersionToken) const mockedSafeWriteText = vi.mocked(safeWriteText) +const mockedResolvePublishTarget = vi.mocked(resolvePublishTarget) let releaseMock: () => Promise = async () => {} const mockedAcquireFileLock = vi.mocked(acquireFileLock) @@ -521,6 +523,25 @@ describe("guardedWrite (S4a, epic #1375)", () => { expect(published).toBe("v1") }) + it("locks the canonical publish target so a safeWriteJson writer serializes with it", async () => { + // safeWriteJson resolves its publish target before locking, and acquireFileLock runs + // with realpath:false. If the guarded write locked the caller's spelling instead, + // the alias and the referent would take two different lock files and a guarded + // write could race past a safeWriteJson publish of the same file. + const alias = abs("alias.txt") + const referent = abs("target.txt") + mockedResolvePublishTarget.mockResolvedValueOnce(referent) + mockedComputeVersionToken.mockResolvedValue("v1") + + await replaceIfVersion(alias, "v1", "new") + + expect(mockedAcquireFileLock).toHaveBeenCalledWith(referent) + expect(mockedAcquireFileLock).not.toHaveBeenCalledWith(alias) + // The publish still goes through the path the caller (and safeWriteText's own + // resolution) owns, so the observation key and symlink semantics are unchanged. + expect(mockedSafeWriteText).toHaveBeenCalledWith(alias, "new") + }) + it("releases the lock when the guard rejects as stale", async () => { const order: string[] = [] releaseMock = async () => { diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index d6d5b0de9fc..5541d4c944b 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -18,7 +18,7 @@ import * as fs from "fs/promises" import * as path from "path" -import { safeWriteText } from "../../services/file-safety/safeWriteText" +import { resolvePublishTarget, safeWriteText } from "../../services/file-safety/safeWriteText" import { computeVersionToken } from "../../utils/versionToken" import { acquireFileLock } from "../../utils/fileLock" import type { Task } from "../task/Task" @@ -102,7 +102,13 @@ function errorCode(error: unknown): string | undefined { * a write that looked valid on the check can overwrite a newer file. */ async function withWriteLock(absolutePath: string, run: () => Promise): Promise { - const release = await acquireFileLock(absolutePath) + // Lock the canonical publish target, not the caller's spelling of the path. + // safeWriteJson resolves its publish target before locking, and acquireFileLock + // runs with realpath:false, so an alias and its referent would otherwise take two + // different lock files: a guarded write through the alias would not serialize with + // a safeWriteJson publish through the referent and could overwrite it. + const lockPath = await resolvePublishTarget(absolutePath) + const release = await acquireFileLock(lockPath) try { return await run() } finally { From 24b12a99afd2a52b13f3ccc54b5097a74087e2e8 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Wed, 7 Oct 2026 08:24:55 +0800 Subject: [PATCH 13/79] test(editor): expose resolvePublishTarget on the DiffViewProvider safeWriteText mock The guarded-write wiring tests in this spec run through guardedWrite.withWriteLock, which now resolves the publish target before locking. The module mock only provided safeWriteText, so vitest threw 'No "resolvePublishTarget" export is defined on the mock' and the S4b stale-version / recreate cases failed on the ubuntu platform-unit-test lane. The mock now supplies an identity resolver, which keeps this spec's path handling identical. Verified locally: DiffViewProvider.spec.ts 78 passed, guardedWrite.spec.ts 31 passed, eslint clean. --- src/integrations/editor/__tests__/DiffViewProvider.spec.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index c7c961d0216..bf80b4e427f 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -34,6 +34,9 @@ vi.mock("fs/promises", () => ({ // Mock safeWriteText (used by saveDirectly) vi.mock("../../../services/file-safety/safeWriteText", () => ({ safeWriteText: vi.fn().mockResolvedValue(undefined), + // guardedWrite locks the canonical publish target, so the module mock has to + // expose the resolver too; identity keeps this spec's path handling unchanged. + resolvePublishTarget: vi.fn(async (p: string) => p), })) // Mock the S1 version token (used by the S4 guarded write); the real From 4bf7625595b04f832edbf7ef349d77dd56afbbc1 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Wed, 7 Oct 2026 10:36:06 +0800 Subject: [PATCH 14/79] fix(file-safety): back up by copy so a failed write never moves the target backup:true used to rename the target to a backup path, commit the staged file, and rename the backup back if anything failed. That window is the problem CR reported: if the commit rename succeeded but a later step failed, or the rollback rename itself failed, persisted state was missing at the path callers expect - the target had been moved away and could not be put back. The backup is now a copy: the target is copied to safeWriteText.bak_* and the copy is fsynced before the commit, so the canonical path is never absent. A failure before the commit leaves the pre-write content at the target and the copy is dropped; a failure after it leaves the published content and the copy is dropped as well. Nothing is ever renamed back over the target. The fsync of the copy opens it "r+" rather than "r": fsync on a read-only handle is EPERM on Windows. Tests: the success case asserts the copy plus a single (commit) rename; the failed-commit case asserts the target keeps its previous content, only one rename ran, and both the copy and the staging temp are released; the post-commit cleanup case now expects one rename. safeWriteJson's rollback-rename cases are reworked to the copy model, and the rename mocks that used to persist across tests are now mockImplementationOnce. 161 passed / 1 skipped across safeWriteText.spec + safeWriteJson + DiffViewProvider + guardedWrite; tsc and eslint clean on the changed files. --- .../__tests__/safeWriteText.spec.ts | 49 ++++++++++--------- src/services/file-safety/safeWriteText.ts | 46 ++++++++++++----- 2 files changed, 59 insertions(+), 36 deletions(-) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index 7ff90de9650..d58d523d8d1 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -10,6 +10,7 @@ import { safeWriteText, type SafeWriteTextOptions } from "../safeWriteText" vi.mock("fs/promises", () => ({ mkdir: vi.fn(), access: vi.fn(), + copyFile: vi.fn(), rename: vi.fn(), unlink: vi.fn(), realpath: vi.fn(), @@ -175,14 +176,17 @@ describe("safeWriteText", () => { await safeWriteText(targetPath, "data", { backup: true, platform: "linux" }) - // the commit rename (temp -> target) still happened - expect(fs.rename).toHaveBeenNthCalledWith(2, expect.stringContaining("safeWriteText_"), targetPath) + // the commit rename (temp -> target) still happened, and it is the only rename: + // the backup is a copy, so the target was never moved out of the way. + expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath) + expect(fs.rename).toHaveBeenCalledTimes(1) // the failing cleanup was the post-commit backup unlink expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.bak_")) - // no rollback rename: the committed target is not restored from the backup - expect(fs.rename).toHaveBeenCalledTimes(2) + // no rollback rename: the backup is a copy, so nothing is renamed back over + // the committed target. + expect(fs.rename).toHaveBeenCalledTimes(1) // the staging temp was already committed by the rename; nothing // temp-shaped is unlinked afterwards @@ -190,10 +194,10 @@ describe("safeWriteText", () => { }) }) - // ── Test 4: backup:true keeps old safeWriteJson semantics incl. rollback ── + // ── Test 4: backup:true keeps old safeWriteJson semantics, copy-based ── describe("backup:true", () => { - it("renames target -> backup before commit, deletes backup on success", async () => { + it("copies target -> backup before commit without moving the target, and deletes the copy on success", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) vi.mocked(fsSync.openSync).mockReturnValue(1) @@ -203,34 +207,33 @@ describe("safeWriteText", () => { // target was accessed (exists check) expect(fs.access).toHaveBeenCalledWith(targetPath) - // first rename: target -> backup - expect(fs.rename).toHaveBeenNthCalledWith(1, targetPath, expect.stringContaining("safeWriteText.bak_")) + // The backup is a copy: the target never leaves its path, so a reader sees the + // pre-write content for the whole attempt and there is nothing to roll back. + expect(fs.copyFile).toHaveBeenCalledWith(targetPath, expect.stringContaining("safeWriteText.bak_")) - // second rename: temp -> target (realpath mock returns targetPath) - expect(fs.rename).toHaveBeenNthCalledWith(2, expect.stringContaining("safeWriteText_"), targetPath) + // The only rename is the commit: temp -> target. + expect(fs.rename).toHaveBeenCalledTimes(1) + expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath) - // backup was deleted on success + // backup copy was deleted on success expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.bak_")) }) - it("rollback: on failure after rename target->backup, restores backup to target", async () => { + it("a failed commit leaves the pre-write content at the target and drops the backup copy", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) vi.mocked(fsSync.openSync).mockReturnValue(1) - // first rename (target->backup) succeeds, second fails - let callCount = 0 - vi.mocked(fs.rename).mockImplementation(async () => { - callCount++ - if (callCount === 1) return // target -> backup - throw new Error("ENOSPC") // temp -> target fails - }) + // The commit rename is the only rename in this flow, and it fails. + vi.mocked(fs.rename).mockRejectedValue(new Error("ENOSPC")) await expect(safeWriteText(targetPath, "new data", { backup: true })).rejects.toThrow("ENOSPC") - // rollback rename is the 3rd call (after target->backup and temp->target failure) - expect(fs.rename).toHaveBeenNthCalledWith(3, expect.stringContaining("safeWriteText.bak_"), targetPath) - - // temp was cleaned up on failure + // The backup was a copy of the target, taken before the commit. + expect(fs.copyFile).toHaveBeenCalledWith(targetPath, expect.stringContaining("safeWriteText.bak_")) + // No restore: the target was never moved, so no rename can put the copy back. + expect(fs.rename).toHaveBeenCalledTimes(1) + // The copy is dropped and the staging temp is released. + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.bak_")) expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_")) }) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index 7e5a94700ae..678cad6710e 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -8,9 +8,11 @@ import { execFile } from "child_process" */ export interface SafeWriteTextOptions { /** - * When true, preserve the old-file semantics: rename target -> backup first, - * after commit rename delete the backup; on failure roll the backup back to - * the target path. When false (default) the atomic rename simply replaces + * When true, preserve the old-file semantics: copy the target to a backup and + * fsync the copy before the commit, delete the backup after a successful commit, + * and drop the backup on failure. The target is never moved, so a failed write + * leaves the pre-write content at the target path instead of rolling anything + * back. When false (default) the atomic rename simply replaces * the target -- crash-safe window is zero. */ backup?: boolean @@ -110,12 +112,12 @@ async function _restoreDaclWindows(dirPath: string, dumpPath: string, execFileRu * 1. Write content to a temp file in a private per-write staging subdir * (same volume -> atomic rename guaranteed). * 2. fsync the temp file, then close it. - * 3. win32 only: if target exists save its DACL dump BEFORE backup rename. - * 4. Optionally rename target -> backup (when backup:true). + * 3. win32 only: if target exists save its DACL dump BEFORE the backup copy. + * 4. Optionally copy target -> backup (when backup:true) and fsync the copy. * 5. Atomic rename temp -> target. * 6. win32 only: restore DACL onto the directory AFTER commit rename. * 7. On success: delete backup (if any) and unlink DACL dump. - * 8. On failure: rollback backup to target path; clean up temp + dump. + * 8. On failure: drop the backup copy; clean up temp + dump. */ /** @@ -241,12 +243,27 @@ export async function safeWriteText(filePath: string, content: string, options?: } try { - // -- Step 3 (backup:true): rename target -> backup -------------- + // -- Step 3 (backup:true): durable copy target -> backup ---- if (options?.backup) { try { await fs.access(targetPath) backupPath = _tempName(dirPath, "safeWriteText.bak") - await fs.rename(targetPath, backupPath) + try { + await fs.copyFile(targetPath, backupPath) + // "r+" not "r": fsync on a read-only handle is EPERM on Windows, and this is + // the same flag the staged temp file is opened with above. + const backupFd = fsSync.openSync(backupPath, "r+") + try { + _fsyncFile(backupFd) + } finally { + fsSync.closeSync(backupFd) + } + } catch (backupError: unknown) { + // A half-written backup is worse than none: it looks like a restore source. + await fs.unlink(backupPath).catch(() => {}) + backupPath = null + throw backupError + } releaseBackupOnSuccess = true } catch (err: unknown) { const code = @@ -312,11 +329,14 @@ export async function safeWriteText(filePath: string, content: string, options?: } catch (originalError: unknown) { // -- Rollback / cleanup on failure ---------------------------------- if (backupPath && releaseBackupOnSuccess) { - try { - await fs.rename(backupPath, targetPath) - } catch { - // rollback failed — do not mask original error - } + // Nothing to restore: the backup is a copy, so the target still holds whatever + // the commit left there - before the commit that is the pre-write content, and + // after it the published content. Either way the copy has served its purpose + // and must not be left beside the target where no caller can find it. The old + // design renamed the target away and back, which could itself fail and leave + // persisted state missing at its expected path. + await fs.unlink(backupPath).catch(() => {}) + backupPath = null } // Always clean up the staging temp file on failure. From 4c29f967bc014426d85a6361160f3631024fa807 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Wed, 7 Oct 2026 11:00:57 +0800 Subject: [PATCH 15/79] fix(file-safety): make the backup copy writable before fsyncing it fs.copyFile creates the destination with the source's mode. When the target is read-only (0o400/0o444) the copy is read-only too, so opening it "r+" to fsync it fails with EACCES - and because safeWriteJson always asks for a backup, that fails the whole write before the commit rename. The copy is narrowed to 0o600 immediately after it is created and before it is opened. That also keeps a backup of a permissive file from sitting world-readable in the user's directory. Test asserts the copy, the chmod to 0o600 after it, and that the copy is then opened with "r+". --- .../__tests__/safeWriteText.spec.ts | 24 +++++++++++++++++++ src/services/file-safety/safeWriteText.ts | 6 +++++ 2 files changed, 30 insertions(+) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index d58d523d8d1..67f1f6ccf0b 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -11,6 +11,7 @@ vi.mock("fs/promises", () => ({ mkdir: vi.fn(), access: vi.fn(), copyFile: vi.fn(), + chmod: vi.fn(), rename: vi.fn(), unlink: vi.fn(), realpath: vi.fn(), @@ -219,6 +220,29 @@ describe("safeWriteText", () => { expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.bak_")) }) + it("narrows the backup copy to owner read/write before opening it for fsync", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + await safeWriteText(targetPath, "new data", { backup: true }) + + // copyFile creates the destination with the source's mode. A read-only target + // (0o400/0o444) would otherwise make the r+ open below fail with EACCES and fail + // the whole write before the commit - safeWriteJson always asks for a backup. + expect(fs.copyFile).toHaveBeenCalledWith(targetPath, expect.stringContaining("safeWriteText.bak_")) + expect(fs.chmod).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.bak_"), 0o600) + expect(vi.mocked(fs.chmod).mock.invocationCallOrder[0]).toBeGreaterThan( + vi.mocked(fs.copyFile).mock.invocationCallOrder[0], + ) + + // The copy is then opened for fsync with the writable flag. + const backupOpen = vi.mocked(fsSync.openSync).mock.calls.find(function (call) { + return String(call[0]).includes("safeWriteText.bak_") + }) + expect(backupOpen?.[1]).toBe("r+") + }) + it("a failed commit leaves the pre-write content at the target and drops the backup copy", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index 678cad6710e..01ee6a62f4d 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -250,6 +250,12 @@ export async function safeWriteText(filePath: string, content: string, options?: backupPath = _tempName(dirPath, "safeWriteText.bak") try { await fs.copyFile(targetPath, backupPath) + // copyFile creates the destination with the source's mode, so a read-only + // target yields a read-only copy and opening it "r+" would fail with EACCES - + // failing the whole write before the commit. Narrowing the copy to owner + // read/write also keeps a backup of a permissive file from being world + // readable in the user's directory. + await fs.chmod(backupPath, 0o600) // "r+" not "r": fsync on a read-only handle is EPERM on Windows, and this is // the same flag the staged temp file is opened with above. const backupFd = fsSync.openSync(backupPath, "r+") From a9943b17fcddb403e4d2a3a6ab3790cb7b350129 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Wed, 7 Oct 2026 11:18:15 +0800 Subject: [PATCH 16/79] fix(file-safety): create the backup privately before its content exists fs.copyFile chooses the destination mode itself: the platform creation mask subject to umask on some platforms, the source's mode - and its read-only attribute - on others. Letting it create the backup therefore leaves either a window where a restrictive target's bytes sit group/world-readable (a chmod afterwards cannot undo it), or an unwritable copy whose fsync open fails with EACCES. The destination is now created first with "wx" and mode 0o600, so no content ever exists at a path whose mode was chosen by someone else. open() ignores its mode argument for an existing file, so the 0o600 survives the copy on POSIX; the chmod stays to clear a copied read-only attribute on Windows and to keep a backup of a permissive file private. Test asserts the seed open ("wx", 0o600) happens before copyFile, the chmod after it, and the r+ fsync open after that. --- .../__tests__/safeWriteText.spec.ts | 23 ++++++++++++++----- src/services/file-safety/safeWriteText.ts | 16 +++++++++---- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index 67f1f6ccf0b..00055991fe6 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -220,16 +220,27 @@ describe("safeWriteText", () => { expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.bak_")) }) - it("narrows the backup copy to owner read/write before opening it for fsync", async () => { + it("creates the backup privately before its content exists, then fsyncs it", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) vi.mocked(fsSync.openSync).mockReturnValue(1) await safeWriteText(targetPath, "new data", { backup: true }) - // copyFile creates the destination with the source's mode. A read-only target - // (0o400/0o444) would otherwise make the r+ open below fail with EACCES and fail - // the whole write before the commit - safeWriteJson always asks for a backup. + // The destination must exist with a private mode before copyFile writes anything + // into it: copyFile chooses the destination mode itself, so a restrictive target + // could otherwise leave a group/world-readable copy that a later chmod cannot + // undo. "wx" also means a pre-existing path is never silently reused. + const seedOpen = vi.mocked(fsSync.openSync).mock.calls.find(function (call) { + return String(call[0]).includes("safeWriteText.bak_") && call[1] === "wx" + }) + expect(seedOpen).toBeDefined() + expect(seedOpen?.[2]).toBe(0o600) + const seedOrder = vi.mocked(fsSync.openSync).mock.invocationCallOrder[vi.mocked(fsSync.openSync).mock.calls.indexOf(seedOpen!)] + expect(seedOrder).toBeLessThan(vi.mocked(fs.copyFile).mock.invocationCallOrder[0]) + + // The chmod keeps a copied read-only attribute (Windows) from breaking the fsync + // open, and keeps a backup of a permissive file private. expect(fs.copyFile).toHaveBeenCalledWith(targetPath, expect.stringContaining("safeWriteText.bak_")) expect(fs.chmod).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.bak_"), 0o600) expect(vi.mocked(fs.chmod).mock.invocationCallOrder[0]).toBeGreaterThan( @@ -238,9 +249,9 @@ describe("safeWriteText", () => { // The copy is then opened for fsync with the writable flag. const backupOpen = vi.mocked(fsSync.openSync).mock.calls.find(function (call) { - return String(call[0]).includes("safeWriteText.bak_") + return String(call[0]).includes("safeWriteText.bak_") && call[1] === "r+" }) - expect(backupOpen?.[1]).toBe("r+") + expect(backupOpen).toBeDefined() }) it("a failed commit leaves the pre-write content at the target and drops the backup copy", async () => { diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index 01ee6a62f4d..0db781b5790 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -249,12 +249,18 @@ export async function safeWriteText(filePath: string, content: string, options?: await fs.access(targetPath) backupPath = _tempName(dirPath, "safeWriteText.bak") try { + // Create the destination BEFORE any content exists at it, with the mode fixed + // at open time. fs.copyFile picks the destination mode itself (the platform + // creation mask subject to umask on some platforms, the source's mode - or its + // read-only attribute - on others), so letting it create the file would either + // leave a restrictive target's bytes briefly readable to others, or leave the + // copy unwritable so the fsync open below fails with EACCES. open() ignores its + // mode argument for an existing file, so this 0o600 survives the copy on POSIX; + // the chmod afterwards is what clears a copied read-only attribute on Windows + // and keeps a backup of a permissive file private. + const seedFd = fsSync.openSync(backupPath, "wx", 0o600) + fsSync.closeSync(seedFd) await fs.copyFile(targetPath, backupPath) - // copyFile creates the destination with the source's mode, so a read-only - // target yields a read-only copy and opening it "r+" would fail with EACCES - - // failing the whole write before the commit. Narrowing the copy to owner - // read/write also keeps a backup of a permissive file from being world - // readable in the user's directory. await fs.chmod(backupPath, 0o600) // "r+" not "r": fsync on a read-only handle is EPERM on Windows, and this is // the same flag the staged temp file is opened with above. From 8821a2ef063638f49b4cf21f4215d147432fcf68 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Wed, 7 Oct 2026 06:49:21 +0000 Subject: [PATCH 17/79] chore: trigger a fresh review pass at this head From 6e0696697bd0ed7aebefc170f0575c357f4fb90d Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Wed, 7 Oct 2026 18:33:38 +0800 Subject: [PATCH 18/79] fix(core): authorize the focus-disruption apply_diff save with its own read With preventFocusDisruption enabled, apply_diff never opens a diff view, so nothing ever observes the path; the saveDirectly(..., "edit") this unit introduced then failed the unobserved-existing check with "File not read yet -- read the file, then retry." The tool had just read the exact content the hunks were computed against. ApplyDiffTool now stats around that read and records the version token when the file did not change underneath it - the same contract ApplyPatchTool's hunk read already follows in this unit. Tests: the observation carries the token of the read the diff was built from, and a read that straddles a write records nothing (the guarded publish keeps its remediation). Control: disabling the observe fails exactly the first test. Also: the mismatched-token apply_patch test asserted only that handleError ran - it now pins the guard error itself, matching its siblings; and the safeWriteJson catch comment no longer claims a backup is moved back over the target (safeWriteText's backup is a copy that gets deleted). --- src/core/tools/ApplyDiffTool.ts | 16 ++++++ .../applyDiffTool.guardedWrite.spec.ts | 50 +++++++++++++++++++ .../__tests__/applyPatchTool.execute.spec.ts | 2 +- 3 files changed, 67 insertions(+), 1 deletion(-) diff --git a/src/core/tools/ApplyDiffTool.ts b/src/core/tools/ApplyDiffTool.ts index 59f5765d409..c88deef3d5c 100644 --- a/src/core/tools/ApplyDiffTool.ts +++ b/src/core/tools/ApplyDiffTool.ts @@ -9,6 +9,7 @@ import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { Task } from "../task/Task" import { formatResponse } from "../prompts/responses" import { fileExistsAtPath } from "../../utils/fs" +import { versionTokenOfStat } from "../../utils/versionToken" import { RecordSource } from "../context-tracking/FileContextTrackerTypes" import { unescapeHtmlEntities } from "../../utils/text-normalization" import { EXPERIMENT_IDS, experiments } from "../../shared/experiments" @@ -74,7 +75,22 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> { return } + // The diff below is built from this exact read, so the save that follows must be + // authorized against the version captured here - not against whatever version the + // diff view happens to stat afterwards (there is no diff view on the + // focus-disruption path). Same contract as ApplyPatchTool's hunk read: stat + // around the read and observe only when the file did not change underneath it. + // Without it the saveDirectly("edit") below has no observation for the path and the + // guarded publish fails with "File not read yet -- read the file, then retry." + const preReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) const originalContent: string = await fs.readFile(absolutePath, "utf-8") + const postReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) + if (preReadStats && postReadStats) { + const preReadToken = versionTokenOfStat(preReadStats) + if (preReadToken === versionTokenOfStat(postReadStats)) { + task.observationRegistry.observe(absolutePath, preReadToken) + } + } // Apply the diff to the original content const diffResult = (await task.diffStrategy?.applyDiff( diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts index 2181c989413..bc7d3a82768 100644 --- a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -1,14 +1,23 @@ // npx vitest run core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +import path from "path" import type { MockedFunction } from "vitest" import { fileExistsAtPath } from "../../../utils/fs" +import { ObservationRegistry } from "../../task/observationRegistry" import type { Task } from "../../task/Task" import { ApplyDiffTool } from "../ApplyDiffTool" vi.mock("fs/promises", () => ({ default: { readFile: vi.fn().mockResolvedValue("original file content\n"), + stat: vi.fn().mockResolvedValue({ + dev: 7n, + ino: 4242n, + size: 1234n, + mtimeNs: 1700000000123456789n, + ctimeNs: 1700000000789999999n, + }), }, })) @@ -49,6 +58,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { | "diffViewProvider" | "providerRef" | "fileContextTracker" + | "observationRegistry" > let mockSaveDirectly: MockedFunction<(...args: unknown[]) => Promise> let mockAskApproval: MockedFunction<(...args: unknown[]) => Promise> @@ -110,6 +120,9 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { fileContextTracker: { trackFileContext: vi.fn().mockResolvedValue(undefined), } as unknown as Task["fileContextTracker"], + // Real registry: the point of these tests is which version token ends up + // recorded, so a stub would only restate the call. + observationRegistry: new ObservationRegistry(), } mockAskApproval = vi.fn().mockResolvedValue(true) @@ -154,4 +167,41 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { expect(mockTask.didEditFile).toBe(false) expect(mockPushToolResult).not.toHaveBeenCalledWith("Saved file") }) + it("records the version the diff was computed against so the guarded edit is authorized", async () => { + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + // The focus-disruption save has no diff view to observe the file, so the tool read + // itself must leave an observation for the version the hunks were computed against - + // otherwise saveDirectly("edit") rejects with "File not read yet". + const observed = mockTask.observationRegistry.get(path.resolve("/workspace/project", "src/thing.ts")) + expect(observed?.version).toBe("7:4242:1234:1700000000123456789:1700000000789999999") + expect(mockSaveDirectly).toHaveBeenCalledWith( + "src/thing.ts", + "modified file content\n", + false, + true, + 1000, + "edit", + ) + }) + + it("does not observe when the file changes underneath the read", async () => { + const statMock = vi.mocked((await import("fs/promises")).default.stat) + statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n }) + statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 9999n, mtimeNs: 3n, ctimeNs: 4n }) + + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + // A read that straddled a write proves nothing about the current version, so no + // observation may be recorded and the guarded publish keeps its remediation. + expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) + }) }) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 378be79b610..019dde3a947 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -279,7 +279,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { }) expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) - expect(mockHandleError).toHaveBeenCalled() + expect(mockHandleError).toHaveBeenCalledWith("apply patch", guardError) }) it("add: publishes the new file through the guarded saveDirectly with create kind", async () => { From e1c12f61fc1bd2dded7cc0154a8468a794651dde Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Wed, 7 Oct 2026 18:45:26 +0800 Subject: [PATCH 19/79] fix(core): type the stat doubles in the apply_diff observation test check-types rejected the new test: the mocked fs/promises stat is typed as returning Stats | BigIntStats, so the partial bigint literals were not assignable (2 x TS2345). The doubles carry exactly the fields versionTokenOfStat reads; a full BigIntStats cannot be built against the mocked module, so the cast is annotated as the narrowest option - the same shape the sibling suites already use. --- .../__tests__/applyDiffTool.guardedWrite.spec.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts index bc7d3a82768..3416d048b51 100644 --- a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -1,6 +1,7 @@ // npx vitest run core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts import path from "path" +import type { BigIntStats } from "fs" import type { MockedFunction } from "vitest" import { fileExistsAtPath } from "../../../utils/fs" @@ -190,9 +191,16 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { }) it("does not observe when the file changes underneath the read", async () => { + // Only the fields versionTokenOfStat reads; a full BigIntStats cannot be built + // against the mocked fs, so the double assertion is the narrowest option. const statMock = vi.mocked((await import("fs/promises")).default.stat) - statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n }) - statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 9999n, mtimeNs: 3n, ctimeNs: 4n }) + statMock + .mockResolvedValueOnce( + { dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n } as unknown as BigIntStats, + ) + .mockResolvedValueOnce( + { dev: 7n, ino: 4242n, size: 9999n, mtimeNs: 3n, ctimeNs: 4n } as unknown as BigIntStats, + ) await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { askApproval: mockAskApproval, From 5da6fe32ef99b71e4b2e8d8f4b0eadf981c6d929 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Thu, 8 Oct 2026 16:05:50 +0800 Subject: [PATCH 20/79] fix(file-safety): verify the guard at commit time and clean the staging dir on failure Addresses the Pre-merge check items raised against 106b9f02e. Persistence Integrity: replaceIfVersion compared the version token and then published as separate operations. The advisory lock serializes only writers that honor it, so a writer that does not can rewrite the file during the staging + fsync span and have its newer content replaced by the older version. safeWriteText now takes a preCommitVerify hook that runs after staging and fsync and immediately BEFORE the commit rename; replaceIfVersion re-computes the token there and createIfAbsent re-asserts absence, so the race window shrinks to the rename syscall and a lost update surfaces as a rejected stale write instead of a silent overwrite. The doc comment states plainly that this is not an atomic compare-and-swap: no portable rename primitive compares on-disk content against an expectation, so full atomicity would need a content-addressed publish or a lock every writer in the ecosystem honors - neither is enforceable from this layer. Lifecycle Resource Cleanup: a failed write removed its temp file but left an empty .file-safety-staging directory in the user's workspace until some later successful write removed it. The failure path now rmdirs it; rmdir only removes an empty directory, so a concurrent write still holding a temp file keeps it in place. Regression Evidence: ApplyDiffTool and ApplyPatchTool each gain pre-read and post-read fs.stat rejection tests (readFile succeeds): the read/patch still runs, no observation is recorded from a read whose version is unknown, and the unauthorized publish is surfaced as a handled error rather than a saved file. safeWriteText gains a failure-path test for the staging directory and a preCommitVerify test proving the commit rename is skipped and the target left untouched; guardedWrite gains tests that both guards hand safeWriteText a verifier and that it rejects when the state moved during staging. Local: tsc --noEmit clean (0 errors); safeWriteText 32, guardedWrite 33, applyDiff guard 6, applyPatch execute 10 passed; eslint clean on all six files. --- .../applyDiffTool.guardedWrite.spec.ts | 49 +++++++++++++++ .../__tests__/applyPatchTool.execute.spec.ts | 42 +++++++++++++ src/core/tools/__tests__/guardedWrite.spec.ts | 61 ++++++++++++++---- src/core/tools/guardedWrite.ts | 62 +++++++++++++++++-- .../__tests__/safeWriteText.spec.ts | 35 +++++++++++ src/services/file-safety/safeWriteText.ts | 37 +++++++++++ 6 files changed, 270 insertions(+), 16 deletions(-) diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts index 3416d048b51..b6310fd5094 100644 --- a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -211,5 +211,54 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { // A read that straddled a write proves nothing about the current version, so no // observation may be recorded and the guarded publish keeps its remediation. expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) + }) + it.each(["pre-read", "post-read"])( + "continues the read and records no observation when the %s stat fails", + async (which) => { + const statMock = vi.mocked((await import("fs/promises")).default.stat) + const stable = { + dev: 7n, + ino: 4242n, + size: 1234n, + mtimeNs: 1700000000123456789n, + ctimeNs: 1700000000789999999n, + } as unknown as BigIntStats + const failure = new Error("EACCES: permission denied") + if (which === "pre-read") { + statMock.mockRejectedValueOnce(failure).mockResolvedValueOnce(stable) + } else { + statMock.mockResolvedValueOnce(stable).mockRejectedValueOnce(failure) + } + + // With no observation the guarded publish refuses, which is what the second half + // of this assertion checks. + const guardError = new Error("File not read yet -- read the file, then retry.") + mockSaveDirectly.mockRejectedValue(guardError) + + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + // A stat failure is not evidence the file changed and not a reason to abort: the + // diff still ran against the content that WAS read successfully. + expect(mockSaveDirectly).toHaveBeenCalledWith( + "src/thing.ts", + "modified file content\n", + false, + true, + 1000, + "edit", + ) + // Nothing may be observed from a read whose version is unknown. + expect( + mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts")), + ).toBe(false) + // And the refused publish surfaces as an error rather than a saved file. + expect(mockHandleError).toHaveBeenCalledWith("applying diff", guardError) + expect(mockPushToolResult).not.toHaveBeenCalledWith("Saved file") + }, + ) }) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 019dde3a947..265e5ab919b 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -282,6 +282,48 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { expect(mockHandleError).toHaveBeenCalledWith("apply patch", guardError) }) + it.each(["pre-read", "post-read"])( + "update: continues the hunk read and records no observation when the %s stat fails", + async (which) => { + const statMock = mockedFsPromises.default.stat + const stable = { + dev: 7n, + ino: 4242n, + size: 1234n, + mtimeNs: 1700000000123456789n, + ctimeNs: 1700000000789999999n, + } + const failure = new Error("EACCES: permission denied") + if (which === "pre-read") { + statMock.mockRejectedValueOnce(failure).mockResolvedValueOnce(stable) + } else { + statMock.mockResolvedValueOnce(stable).mockRejectedValueOnce(failure) + } + + const guardError = new Error( + "File already exists at /workspace/project/src/thing.ts and was not read before this write -- read the file first, then retry.", + ) + mockSaveDirectly.mockRejectedValue(guardError) + + await tool.execute({ patch: updatePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + // A stat failure is not evidence the file changed and not a reason to abort the + // read: the hunk was still processed against the content that was read. + expect(mockSaveDirectly).toHaveBeenCalledTimes(1) + // But a read whose version is unknown may not be observed... + expect( + mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts")), + ).toBe(false) + // ...and the publish it leaves unauthorized is reported as an error, not a save. + expect(mockHandleError).toHaveBeenCalledWith("apply patch", guardError) + expect(mockPushToolResult).not.toHaveBeenCalledWith("Saved file") + }, + ) + it("add: publishes the new file through the guarded saveDirectly with create kind", async () => { mockedFileExistsAtPath.mockResolvedValueOnce(false) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index 8da4ea08026..af09c072184 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -88,7 +88,7 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "new-file.txt", "hello", "create") expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("new-file.txt"), "hello") + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("new-file.txt"), "hello", { preCommitVerify: expect.any(Function) }) }) it("fails with the read-first remediation when the file exists - nothing published", async () => { @@ -145,7 +145,7 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "new-file.txt", "hello", "update") - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("new-file.txt"), "hello") + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("new-file.txt"), "hello", { preCommitVerify: expect.any(Function) }) }) it("fails with the read-first remediation when the file exists - nothing published", async () => { @@ -171,7 +171,7 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "gone.txt", "back", "create") expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("gone.txt"), "back") + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("gone.txt"), "back", { preCommitVerify: expect.any(Function) }) }) it("goes through the version guard when the file still exists", async () => { @@ -183,7 +183,7 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "kept.txt", "rewritten", "create") - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("kept.txt"), "rewritten") + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("kept.txt"), "rewritten", { preCommitVerify: expect.any(Function) }) }) it("fails with the stale remediation suffix when the version moved", async () => { @@ -223,7 +223,7 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "doc.txt", "new content", "update") expect(mockedComputeVersionToken).toHaveBeenCalledWith(abs("doc.txt")) - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "new content") + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "new content", { preCommitVerify: expect.any(Function) }) }) it("fails with the stale remediation suffix when the version moved - nothing published", async () => { @@ -259,7 +259,7 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "doc.txt", "patched", "edit") - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "patched") + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "patched", { preCommitVerify: expect.any(Function) }) }) it("fails with the stale remediation suffix when the version moved", async () => { @@ -292,7 +292,7 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "created.txt", "again", "update") expect(mockedSafeWriteText).toHaveBeenCalledTimes(2) - expect(mockedSafeWriteText).toHaveBeenLastCalledWith(abs("created.txt"), "again") + expect(mockedSafeWriteText).toHaveBeenLastCalledWith(abs("created.txt"), "again", { preCommitVerify: expect.any(Function) }) }) it("replaces the read-time token after a successful update", async () => { @@ -380,7 +380,7 @@ describe("guardedWrite (S4a, epic #1375)", () => { await expect(p2).resolves.toBeUndefined() expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("settle.txt"), "second") + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("settle.txt"), "second", { preCommitVerify: expect.any(Function) }) }) it("evicts settled chain entries - a later write still serializes in order", async () => { @@ -434,7 +434,7 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "sub/dir.txt", "content", "update") - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("sub/dir.txt"), "content") + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("sub/dir.txt"), "content", { preCommitVerify: expect.any(Function) }) }) it("normalizes an already-absolute input (trailing separator) to the observation key", async () => { @@ -451,7 +451,7 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, canonical + "/", "content", "update") expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) - expect(mockedSafeWriteText).toHaveBeenCalledWith(canonical, "content") + expect(mockedSafeWriteText).toHaveBeenCalledWith(canonical, "content", { preCommitVerify: expect.any(Function) }) }) it("serializes two spellings of one file through a single chain key", async () => { @@ -493,7 +493,7 @@ describe("guardedWrite (S4a, epic #1375)", () => { resetChain() await guardedWrite(task, "x.txt", "b", "update") - expect(mockedSafeWriteText).toHaveBeenLastCalledWith(abs("x.txt"), "b") + expect(mockedSafeWriteText).toHaveBeenLastCalledWith(abs("x.txt"), "b", { preCommitVerify: expect.any(Function) }) }) }) @@ -539,7 +539,7 @@ describe("guardedWrite (S4a, epic #1375)", () => { expect(mockedAcquireFileLock).not.toHaveBeenCalledWith(alias) // The publish still goes through the path the caller (and safeWriteText's own // resolution) owns, so the observation key and symlink semantics are unchanged. - expect(mockedSafeWriteText).toHaveBeenCalledWith(alias, "new") + expect(mockedSafeWriteText).toHaveBeenCalledWith(alias, "new", { preCommitVerify: expect.any(Function) }) }) it("releases the lock when the guard rejects as stale", async () => { @@ -558,6 +558,43 @@ describe("guardedWrite (S4a, epic #1375)", () => { expect(order).toEqual(["acquire", "release"]) }) + it("re-checks the version token immediately before the commit rename", async () => { + // The pre-flight check passes, then a writer that ignores the advisory lock + // rewrites the file while the staged copy is being written and fsynced. + mockedComputeVersionToken.mockResolvedValueOnce("v1").mockResolvedValueOnce("v2") + + await replaceIfVersion(abs("x.txt"), "v1", "new") + + // The publish is handed a verifier, so the comparison runs after staging and fsync + // rather than only before them: the race window shrinks to the commit syscall, and + // a newer version cannot be replaced by an older one without the write being refused. + const verifier = mockedSafeWriteText.mock.calls[0]?.[2]?.preCommitVerify + expect(verifier).toBeTypeOf("function") + if (verifier) { + await expect(verifier(abs("x.txt"))).rejects.toThrow(/Stale version at commit time/) + } + }) + + it("re-asserts absence immediately before the commit rename", async () => { + mockedComputeVersionToken.mockResolvedValue("v1") + // Guard check: the file is absent, so the create is allowed to proceed. + mockedFsAccess.mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + + await createIfAbsent(abs("new.txt"), "content") + + const verifier = mockedSafeWriteText.mock.calls[0]?.[2]?.preCommitVerify + expect(verifier).toBeTypeOf("function") + if (verifier) { + // Still absent: the commit may land. + mockedFsAccess.mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + await expect(verifier(abs("new.txt"))).resolves.toBeUndefined() + // Created by someone during the staging span: the commit must be refused rather + // than clobbering whoever created the file. + mockedFsAccess.mockResolvedValueOnce(undefined) + await expect(verifier(abs("new.txt"))).rejects.toThrow(/appeared at/) + } + }) + it("holds the lock across the absence check and the create publish", async () => { const order: string[] = [] releaseMock = async () => { diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index 5541d4c944b..a3b396600ac 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -143,8 +143,29 @@ export async function createIfAbsent(absolutePath: string, content: string): Pro throw error } // Absent under the lock: no other lock-honoring writer can create it between - // this check and the publish. - await safeWriteText(absolutePath, content) + // this check and the publish. A writer that does NOT honor the advisory lock can + // still create the file while the staged copy is being written and fsynced, so + // absence is re-asserted inside safeWriteText immediately before the commit + // rename: the window then covers only that syscall, and the race surfaces as a + // rejected write instead of silently clobbering whoever created the file. + await safeWriteText(absolutePath, content, { + preCommitVerify: async (targetPath) => { + try { + await fs.access(targetPath) + } catch (error: unknown) { + if (errorCode(error) === "ENOENT") { + return + } + throw error + } + throw new GuardRejectedError( + "File appeared at " + + targetPath + + " while this write was being staged -- read the file first, then retry.", + absolutePath, + ) + }, + }) // Recomputed under the same lock: the caller records this as the new // observation, so a later write is compared against what this publish // actually wrote rather than against no observation at all. @@ -196,8 +217,41 @@ export async function replaceIfVersion( if (currentVersion === expectedVersion) { // The check and the publish run under the same lock, so the token cannot - // change between them for any writer that honors it. - await safeWriteText(absolutePath, content) + // change between them for any writer that honors it. A writer that does NOT + // honor the advisory lock can still rewrite the file while the staged copy is + // being written and fsynced, so the token is re-checked inside safeWriteText + // immediately before the commit rename: the window then covers only that + // syscall, and the race surfaces as a rejected stale write instead of a newer + // version being replaced by the older one. + await safeWriteText(absolutePath, content, { + preCommitVerify: async (targetPath) => { + let verifiedVersion: string + try { + verifiedVersion = await computeVersionToken(targetPath) + } catch (error: unknown) { + if (errorCode(error) === "ENOENT") { + throw new GuardRejectedError( + "File was deleted after it was read -- the version recorded at read time (" + + expectedVersion + + ") no longer exists; re-read the file, then retry.", + absolutePath, + ) + } + throw error + } + if (verifiedVersion !== expectedVersion) { + throw new GuardRejectedError( + "Stale version at commit time -- the file changed while this write was being " + + "staged (expected " + + expectedVersion + + ", current " + + verifiedVersion + + "); re-read the file, then retry.", + absolutePath, + ) + } + }, + }) // The publish moved the token; hand the new one back so the caller can // record it instead of leaving the read-time token in the registry. return computeVersionToken(absolutePath) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index 00055991fe6..58bd41f37b5 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -166,6 +166,41 @@ describe("safeWriteText", () => { expect(fs.rename).toHaveBeenCalledTimes(1) }) + it("removes the empty staging directory when the commit fails", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + vi.mocked(fs.rename).mockRejectedValue(new Error("ENOSPC")) + + await expect(safeWriteText(targetPath, "new data", { platform: "linux" })).rejects.toThrow("ENOSPC") + + // The temp file is gone, so the staging directory it was created for is empty. + // Leaving it behind puts hidden clutter in the user's workspace until some later + // successful write happens to remove it. + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_")) + expect(fs.rmdir).toHaveBeenCalledWith(expect.stringContaining(".file-safety-staging")) + }) + + it("a preCommitVerify rejection skips the commit rename and leaves the target untouched", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + const verify = vi.fn(async () => { + throw new Error("Stale version at commit time") + }) + + await expect( + safeWriteText(targetPath, "new data", { platform: "linux", preCommitVerify: verify }), + ).rejects.toThrow("Stale version at commit time") + + // The verifier runs after staging and fsync but before the rename, so the target + // was never moved and the staged content was cleaned up. + expect(verify).toHaveBeenCalledWith(targetPath) + expect(fs.rename).not.toHaveBeenCalled() + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_")) + expect(fs.rmdir).toHaveBeenCalledWith(expect.stringContaining(".file-safety-staging")) + }) + it("a post-commit backup cleanup failure is non-fatal: the target stays committed and no temp is left behind", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index 0db781b5790..bf9ce41d5c0 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -37,6 +37,24 @@ export interface SafeWriteTextOptions { * already written data to a temp file via a custom stream. */ tempPath?: string + + /** + * Verification that runs AFTER the staged copy is written and fsynced and IMMEDIATELY + * BEFORE the commit rename. A guard that has to compare on-disk state against an + * expectation (a version token, or absence) cannot do that before the staging work: + * the window between check and publish would then span the whole staging + fsync + * sequence. Running the check here shrinks it to the rename syscall itself. A + * rejection skips the commit rename, so the target is left exactly as it was and the + * staged temp is cleaned up by the failure path. + * + * This is not an atomic compare-and-swap. No portable rename primitive compares the + * on-disk CONTENT against an expectation, so a writer that neither takes the advisory + * lock nor goes through this path can still change the file inside that last window. + * The guard narrows the window and turns a silent lost update into a rejected write; + * full atomicity would need a content-addressed publish (or a lock every writer in + * the ecosystem honors), which this layer cannot enforce from outside. + */ + preCommitVerify?: (targetPath: string) => Promise } // -- helpers --------------------------------------------------------------- @@ -286,6 +304,13 @@ export async function safeWriteText(filePath: string, content: string, options?: } } + // -- Step 3a: pre-commit verification ------------------------- + // Runs before the commit rename so a rejection leaves the target untouched - + // no backup is taken and nothing is moved yet. + if (options?.preCommitVerify) { + await options.preCommitVerify(targetPath) + } + // -- Step 4: atomic rename temp -> target --------------------- await fs.rename(tempPath, targetPath) @@ -358,6 +383,18 @@ export async function safeWriteText(filePath: string, content: string, options?: // cleanup failure is non-fatal } + // The staging directory was created for this write's temp file, so a failed write + // must not leave an empty .file-safety-staging in the user's workspace. rmdir only + // removes an empty directory, so a concurrent write still holding a temp file here + // keeps it in place. + if (stagingDir !== null) { + try { + await fs.rmdir(stagingDir) + } catch { + // best-effort: non-empty (concurrent write) or already removed + } + } + if (daclDumpPath !== null) { await fs.unlink(daclDumpPath).catch(() => {}) } From 6cd0d0679037bf529efd9ffa923d210df585f6b8 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Thu, 8 Oct 2026 16:14:53 +0800 Subject: [PATCH 21/79] test(editor): expect the commit verifier on the guarded saveDirectly publish platform-unit-test failed at 43a0870f9: DiffViewProvider.saveDirectly routes its guarded edit through guardedWrite, and the guards now hand safeWriteText a preCommitVerify hook, so the five assertions pinning the publish still expected two arguments. They now expect the verifier as the third, which is the behavior the previous commit introduced. Local: DiffViewProvider 78 passed; integrations + core/tools + services/file-safety + activate lanes 1285 passed / 17 skipped across 61 files. --- .../editor/__tests__/DiffViewProvider.spec.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index bf80b4e427f..106c35b510b 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -834,7 +834,7 @@ describe("DiffViewProvider", () => { // Verify file was written via safeWriteText const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") - expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content") + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function) }) // Verify file was opened without focus expect(vscode.window.showTextDocument).toHaveBeenCalledWith( @@ -857,7 +857,7 @@ describe("DiffViewProvider", () => { // Verify file was written via safeWriteText const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") - expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content") + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function) }) // Verify file was NOT opened expect(vscode.window.showTextDocument).not.toHaveBeenCalled() @@ -872,7 +872,7 @@ describe("DiffViewProvider", () => { // Verify file was written via safeWriteText const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") - expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content") + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function) }) // Verify delay was NOT called expect(mockDelay).not.toHaveBeenCalled() @@ -918,7 +918,7 @@ describe("DiffViewProvider", () => { await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) - expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content") + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function) }) }) it("holds the lock across the guard check and the publish", async () => { @@ -966,7 +966,7 @@ describe("DiffViewProvider", () => { await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) - expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content") + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function) }) }) it("fails closed when the owning task has been collected", async () => { From 77a95486b5f0664c727fb466b39aa3f9dfcc5cb1 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Thu, 8 Oct 2026 16:31:41 +0800 Subject: [PATCH 22/79] test(tools): pin that both stat reads happen when one fails ApplyDiffTool.execute performs a pre-read and a post-read fs.stat. The it.each test queued one rejection and one success but never asserted that both calls were consumed, so a regression that skipped a read would still pass and leave a mockResolvedValueOnce value queued - beforeEach uses clearAllMocks, which clears call history but not queued one-time values, so the leftover would silently shape the next test. Local: applyDiffTool.guardedWrite 6 passed; eslint clean. --- src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts index b6310fd5094..daf5320d0a9 100644 --- a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -242,6 +242,11 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { pushToolResult: mockPushToolResult, }) + // Both stat calls must be consumed: beforeEach only clears call history, so a + // queued mockResolvedValueOnce would leak into the next test if the tool ever + // skipped one of the reads. + expect(statMock).toHaveBeenCalledTimes(2) + // A stat failure is not evidence the file changed and not a reason to abort: the // diff still ran against the content that WAS read successfully. expect(mockSaveDirectly).toHaveBeenCalledWith( From 530b3a8360ad941d57cd2419cb84b9aa256a68ab Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Thu, 8 Oct 2026 20:53:57 +0800 Subject: [PATCH 23/79] fix(tools): stop a queued guarded write once its task is disposed, and pin the move failure path Lifecycle Resource Cleanup: the per-path FIFO chain in guardedWrite runs a link when it reaches the head of the queue, which can be long after the task that issued the write is gone (panel closed, task switched, abort landed while another write held the path). The link then published for a task that no longer serves requests and re-observed the path. guardedWrite now checks task.abort - the same flag Task.dispose() sets synchronously (Task.disposeOnce) - and throws CancelledTaskWriteError before any I/O. Regression Evidence: the guarded move path had only positive coverage. Added the negative case - a destination publish that rejects must route through handleError("apply patch", err), reset the diff view, leave didEditFile false and push no success result. Tests: 'does not publish a queued write after the issuing task is disposed' (first link gated, abort lands while the second is queued, only the first content reaches safeWriteText) and 'refuses an already-cancelled task's write before any I/O'. Pin: deleting the task.abort check fails both. Local: applyPatchTool.execute.spec + guardedWrite.spec + DiffViewProvider.spec = 124 passed; tsc --noEmit 0; eslint 0 err / 0 warn on all three files. --- .../__tests__/applyPatchTool.execute.spec.ts | 21 +++++++++ src/core/tools/__tests__/guardedWrite.spec.ts | 45 +++++++++++++++++-- src/core/tools/guardedWrite.ts | 26 +++++++++++ 3 files changed, 89 insertions(+), 3 deletions(-) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 265e5ab919b..f1dced2d546 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -365,6 +365,27 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { expect(mockHandleError).not.toHaveBeenCalled() }) + it("move: surfaces a guarded destination publish failure as a tool error", async () => { + const publishError = new Error( + "Stale version at commit time -- the file changed while this write was being staged; re-read the file, then retry.", + ) + mockSaveDirectly.mockRejectedValue(publishError) + + await tool.execute({ patch: movePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + // The destination saveDirectly is the guarded publish for a move: a failure there + // must route through handleError, reset the diff view, and leave no success result + // (the source file stays where it was). + expect(mockHandleError).toHaveBeenCalledWith("apply patch", publishError) + expect(vi.mocked(mockTask.diffViewProvider.reset)).toHaveBeenCalled() + expect(mockTask.didEditFile).toBe(false) + expect(mockPushToolResult).not.toHaveBeenCalledWith("Saved file") + }) + it("update: surfaces the unobserved-existing remediation as a tool error", async () => { const guardError = new Error( "File already exists at /workspace/project/src/thing.ts and was not read before this write -- read the file first, then retry.", diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index af09c072184..68cc11f4253 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -60,14 +60,15 @@ interface MockTaskOptions { } /** - * Minimal structural Task: guardedWrite only reads task.cwd and - * task.observationRegistry. The real Task constructor needs the full provider - * machinery, so a single documented double cast stands in for the class. + * Minimal structural Task: guardedWrite reads task.cwd, task.observationRegistry and + * task.abort (the flag Task.dispose() sets). The real Task constructor needs the + * full provider machinery, so a single documented double cast stands in for the class. */ function createMockTask(options: MockTaskOptions = {}): Task { const task = { cwd: options.cwd ?? WORKSPACE, observationRegistry: options.observationRegistry ?? new ObservationRegistry(), + abort: false, } return task as unknown as Task } @@ -617,4 +618,42 @@ describe("guardedWrite (S4a, epic #1375)", () => { expect(order).toEqual(["acquire", "check", "publish", "release"]) }) }) + + describe("cancellation while queued (S4b lifecycle)", () => { + it("does not publish a queued write after the issuing task is disposed", async () => { + mockedFsAccess.mockRejectedValue({ code: "ENOENT" }) + mockedComputeVersionToken.mockResolvedValue("v1") + // The first link holds the path's chain, so the second write is genuinely queued. + let releaseFirst: () => void = () => {} + const firstGate = new Promise(function (resolve) { + releaseFirst = resolve + }) + mockedSafeWriteText.mockImplementationOnce(async () => { + await firstGate + }) + const task = createMockTask() + const first = guardedWrite(task, "queued.txt", "first", "create") + const second = guardedWrite(task, "queued.txt", "second", "create") + // Let the first link enter the publish (the chain runs on microtasks) before the + // disposal lands: Task.dispose() sets task.abort while the second write is still + // queued behind it. + await new Promise(function (resolve) { + setImmediate(resolve) + }) + task.abort = true + releaseFirst() + await first + await expect(second).rejects.toThrow(/was cancelled/) + // Only the first write published; the cancelled one touched nothing. + expect(mockedSafeWriteText.mock.calls.map(function (call) { return call[1] })).toEqual(["first"]) + }) + + it("refuses an already-cancelled task's write before any I/O", async () => { + const task = createMockTask() + task.abort = true + await expect(guardedWrite(task, "gone.txt", "x", "create")).rejects.toThrow(/was cancelled/) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + expect(mockedFsAccess).not.toHaveBeenCalled() + }) + }) }) diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index a3b396600ac..1aca8bd3819 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -39,6 +39,24 @@ class GuardRejectedError extends Error { } } +/** + * A queued guarded write reached the head of its path's chain after the task that + * issued it had already been aborted or disposed. Task.dispose() sets the same + * `abort` flag that abortTask() sets, so that flag is the disposal signal visible + * at this layer. + */ +export class CancelledTaskWriteError extends Error { + readonly path: string + constructor(absolutePath: string) { + super( + `Guarded write for ${absolutePath} was cancelled -- the task was aborted or disposed ` + + "before its turn in the per-path write queue; nothing was published.", + ) + this.name = "CancelledTaskWriteError" + this.path = absolutePath + } +} + // -- Per-path tail-promise chain -------------------------------------------- /** @@ -322,6 +340,14 @@ export async function guardedWrite( const obs = task.observationRegistry.get(absolutePath) return enqueue(absolutePath, async () => { + // The link can reach the head of the queue long after the task that issued it is + // gone (panel closed, task switched, abort landed while another write held the + // path). Running it then would publish for a task that no longer serves requests + // and re-observe the path, so the write stops here instead. + if (task.abort) { + throw new CancelledTaskWriteError(absolutePath) + } + let publishedVersion: string if (obs === undefined) { From e1d6841e968b158cc7bedd8def43332a6b85c44a Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Fri, 9 Oct 2026 07:16:04 +0800 Subject: [PATCH 24/79] test(tools): cover the commit-time verifiers in guardedWrite Regression Evidence: createIfAbsent rethrows non-ENOENT errors from its preCommitVerify access check (guardedWrite.ts:169-185) and replaceIfVersion turns a commit-time ENOENT into the re-read remediation (guardedWrite.ts:244-259). Neither callback had ever been invoked by a test, so all three branches were unexercised. Added a describe that mocks safeWriteText so it actually runs the callback the way the real publish does (after staging, immediately before the commit rename), then asserts: a non-ENOENT access error propagates unchanged; a file that appears at commit time is rejected with the appeared-while-staging verdict; and a commit-time ENOENT on the observed update path becomes the re-read-then-retry remediation. Negative controls, as measured: swallowing every error in the create verifier -> exactly 1 failed (the propagation test); disabling the update verifier's ENOENT branch -> exactly 1 failed (the remediation test). Production restored byte-identical. The appeared-at-commit test has no dedicated control yet. Local: guardedWrite.spec 38 passed; src-level tsc --noEmit 0; eslint 0 err / 0 warn. --- src/core/tools/__tests__/guardedWrite.spec.ts | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index 68cc11f4253..fd364cf12a3 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -657,3 +657,47 @@ describe("guardedWrite (S4a, epic #1375)", () => { }) }) }) + +describe("commit-time verifier (S4a, epic #1375)", () => { + beforeEach(() => { + vi.resetAllMocks() + resetChain() + mockedSafeWriteText.mockImplementation((async (p: string, _c: string, options: { preCommitVerify?: (target: string) => Promise }) => { + // Run the verifier the way safeWriteText does: after staging, immediately before the + // commit rename. Without this the callback would never execute and the assertions below + // would pass against a verifier that was never called. + await options.preCommitVerify?.(p) + return undefined + }) as never) + }) + + it("propagates a non-ENOENT access error from the create verifier instead of publishing", async () => { + const ioError = Object.assign(new Error("EACCES"), { code: "EACCES" }) + mockedFsAccess.mockRejectedValueOnce({ code: "ENOENT" }) + mockedFsAccess.mockRejectedValueOnce(ioError) + const task = createMockTask() + + await expect(guardedWrite(task, "new-file.txt", "hello", "create")).rejects.toBe(ioError) + }) + + it("rejects when the file appears at commit time on the create path", async () => { + mockedFsAccess.mockRejectedValueOnce({ code: "ENOENT" }) + mockedFsAccess.mockResolvedValue(undefined) + const task = createMockTask() + + await expect(guardedWrite(task, "new-file.txt", "hello", "create")).rejects.toThrow(/File appeared at/) + }) + + it("converts a commit-time ENOENT on the observed update path into the re-read remediation", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("doc.txt"), "v1") + const task = createMockTask({ observationRegistry: reg }) + mockedFsAccess.mockResolvedValue(undefined) + // The guard's read-time check runs first, then the commit-time verifier re-computes the + // token: the first call is the guard, the second is the verifier finding the file gone. + mockedComputeVersionToken.mockResolvedValueOnce("v1") + mockedComputeVersionToken.mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) + + await expect(guardedWrite(task, "doc.txt", "new content", "update")).rejects.toThrow(/no longer exists; re-read the file, then retry/) + }) +}) \ No newline at end of file From 825af6f60a9f8c1c6f8a695d2a6b789788722e87 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Sun, 11 Oct 2026 07:38:12 +0800 Subject: [PATCH 25/79] fix(test): drop the duplicate Task import the merge with main left behind Both this branch and main added an identical type-only import of Task to readFileTool.spec.ts at different positions, so the auto-merge kept both copies and vite:oxc rejected the file with a redeclaration parse error. That is what turned platform-unit-test (ubuntu-latest) red and cancelled the windows leg; the defect is visible at the head because the head already contains main. Keep the copy beside the ToolUse import that main added and drop the second one. The import is type-only, so no runtime behaviour changes, and the merged suppression entry for this file (95) still matches: eslint --max-warnings=0 passes on every touched file without pruning. --- src/core/tools/__tests__/readFileTool.spec.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 2877cbda1d8..4e1913e88c5 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -22,7 +22,6 @@ import { readFileTool } from "../ReadFileTool" import type { Stats } from "fs" import type { LegacyReadFileParams } from "@roo-code/types" import { readFileTool, ReadFileTool } from "../ReadFileTool" -import type { Task } from "../../task/Task" import { ObservationRegistry } from "../../task/observationRegistry" import { computeVersionToken } from "../../../utils/versionToken" import { formatResponse } from "../../prompts/responses" From ccc859430eb87890789728c1a6eb35e72926c684 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Sun, 11 Oct 2026 07:47:54 +0800 Subject: [PATCH 26/79] style: reformat the guarded-write files to prettier output The compile job now starts with pnpm format:check, a repo-wide prettier run on the merge commit, so the gate lands on this branch whether or not a unit touched a formatter. All seven files here are inside this pull request's own diff and were already prettier-dirty at the branch tip before main was merged in; main's copies of the four that exist there are clean, so the dirt is ours and the fix belongs in this pull request. Each committed blob is byte-identical to prettier --write of the previous head blob, so this commit changes whitespace and line breaks only. The affected specs pass unchanged after the reflow. --- .../applyDiffTool.guardedWrite.spec.ts | 25 ++++--- .../__tests__/applyPatchTool.execute.spec.ts | 4 +- src/core/tools/__tests__/guardedWrite.spec.ts | 68 ++++++++++++++----- .../editor/__tests__/DiffViewProvider.spec.ts | 29 +++++--- .../__tests__/safeWriteText.spec.ts | 4 +- 5 files changed, 90 insertions(+), 40 deletions(-) diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts index daf5320d0a9..2f2dba2acc1 100644 --- a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -195,12 +195,20 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { // against the mocked fs, so the double assertion is the narrowest option. const statMock = vi.mocked((await import("fs/promises")).default.stat) statMock - .mockResolvedValueOnce( - { dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n } as unknown as BigIntStats, - ) - .mockResolvedValueOnce( - { dev: 7n, ino: 4242n, size: 9999n, mtimeNs: 3n, ctimeNs: 4n } as unknown as BigIntStats, - ) + .mockResolvedValueOnce({ + dev: 7n, + ino: 4242n, + size: 1234n, + mtimeNs: 1n, + ctimeNs: 2n, + } as unknown as BigIntStats) + .mockResolvedValueOnce({ + dev: 7n, + ino: 4242n, + size: 9999n, + mtimeNs: 3n, + ctimeNs: 4n, + } as unknown as BigIntStats) await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { askApproval: mockAskApproval, @@ -211,7 +219,6 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { // A read that straddled a write proves nothing about the current version, so no // observation may be recorded and the guarded publish keeps its remediation. expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) - }) it.each(["pre-read", "post-read"])( "continues the read and records no observation when the %s stat fails", @@ -258,9 +265,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { "edit", ) // Nothing may be observed from a read whose version is unknown. - expect( - mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts")), - ).toBe(false) + expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) // And the refused publish surfaces as an error rather than a saved file. expect(mockHandleError).toHaveBeenCalledWith("applying diff", guardError) expect(mockPushToolResult).not.toHaveBeenCalledWith("Saved file") diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index f1dced2d546..ef8c9d4803b 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -315,9 +315,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { // read: the hunk was still processed against the content that was read. expect(mockSaveDirectly).toHaveBeenCalledTimes(1) // But a read whose version is unknown may not be observed... - expect( - mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts")), - ).toBe(false) + expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) // ...and the publish it leaves unauthorized is reported as an error, not a save. expect(mockHandleError).toHaveBeenCalledWith("apply patch", guardError) expect(mockPushToolResult).not.toHaveBeenCalledWith("Saved file") diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index fd364cf12a3..3325707353d 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -60,9 +60,9 @@ interface MockTaskOptions { } /** - * Minimal structural Task: guardedWrite reads task.cwd, task.observationRegistry and - * task.abort (the flag Task.dispose() sets). The real Task constructor needs the - * full provider machinery, so a single documented double cast stands in for the class. + * Minimal structural Task: guardedWrite reads task.cwd, task.observationRegistry and + * task.abort (the flag Task.dispose() sets). The real Task constructor needs the + * full provider machinery, so a single documented double cast stands in for the class. */ function createMockTask(options: MockTaskOptions = {}): Task { const task = { @@ -89,7 +89,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "new-file.txt", "hello", "create") expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("new-file.txt"), "hello", { preCommitVerify: expect.any(Function) }) + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("new-file.txt"), "hello", { + preCommitVerify: expect.any(Function), + }) }) it("fails with the read-first remediation when the file exists - nothing published", async () => { @@ -146,7 +148,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "new-file.txt", "hello", "update") - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("new-file.txt"), "hello", { preCommitVerify: expect.any(Function) }) + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("new-file.txt"), "hello", { + preCommitVerify: expect.any(Function), + }) }) it("fails with the read-first remediation when the file exists - nothing published", async () => { @@ -172,7 +176,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "gone.txt", "back", "create") expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("gone.txt"), "back", { preCommitVerify: expect.any(Function) }) + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("gone.txt"), "back", { + preCommitVerify: expect.any(Function), + }) }) it("goes through the version guard when the file still exists", async () => { @@ -184,7 +190,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "kept.txt", "rewritten", "create") - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("kept.txt"), "rewritten", { preCommitVerify: expect.any(Function) }) + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("kept.txt"), "rewritten", { + preCommitVerify: expect.any(Function), + }) }) it("fails with the stale remediation suffix when the version moved", async () => { @@ -224,7 +232,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "doc.txt", "new content", "update") expect(mockedComputeVersionToken).toHaveBeenCalledWith(abs("doc.txt")) - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "new content", { preCommitVerify: expect.any(Function) }) + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "new content", { + preCommitVerify: expect.any(Function), + }) }) it("fails with the stale remediation suffix when the version moved - nothing published", async () => { @@ -260,7 +270,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "doc.txt", "patched", "edit") - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "patched", { preCommitVerify: expect.any(Function) }) + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "patched", { + preCommitVerify: expect.any(Function), + }) }) it("fails with the stale remediation suffix when the version moved", async () => { @@ -293,7 +305,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "created.txt", "again", "update") expect(mockedSafeWriteText).toHaveBeenCalledTimes(2) - expect(mockedSafeWriteText).toHaveBeenLastCalledWith(abs("created.txt"), "again", { preCommitVerify: expect.any(Function) }) + expect(mockedSafeWriteText).toHaveBeenLastCalledWith(abs("created.txt"), "again", { + preCommitVerify: expect.any(Function), + }) }) it("replaces the read-time token after a successful update", async () => { @@ -381,7 +395,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { await expect(p2).resolves.toBeUndefined() expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("settle.txt"), "second", { preCommitVerify: expect.any(Function) }) + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("settle.txt"), "second", { + preCommitVerify: expect.any(Function), + }) }) it("evicts settled chain entries - a later write still serializes in order", async () => { @@ -435,7 +451,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, "sub/dir.txt", "content", "update") - expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("sub/dir.txt"), "content", { preCommitVerify: expect.any(Function) }) + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("sub/dir.txt"), "content", { + preCommitVerify: expect.any(Function), + }) }) it("normalizes an already-absolute input (trailing separator) to the observation key", async () => { @@ -452,7 +470,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { await guardedWrite(task, canonical + "/", "content", "update") expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) - expect(mockedSafeWriteText).toHaveBeenCalledWith(canonical, "content", { preCommitVerify: expect.any(Function) }) + expect(mockedSafeWriteText).toHaveBeenCalledWith(canonical, "content", { + preCommitVerify: expect.any(Function), + }) }) it("serializes two spellings of one file through a single chain key", async () => { @@ -494,7 +514,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { resetChain() await guardedWrite(task, "x.txt", "b", "update") - expect(mockedSafeWriteText).toHaveBeenLastCalledWith(abs("x.txt"), "b", { preCommitVerify: expect.any(Function) }) + expect(mockedSafeWriteText).toHaveBeenLastCalledWith(abs("x.txt"), "b", { + preCommitVerify: expect.any(Function), + }) }) }) @@ -645,7 +667,11 @@ describe("guardedWrite (S4a, epic #1375)", () => { await first await expect(second).rejects.toThrow(/was cancelled/) // Only the first write published; the cancelled one touched nothing. - expect(mockedSafeWriteText.mock.calls.map(function (call) { return call[1] })).toEqual(["first"]) + expect( + mockedSafeWriteText.mock.calls.map(function (call) { + return call[1] + }), + ).toEqual(["first"]) }) it("refuses an already-cancelled task's write before any I/O", async () => { @@ -662,7 +688,11 @@ describe("commit-time verifier (S4a, epic #1375)", () => { beforeEach(() => { vi.resetAllMocks() resetChain() - mockedSafeWriteText.mockImplementation((async (p: string, _c: string, options: { preCommitVerify?: (target: string) => Promise }) => { + mockedSafeWriteText.mockImplementation((async ( + p: string, + _c: string, + options: { preCommitVerify?: (target: string) => Promise }, + ) => { // Run the verifier the way safeWriteText does: after staging, immediately before the // commit rename. Without this the callback would never execute and the assertions below // would pass against a verifier that was never called. @@ -698,6 +728,8 @@ describe("commit-time verifier (S4a, epic #1375)", () => { mockedComputeVersionToken.mockResolvedValueOnce("v1") mockedComputeVersionToken.mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })) - await expect(guardedWrite(task, "doc.txt", "new content", "update")).rejects.toThrow(/no longer exists; re-read the file, then retry/) + await expect(guardedWrite(task, "doc.txt", "new content", "update")).rejects.toThrow( + /no longer exists; re-read the file, then retry/, + ) }) -}) \ No newline at end of file +}) diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 106c35b510b..e9388e94515 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -834,7 +834,9 @@ describe("DiffViewProvider", () => { // Verify file was written via safeWriteText const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") - expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function) }) + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { + preCommitVerify: expect.any(Function), + }) // Verify file was opened without focus expect(vscode.window.showTextDocument).toHaveBeenCalledWith( @@ -857,7 +859,9 @@ describe("DiffViewProvider", () => { // Verify file was written via safeWriteText const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") - expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function) }) + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { + preCommitVerify: expect.any(Function), + }) // Verify file was NOT opened expect(vscode.window.showTextDocument).not.toHaveBeenCalled() @@ -872,7 +876,9 @@ describe("DiffViewProvider", () => { // Verify file was written via safeWriteText const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") - expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function) }) + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { + preCommitVerify: expect.any(Function), + }) // Verify delay was NOT called expect(mockDelay).not.toHaveBeenCalled() @@ -918,21 +924,26 @@ describe("DiffViewProvider", () => { await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) - expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function) }) - + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { + preCommitVerify: expect.any(Function), + }) }) it("holds the lock across the guard check and the publish", async () => { const order: string[] = [] vi.mocked(acquireFileLock).mockImplementation(async () => { order.push("acquire") - return async () => { order.push("release") } + return async () => { + order.push("release") + } }) mockTask.observationRegistry.clear() vi.mocked(fs.access).mockImplementation(async () => { order.push("check") throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) }) - vi.mocked(safeWriteText).mockImplementation(async () => { order.push("publish") }) + vi.mocked(safeWriteText).mockImplementation(async () => { + order.push("publish") + }) await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) @@ -966,7 +977,9 @@ describe("DiffViewProvider", () => { await diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0) - expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function) }) + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { + preCommitVerify: expect.any(Function), + }) }) it("fails closed when the owning task has been collected", async () => { diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index 58bd41f37b5..ebb314cdb22 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -271,7 +271,9 @@ describe("safeWriteText", () => { }) expect(seedOpen).toBeDefined() expect(seedOpen?.[2]).toBe(0o600) - const seedOrder = vi.mocked(fsSync.openSync).mock.invocationCallOrder[vi.mocked(fsSync.openSync).mock.calls.indexOf(seedOpen!)] + const seedOrder = vi.mocked(fsSync.openSync).mock.invocationCallOrder[ + vi.mocked(fsSync.openSync).mock.calls.indexOf(seedOpen!) + ] expect(seedOrder).toBeLessThan(vi.mocked(fs.copyFile).mock.invocationCallOrder[0]) // The chmod keeps a copied read-only attribute (Windows) from breaking the fsync From ff2ab63c49217c58a825de1d8e5c867bef4aa9b2 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Sun, 11 Oct 2026 11:17:05 +0800 Subject: [PATCH 27/79] fix(tools): record the version each edit tool reads before a guarded save EditFileTool, EditTool and SearchReplaceTool read the target file and match old_string against it, but never recorded the version they read. With prevent-focus-disruption enabled and no prior read_file observation, the guarded saveDirectly("edit") publish rejected with "File not read yet" where the same call used to publish the file. ApplyDiffTool and ApplyPatchTool already close this hole in this branch; the three tools here now stat around their own read and observe the version only when the file did not change underneath the read, the same contract as those two. Each tool gets a regression test that runs the focus-disruption save with an empty registry and asserts the observation the tool's own read leaves behind: all three fail on the previous head, pass with the fix, and deleting each observe call reddens exactly its own new test. Also from the review at this head: move the three staging-directory lifecycle tests out of the pre-written-temp-path block into staging and cleanup, where the block name matches the code path they exercise; pin the backup's writable open to run after the chmod with invocationCallOrder; correct the preCommitVerify contract comments in safeWriteText and guardedWrite, which claimed every silent lost update becomes a rejected write although a change landing after verification and before the rename can still be overwritten; and fix the stale lock-path comment in the safeWriteJson symlink test, which described the lock as taken on the caller path while the code and the assertions lock the resolved referent. --- src/core/tools/EditFileTool.ts | 14 +++ src/core/tools/EditTool.ts | 16 ++- src/core/tools/SearchReplaceTool.ts | 16 ++- src/core/tools/__tests__/editFileTool.spec.ts | 35 ++++++ src/core/tools/__tests__/editTool.spec.ts | 35 ++++++ .../tools/__tests__/searchReplaceTool.spec.ts | 35 ++++++ src/core/tools/guardedWrite.ts | 5 +- .../__tests__/safeWriteText.spec.ts | 100 ++++++++++-------- src/services/file-safety/safeWriteText.ts | 8 +- 9 files changed, 210 insertions(+), 54 deletions(-) diff --git a/src/core/tools/EditFileTool.ts b/src/core/tools/EditFileTool.ts index 911d4ed85b6..0e10184100b 100644 --- a/src/core/tools/EditFileTool.ts +++ b/src/core/tools/EditFileTool.ts @@ -4,6 +4,7 @@ import path from "path" import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" import { getReadablePath } from "../../utils/path" +import { versionTokenOfStat } from "../../utils/versionToken" import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { Task } from "../task/Task" import { formatResponse } from "../prompts/responses" @@ -231,10 +232,23 @@ export class EditFileTool extends BaseTool<"edit_file"> { // Read file or determine if creating new if (fileExists) { try { + // The guarded saveDirectly below authorizes the publish against the version + // this read saw, and the focus-disruption path has no diff view that could + // observe the file. Same contract as ApplyDiffTool/ApplyPatchTool: stat around + // the read and observe only when the file did not change underneath it. Without + // it the saveDirectly("edit") below rejects with "File not read yet". + const preReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) currentContent = await fs.readFile(absolutePath, "utf8") + const postReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) originalEol = detectLineEnding(currentContent) // Normalize line endings to LF for matching currentContentLF = normalizeToLF(currentContent) + if (preReadStats && postReadStats) { + const preReadToken = versionTokenOfStat(preReadStats) + if (preReadToken === versionTokenOfStat(postReadStats)) { + task.observationRegistry.observe(absolutePath, preReadToken) + } + } } catch (error) { task.consecutiveMistakeCount++ task.didToolFailInCurrentTurn = true diff --git a/src/core/tools/EditTool.ts b/src/core/tools/EditTool.ts index be709004e26..9cf693069f2 100644 --- a/src/core/tools/EditTool.ts +++ b/src/core/tools/EditTool.ts @@ -4,6 +4,7 @@ import path from "path" import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" import { getReadablePath } from "../../utils/path" +import { versionTokenOfStat } from "../../utils/versionToken" import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { Task } from "../task/Task" import { formatResponse } from "../prompts/responses" @@ -89,10 +90,23 @@ export class EditTool extends BaseTool<"edit"> { let fileContent: string try { + // The guarded saveDirectly below authorizes the publish against the version this + // read saw, and the focus-disruption path has no diff view that could observe + // the file. Same contract as ApplyDiffTool/ApplyPatchTool: stat around the read + // and observe only when the file did not change underneath it. Without it the + // saveDirectly("edit") below rejects with "File not read yet". + const preReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) fileContent = await fs.readFile(absolutePath, "utf8") + const postReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) // Normalize line endings to LF for consistent matching fileContent = fileContent.replace(/\r\n/g, "\n") - } catch { + if (preReadStats && postReadStats) { + const preReadToken = versionTokenOfStat(preReadStats) + if (preReadToken === versionTokenOfStat(postReadStats)) { + task.observationRegistry.observe(absolutePath, preReadToken) + } + } + } catch (error) { task.consecutiveMistakeCount++ task.recordToolError("edit") const errorMessage = `Failed to read file '${relPath}'. Please verify file permissions and try again.` diff --git a/src/core/tools/SearchReplaceTool.ts b/src/core/tools/SearchReplaceTool.ts index 18470220fe3..4e932ee5c4b 100644 --- a/src/core/tools/SearchReplaceTool.ts +++ b/src/core/tools/SearchReplaceTool.ts @@ -4,6 +4,7 @@ import path from "path" import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types" import { getReadablePath } from "../../utils/path" +import { versionTokenOfStat } from "../../utils/versionToken" import { isPathOutsideWorkspace } from "../../utils/pathUtils" import { Task } from "../task/Task" import { formatResponse } from "../prompts/responses" @@ -94,10 +95,23 @@ export class SearchReplaceTool extends BaseTool<"search_replace"> { let fileContent: string try { + // The guarded saveDirectly below authorizes the publish against the version this + // read saw, and the focus-disruption path has no diff view that could observe + // the file. Same contract as ApplyDiffTool/ApplyPatchTool: stat around the read + // and observe only when the file did not change underneath it. Without it the + // saveDirectly("edit") below rejects with "File not read yet". + const preReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) fileContent = await fs.readFile(absolutePath, "utf8") + const postReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) // Normalize line endings to LF for consistent matching fileContent = fileContent.replace(/\r\n/g, "\n") - } catch { + if (preReadStats && postReadStats) { + const preReadToken = versionTokenOfStat(preReadStats) + if (preReadToken === versionTokenOfStat(postReadStats)) { + task.observationRegistry.observe(absolutePath, preReadToken) + } + } + } catch (error) { task.consecutiveMistakeCount++ task.recordToolError("search_replace") const errorMessage = `Failed to read file '${relPath}'. Please verify file permissions and try again.` diff --git a/src/core/tools/__tests__/editFileTool.spec.ts b/src/core/tools/__tests__/editFileTool.spec.ts index 14580accab3..16be7bb5666 100644 --- a/src/core/tools/__tests__/editFileTool.spec.ts +++ b/src/core/tools/__tests__/editFileTool.spec.ts @@ -4,6 +4,7 @@ import fs from "fs/promises" import type { MockedFunction } from "vitest" import { fileExistsAtPath } from "../../../utils/fs" +import { ObservationRegistry } from "../../task/observationRegistry" import { isPathOutsideWorkspace } from "../../../utils/pathUtils" import { getReadablePath } from "../../../utils/path" import { ToolUse, ToolResponse, AskApproval, HandleError, PushToolResult } from "../../../shared/tools" @@ -12,6 +13,13 @@ import { editFileTool } from "../EditFileTool" vi.mock("fs/promises", () => ({ default: { readFile: vi.fn().mockResolvedValue(""), + stat: vi.fn().mockResolvedValue({ + dev: 7n, + ino: 4242n, + size: 1234n, + mtimeNs: 1700000000123456789n, + ctimeNs: 1700000000789999999n, + }), }, })) @@ -145,6 +153,9 @@ describe("editFileTool", () => { mockTask.fileContextTracker = { trackFileContext: vi.fn().mockResolvedValue(undefined), } + // Real registry: the regression test asserts which version token the tool's own + // read leaves behind, so a stub would only restate the call. + mockTask.observationRegistry = new ObservationRegistry() mockTask.say = vi.fn().mockResolvedValue(undefined) mockTask.ask = vi.fn().mockResolvedValue(undefined) mockTask.recordToolError = vi.fn() @@ -721,6 +732,30 @@ describe("editFileTool", () => { expect(mockHandleError).not.toHaveBeenCalled() }) + it("records the version its own read saw so the guarded edit is authorized", async () => { + // No prior read_file observation exists for this path. The tool's own read + // must leave the observation that authorizes saveDirectly("edit"), or the + // guarded publish rejects with "File not read yet". + const result = await executeEditFileTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileExists: true, fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(mockTask.observationRegistry.get(absoluteFilePath)?.version).toBe( + "7:4242:1234:1700000000123456789:1700000000789999999", + ) + expect(mockTask.diffViewProvider.saveDirectly).toHaveBeenCalledWith( + testFilePath, + "Line 1\nModified Line 2\nLine 3", + false, + true, + 1000, + "edit", + ) + expect(result).toContain("Tool result message") + expect(mockHandleError).not.toHaveBeenCalled() + }) + it("publishes new-file creation through saveDirectly with create kind", async () => { await executeEditFileTool( { old_string: "", new_string: "New file content" }, diff --git a/src/core/tools/__tests__/editTool.spec.ts b/src/core/tools/__tests__/editTool.spec.ts index 1315cf8f55c..15a92323453 100644 --- a/src/core/tools/__tests__/editTool.spec.ts +++ b/src/core/tools/__tests__/editTool.spec.ts @@ -4,6 +4,7 @@ import fs from "fs/promises" import type { MockedFunction } from "vitest" import { fileExistsAtPath } from "../../../utils/fs" +import { ObservationRegistry } from "../../task/observationRegistry" import { isPathOutsideWorkspace } from "../../../utils/pathUtils" import { getReadablePath } from "../../../utils/path" import { ToolUse, ToolResponse, AskApproval, HandleError, PushToolResult } from "../../../shared/tools" @@ -12,6 +13,13 @@ import { editTool } from "../EditTool" vi.mock("fs/promises", () => ({ default: { readFile: vi.fn().mockResolvedValue(""), + stat: vi.fn().mockResolvedValue({ + dev: 7n, + ino: 4242n, + size: 1234n, + mtimeNs: 1700000000123456789n, + ctimeNs: 1700000000789999999n, + }), }, })) @@ -141,6 +149,9 @@ describe("editTool", () => { mockTask.fileContextTracker = { trackFileContext: vi.fn().mockResolvedValue(undefined), } + // Real registry: the regression test asserts which version token the tool's own + // read leaves behind, so a stub would only restate the call. + mockTask.observationRegistry = new ObservationRegistry() mockTask.say = vi.fn().mockResolvedValue(undefined) mockTask.ask = vi.fn().mockResolvedValue(undefined) mockTask.recordToolError = vi.fn() @@ -457,6 +468,30 @@ describe("editTool", () => { expect(mockHandleError).not.toHaveBeenCalled() }) + it("records the version its own read saw so the guarded edit is authorized", async () => { + // No prior read_file observation exists for this path. The tool's own read + // must leave the observation that authorizes saveDirectly("edit"), or the + // guarded publish rejects with "File not read yet". + const result = await executeEditTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(mockTask.observationRegistry.get(absoluteFilePath)?.version).toBe( + "7:4242:1234:1700000000123456789:1700000000789999999", + ) + expect(mockTask.diffViewProvider.saveDirectly).toHaveBeenCalledWith( + testFilePath, + "Line 1\nModified Line 2\nLine 3", + false, + true, + 1000, + "edit", + ) + expect(result).toBe("Tool result message") + expect(mockHandleError).not.toHaveBeenCalled() + }) + it("surfaces the unobserved edit remediation as a tool error and publishes nothing", async () => { const guardError = new Error("File not read yet -- read the file, then retry.") mockTask.diffViewProvider.saveDirectly.mockRejectedValue(guardError) diff --git a/src/core/tools/__tests__/searchReplaceTool.spec.ts b/src/core/tools/__tests__/searchReplaceTool.spec.ts index f187b7f237f..f489fefc0c0 100644 --- a/src/core/tools/__tests__/searchReplaceTool.spec.ts +++ b/src/core/tools/__tests__/searchReplaceTool.spec.ts @@ -4,6 +4,7 @@ import fs from "fs/promises" import type { MockedFunction } from "vitest" import { fileExistsAtPath } from "../../../utils/fs" +import { ObservationRegistry } from "../../task/observationRegistry" import { isPathOutsideWorkspace } from "../../../utils/pathUtils" import { getReadablePath } from "../../../utils/path" import { ToolUse, ToolResponse, AskApproval, HandleError, PushToolResult } from "../../../shared/tools" @@ -12,6 +13,13 @@ import { searchReplaceTool } from "../SearchReplaceTool" vi.mock("fs/promises", () => ({ default: { readFile: vi.fn().mockResolvedValue(""), + stat: vi.fn().mockResolvedValue({ + dev: 7n, + ino: 4242n, + size: 1234n, + mtimeNs: 1700000000123456789n, + ctimeNs: 1700000000789999999n, + }), }, })) @@ -143,6 +151,9 @@ describe("searchReplaceTool", () => { mockCline.fileContextTracker = { trackFileContext: vi.fn().mockResolvedValue(undefined), } + // Real registry: the regression test asserts which version token the tool's own + // read leaves behind, so a stub would only restate the call. + mockCline.observationRegistry = new ObservationRegistry() mockCline.say = vi.fn().mockResolvedValue(undefined) mockCline.ask = vi.fn().mockResolvedValue(undefined) mockCline.recordToolError = vi.fn() @@ -472,6 +483,30 @@ describe("searchReplaceTool", () => { expect(mockHandleError).not.toHaveBeenCalled() }) + it("records the version its own read saw so the guarded edit is authorized", async () => { + // No prior read_file observation exists for this path. The tool's own read + // must leave the observation that authorizes saveDirectly("edit"), or the + // guarded publish rejects with "File not read yet". + const result = await executeSearchReplaceTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(mockCline.observationRegistry.get(absoluteFilePath)?.version).toBe( + "7:4242:1234:1700000000123456789:1700000000789999999", + ) + expect(mockCline.diffViewProvider.saveDirectly).toHaveBeenCalledWith( + testFilePath, + "Line 1\nModified Line 2\nLine 3", + false, + true, + 1000, + "edit", + ) + expect(result).toBe("Tool result message") + expect(mockHandleError).not.toHaveBeenCalled() + }) + it("surfaces the unobserved edit remediation as a tool error and publishes nothing", async () => { const guardError = new Error("File not read yet -- read the file, then retry.") mockCline.diffViewProvider.saveDirectly.mockRejectedValue(guardError) diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index 1aca8bd3819..bb340bd1ee6 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -164,8 +164,9 @@ export async function createIfAbsent(absolutePath: string, content: string): Pro // this check and the publish. A writer that does NOT honor the advisory lock can // still create the file while the staged copy is being written and fsynced, so // absence is re-asserted inside safeWriteText immediately before the commit - // rename: the window then covers only that syscall, and the race surfaces as a - // rejected write instead of silently clobbering whoever created the file. + // rename: the window then covers only that syscall, and a file that appears + // before verification rejects the write instead of being silently clobbered; + // one that appears after verification returns can still be overwritten. await safeWriteText(absolutePath, content, { preCommitVerify: async (targetPath) => { try { diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index ebb314cdb22..f9d5430960f 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -117,6 +117,53 @@ describe("safeWriteText", () => { // no unlink of temp (it's now the committed file; DACL skipped via platform:linux) expect(fs.unlink).not.toHaveBeenCalled() }) + + it("removes the staging directory after the commit lands", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + await safeWriteText(targetPath, "data", { platform: "linux" }) + + // The directory only exists to hold this write's temp file, so a successful publish + // must not leave it behind in the user's workspace. + expect(fs.rmdir).toHaveBeenCalledWith(expect.stringContaining(".file-safety-staging")) + }) + + it("re-creates the staging directory when a concurrent write removes it mid-write", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync) + .mockImplementationOnce(() => { + // Another writer committed and rmdir'd the shared staging directory + // between _stagingDir() and this open. + throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) + }) + .mockReturnValue(1) + + await safeWriteText(targetPath, "data", { platform: "linux" }) + + // Once for the original staging call, once for the recovery. + expect(fsSync.mkdirSync).toHaveBeenCalledTimes(2) + expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath) + }) + + it("gives up after one recovery when the staging open keeps failing with ENOENT", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + const enoent = Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) + vi.mocked(fsSync.openSync).mockImplementation(() => { + throw enoent + }) + + await expect(safeWriteText(targetPath, "data", { platform: "linux" })).rejects.toBe(enoent) + + // One staging create plus one recovery attempt, then the error surfaces + // instead of looping. + expect(fsSync.mkdirSync).toHaveBeenCalledTimes(2) + expect(fsSync.openSync).toHaveBeenCalledTimes(2) + expect(fs.rename).not.toHaveBeenCalled() + }) }) // ── Test 2: fsync ordering ─────────────────────────────────────────────── @@ -289,6 +336,12 @@ describe("safeWriteText", () => { return String(call[0]).includes("safeWriteText.bak_") && call[1] === "r+" }) expect(backupOpen).toBeDefined() + // The writable open must come after the chmod: an open taken before it would + // fsync the copy while copyFile's chosen mode is still on the file. + const backupOpenOrder = vi.mocked(fsSync.openSync).mock.invocationCallOrder[ + vi.mocked(fsSync.openSync).mock.calls.indexOf(backupOpen!) + ] + expect(backupOpenOrder).toBeGreaterThan(vi.mocked(fs.chmod).mock.invocationCallOrder[0]) }) it("a failed commit leaves the pre-write content at the target and drops the backup copy", async () => { @@ -476,53 +529,6 @@ describe("safeWriteText", () => { expect(fsSync.mkdirSync).not.toHaveBeenCalled() }) - it("removes the staging directory after the commit lands", async () => { - const targetPath = "/tmp/test-dir/target.txt" - vi.mocked(fs.realpath).mockResolvedValue(targetPath) - vi.mocked(fsSync.openSync).mockReturnValue(1) - - await safeWriteText(targetPath, "data", { platform: "linux" }) - - // The directory only exists to hold this write's temp file, so a successful publish - // must not leave it behind in the user's workspace. - expect(fs.rmdir).toHaveBeenCalledWith(expect.stringContaining(".file-safety-staging")) - }) - - it("re-creates the staging directory when a concurrent write removes it mid-write", async () => { - const targetPath = "/tmp/test-dir/target.txt" - vi.mocked(fs.realpath).mockResolvedValue(targetPath) - vi.mocked(fsSync.openSync) - .mockImplementationOnce(() => { - // Another writer committed and rmdir'd the shared staging directory - // between _stagingDir() and this open. - throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) - }) - .mockReturnValue(1) - - await safeWriteText(targetPath, "data", { platform: "linux" }) - - // Once for the original staging call, once for the recovery. - expect(fsSync.mkdirSync).toHaveBeenCalledTimes(2) - expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath) - }) - - it("gives up after one recovery when the staging open keeps failing with ENOENT", async () => { - const targetPath = "/tmp/test-dir/target.txt" - vi.mocked(fs.realpath).mockResolvedValue(targetPath) - const enoent = Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) - vi.mocked(fsSync.openSync).mockImplementation(() => { - throw enoent - }) - - await expect(safeWriteText(targetPath, "data", { platform: "linux" })).rejects.toBe(enoent) - - // One staging create plus one recovery attempt, then the error surfaces - // instead of looping. - expect(fsSync.mkdirSync).toHaveBeenCalledTimes(2) - expect(fsSync.openSync).toHaveBeenCalledTimes(2) - expect(fs.rename).not.toHaveBeenCalled() - }) - it("applies the existing target's mode to a caller-supplied tempPath before publishing", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index bf9ce41d5c0..ac93a789bf6 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -50,9 +50,11 @@ export interface SafeWriteTextOptions { * This is not an atomic compare-and-swap. No portable rename primitive compares the * on-disk CONTENT against an expectation, so a writer that neither takes the advisory * lock nor goes through this path can still change the file inside that last window. - * The guard narrows the window and turns a silent lost update into a rejected write; - * full atomicity would need a content-addressed publish (or a lock every writer in - * the ecosystem honors), which this layer cannot enforce from outside. + * The guard narrows the window: a change detected during verification rejects the + * write instead of being silently lost, but a change that lands after verification + * returns and before the rename can still be overwritten. Full atomicity would need + * a content-addressed publish (or a lock every writer in the ecosystem honors), + * which this layer cannot enforce from outside. */ preCommitVerify?: (targetPath: string) => Promise } From 08a30dc802a112a0fa2d5ede3e6732c152dc70a5 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Sun, 11 Oct 2026 12:27:59 +0800 Subject: [PATCH 28/79] test(tools): make the path mock cover the default import The windows leg of the previous commit went red on the three new guarded write tests. The specs mocked the path module by spreading the actual module and overriding the named exports, but the tools read path through a default import, and the spread left the default export pointing at the real module. Production therefore resolved the absolute path with the real resolve against the runner's working directory - a C-drive spelling on a C-drive checkout, a D-drive spelling on the CI runner - so the observation was recorded under a key the test never looked up and the registry read came back undefined. The mock now returns the mocked object as the default export too, so production gets the mocked resolve on every platform and the registry key is the platform-pinned absolute path the assertions use. Verified by pinning the specs' expected path to a D-drive spelling: the three tests pass with this change, and the CI leg's failure is exactly the pre-fix mismatch. No production change. --- src/core/tools/__tests__/editFileTool.spec.ts | 7 ++++++- src/core/tools/__tests__/editTool.spec.ts | 7 ++++++- src/core/tools/__tests__/searchReplaceTool.spec.ts | 7 ++++++- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/core/tools/__tests__/editFileTool.spec.ts b/src/core/tools/__tests__/editFileTool.spec.ts index 16be7bb5666..7d9f3dde43f 100644 --- a/src/core/tools/__tests__/editFileTool.spec.ts +++ b/src/core/tools/__tests__/editFileTool.spec.ts @@ -25,7 +25,11 @@ vi.mock("fs/promises", () => ({ vi.mock("path", async () => { const originalPath = await vi.importActual("path") - return { + // The default import must be the mocked object too: the tools read path through + // `import path from "path"`, and spreading originalPath alone left the default + // import on the REAL module - production then resolved against the runner's cwd + // (drive-dependent on Windows) instead of the mocked resolve. + const mocked = { ...originalPath, resolve: vi.fn().mockImplementation((...args) => { const separator = process.platform === "win32" ? "\\" : "/" @@ -36,6 +40,7 @@ vi.mock("path", async () => { return to }), } + return { ...mocked, default: mocked } }) vi.mock("delay", () => ({ diff --git a/src/core/tools/__tests__/editTool.spec.ts b/src/core/tools/__tests__/editTool.spec.ts index 15a92323453..d2f1021f505 100644 --- a/src/core/tools/__tests__/editTool.spec.ts +++ b/src/core/tools/__tests__/editTool.spec.ts @@ -25,7 +25,11 @@ vi.mock("fs/promises", () => ({ vi.mock("path", async () => { const originalPath = await vi.importActual("path") - return { + // The default import must be the mocked object too: the tools read path through + // `import path from "path"`, and spreading originalPath alone left the default + // import on the REAL module - production then resolved against the runner's cwd + // (drive-dependent on Windows) instead of the mocked resolve. + const mocked = { ...originalPath, resolve: vi.fn().mockImplementation((...args) => { const separator = process.platform === "win32" ? "\\" : "/" @@ -36,6 +40,7 @@ vi.mock("path", async () => { return to }), } + return { ...mocked, default: mocked } }) vi.mock("delay", () => ({ diff --git a/src/core/tools/__tests__/searchReplaceTool.spec.ts b/src/core/tools/__tests__/searchReplaceTool.spec.ts index f489fefc0c0..286e3bd4eef 100644 --- a/src/core/tools/__tests__/searchReplaceTool.spec.ts +++ b/src/core/tools/__tests__/searchReplaceTool.spec.ts @@ -25,7 +25,11 @@ vi.mock("fs/promises", () => ({ vi.mock("path", async () => { const originalPath = await vi.importActual("path") - return { + // The default import must be the mocked object too: the tools read path through + // `import path from "path"`, and spreading originalPath alone left the default + // import on the REAL module - production then resolved against the runner's cwd + // (drive-dependent on Windows) instead of the mocked resolve. + const mocked = { ...originalPath, resolve: vi.fn().mockImplementation((...args) => { const separator = process.platform === "win32" ? "\\" : "/" @@ -36,6 +40,7 @@ vi.mock("path", async () => { return to }), } + return { ...mocked, default: mocked } }) vi.mock("delay", () => ({ From 5f7772659db5a92abec907d4c78b54101b71f08e Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Sun, 11 Oct 2026 15:37:02 +0800 Subject: [PATCH 29/79] fix(file-safety): remove a partial DACL dump, and finish the verify-contract correction Two rows left over from the review at this head. Lifecycle Resource Cleanup: when icacls /save failed, safeWriteText set daclDumpPath to null and the cleanup below only unlinks a tracked dump, so a dump that icacls created or partially wrote before erroring stayed in the user's directory forever. Track the dump only when the save succeeded and unlink it in the failure branch, which is the shape the sibling branches of this chain already carry - converging on it rather than adding a second mechanism. The negative control replaces the unlink with a resolved promise: exactly the two tests that name this behaviour go red (the new one and the existing fallback test), everything else stays green, and the file restores byte-for-byte (sha256 bedeb2b21d5d5f0d). The preCommitVerify contract comment in replaceIfVersion still claimed the race "surfaces as a rejected stale write instead of a newer version being replaced by the older one". createIfAbsent got the correction in the previous commit; this is the remaining half of the same finding. Verification rejects a change it detects; a change that lands after verification returns and before the rename can still be overwritten. Comments only, no behaviour change. Local: services/file-safety/__tests__/safeWriteText.spec.ts 33 passed, core/tools/__tests__/guardedWrite.spec.ts 38 passed, eslint 0 errors / 0 warnings on all three touched files. --- src/core/tools/guardedWrite.ts | 5 ++-- .../__tests__/safeWriteText.spec.ts | 25 +++++++++++++++++++ src/services/file-safety/safeWriteText.ts | 17 ++++++++++--- 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index bb340bd1ee6..8eb22beac50 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -240,8 +240,9 @@ export async function replaceIfVersion( // honor the advisory lock can still rewrite the file while the staged copy is // being written and fsynced, so the token is re-checked inside safeWriteText // immediately before the commit rename: the window then covers only that - // syscall, and the race surfaces as a rejected stale write instead of a newer - // version being replaced by the older one. + // syscall. A change the verification detects rejects the write; a change that + // lands after verification returns and before the rename can still be + // overwritten, so this narrows the race rather than closing it. await safeWriteText(absolutePath, content, { preCommitVerify: async (targetPath) => { let verifiedVersion: string diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index f9d5430960f..74b28b5c8de 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -425,6 +425,31 @@ describe("safeWriteText", () => { // write succeeded despite icacls failure (fallback to plain rename) expect(fs.rename).toHaveBeenCalled() + // and the fallback leaves no dump file behind + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining(".acl.tmp")) + }) + + it("win32 DACL: a partial dump left by a failed save is removed and never restored", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + // icacls save fails. A real icacls can create or partially write the dump + // before it errors, so the dump path must be cleaned up even though nothing + // valid may be restored from it. + vi.mocked(execFile).mockImplementation((_cmd, _args, _opts, cb) => { + if (typeof cb === "function") cb(new Error("icacls save error"), "", "") + return fakeChild + }) + + await safeWriteText(targetPath, "data", { platform: "win32" }) + + // The write still committed and only the save was attempted: a failed dump + // must never be handed to a restore. + expect(fs.rename).toHaveBeenCalledTimes(1) + expect(execFile).toHaveBeenCalledTimes(1) + expect(vi.mocked(execFile).mock.calls[0]?.[1]?.[1]).toBe("/save") + // The possibly partial dump was unlinked, not merely forgotten. + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining(".acl.tmp")) }) it("win32 DACL save args are [targetPath, /save, dumpPath, /T] before backup rename", async () => { diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index ac93a789bf6..9fb90079b3e 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -251,10 +251,19 @@ export async function safeWriteText(filePath: string, content: string, options?: if (platform === "win32") { try { await fs.access(targetPath) // target exists? - daclDumpPath = targetPath + ".acl.tmp" - const saved = await _saveDaclWindows(targetPath, daclDumpPath, options?.execFileRunner) - if (!saved) { - daclDumpPath = null // skip DACL handling entirely + const dumpPath = targetPath + ".acl.tmp" + const saved = await _saveDaclWindows(targetPath, dumpPath, options?.execFileRunner) + if (saved) { + // Only a successfully saved dump may be restored onto the + // committed file (step 5). + daclDumpPath = dumpPath + } else { + // A failed icacls may have left a partial dump behind. Clearing the + // reference alone hands that file to nobody - the cleanup below only + // unlinks a tracked dump - so remove it here (best-effort). Nothing + // later may restore from a dump whose save failed. + await fs.unlink(dumpPath).catch(() => {}) + daclDumpPath = null } } catch { // target does not exist or access failed — no DACL handling From 27797d2c9a6cf8e536913fd88009754c73e27a8f Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Sun, 11 Oct 2026 16:01:26 +0800 Subject: [PATCH 30/79] test(tools): cover the stat branches the guarded edit observation added Regression Evidence (warning): EditTool, SearchReplaceTool and EditFileTool now continue after a failed pre-read or post-read stat and after a token mismatch without recording an observation, and the added tests covered only the stable-match path. The injected saveDirectly rejection could not tell an unobserved read from an observed one, because the error was supplied by the test rather than derived from the registry. Each spec gains a saveDirectly double that applies guardedWrite's own rule - an "edit" publish with no observation for the target is rejected as unobserved - and three cases per tool run through it: pre-read stat failure, post-read stat failure, and differing pre/post tokens. Each asserts that the read still happened, that both queued stats were consumed (vi.clearAllMocks clears call history, not queued one-time values), that the registry holds no observation, and that the publish is rejected rather than reported as a save. The existing authorization test now runs through the same double, so the positive and negative halves are decided by the same rule. Negative controls, one per half of the branch, restored byte-for-byte: - "preReadStats && postReadStats" -> "||" reddens exactly the two stat-failure tests of that tool and nothing else; - "preReadToken === versionTokenOfStat(postReadStats)" -> "... || true" reddens exactly the token-mismatch test of that tool and nothing else. Run for all three tools: 2 red / 1 red respectively, all green after restore. Local: editTool.spec 22 passed, searchReplaceTool.spec 24 passed, editFileTool.spec 48 passed; eslint 0 errors / 0 warnings on all six touched files; tsc --noEmit reports no error in any touched file. --- src/core/tools/__tests__/editFileTool.spec.ts | 93 +++++++++++++++++++ src/core/tools/__tests__/editTool.spec.ts | 91 ++++++++++++++++++ .../tools/__tests__/searchReplaceTool.spec.ts | 91 ++++++++++++++++++ 3 files changed, 275 insertions(+) diff --git a/src/core/tools/__tests__/editFileTool.spec.ts b/src/core/tools/__tests__/editFileTool.spec.ts index 7d9f3dde43f..28078b1d37a 100644 --- a/src/core/tools/__tests__/editFileTool.spec.ts +++ b/src/core/tools/__tests__/editFileTool.spec.ts @@ -97,6 +97,7 @@ describe("editFileTool", () => { const mockedFsReadFile = fs.readFile as unknown as MockedFunction< (path: string, encoding: string) => Promise > + const mockedFsStat = fs.stat as unknown as MockedFunction<(path: string, options?: unknown) => Promise> const mockedIsPathOutsideWorkspace = isPathOutsideWorkspace as MockedFunction const mockedGetReadablePath = getReadablePath as MockedFunction const mockedPathResolve = path.resolve as MockedFunction @@ -717,6 +718,27 @@ describe("editFileTool", () => { describe("guarded write (S4b, epic #1375)", () => { const focusDisruption = { preventFocusDisruption: true } + // A saveDirectly double that applies guardedWrite's own rule instead of being told what + // to throw: an "edit" publish with no observation for the target is rejected as + // unobserved. Injecting the expected error by hand would pass whether or not the tool's + // own read left an observation behind, so it proves nothing about the read. + const authorizeGuardedPublish = () => { + mockTask.diffViewProvider.saveDirectly.mockImplementation( + async ( + _relPath: string, + _content: string, + _isNewFile: boolean, + _diagnosticsEnabled: boolean, + _writeDelayMs: number, + kind: string, + ) => { + if (kind === "edit" && !mockTask.observationRegistry.get(absoluteFilePath)) { + throw new Error("File not read yet -- read the file, then retry.") + } + }, + ) + } + it("publishes an existing-file edit through saveDirectly with edit kind", async () => { const result = await executeEditFileTool( { old_string: "Line 2", new_string: "Modified Line 2" }, @@ -741,6 +763,7 @@ describe("editFileTool", () => { // No prior read_file observation exists for this path. The tool's own read // must leave the observation that authorizes saveDirectly("edit"), or the // guarded publish rejects with "File not read yet". + authorizeGuardedPublish() const result = await executeEditFileTool( { old_string: "Line 2", new_string: "Modified Line 2" }, { fileExists: true, fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, @@ -779,6 +802,76 @@ describe("editFileTool", () => { expect(mockHandleError).not.toHaveBeenCalled() }) + it.each(["pre-read", "post-read"])( + "records no observation when the %s stat fails, and the guard rejects the edit", + async (which) => { + // A stat failure is neither evidence that the file changed nor a reason to abort + // the read, but it leaves the version unknown, so nothing may be observed. The + // publish that follows is then rejected by the guard's own rule. + const stable = { + dev: 7n, + ino: 4242n, + size: 1234n, + mtimeNs: 1700000000123456789n, + ctimeNs: 1700000000789999999n, + } + const failure = new Error("EACCES: permission denied") + if (which === "pre-read") { + mockedFsStat.mockRejectedValueOnce(failure).mockResolvedValueOnce(stable) + } else { + mockedFsStat.mockResolvedValueOnce(stable).mockRejectedValueOnce(failure) + } + authorizeGuardedPublish() + + const result = await executeEditFileTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + // The read still happened: a stat failure never fails the read itself. + expect(mockedFsReadFile).toHaveBeenCalledWith(absoluteFilePath, "utf8") + // Both queued stats were consumed, so no one-time value leaks into the next + // test - vi.clearAllMocks() clears call history, not queued values. + expect(mockedFsStat).toHaveBeenCalledTimes(2) + // A read whose version is unknown may not be observed... + expect(mockTask.observationRegistry.get(absoluteFilePath)).toBeUndefined() + // ...and the publish it leaves unauthorized is reported as an error, not a save. + expect(mockHandleError).toHaveBeenCalledWith( + "edit_file", + expect.objectContaining({ message: "File not read yet -- read the file, then retry." }), + ) + expect(result).toBeUndefined() + expect(mockTask.diffViewProvider.reset).toHaveBeenCalled() + expect(mockTask.didEditFile).toBe(false) + expect(mockTask.didToolFailInCurrentTurn).toBe(true) + }, + ) + + it("records no observation when the pre- and post-read tokens disagree, and the guard rejects the edit", async () => { + // The file changed underneath the read: old_string was matched against content that + // neither token fully describes, so observing either one would authorize a publish + // against a version this tool never saw. + mockedFsStat + .mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n }) + .mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 9999n, mtimeNs: 3n, ctimeNs: 4n }) + authorizeGuardedPublish() + + const result = await executeEditFileTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(mockedFsReadFile).toHaveBeenCalledWith(absoluteFilePath, "utf8") + expect(mockedFsStat).toHaveBeenCalledTimes(2) + expect(mockTask.observationRegistry.get(absoluteFilePath)).toBeUndefined() + expect(mockHandleError).toHaveBeenCalledWith( + "edit_file", + expect.objectContaining({ message: "File not read yet -- read the file, then retry." }), + ) + expect(result).toBeUndefined() + expect(mockTask.didEditFile).toBe(false) + expect(mockTask.didToolFailInCurrentTurn).toBe(true) + }) it("surfaces the unobserved edit remediation as a tool error and publishes nothing", async () => { const guardError = new Error("File not read yet -- read the file, then retry.") mockTask.diffViewProvider.saveDirectly.mockRejectedValue(guardError) diff --git a/src/core/tools/__tests__/editTool.spec.ts b/src/core/tools/__tests__/editTool.spec.ts index d2f1021f505..6ca7d2a518f 100644 --- a/src/core/tools/__tests__/editTool.spec.ts +++ b/src/core/tools/__tests__/editTool.spec.ts @@ -95,6 +95,7 @@ describe("editTool", () => { const mockedFsReadFile = fs.readFile as unknown as MockedFunction< (path: string, encoding: string) => Promise > + const mockedFsStat = fs.stat as unknown as MockedFunction<(path: string, options?: unknown) => Promise> const mockedIsPathOutsideWorkspace = isPathOutsideWorkspace as MockedFunction const mockedGetReadablePath = getReadablePath as MockedFunction const mockedPathResolve = path.resolve as MockedFunction @@ -454,6 +455,27 @@ describe("editTool", () => { describe("guarded write (S4b, epic #1375)", () => { const focusDisruption = { preventFocusDisruption: true } + // A saveDirectly double that applies guardedWrite's own rule instead of being told what + // to throw: an "edit" publish with no observation for the target is rejected as + // unobserved. Injecting the expected error by hand would pass whether or not the tool's + // own read left an observation behind, so it proves nothing about the read. + const authorizeGuardedPublish = () => { + mockTask.diffViewProvider.saveDirectly.mockImplementation( + async ( + _relPath: string, + _content: string, + _isNewFile: boolean, + _diagnosticsEnabled: boolean, + _writeDelayMs: number, + kind: string, + ) => { + if (kind === "edit" && !mockTask.observationRegistry.get(absoluteFilePath)) { + throw new Error("File not read yet -- read the file, then retry.") + } + }, + ) + } + it("publishes through saveDirectly with edit kind", async () => { const result = await executeEditTool( { old_string: "Line 2", new_string: "Modified Line 2" }, @@ -477,6 +499,7 @@ describe("editTool", () => { // No prior read_file observation exists for this path. The tool's own read // must leave the observation that authorizes saveDirectly("edit"), or the // guarded publish rejects with "File not read yet". + authorizeGuardedPublish() const result = await executeEditTool( { old_string: "Line 2", new_string: "Modified Line 2" }, { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, @@ -497,6 +520,74 @@ describe("editTool", () => { expect(mockHandleError).not.toHaveBeenCalled() }) + it.each(["pre-read", "post-read"])( + "records no observation when the %s stat fails, and the guard rejects the edit", + async (which) => { + // A stat failure is neither evidence that the file changed nor a reason to abort + // the read, but it leaves the version unknown, so nothing may be observed. The + // publish that follows is then rejected by the guard's own rule. + const stable = { + dev: 7n, + ino: 4242n, + size: 1234n, + mtimeNs: 1700000000123456789n, + ctimeNs: 1700000000789999999n, + } + const failure = new Error("EACCES: permission denied") + if (which === "pre-read") { + mockedFsStat.mockRejectedValueOnce(failure).mockResolvedValueOnce(stable) + } else { + mockedFsStat.mockResolvedValueOnce(stable).mockRejectedValueOnce(failure) + } + authorizeGuardedPublish() + + const result = await executeEditTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + // The read still happened: a stat failure never fails the read itself. + expect(mockedFsReadFile).toHaveBeenCalledWith(absoluteFilePath, "utf8") + // Both queued stats were consumed, so no one-time value leaks into the next + // test - vi.clearAllMocks() clears call history, not queued values. + expect(mockedFsStat).toHaveBeenCalledTimes(2) + // A read whose version is unknown may not be observed... + expect(mockTask.observationRegistry.get(absoluteFilePath)).toBeUndefined() + // ...and the publish it leaves unauthorized is reported as an error, not a save. + expect(mockHandleError).toHaveBeenCalledWith( + "edit", + expect.objectContaining({ message: "File not read yet -- read the file, then retry." }), + ) + expect(result).toBeUndefined() + expect(mockTask.diffViewProvider.reset).toHaveBeenCalled() + expect(mockTask.didEditFile).toBe(false) + }, + ) + + it("records no observation when the pre- and post-read tokens disagree, and the guard rejects the edit", async () => { + // The file changed underneath the read: old_string was matched against content that + // neither token fully describes, so observing either one would authorize a publish + // against a version this tool never saw. + mockedFsStat + .mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n }) + .mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 9999n, mtimeNs: 3n, ctimeNs: 4n }) + authorizeGuardedPublish() + + const result = await executeEditTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(mockedFsReadFile).toHaveBeenCalledWith(absoluteFilePath, "utf8") + expect(mockedFsStat).toHaveBeenCalledTimes(2) + expect(mockTask.observationRegistry.get(absoluteFilePath)).toBeUndefined() + expect(mockHandleError).toHaveBeenCalledWith( + "edit", + expect.objectContaining({ message: "File not read yet -- read the file, then retry." }), + ) + expect(result).toBeUndefined() + expect(mockTask.didEditFile).toBe(false) + }) it("surfaces the unobserved edit remediation as a tool error and publishes nothing", async () => { const guardError = new Error("File not read yet -- read the file, then retry.") mockTask.diffViewProvider.saveDirectly.mockRejectedValue(guardError) diff --git a/src/core/tools/__tests__/searchReplaceTool.spec.ts b/src/core/tools/__tests__/searchReplaceTool.spec.ts index 286e3bd4eef..0969e74a3b6 100644 --- a/src/core/tools/__tests__/searchReplaceTool.spec.ts +++ b/src/core/tools/__tests__/searchReplaceTool.spec.ts @@ -97,6 +97,7 @@ describe("searchReplaceTool", () => { const mockedFsReadFile = fs.readFile as unknown as MockedFunction< (path: string, encoding: string) => Promise > + const mockedFsStat = fs.stat as unknown as MockedFunction<(path: string, options?: unknown) => Promise> const mockedIsPathOutsideWorkspace = isPathOutsideWorkspace as MockedFunction const mockedGetReadablePath = getReadablePath as MockedFunction const mockedPathResolve = path.resolve as MockedFunction @@ -469,6 +470,27 @@ describe("searchReplaceTool", () => { describe("guarded write (S4b, epic #1375)", () => { const focusDisruption = { preventFocusDisruption: true } + // A saveDirectly double that applies guardedWrite's own rule instead of being told what + // to throw: an "edit" publish with no observation for the target is rejected as + // unobserved. Injecting the expected error by hand would pass whether or not the tool's + // own read left an observation behind, so it proves nothing about the read. + const authorizeGuardedPublish = () => { + mockCline.diffViewProvider.saveDirectly.mockImplementation( + async ( + _relPath: string, + _content: string, + _isNewFile: boolean, + _diagnosticsEnabled: boolean, + _writeDelayMs: number, + kind: string, + ) => { + if (kind === "edit" && !mockCline.observationRegistry.get(absoluteFilePath)) { + throw new Error("File not read yet -- read the file, then retry.") + } + }, + ) + } + it("publishes through saveDirectly with edit kind", async () => { const result = await executeSearchReplaceTool( { old_string: "Line 2", new_string: "Modified Line 2" }, @@ -492,6 +514,7 @@ describe("searchReplaceTool", () => { // No prior read_file observation exists for this path. The tool's own read // must leave the observation that authorizes saveDirectly("edit"), or the // guarded publish rejects with "File not read yet". + authorizeGuardedPublish() const result = await executeSearchReplaceTool( { old_string: "Line 2", new_string: "Modified Line 2" }, { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, @@ -512,6 +535,74 @@ describe("searchReplaceTool", () => { expect(mockHandleError).not.toHaveBeenCalled() }) + it.each(["pre-read", "post-read"])( + "records no observation when the %s stat fails, and the guard rejects the edit", + async (which) => { + // A stat failure is neither evidence that the file changed nor a reason to abort + // the read, but it leaves the version unknown, so nothing may be observed. The + // publish that follows is then rejected by the guard's own rule. + const stable = { + dev: 7n, + ino: 4242n, + size: 1234n, + mtimeNs: 1700000000123456789n, + ctimeNs: 1700000000789999999n, + } + const failure = new Error("EACCES: permission denied") + if (which === "pre-read") { + mockedFsStat.mockRejectedValueOnce(failure).mockResolvedValueOnce(stable) + } else { + mockedFsStat.mockResolvedValueOnce(stable).mockRejectedValueOnce(failure) + } + authorizeGuardedPublish() + + const result = await executeSearchReplaceTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + // The read still happened: a stat failure never fails the read itself. + expect(mockedFsReadFile).toHaveBeenCalledWith(absoluteFilePath, "utf8") + // Both queued stats were consumed, so no one-time value leaks into the next + // test - vi.clearAllMocks() clears call history, not queued values. + expect(mockedFsStat).toHaveBeenCalledTimes(2) + // A read whose version is unknown may not be observed... + expect(mockCline.observationRegistry.get(absoluteFilePath)).toBeUndefined() + // ...and the publish it leaves unauthorized is reported as an error, not a save. + expect(mockHandleError).toHaveBeenCalledWith( + "search and replace", + expect.objectContaining({ message: "File not read yet -- read the file, then retry." }), + ) + expect(result).toBeUndefined() + expect(mockCline.diffViewProvider.reset).toHaveBeenCalled() + expect(mockCline.didEditFile).toBe(false) + }, + ) + + it("records no observation when the pre- and post-read tokens disagree, and the guard rejects the edit", async () => { + // The file changed underneath the read: old_string was matched against content that + // neither token fully describes, so observing either one would authorize a publish + // against a version this tool never saw. + mockedFsStat + .mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n }) + .mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 9999n, mtimeNs: 3n, ctimeNs: 4n }) + authorizeGuardedPublish() + + const result = await executeSearchReplaceTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(mockedFsReadFile).toHaveBeenCalledWith(absoluteFilePath, "utf8") + expect(mockedFsStat).toHaveBeenCalledTimes(2) + expect(mockCline.observationRegistry.get(absoluteFilePath)).toBeUndefined() + expect(mockHandleError).toHaveBeenCalledWith( + "search and replace", + expect.objectContaining({ message: "File not read yet -- read the file, then retry." }), + ) + expect(result).toBeUndefined() + expect(mockCline.didEditFile).toBe(false) + }) it("surfaces the unobserved edit remediation as a tool error and publishes nothing", async () => { const guardError = new Error("File not read yet -- read the file, then retry.") mockCline.diffViewProvider.saveDirectly.mockRejectedValue(guardError) From f20acbd4b7e2e4bcde42de4ab09ffd0451316f4f Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Sun, 11 Oct 2026 17:03:49 +0800 Subject: [PATCH 31/79] fix(file-safety): give this write's own dump and staging paths names it owns Two threads raised against the head this branch just pushed. Both are the same mistake seen from two sides: a path derived from a fixed, predictable name can already exist and belong to something else, and a cleanup that reaches that name then acts on data this write never created. ACL dump (raised against the previous commit's own fix): the dump lived at ".acl.tmp". icacls /save writes to the file it is named, so a failed save can leave a partial dump - but it can also fail against a dump file that was already there, and the failure cleanup then unlinked a file this write did not create. The dump now gets a generated name in the target's directory, the same owned-unique shape as the staging temp, so the cleanup can only ever reach a path this call made. Staging directory: mkdirSync with recursive:true accepts an existing entry of the requested name without creating anything, and the permission repair uses chmodSync, which follows a symlink. A workspace that ships a directory entry named .file-safety-staging as a symlink therefore had its chmod applied to a directory outside the workspace, and its staged file written there, before the commit rename. The staging directory is now named per write, which is the shape every other branch of this chain already carries - a convergence port to the chain's single shape, not a new mechanism, and it is what removes the hazard by construction rather than by an extra lstat check. Negative controls, each restored byte for byte (sha256 603d38b69a77): - reverting the dump to the target-derived name reddens the new ownership test along with the four tests whose assertions name the dump path, since the assertions moved with the path; - reverting the staging directory to the shared fixed name reddens exactly the new "gives each self-staged write its own staging directory" test. Local: safeWriteText.spec 35 passed, safeWriteJson.test 23 passed / 1 skipped, guardedWrite.spec 38, editTool.spec 22, searchReplaceTool.spec 24, editFileTool.spec 48, applyPatchTool.execute.spec 11, applyDiffTool.guardedWrite.spec 6, writeToFileTool.spec 22 / 5 skipped, readFileTool.spec 88. DiffViewProvider.spec fails 2 tests identically with and without this change (verified by stashing), so those two are not from this commit. eslint 0 errors / 0 warnings on both touched files; tsc --noEmit reports no error naming either of them. --- .../__tests__/safeWriteText.spec.ts | 60 +++++++++++++++++-- src/services/file-safety/safeWriteText.ts | 14 ++++- 2 files changed, 66 insertions(+), 8 deletions(-) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index 74b28b5c8de..8d8fb5ef0da 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -118,6 +118,27 @@ describe("safeWriteText", () => { expect(fs.unlink).not.toHaveBeenCalled() }) + it("gives each self-staged write its own staging directory", async () => { + // A workspace can ship a directory entry named .file-safety-staging, and a + // shared fixed name is then a path the workspace controls rather than one this + // write created. Each self-staged write must get its own name. + const first = "/tmp/test-dir/a.txt" + const second = "/tmp/test-dir/b.txt" + vi.mocked(fs.realpath).mockImplementation(async (p) => String(p)) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + await safeWriteText(first, "one", { platform: "linux" }) + await safeWriteText(second, "two", { platform: "linux" }) + + const staging = vi + .mocked(fsSync.mkdirSync) + .mock.calls.map((c) => String(c[0])) + .filter((p) => p.includes(".file-safety-staging_")) + expect(staging).toHaveLength(2) + expect(staging[0]).not.toBe(staging[1]) + for (const sd of staging) expect(sd).toMatch(/\.file-safety-staging_\d+_[a-z0-9]+$/) + }) + it("removes the staging directory after the commit lands", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) @@ -426,7 +447,34 @@ describe("safeWriteText", () => { // write succeeded despite icacls failure (fallback to plain rename) expect(fs.rename).toHaveBeenCalled() // and the fallback leaves no dump file behind - expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining(".acl.tmp")) + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.acl")) + }) + + it("win32 DACL: a failed save never unlinks a dump this write did not create", async () => { + const targetPath = "/tmp/test-dir/target.txt" + // A file that already sits at the name an earlier fixed scheme would have used. + // It belongs to whatever put it there, not to this write. + const preExisting = targetPath + ".acl.tmp" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + vi.mocked(execFile).mockImplementation((_cmd, _args, _opts, cb) => { + if (typeof cb === "function") cb(new Error("icacls save error"), "", "") + return fakeChild + }) + + await safeWriteText(targetPath, "data", { platform: "win32" }) + + // The dump icacls was told to write is a name this call generated... + const dumpArg = vi.mocked(execFile).mock.calls[0]?.[1]?.[2] + expect(typeof dumpArg).toBe("string") + expect(String(dumpArg)).toContain("safeWriteText.acl") + expect(String(dumpArg)).not.toBe(preExisting) + // ...and the cleanup only ever reaches that owned name. The pre-existing file + // survives a failed save instead of being deleted as if this write owned it. + for (const call of vi.mocked(fs.unlink).mock.calls) { + expect(String(call[0])).not.toBe(preExisting) + } + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.acl")) }) it("win32 DACL: a partial dump left by a failed save is removed and never restored", async () => { @@ -449,7 +497,7 @@ describe("safeWriteText", () => { expect(execFile).toHaveBeenCalledTimes(1) expect(vi.mocked(execFile).mock.calls[0]?.[1]?.[1]).toBe("/save") // The possibly partial dump was unlinked, not merely forgotten. - expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining(".acl.tmp")) + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.acl")) }) it("win32 DACL save args are [targetPath, /save, dumpPath, /T] before backup rename", async () => { @@ -465,7 +513,7 @@ describe("safeWriteText", () => { // First call: save DACL from target before backup rename const firstCall = vi.mocked(execFile).mock.calls[0] expect(firstCall[0]).toBe("icacls") - expect(firstCall[1]).toEqual([targetPath, "/save", expect.stringContaining(".acl.tmp"), "/T"]) + expect(firstCall[1]).toEqual([targetPath, "/save", expect.stringContaining("safeWriteText.acl"), "/T"]) // Second call: restore DACL onto directory after commit rename const secondCall = vi.mocked(execFile).mock.calls[1] @@ -473,11 +521,11 @@ describe("safeWriteText", () => { expect(secondCall[1]).toEqual([ expect.stringContaining("/tmp/test-dir"), "/restore", - expect.stringContaining(".acl.tmp"), + expect.stringContaining("safeWriteText.acl"), ]) // dump file was unlinked after restore - expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining(".acl.tmp")) + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.acl")) }) it("win32 DACL: dump is unlinked even when restore fails", async () => { @@ -501,7 +549,7 @@ describe("safeWriteText", () => { expect(fs.rename).toHaveBeenCalled() // dump file was still unlinked in finally - expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining(".acl.tmp")) + expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.acl")) }) it("win32 DACL: when target does not exist, no save/restore/dump", async () => { diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index 9fb90079b3e..f18dd243504 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -69,7 +69,13 @@ function _tempName(dir: string, prefix: string): string { /** Create a private staging sub-directory inside *dir* so that multiple * concurrent writes never collide on their temp names. */ function _stagingDir(dir: string): string { - const sd = path.join(dir, ".file-safety-staging") + // One directory per write, named the way the temp inside it is named. A shared + // fixed name is a path the workspace controls: mkdirSync(recursive) accepts an + // existing entry of that name without creating anything, and a committed symlink + // at that name would make the chmod below rewrite the permissions of a directory + // outside the workspace and put the staged file in it. A name this call generated + // cannot be pre-planted by the content being written. + const sd = path.join(dir, ".file-safety-staging_" + Date.now() + "_" + Math.random().toString(36).substring(2)) // mode:0o700 protects a freshly created staging dir; the best-effort chmod // repairs a pre-existing one (mkdirSync with recursive:true never chmods an // existing directory), so staged temp files are never group/world readable. @@ -251,7 +257,11 @@ export async function safeWriteText(filePath: string, content: string, options?: if (platform === "win32") { try { await fs.access(targetPath) // target exists? - const dumpPath = targetPath + ".acl.tmp" + // A name this call generates, not a name derived from the target. A fixed + // ".acl.tmp" can already exist beside the target and belong to + // something else; the cleanup below would then unlink a file this write + // never created. Same owned-unique shape as the staging temp. + const dumpPath = _tempName(dirPath, "safeWriteText.acl") const saved = await _saveDaclWindows(targetPath, dumpPath, options?.execFileRunner) if (saved) { // Only a successfully saved dump may be restored onto the From 53ad7d7c323ee1659cc9485e40edf3c92dcb4819 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Sun, 11 Oct 2026 17:41:52 +0800 Subject: [PATCH 32/79] fix(file-safety): stop retrying a staging open that cannot recover The per-write staging directory made this retry dead, and the review caught it. The branch used to exist because every write shared one staging directory: a writer that finished removed it when empty, so a concurrent writer could find its parent gone between the create and the open, and re-creating it put the original temp path back under a parent. With a name this call generates, no other write shares the directory, and the retry's re-create makes a DIFFERENT directory while the retry still opens the original temp path - so it could only fail a second time, and it hid the real failure behind a second errno. Removing the branch is also the shape every other branch of this chain already carries: they open the staging temp directly, with no ENOENT recovery, for the same reason. Convergence port, not a new decision. The two tests that pinned the retry are replaced by one that pins the new contract: a failed staging open surfaces once, with one directory create and one open attempt, and nothing published. Negative control, restored byte for byte (sha256 99172f0b05ed): putting the retry back reddens exactly that test and nothing else. Local: safeWriteText.spec 34 passed, safeWriteJson.test 23 passed / 1 skipped, guardedWrite.spec 38 passed; eslint 0 errors / 0 warnings on both touched files; tsc --noEmit reports no error naming either of them. --- .../__tests__/safeWriteText.spec.ts | 30 +++++-------------- src/services/file-safety/safeWriteText.ts | 22 ++++---------- 2 files changed, 13 insertions(+), 39 deletions(-) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index 8d8fb5ef0da..ccfcffd3e8b 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -151,25 +151,7 @@ describe("safeWriteText", () => { expect(fs.rmdir).toHaveBeenCalledWith(expect.stringContaining(".file-safety-staging")) }) - it("re-creates the staging directory when a concurrent write removes it mid-write", async () => { - const targetPath = "/tmp/test-dir/target.txt" - vi.mocked(fs.realpath).mockResolvedValue(targetPath) - vi.mocked(fsSync.openSync) - .mockImplementationOnce(() => { - // Another writer committed and rmdir'd the shared staging directory - // between _stagingDir() and this open. - throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) - }) - .mockReturnValue(1) - - await safeWriteText(targetPath, "data", { platform: "linux" }) - - // Once for the original staging call, once for the recovery. - expect(fsSync.mkdirSync).toHaveBeenCalledTimes(2) - expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath) - }) - - it("gives up after one recovery when the staging open keeps failing with ENOENT", async () => { + it("surfaces a failed staging open once, without re-creating a directory it cannot recover", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) const enoent = Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) @@ -179,10 +161,12 @@ describe("safeWriteText", () => { await expect(safeWriteText(targetPath, "data", { platform: "linux" })).rejects.toBe(enoent) - // One staging create plus one recovery attempt, then the error surfaces - // instead of looping. - expect(fsSync.mkdirSync).toHaveBeenCalledTimes(2) - expect(fsSync.openSync).toHaveBeenCalledTimes(2) + // The staging directory carries a name this call generated, so nothing shares it + // and a failed open has no recovery to reach for. Re-creating a directory would + // create a different one and leave tempPath without a parent, so the retry that + // used to live here could only fail a second time: one create, one open. + expect(fsSync.mkdirSync).toHaveBeenCalledTimes(1) + expect(fsSync.openSync).toHaveBeenCalledTimes(1) expect(fs.rename).not.toHaveBeenCalled() }) }) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index f18dd243504..d135f040604 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -199,22 +199,12 @@ export async function safeWriteText(filePath: string, content: string, options?: } catch { // target does not exist yet - keep the default } - let fd: number - try { - fd = fsSync.openSync(tempPath, "w", targetMode) - } catch (error: unknown) { - // Every write to one directory shares the staging dir, and a write that finishes - // removes it when empty. A concurrent writer can therefore remove it between - // _stagingDir() and this open. Re-create it and try once; any other errno, or - // a second ENOENT, is a real failure. - const code = - typeof error === "object" && error !== null && "code" in error - ? (error as { code?: string }).code - : undefined - if (code !== "ENOENT" || stagingDir === null) throw error - _stagingDir(dirPath) - fd = fsSync.openSync(tempPath, "w", targetMode) - } + // No retry on ENOENT here. The staging directory carries a name this call + // generated, so no other write shares it and none can remove it between the + // create and this open; whatever removed it is not something re-creating a + // directory under a fresh name would put back under tempPath. The retry this + // branch used to carry therefore could only fail a second time. + const fd = fsSync.openSync(tempPath, "w", targetMode) try { // Loop until every byte is written: writeSync can report a short // (partial) write, and publishing a truncated staging file would From 4f299c58fd5b8a21b96a3c5f434319c22a8ec5e9 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Sun, 11 Oct 2026 19:25:54 +0800 Subject: [PATCH 33/79] fix(tools): observe the self-read token only at the guarded publish The five edit tools recorded their self-read observation in the task-wide registry at read time. Every path that then stopped without publishing - a failed match, a rejected approval, the empty-old_string handoff to write_to_file, the diff-view branch - left the token behind, and a later write_to_file could spend it: guardedWrite saw an observation whose token still matched the disk and CAS-published a full-file overwrite the model had never read, breaking the contract that a write to an unobserved existing file fails. The token now stays local to the tool call and is observed immediately before the focus-disruption saveDirectly that consumes it. ApplyPatchTool holds the hunk-read tokens in a map keyed by absolute path and observes the update publish's path only. The diff-view branch never observes: saveChanges() does not consult the registry. Negative controls, each restored byte for byte and hash-verified: - removing the observe-before-publish at each of the five production call sites reddens exactly that tool's read-authorization test (5 mutants, 5 killed, exactly 1 red test each); - the 11 new "leaves the registry empty" tests run 11/11 red against the pre-fix production files and green after the fix. Local: the five touched specs 122 passed; adjacent consumer specs (applyPatchTool.partial, searchAndReplaceTool, guardedWrite, writeToFileTool) 67 passed / 5 skipped. eslint --max-warnings=0 clean on all ten touched files; prettier --check clean on the LF-normalized content; tsc --noEmit reports no error naming any of them. --- src/core/tools/ApplyDiffTool.ts | 17 ++++++-- src/core/tools/ApplyPatchTool.ts | 36 +++++++++++++---- src/core/tools/EditFileTool.ts | 17 ++++++-- src/core/tools/EditTool.ts | 18 +++++++-- src/core/tools/SearchReplaceTool.ts | 18 +++++++-- .../applyDiffTool.guardedWrite.spec.ts | 33 +++++++++++++++ .../__tests__/applyPatchTool.execute.spec.ts | 38 ++++++++++++++++++ src/core/tools/__tests__/editFileTool.spec.ts | 40 +++++++++++++++++++ src/core/tools/__tests__/editTool.spec.ts | 27 +++++++++++++ .../tools/__tests__/searchReplaceTool.spec.ts | 27 +++++++++++++ 10 files changed, 248 insertions(+), 23 deletions(-) diff --git a/src/core/tools/ApplyDiffTool.ts b/src/core/tools/ApplyDiffTool.ts index c88deef3d5c..0160c571b9d 100644 --- a/src/core/tools/ApplyDiffTool.ts +++ b/src/core/tools/ApplyDiffTool.ts @@ -79,16 +79,19 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> { // authorized against the version captured here - not against whatever version the // diff view happens to stat afterwards (there is no diff view on the // focus-disruption path). Same contract as ApplyPatchTool's hunk read: stat - // around the read and observe only when the file did not change underneath it. - // Without it the saveDirectly("edit") below has no observation for the path and the - // guarded publish fails with "File not read yet -- read the file, then retry." + // around the read and keep the token only when the file did not change underneath + // it. The token stays local until the guarded publish consumes it: observing at + // read time would leave it in the task-wide registry through a failed hunk, a + // rejection, and the diff-view branch, where a later write_to_file could spend it + // on an unrelated overwrite. + let readVersionToken: string | undefined const preReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) const originalContent: string = await fs.readFile(absolutePath, "utf-8") const postReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) if (preReadStats && postReadStats) { const preReadToken = versionTokenOfStat(preReadStats) if (preReadToken === versionTokenOfStat(postReadStats)) { - task.observationRegistry.observe(absolutePath, preReadToken) + readVersionToken = preReadToken } } @@ -195,8 +198,14 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> { // Save directly without showing diff view or opening the file. The diff is // applied to an existing file, so edit-guard semantics require a prior read. + // The observation is recorded here, at the guarded publish that consumes it, + // so a failed hunk, a rejection, and the diff-view branch leave no token in + // the task-wide registry. task.diffViewProvider.editType = "modify" task.diffViewProvider.originalContent = originalContent + if (readVersionToken !== undefined) { + task.observationRegistry.observe(absolutePath, readVersionToken) + } await task.diffViewProvider.saveDirectly( relPath, diffResult.content, diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 9ea6620b067..220c07ae144 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -86,13 +86,19 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { return } - // Process each hunk. The read doubles as the S2 observation for the + // Process each hunk. The read also captures the on-disk version for the // guarded publish (ReadFileTool contract: stat before and after the - // read, observe only when the on-disk version is unchanged between the - // two stats). Without it, the in-place modify publish is an unobserved + // read, keep the token only when the on-disk version is unchanged between + // the two stats). Without it, the in-place modify publish is an unobserved // write and the composed chat-diff default rejects it ("File already // exists ... and was not read before this write") even though this tool - // just read the exact content the patch was applied to. + // just read the exact content the patch was applied to. Tokens are held in + // a local map keyed by absolute path and observed only at the guarded + // publish that consumes them: observing at read time would leave them in + // the task-wide registry through a failed patch, a rejection, and the + // diff-view branch, where a later write_to_file could spend one on an + // unrelated overwrite. + const readTokens = new Map() const readFile = async (filePath: string): Promise => { const absolutePath = path.resolve(task.cwd, filePath) const preReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) @@ -101,7 +107,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { if (preReadStats && postReadStats) { const preReadToken = versionTokenOfStat(preReadStats) if (preReadToken === versionTokenOfStat(postReadStats)) { - task.observationRegistry.observe(absolutePath, preReadToken) + readTokens.set(absolutePath, preReadToken) } } return content @@ -142,7 +148,15 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { await this.handleDeleteFile(absolutePath, relPath, task, callbacks, isWriteProtected) } else if (change.type === "update") { // Update file - await this.handleUpdateFile(change, absolutePath, relPath, task, callbacks, isWriteProtected) + await this.handleUpdateFile( + change, + absolutePath, + relPath, + task, + callbacks, + isWriteProtected, + readTokens, + ) } } @@ -318,6 +332,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { task: Task, callbacks: ToolCallbacks, isWriteProtected: boolean, + readTokens: Map, ): Promise { const { askApproval, pushToolResult } = callbacks @@ -461,7 +476,14 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // Save changes to the same file if (isPreventFocusDisruptionEnabled) { // Guarded publish: the patched file content is complete, so create-guard - // semantics apply (stale observed versions are rejected with a re-read hint). + // semantics apply (stale observed versions are rejected with a re-read + // hint). The hunk read's token is observed here, at the guarded publish + // that consumes it, so a failed patch, a rejection, and the diff-view + // branch leave no token in the task-wide registry. + const readToken = readTokens.get(absolutePath) + if (readToken !== undefined) { + task.observationRegistry.observe(absolutePath, readToken) + } await task.diffViewProvider.saveDirectly( relPath, newContent, diff --git a/src/core/tools/EditFileTool.ts b/src/core/tools/EditFileTool.ts index 0e10184100b..bfad923e885 100644 --- a/src/core/tools/EditFileTool.ts +++ b/src/core/tools/EditFileTool.ts @@ -228,6 +228,8 @@ export class EditFileTool extends BaseTool<"edit_file"> { let currentContentLF: string | null = null let originalEol: LineEnding = "\n" let isNewFile = false + // Version token from this tool's own read; observed only at the guarded publish below. + let readVersionToken: string | undefined // Read file or determine if creating new if (fileExists) { @@ -235,8 +237,10 @@ export class EditFileTool extends BaseTool<"edit_file"> { // The guarded saveDirectly below authorizes the publish against the version // this read saw, and the focus-disruption path has no diff view that could // observe the file. Same contract as ApplyDiffTool/ApplyPatchTool: stat around - // the read and observe only when the file did not change underneath it. Without - // it the saveDirectly("edit") below rejects with "File not read yet". + // the read and keep the token only when the file did not change underneath it. + // The token stays local until the guarded publish consumes it: observing at read + // time would leave it in the task-wide registry through every later failure and + // rejection, where a later write_to_file could spend it on an unrelated overwrite. const preReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) currentContent = await fs.readFile(absolutePath, "utf8") const postReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) @@ -246,7 +250,7 @@ export class EditFileTool extends BaseTool<"edit_file"> { if (preReadStats && postReadStats) { const preReadToken = versionTokenOfStat(preReadStats) if (preReadToken === versionTokenOfStat(postReadStats)) { - task.observationRegistry.observe(absolutePath, preReadToken) + readVersionToken = preReadToken } } } catch (error) { @@ -452,7 +456,12 @@ export class EditFileTool extends BaseTool<"edit_file"> { if (isPreventFocusDisruptionEnabled) { // Direct file write without diff view or opening the file. In-place edits // use edit-guard semantics (a prior read is required); new-file creation - // keeps create-guard semantics. + // keeps create-guard semantics. The observation is recorded here, at the + // guarded publish that consumes it, so a failed match, a rejection, or the + // diff-view save never leaves this read's token in the task-wide registry. + if (readVersionToken !== undefined) { + task.observationRegistry.observe(absolutePath, readVersionToken) + } await task.diffViewProvider.saveDirectly( relPath, newContent, diff --git a/src/core/tools/EditTool.ts b/src/core/tools/EditTool.ts index 9cf693069f2..49596e9cc53 100644 --- a/src/core/tools/EditTool.ts +++ b/src/core/tools/EditTool.ts @@ -89,12 +89,16 @@ export class EditTool extends BaseTool<"edit"> { } let fileContent: string + // Version token from this tool's own read; observed only at the guarded publish below. + let readVersionToken: string | undefined try { // The guarded saveDirectly below authorizes the publish against the version this // read saw, and the focus-disruption path has no diff view that could observe // the file. Same contract as ApplyDiffTool/ApplyPatchTool: stat around the read - // and observe only when the file did not change underneath it. Without it the - // saveDirectly("edit") below rejects with "File not read yet". + // and keep the token only when the file did not change underneath it. The token + // stays local until the guarded publish consumes it: observing at read time would + // leave it in the task-wide registry through every later failure and rejection, + // where a later write_to_file could spend it on an unrelated overwrite. const preReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) fileContent = await fs.readFile(absolutePath, "utf8") const postReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) @@ -103,7 +107,7 @@ export class EditTool extends BaseTool<"edit"> { if (preReadStats && postReadStats) { const preReadToken = versionTokenOfStat(preReadStats) if (preReadToken === versionTokenOfStat(postReadStats)) { - task.observationRegistry.observe(absolutePath, preReadToken) + readVersionToken = preReadToken } } } catch (error) { @@ -226,7 +230,13 @@ export class EditTool extends BaseTool<"edit"> { // Save the changes if (isPreventFocusDisruptionEnabled) { // Direct file write without diff view or opening the file. This tool only - // edits existing files, so edit-guard semantics require a prior read. + // edits existing files, so edit-guard semantics require a prior read. The + // observation is recorded here, at the guarded publish that consumes it, so a + // failed match, a rejection, or the diff-view save never leaves this read's + // token in the task-wide registry. + if (readVersionToken !== undefined) { + task.observationRegistry.observe(absolutePath, readVersionToken) + } await task.diffViewProvider.saveDirectly( relPath, newContent, diff --git a/src/core/tools/SearchReplaceTool.ts b/src/core/tools/SearchReplaceTool.ts index 4e932ee5c4b..3faf1630973 100644 --- a/src/core/tools/SearchReplaceTool.ts +++ b/src/core/tools/SearchReplaceTool.ts @@ -94,12 +94,16 @@ export class SearchReplaceTool extends BaseTool<"search_replace"> { } let fileContent: string + // Version token from this tool's own read; observed only at the guarded publish below. + let readVersionToken: string | undefined try { // The guarded saveDirectly below authorizes the publish against the version this // read saw, and the focus-disruption path has no diff view that could observe // the file. Same contract as ApplyDiffTool/ApplyPatchTool: stat around the read - // and observe only when the file did not change underneath it. Without it the - // saveDirectly("edit") below rejects with "File not read yet". + // and keep the token only when the file did not change underneath it. The token + // stays local until the guarded publish consumes it: observing at read time would + // leave it in the task-wide registry through every later failure and rejection, + // where a later write_to_file could spend it on an unrelated overwrite. const preReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) fileContent = await fs.readFile(absolutePath, "utf8") const postReadStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined) @@ -108,7 +112,7 @@ export class SearchReplaceTool extends BaseTool<"search_replace"> { if (preReadStats && postReadStats) { const preReadToken = versionTokenOfStat(preReadStats) if (preReadToken === versionTokenOfStat(postReadStats)) { - task.observationRegistry.observe(absolutePath, preReadToken) + readVersionToken = preReadToken } } } catch (error) { @@ -222,7 +226,13 @@ export class SearchReplaceTool extends BaseTool<"search_replace"> { // Save the changes if (isPreventFocusDisruptionEnabled) { // Direct file write without diff view or opening the file. This tool only - // edits existing files, so edit-guard semantics require a prior read. + // edits existing files, so edit-guard semantics require a prior read. The + // observation is recorded here, at the guarded publish that consumes it, so a + // failed match, a rejection, or the diff-view save never leaves this read's + // token in the task-wide registry. + if (readVersionToken !== undefined) { + task.observationRegistry.observe(absolutePath, readVersionToken) + } await task.diffViewProvider.saveDirectly( relPath, newContent, diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts index 2f2dba2acc1..9d45e66f627 100644 --- a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -271,4 +271,37 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { expect(mockPushToolResult).not.toHaveBeenCalledWith("Saved file") }, ) + + it("leaves the registry empty when the diff fails to apply", async () => { + // The read happened but no hunk landed. The token must not stay in the task-wide + // registry, or a later write_to_file could spend this read's token on a + // full-file overwrite of content the model never received. + mockTask.diffStrategy = { + applyDiff: vi.fn().mockResolvedValue({ success: false, error: "context mismatch" }), + } as unknown as Task["diffStrategy"] + + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockSaveDirectly).not.toHaveBeenCalled() + expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) + }) + + it("leaves the registry empty when the user rejects the diff", async () => { + // A rejection publishes nothing, so the read's token must not authorize a later + // write either. + mockAskApproval.mockResolvedValueOnce(false) + + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockSaveDirectly).not.toHaveBeenCalled() + expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) + }) }) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index ef8c9d4803b..12994bc626c 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -322,6 +322,44 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { }, ) + it("update: leaves the registry empty when the hunk fails to apply", async () => { + // The hunk read happened; the patch did not land. The token must not stay in the + // task-wide registry, or a later write_to_file could spend this read's token on a + // full-file overwrite of content the model never received. + const failingPatch = `*** Begin Patch +*** Update File: src/thing.ts +@@ +-absent context line ++modified file content +*** End Patch` + + await tool.execute({ patch: failingPatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Failed to process patch")) + expect(mockSaveDirectly).not.toHaveBeenCalled() + expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) + }) + + it("update: leaves the registry empty when the user rejects the change", async () => { + // A rejection publishes nothing, so the read's token must not authorize a later + // write either. + mockAskApproval.mockResolvedValueOnce(false) + + await tool.execute({ patch: updatePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(mockPushToolResult).toHaveBeenCalledWith("Changes were rejected by the user.") + expect(mockSaveDirectly).not.toHaveBeenCalled() + expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) + }) + it("add: publishes the new file through the guarded saveDirectly with create kind", async () => { mockedFileExistsAtPath.mockResolvedValueOnce(false) diff --git a/src/core/tools/__tests__/editFileTool.spec.ts b/src/core/tools/__tests__/editFileTool.spec.ts index 28078b1d37a..cf2aab67c00 100644 --- a/src/core/tools/__tests__/editFileTool.spec.ts +++ b/src/core/tools/__tests__/editFileTool.spec.ts @@ -916,6 +916,46 @@ describe("editFileTool", () => { expect(mockTask.diffViewProvider.saveDirectly).not.toHaveBeenCalled() expect(mockHandleError).not.toHaveBeenCalled() }) + + it("leaves the registry empty when old_string does not match", async () => { + // The read happened but the edit failed. The token must not stay in the + // task-wide registry, or a later write_to_file could spend this read's token + // on a full-file overwrite of content the model never received. + const result = await executeEditFileTool( + { old_string: "NonExistent", new_string: "Whatever" }, + { fileExists: true, fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(result).toContain("No match found") + expect(mockTask.observationRegistry.get(absoluteFilePath)).toBeUndefined() + }) + + it("leaves the registry empty when an empty old_string hits an existing file", async () => { + // The reproduction from review: edit_file with an empty old_string records the + // read, then returns "use write_to_file instead". The registry must stay empty + // so the write_to_file that follows still needs a read of its own. + const result = await executeEditFileTool( + { old_string: "", new_string: "New file content" }, + { fileExists: true, fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(result).toContain("File already exists") + expect(mockTask.observationRegistry.get(absoluteFilePath)).toBeUndefined() + }) + + it("leaves the registry empty when the user rejects the edit", async () => { + // A rejection publishes nothing, so the read's token must not authorize a + // later write either. + mockAskApproval.mockResolvedValueOnce(false) + + const result = await executeEditFileTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileExists: true, fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(result).toContain("Changes were rejected by the user.") + expect(mockTask.observationRegistry.get(absoluteFilePath)).toBeUndefined() + }) }) describe("CRLF normalization", () => { diff --git a/src/core/tools/__tests__/editTool.spec.ts b/src/core/tools/__tests__/editTool.spec.ts index 6ca7d2a518f..81afc6baeba 100644 --- a/src/core/tools/__tests__/editTool.spec.ts +++ b/src/core/tools/__tests__/editTool.spec.ts @@ -602,5 +602,32 @@ describe("editTool", () => { expect(mockTask.diffViewProvider.reset).toHaveBeenCalled() expect(mockTask.didEditFile).toBe(false) }) + + it("leaves the registry empty when old_string does not match", async () => { + // The read happened but the edit failed. The token must not stay in the + // task-wide registry, or a later write_to_file could spend this read's token + // on a full-file overwrite of content the model never received. + const result = await executeEditTool( + { old_string: "NonExistent", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(result).toContain("No match found") + expect(mockTask.observationRegistry.get(absoluteFilePath)).toBeUndefined() + }) + + it("leaves the registry empty when the user rejects the edit", async () => { + // A rejection publishes nothing, so the read's token must not authorize a + // later write either. + mockAskApproval.mockResolvedValueOnce(false) + + const result = await executeEditTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(result).toContain("Changes were rejected by the user.") + expect(mockTask.observationRegistry.get(absoluteFilePath)).toBeUndefined() + }) }) }) diff --git a/src/core/tools/__tests__/searchReplaceTool.spec.ts b/src/core/tools/__tests__/searchReplaceTool.spec.ts index 0969e74a3b6..d524cf5cb68 100644 --- a/src/core/tools/__tests__/searchReplaceTool.spec.ts +++ b/src/core/tools/__tests__/searchReplaceTool.spec.ts @@ -617,5 +617,32 @@ describe("searchReplaceTool", () => { expect(mockCline.diffViewProvider.reset).toHaveBeenCalled() expect(mockCline.didEditFile).toBe(false) }) + + it("leaves the registry empty when old_string does not match", async () => { + // The read happened but the edit failed. The token must not stay in the + // task-wide registry, or a later write_to_file could spend this read's token + // on a full-file overwrite of content the model never received. + const result = await executeSearchReplaceTool( + { old_string: "NonExistent", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(result).toContain("No match found") + expect(mockCline.observationRegistry.get(absoluteFilePath)).toBeUndefined() + }) + + it("leaves the registry empty when the user rejects the edit", async () => { + // A rejection publishes nothing, so the read's token must not authorize a + // later write either. + mockAskApproval.mockResolvedValueOnce(false) + + const result = await executeSearchReplaceTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3", experiments: focusDisruption }, + ) + + expect(result).toContain("Changes were rejected by the user.") + expect(mockCline.observationRegistry.get(absoluteFilePath)).toBeUndefined() + }) }) }) From e976591c4da2446b6fbd35df3a0452bd60df5d1e Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Sun, 11 Oct 2026 20:23:46 +0800 Subject: [PATCH 34/79] test(tools): cover the diff-view branch of the observation rule The registration for this row (comment 6107451284) lists three non-publishing outcomes that must leave the task-wide registry as they found it: a failed match, a rejected approval, and the diff-view branch. The previous commit shipped tests for the first two; this adds the third for each tool: run the tool with the focus-disruption experiment off, let the edit succeed through saveChanges(), and assert the registry holds no entry for the path. Before the fix the read-time observe left the token behind on this branch too, so all five new tests run red against the pre-fix production file (5/5) and green after it; the five touched specs are 127 passed. eslint --max-warnings=0 and prettier --check are clean on all five spec files. --- .../applyDiffTool.guardedWrite.spec.ts | 35 +++++++++++++++++++ .../__tests__/applyPatchTool.execute.spec.ts | 35 +++++++++++++++++++ src/core/tools/__tests__/editFileTool.spec.ts | 14 ++++++++ src/core/tools/__tests__/editTool.spec.ts | 14 ++++++++ .../tools/__tests__/searchReplaceTool.spec.ts | 14 ++++++++ 5 files changed, 112 insertions(+) diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts index 9d45e66f627..f0381c0a30c 100644 --- a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -304,4 +304,39 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) }) + + it("leaves the registry empty after the diff-view save", async () => { + // The diff-view branch saves through saveChanges(), which never consults the + // registry, so the read must not leave a token behind for a later write_to_file + // to spend on an unrelated overwrite. + const diffViewStub = mockTask.diffViewProvider as unknown as Record + diffViewStub.open = vi.fn().mockResolvedValue(undefined) + diffViewStub.update = vi.fn().mockResolvedValue(undefined) + diffViewStub.scrollToFirstDiff = vi.fn() + diffViewStub.saveChanges = vi.fn().mockResolvedValue({ + newProblemsMessage: "", + userEdits: undefined, + finalContent: "new content", + }) + mockTask.providerRef = { + deref: vi.fn().mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + diagnosticsEnabled: true, + writeDelayMs: 1000, + // Diff-view save path: no focus-disruption experiment. + experiments: {}, + }), + }), + } as unknown as Task["providerRef"] + + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(diffViewStub.saveChanges).toHaveBeenCalled() + expect(mockSaveDirectly).not.toHaveBeenCalled() + expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) + }) }) diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 12994bc626c..d341d3b0f13 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -360,6 +360,41 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) }) + it("leaves the registry empty after the diff-view save", async () => { + // The diff-view branch saves through saveChanges(), which never consults the + // registry, so the read must not leave a token behind for a later write_to_file + // to spend on an unrelated overwrite. + const diffViewStub = mockTask.diffViewProvider as unknown as Record + diffViewStub.open = vi.fn().mockResolvedValue(undefined) + diffViewStub.update = vi.fn().mockResolvedValue(undefined) + diffViewStub.scrollToFirstDiff = vi.fn() + diffViewStub.saveChanges = vi.fn().mockResolvedValue({ + newProblemsMessage: "", + userEdits: undefined, + finalContent: "new content", + }) + mockTask.providerRef = { + deref: vi.fn().mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + diagnosticsEnabled: true, + writeDelayMs: 1000, + // Diff-view save path: no focus-disruption experiment. + experiments: {}, + }), + }), + } as unknown as Task["providerRef"] + + await tool.execute({ patch: updatePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + }) + + expect(diffViewStub.saveChanges).toHaveBeenCalled() + expect(mockSaveDirectly).not.toHaveBeenCalled() + expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) + }) + it("add: publishes the new file through the guarded saveDirectly with create kind", async () => { mockedFileExistsAtPath.mockResolvedValueOnce(false) diff --git a/src/core/tools/__tests__/editFileTool.spec.ts b/src/core/tools/__tests__/editFileTool.spec.ts index cf2aab67c00..fc7f5daf88e 100644 --- a/src/core/tools/__tests__/editFileTool.spec.ts +++ b/src/core/tools/__tests__/editFileTool.spec.ts @@ -956,6 +956,20 @@ describe("editFileTool", () => { expect(result).toContain("Changes were rejected by the user.") expect(mockTask.observationRegistry.get(absoluteFilePath)).toBeUndefined() }) + + it("leaves the registry empty after the diff-view save", async () => { + // The diff-view branch saves through saveChanges(), which never consults the + // registry, so this tool's read must not leave a token behind for a later + // write_to_file to spend on an unrelated overwrite. + const result = await executeEditFileTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileExists: true, fileContent: "Line 1\nLine 2\nLine 3" }, + ) + + expect(result).toContain("Tool result message") + expect(mockTask.diffViewProvider.saveChanges).toHaveBeenCalled() + expect(mockTask.observationRegistry.get(absoluteFilePath)).toBeUndefined() + }) }) describe("CRLF normalization", () => { diff --git a/src/core/tools/__tests__/editTool.spec.ts b/src/core/tools/__tests__/editTool.spec.ts index 81afc6baeba..e5311744d92 100644 --- a/src/core/tools/__tests__/editTool.spec.ts +++ b/src/core/tools/__tests__/editTool.spec.ts @@ -629,5 +629,19 @@ describe("editTool", () => { expect(result).toContain("Changes were rejected by the user.") expect(mockTask.observationRegistry.get(absoluteFilePath)).toBeUndefined() }) + + it("leaves the registry empty after the diff-view save", async () => { + // The diff-view branch saves through saveChanges(), which never consults the + // registry, so this tool's read must not leave a token behind for a later + // write_to_file to spend on an unrelated overwrite. + const result = await executeEditTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3" }, + ) + + expect(result).toContain("Tool result message") + expect(mockTask.diffViewProvider.saveChanges).toHaveBeenCalled() + expect(mockTask.observationRegistry.get(absoluteFilePath)).toBeUndefined() + }) }) }) diff --git a/src/core/tools/__tests__/searchReplaceTool.spec.ts b/src/core/tools/__tests__/searchReplaceTool.spec.ts index d524cf5cb68..2e6ce615a79 100644 --- a/src/core/tools/__tests__/searchReplaceTool.spec.ts +++ b/src/core/tools/__tests__/searchReplaceTool.spec.ts @@ -644,5 +644,19 @@ describe("searchReplaceTool", () => { expect(result).toContain("Changes were rejected by the user.") expect(mockCline.observationRegistry.get(absoluteFilePath)).toBeUndefined() }) + + it("leaves the registry empty after the diff-view save", async () => { + // The diff-view branch saves through saveChanges(), which never consults the + // registry, so this tool's read must not leave a token behind for a later + // write_to_file to spend on an unrelated overwrite. + const result = await executeSearchReplaceTool( + { old_string: "Line 2", new_string: "Modified Line 2" }, + { fileContent: "Line 1\nLine 2\nLine 3" }, + ) + + expect(result).toContain("Tool result message") + expect(mockCline.diffViewProvider.saveChanges).toHaveBeenCalled() + expect(mockCline.observationRegistry.get(absoluteFilePath)).toBeUndefined() + }) }) }) From 6e0b4af2764f5c895e51b995b4320852c02a443e Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:40:16 +0800 Subject: [PATCH 35/79] style(tools): drop imports unused after the main refresh (lint gate) --- src/core/tools/__tests__/readFileTool.spec.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 4e1913e88c5..ace686f3bfe 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -18,12 +18,9 @@ import * as vscode from "vscode" import type { ToolUse } from "../../../shared/tools" import type { Task, ToolExecutionContext } from "../../task/Task" import { isBinaryFile } from "isbinaryfile" + import { readFileTool } from "../ReadFileTool" -import type { Stats } from "fs" -import type { LegacyReadFileParams } from "@roo-code/types" -import { readFileTool, ReadFileTool } from "../ReadFileTool" import { ObservationRegistry } from "../../task/observationRegistry" -import { computeVersionToken } from "../../../utils/versionToken" import { formatResponse } from "../../prompts/responses" import { validateImageForProcessing, processImageFile, isSupportedImageFormat } from "../helpers/imageHelpers" import { extractTextFromFile, getSupportedBinaryFormats } from "../../../integrations/misc/extract-text" From 24d36f9047f3b9718586b379cbd82a358decd477 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 17 Oct 2026 02:14:32 +0800 Subject: [PATCH 36/79] style(file-safety): drop SafeWriteTextOptions type import unused after the main refresh (lint gate) --- src/services/file-safety/__tests__/safeWriteText.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index ccfcffd3e8b..b6b33e4371c 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -4,7 +4,7 @@ import { execFile } from "child_process" import type { ChildProcess } from "child_process" import * as path from "path" -import { safeWriteText, type SafeWriteTextOptions } from "../safeWriteText" +import { safeWriteText } from "../safeWriteText" // Full mock for fs/promises — all methods are vi.fn() stubs vi.mock("fs/promises", () => ({ From ca6c518702d154d1a95feb635576493569be8bec Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:12:39 +0800 Subject: [PATCH 37/79] fix(tools): enforce the canonical working directory in guardedWrite resolveAbsolutePath was lexical only: a ".." segment or an intermediate symlink (link -> /external) let an approved workspace spelling publish outside the workspace while approval and .rooignore judged the workspace spelling (Security Boundaries row). guardedWrite now canonicalizes the target through its nearest existing ancestor and refuses the write before any guarded I/O when the bytes would land outside the working directory; the final under-lock check remains the shared publish-primitive design tracked at #1395. --- .../applyDiffTool.guardedWrite.spec.ts | 1 + src/core/tools/__tests__/guardedWrite.spec.ts | 37 +++++++++++ src/core/tools/guardedWrite.ts | 61 +++++++++++++++++++ 3 files changed, 99 insertions(+) diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts index f0381c0a30c..29a676df203 100644 --- a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -10,6 +10,7 @@ import type { Task } from "../../task/Task" import { ApplyDiffTool } from "../ApplyDiffTool" vi.mock("fs/promises", () => ({ + realpath: vi.fn(async (p: string) => String(p)), default: { readFile: vi.fn().mockResolvedValue("original file content\n"), stat: vi.fn().mockResolvedValue({ diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index 3325707353d..65765f4a6f4 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -25,6 +25,7 @@ import type { Task } from "../../task/Task" vi.mock("fs/promises", () => ({ access: vi.fn(), stat: vi.fn(), + realpath: vi.fn(), })) vi.mock("../../../utils/versionToken", () => ({ @@ -79,6 +80,9 @@ describe("guardedWrite (S4a, epic #1375)", () => { beforeEach(() => { vi.resetAllMocks() resetChain() + // Canonical-root check default: every path is its own real path, so the + // inside-workspace fixtures stay inside without per-test setup. + vi.mocked(fs.realpath).mockImplementation(async (p) => String(p)) }) describe("unobserved create", () => { @@ -455,6 +459,39 @@ describe("guardedWrite (S4a, epic #1375)", () => { preCommitVerify: expect.any(Function), }) }) + it("rejects a relative path that escapes the working directory", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("../outside/x.txt"), "v1") + const task = createMockTask({ observationRegistry: reg }) + + await expect(guardedWrite(task, "../outside/x.txt", "content", "update")).rejects.toThrow( + "outside the working directory", + ) + // The escape is refused before any guarded I/O: nothing was staged or published. + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) + + it("rejects a write whose intermediate directory is a symlink outside the workspace", async () => { + const reg = new ObservationRegistry() + const target = abs("link/config.json") + reg.observe(target, "v1") + mockedComputeVersionToken.mockResolvedValue("v1") + // link -> /external: the approval and the observation carry the workspace + // spelling, but the bytes land in /external without a canonical check. + vi.mocked(fs.realpath).mockImplementation(async (p) => { + const text = String(p) + if (text === abs("link") || text === target) { + return path.join("/external", path.basename(text)) + } + return text + }) + const task = createMockTask({ observationRegistry: reg }) + + await expect(guardedWrite(task, "link/config.json", "content", "update")).rejects.toThrow( + "outside the working directory", + ) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) it("normalizes an already-absolute input (trailing separator) to the observation key", async () => { const reg = new ObservationRegistry() diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index 8eb22beac50..d94102fedb9 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -315,6 +315,63 @@ function resolveAbsolutePath(task: Task, relPathOrAbsolute: string): string { return path.resolve(task.cwd, relPathOrAbsolute) } +/** + * Reject a write whose bytes would land outside the task working directory. + * The lexical resolve above is not a boundary: a relative path can carry ".." + * segments, and an intermediate symlink (link -> /external) makes an approved + * workspace spelling publish outside the workspace while approval and + * .rooignore judged the workspace spelling. Canonicalize through the nearest + * existing ancestor - the shape the publish itself follows - and require the + * result to sit under the canonical working directory. A workspace opened + * through a symlink matches the lexical root too, so inside paths keep working. + */ +async function assertWithinCanonicalRoot(cwd: string, absolutePath: string): Promise { + let root: string + try { + root = await fs.realpath(cwd) + } catch (error: unknown) { + // ENOENT falls back to the lexical root: the workspace directory may be + // created by this very write. Any other inspection error propagates + // rather than silently skipping the boundary. + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + throw error + } + root = path.resolve(cwd) + } + const lexicalRoot = path.resolve(cwd) + const roots = lexicalRoot === root ? [root] : [root, lexicalRoot] + // Resolve the nearest existing ancestor and re-append the missing tail, so + // symlinked parents are judged by where the bytes actually land. + let effective = absolutePath + const tail: string[] = [] + let probe = absolutePath + for (;;) { + try { + const real = await fs.realpath(probe) + effective = tail.length > 0 ? path.join(real, ...tail) : real + break + } catch (error: unknown) { + const code = (error as NodeJS.ErrnoException).code + if (code !== "ENOENT" && code !== "ENOTDIR") { + throw error + } + const parent = path.dirname(probe) + if (parent === probe) { + effective = absolutePath + break + } + tail.unshift(path.basename(probe)) + probe = parent + } + } + const inside = roots.some((candidate) => effective === candidate || effective.startsWith(candidate + path.sep)) + if (!inside) { + throw new Error( + `guardedWrite: refusing to write ${absolutePath}: the target resolves to ${effective}, outside the working directory ${lexicalRoot}`, + ) + } +} + /** * Guarded write entry point. * @@ -334,6 +391,10 @@ export async function guardedWrite( kind: GuardedWriteKind = "update", ): Promise { const absolutePath = resolveAbsolutePath(task, relPathOrAbsolute) + // The approval and .rooignore decisions were made on the workspace + // spelling; verify the canonical target before any guarded I/O so a ".." + // escape or a symlinked ancestor cannot publish outside the workspace. + await assertWithinCanonicalRoot(task.cwd, absolutePath) // Snapshot the observation when the write is issued, not when its link runs. // A refresh after a publish must not retroactively validate a second write that From 3519b239d42a50b0cff83b3762bce26445099116 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 17 Oct 2026 07:40:19 +0800 Subject: [PATCH 38/79] test(editor): give the saveDirectly spec the mocks the root check needs The canonical working-directory check reads realpath and calls resolve with a single argument; the spec's fs/promises and path mocks did not export realpath and sep, and its resolve mock required two arguments, so the misc lane failed on windows CI. Identity realpath, variadic resolve and sep keep every fixture inside the workspace. --- .../editor/__tests__/DiffViewProvider.spec.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index e9388e94515..dd6225f4b6c 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -24,6 +24,9 @@ vi.mock("delay", () => ({ // Mock fs/promises vi.mock("fs/promises", () => ({ readFile: vi.fn().mockResolvedValue("file content"), + // guardedWrite canonicalizes the target before publishing; identity realpath + // keeps every fixture inside the workspace. + realpath: vi.fn(async (p: string) => String(p)), writeFile: vi.fn().mockResolvedValue(undefined), access: vi.fn().mockResolvedValue(undefined), mkdir: vi.fn().mockResolvedValue(undefined), @@ -57,7 +60,10 @@ vi.mock("../../../utils/fs", () => ({ // Mock path vi.mock("path", () => ({ - resolve: vi.fn((cwd, relPath) => `${cwd}/${relPath}`), + // Variadic like the real resolve: guardedWrite also calls resolve(cwd) + // with a single argument. + resolve: vi.fn((...parts: string[]) => (parts.length === 1 ? parts[0] : `${parts[0]}/${parts.slice(1).join("/")}`)), + sep: "/", isAbsolute: vi.fn((p: string) => p.startsWith("/")), basename: vi.fn((path) => path.split("/").pop()), dirname: vi.fn((path) => path.split("/").slice(0, -1).join("/") || "/"), From 1f316d1de11bf8428865972a98733a047dea5c8b Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 17 Oct 2026 11:05:18 +0800 Subject: [PATCH 39/79] feat(s4b): guard the legacy diff-editor save path and re-check the root under the lock #1400's scope names both saveDirectly and saveChanges; saveChanges still published through updatedDocument.save(), leaving the legacy path outside the CAS guard. saveChanges now publishes the dirty buffer through guardedWrite (update kind), resyncs the buffer with a no-write revert on success, and rolls it back to the untouched on-disk content when the guard rejects. userEdits semantics are unchanged. The canonical working-directory check also moved where CR asked for it: saveDirectly validates the target before createDirectoriesForFile (mkdir through a symlinked ancestor used to land outside before the guard ran), and createIfAbsent/replaceIfVersion re-verify the authorized root inside their pre-commit verifiers - under the write lock, immediately before the rename - so an ancestor swapped after the entry check is caught before the rename follows it. Refs #1400, #1375 --- src/core/tools/__tests__/guardedWrite.spec.ts | 43 +++++++ src/core/tools/guardedWrite.ts | 22 +++- src/integrations/editor/DiffViewProvider.ts | 32 ++++- .../editor/__tests__/DiffViewProvider.spec.ts | 121 ++++++++++++++++++ 4 files changed, 210 insertions(+), 8 deletions(-) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index 65765f4a6f4..ccd53563891 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -492,6 +492,49 @@ describe("guardedWrite (S4a, epic #1375)", () => { ) expect(mockedSafeWriteText).not.toHaveBeenCalled() }) + it("re-checks the working directory under the lock before the commit rename (update)", async () => { + const reg = new ObservationRegistry() + const target = abs("sub/dir.txt") + reg.observe(target, "v1") + mockedComputeVersionToken.mockResolvedValue("v1") + const task = createMockTask({ observationRegistry: reg }) + + await guardedWrite(task, "sub/dir.txt", "content", "update") + + // The mocked publish captured the verifier the guard hands safeWriteText; + // it runs under the write lock immediately before the commit rename. Swap + // the ancestor now - after the entry check already ran - and the verifier + // must reject the rename instead of following the new link. + const verify = mockedSafeWriteText.mock.calls[0]![2]!.preCommitVerify! + vi.mocked(fs.realpath).mockImplementation(async (p) => { + const text = String(p) + if (text === abs("sub") || text === target) { + return path.join("/external", path.basename(text)) + } + return text + }) + + await expect(verify(target)).rejects.toThrow("outside the working directory") + }) + + it("re-checks the working directory under the lock before the commit rename (create)", async () => { + mockedFsAccess.mockRejectedValue({ code: "ENOENT" }) + const task = createMockTask() + + await guardedWrite(task, "sub/new.txt", "content", "create") + + const target = abs("sub/new.txt") + const verify = mockedSafeWriteText.mock.calls[0]![2]!.preCommitVerify! + vi.mocked(fs.realpath).mockImplementation(async (p) => { + const text = String(p) + if (text === abs("sub") || text === target) { + return path.join("/external", path.basename(text)) + } + return text + }) + + await expect(verify(target)).rejects.toThrow("outside the working directory") + }) it("normalizes an already-absolute input (trailing separator) to the observation key", async () => { const reg = new ObservationRegistry() diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index d94102fedb9..cbfd1b22eeb 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -151,7 +151,10 @@ async function fileIsAbsent(absolutePath: string): Promise { * write was issued for a file that was never read, so the caller must read * the file first, then retry. */ -export async function createIfAbsent(absolutePath: string, content: string): Promise { +// authorizedRoot (when supplied) is re-verified under the write lock immediately +// before the commit rename: an ancestor swapped to an outside link after the +// caller-side check is caught before the rename follows it. +export async function createIfAbsent(absolutePath: string, content: string, authorizedRoot?: string): Promise { return withWriteLock(absolutePath, async () => { try { await fs.access(absolutePath) @@ -169,6 +172,9 @@ export async function createIfAbsent(absolutePath: string, content: string): Pro // one that appears after verification returns can still be overwritten. await safeWriteText(absolutePath, content, { preCommitVerify: async (targetPath) => { + if (authorizedRoot !== undefined) { + await assertWithinCanonicalRoot(authorizedRoot, targetPath) + } try { await fs.access(targetPath) } catch (error: unknown) { @@ -212,6 +218,7 @@ export async function replaceIfVersion( absolutePath: string, expectedVersion: string, content: string, + authorizedRoot?: string, ): Promise { return withWriteLock(absolutePath, async () => { let currentVersion: string @@ -245,6 +252,9 @@ export async function replaceIfVersion( // overwritten, so this narrows the race rather than closing it. await safeWriteText(absolutePath, content, { preCommitVerify: async (targetPath) => { + if (authorizedRoot !== undefined) { + await assertWithinCanonicalRoot(authorizedRoot, targetPath) + } let verifiedVersion: string try { verifiedVersion = await computeVersionToken(targetPath) @@ -325,7 +335,7 @@ function resolveAbsolutePath(task: Task, relPathOrAbsolute: string): string { * result to sit under the canonical working directory. A workspace opened * through a symlink matches the lexical root too, so inside paths keep working. */ -async function assertWithinCanonicalRoot(cwd: string, absolutePath: string): Promise { +export async function assertWithinCanonicalRoot(cwd: string, absolutePath: string): Promise { let root: string try { root = await fs.realpath(cwd) @@ -420,17 +430,17 @@ export async function guardedWrite( } // Never read: only an absent target may be created. (The edit guard // above rejects before reaching this line.) - publishedVersion = await createIfAbsent(absolutePath, content) + publishedVersion = await createIfAbsent(absolutePath, content, task.cwd) } else if (kind === "edit") { - publishedVersion = await replaceIfVersion(absolutePath, obs.version, content) + publishedVersion = await replaceIfVersion(absolutePath, obs.version, content, task.cwd) } else if (kind === "create" && (await fileIsAbsent(absolutePath))) { // kind is "create" or "update": a "create" on a file that vanished // after the read recreates it. - publishedVersion = await createIfAbsent(absolutePath, content) + publishedVersion = await createIfAbsent(absolutePath, content, task.cwd) } else { // Otherwise the version recorded at read time must still match the // on-disk token. - publishedVersion = await replaceIfVersion(absolutePath, obs.version, content) + publishedVersion = await replaceIfVersion(absolutePath, obs.version, content, task.cwd) } // The file on disk is now what this write published. Record that token: a diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index f0152108d59..df24ca9281d 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -18,7 +18,7 @@ import { arePathsEqual, getReadablePath } from "../../utils/path" import { formatResponse } from "../../core/prompts/responses" import { diagnosticsToProblemsString, getNewDiagnostics } from "../diagnostics" import { Task } from "../../core/task/Task" -import { guardedWrite, type GuardedWriteKind } from "../../core/tools/guardedWrite" +import { assertWithinCanonicalRoot, guardedWrite, type GuardedWriteKind } from "../../core/tools/guardedWrite" import { DecorationController } from "./DecorationController" @@ -341,7 +341,31 @@ export class DiffViewProvider { const editedContent = updatedDocument.getText() if (updatedDocument.isDirty) { - await updatedDocument.save() + // Publish through the S4b guarded-write API (epic #1375, #1400): the + // legacy diff-editor save path must pass the same CAS guard as the + // plain-diff path; saving the editor buffer directly would overwrite + // changes the model never re-read. + const guardTask = this.taskRef.deref() + if (!guardTask) { + // Fail closed: without the owning task the observation registry is + // unreachable and the write cannot be guarded. + throw new Error("Cannot guard the write: the owning task is no longer available") + } + let guardError: unknown + try { + await guardedWrite(guardTask, this.relPath, editedContent, "update") + } catch (error: unknown) { + guardError = error + } + // The guard published the buffer's bytes (or rejected): resync the buffer + // to the file either way. On success the revert is content-preserving + // (the guard wrote these bytes); on failure it rolls the buffer back to + // the untouched on-disk content so no unsaved buffer survives a rejected + // publish. The revert writes nothing itself. + await updatedDocument.revert({ save: false }) + if (guardError) { + throw guardError + } } // Stop tracking touches and cancel any pending scroll-to-diff before any @@ -1172,6 +1196,10 @@ export class DiffViewProvider { // unreachable and the write cannot be guarded. throw new Error("Cannot guard the write: the owning task is no longer available") } + // Fail closed on an escaped target before creating directories for it: + // mkdir -p through a symlinked ancestor would materialize directories + // outside the working directory before the guard's own check could run. + await assertWithinCanonicalRoot(task.cwd, absolutePath) await createDirectoriesForFile(absolutePath) await guardedWrite(task, relPath, content, writeKind) diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index dd6225f4b6c..8a981f0abf1 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -13,6 +13,7 @@ import * as fs from "fs/promises" import { computeVersionToken } from "../../../utils/versionToken" import { safeWriteText } from "../../../services/file-safety/safeWriteText" import { ObservationRegistry } from "../../../core/task/observationRegistry" +import { createDirectoriesForFile } from "../../../utils/fs" import { acquireFileLock } from "../../../utils/fileLock" import type { Task } from "../../../core/task/Task" @@ -998,6 +999,126 @@ describe("DiffViewProvider", () => { ) expect(safeWriteText).not.toHaveBeenCalled() }) + it("rejects an escaped target before creating directories for it", async () => { + // The target resolves outside the workspace (symlinked file). The check + // must run before mkdir -p: creating directories through a symlinked + // ancestor would already have written outside when the guard next ran. + vi.mocked(fs.realpath) + .mockImplementationOnce(async (p) => String(p)) + .mockImplementationOnce(async () => "/external/test.ts") + + await expect(diffViewProvider.saveDirectly("test.ts", "new content", true, false, 0)).rejects.toThrow( + "outside the working directory", + ) + expect(createDirectoriesForFile).not.toHaveBeenCalled() + expect(safeWriteText).not.toHaveBeenCalled() + }) + + describe("guarded saveChanges publish (S4b, #1400)", () => { + const setupDirtyDoc = (text = "new content") => { + const document = { + getText: vi.fn().mockReturnValue(text), + isDirty: true, + save: vi.fn().mockResolvedValue(undefined), + revert: vi.fn().mockResolvedValue(undefined), + } + diffViewProvider["relPath"] = "test.ts" + diffViewProvider["newContent"] = "new content" + // Structural double: saveChanges only reaches the document's + // getText/isDirty/save/revert members. + diffViewProvider["activeDiffEditor"] = { document } as unknown as vscode.TextEditor + diffViewProvider["preDiagnostics"] = [] + diffViewProvider.closeAllDiffViews = vi.fn().mockResolvedValue(undefined) + diffViewProvider.keepOrCloseEditedFile = vi.fn().mockResolvedValue(undefined) + diffViewProvider.restorePreviewTabs = vi.fn().mockResolvedValue(undefined) + return document + } + + it("publishes the dirty buffer through the guarded write and resyncs without a second write", async () => { + const document = setupDirtyDoc() + + const result = await diffViewProvider.saveChanges(false, 0) + + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { + preCommitVerify: expect.any(Function), + }) + // The guard wrote the buffer bytes; the buffer is resynced with a no-write + // revert instead of a second unguarded document save. + expect(document.revert).toHaveBeenCalledWith({ save: false }) + expect(document.save).not.toHaveBeenCalled() + // Clean save: no userEdits behavior change. + expect(result.userEdits).toBeUndefined() + }) + + it("reports userEdits when the buffer diverged from the proposed content", async () => { + setupDirtyDoc("new content with user tweak") + + const result = await diffViewProvider.saveChanges(false, 0) + + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content with user tweak", { + preCommitVerify: expect.any(Function), + }) + expect(result.userEdits).toBeDefined() + }) + + it("rejects an unobserved saveChanges to an existing file and rolls the buffer back", async () => { + const document = setupDirtyDoc() + mockTask.observationRegistry.clear() + + await expect(diffViewProvider.saveChanges(false, 0)).rejects.toThrow( + "File already exists at /mock/cwd/test.ts and was not read before this write -- read the file first, then retry.", + ) + expect(safeWriteText).not.toHaveBeenCalled() + // The rejected publish leaves no unsaved buffer and no unguarded save. + expect(document.revert).toHaveBeenCalledWith({ save: false }) + expect(document.save).not.toHaveBeenCalled() + }) + + it("rejects a stale saveChanges and rolls the editor buffer back", async () => { + const document = setupDirtyDoc() + vi.mocked(computeVersionToken).mockResolvedValue("v2") + + await expect(diffViewProvider.saveChanges(false, 0)).rejects.toThrow("Stale version") + expect(safeWriteText).not.toHaveBeenCalled() + expect(document.revert).toHaveBeenCalledWith({ save: false }) + }) + + it("fails a deleted-after-read saveChanges with the re-read remediation", async () => { + setupDirtyDoc() + vi.mocked(computeVersionToken).mockRejectedValue( + Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }), + ) + + await expect(diffViewProvider.saveChanges(false, 0)).rejects.toThrow( + "File was deleted after it was read", + ) + expect(safeWriteText).not.toHaveBeenCalled() + }) + + it("creates an unobserved file when the saveChanges target is absent", async () => { + setupDirtyDoc() + mockTask.observationRegistry.clear() + vi.mocked(fs.access).mockRejectedValue( + Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }), + ) + + await diffViewProvider.saveChanges(false, 0) + + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { + preCommitVerify: expect.any(Function), + }) + }) + + it("fails closed when the owning task has been collected", async () => { + setupDirtyDoc() + diffViewProvider["taskRef"] = { deref: () => undefined } as unknown as WeakRef + + await expect(diffViewProvider.saveChanges(false, 0)).rejects.toThrow( + "Cannot guard the write: the owning task is no longer available", + ) + expect(safeWriteText).not.toHaveBeenCalled() + }) + }) }) }) From 2eec81c1cb9ee86beefbfe178c7454f0d3176655 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 17 Oct 2026 11:21:55 +0800 Subject: [PATCH 40/79] fix(s4b): roll the rejected saveChanges buffer back with an editor edit TextDocument has no revert() in the extension API surface this repo compiles against (CI compile 22cf25c7d), and the three tab-management methods are private. The rejected publish now rolls the buffer back to the pre-diff content through the editor's edit builder over a whole-document validateRange; the success path keeps save() purely to re-sync the dirty flag over the bytes the guard already wrote. Private members in the test double are reached with bracket access. --- src/integrations/editor/DiffViewProvider.ts | 30 +++++++----- .../editor/__tests__/DiffViewProvider.spec.ts | 47 ++++++++++++------- 2 files changed, 49 insertions(+), 28 deletions(-) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index df24ca9281d..cf4dc4a846d 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -351,21 +351,29 @@ export class DiffViewProvider { // unreachable and the write cannot be guarded. throw new Error("Cannot guard the write: the owning task is no longer available") } - let guardError: unknown try { await guardedWrite(guardTask, this.relPath, editedContent, "update") } catch (error: unknown) { - guardError = error - } - // The guard published the buffer's bytes (or rejected): resync the buffer - // to the file either way. On success the revert is content-preserving - // (the guard wrote these bytes); on failure it rolls the buffer back to - // the untouched on-disk content so no unsaved buffer survives a rejected - // publish. The revert writes nothing itself. - await updatedDocument.revert({ save: false }) - if (guardError) { - throw guardError + // The guard rejected the publish: roll the editor buffer back to the + // content the diff started from - the file on disk is untouched - so no + // unsaved buffer survives a rejected publish, then surface the + // remediation to the tool layer. + const editor = this.activeDiffEditor + const rollback = this.originalContent ?? "" + const fullRange = updatedDocument.validateRange( + // Whole-document range: lineCount is one past the last line, so this + // covers every byte the buffer holds. + new vscode.Range(0, 0, updatedDocument.lineCount, 0), + ) + await editor.edit((builder) => { + builder.replace(fullRange, rollback) + }) + throw error } + // The guarded publish already wrote the buffer's bytes; save() only + // re-syncs the editor's dirty flag over identical content - it carries + // the guard's verdict, it does not bypass the guard. + await updatedDocument.save() } // Stop tracking touches and cancel any pending scroll-to-diff before any diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 8a981f0abf1..12e52da54c8 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -1016,36 +1016,45 @@ describe("DiffViewProvider", () => { describe("guarded saveChanges publish (S4b, #1400)", () => { const setupDirtyDoc = (text = "new content") => { + const replace = vi.fn() const document = { getText: vi.fn().mockReturnValue(text), isDirty: true, save: vi.fn().mockResolvedValue(undefined), - revert: vi.fn().mockResolvedValue(undefined), + lineCount: 1, + validateRange: vi.fn((r: unknown) => r), } diffViewProvider["relPath"] = "test.ts" diffViewProvider["newContent"] = "new content" + diffViewProvider["originalContent"] = "disk content" // Structural double: saveChanges only reaches the document's - // getText/isDirty/save/revert members. - diffViewProvider["activeDiffEditor"] = { document } as unknown as vscode.TextEditor + // getText/isDirty/save/lineCount/validateRange members and the editor's edit. + diffViewProvider["activeDiffEditor"] = { + document, + edit: vi.fn(async (cb: (b: { replace: typeof replace }) => void) => { + cb({ replace }) + return true + }), + } as unknown as vscode.TextEditor diffViewProvider["preDiagnostics"] = [] - diffViewProvider.closeAllDiffViews = vi.fn().mockResolvedValue(undefined) - diffViewProvider.keepOrCloseEditedFile = vi.fn().mockResolvedValue(undefined) - diffViewProvider.restorePreviewTabs = vi.fn().mockResolvedValue(undefined) - return document + diffViewProvider["closeAllDiffViews"] = vi.fn().mockResolvedValue(undefined) + diffViewProvider["keepOrCloseEditedFile"] = vi.fn().mockResolvedValue(undefined) + diffViewProvider["restorePreviewTabs"] = vi.fn().mockResolvedValue(undefined) + return { document, replace } } it("publishes the dirty buffer through the guarded write and resyncs without a second write", async () => { - const document = setupDirtyDoc() + const { document, replace } = setupDirtyDoc() const result = await diffViewProvider.saveChanges(false, 0) expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function), }) - // The guard wrote the buffer bytes; the buffer is resynced with a no-write - // revert instead of a second unguarded document save. - expect(document.revert).toHaveBeenCalledWith({ save: false }) - expect(document.save).not.toHaveBeenCalled() + // The guard wrote the buffer bytes; save() only re-syncs the dirty + // flag over identical content, and no rollback edit is made. + expect(document.save).toHaveBeenCalled() + expect(replace).not.toHaveBeenCalled() // Clean save: no userEdits behavior change. expect(result.userEdits).toBeUndefined() }) @@ -1062,25 +1071,27 @@ describe("DiffViewProvider", () => { }) it("rejects an unobserved saveChanges to an existing file and rolls the buffer back", async () => { - const document = setupDirtyDoc() + const { document, replace } = setupDirtyDoc() mockTask.observationRegistry.clear() await expect(diffViewProvider.saveChanges(false, 0)).rejects.toThrow( "File already exists at /mock/cwd/test.ts and was not read before this write -- read the file first, then retry.", ) expect(safeWriteText).not.toHaveBeenCalled() - // The rejected publish leaves no unsaved buffer and no unguarded save. - expect(document.revert).toHaveBeenCalledWith({ save: false }) + // The rejected publish rolls the buffer back to the pre-diff content + // (the untouched file) and never saves the rejected bytes. + expect(replace).toHaveBeenCalledWith(expect.anything(), "disk content") expect(document.save).not.toHaveBeenCalled() }) it("rejects a stale saveChanges and rolls the editor buffer back", async () => { - const document = setupDirtyDoc() + const { document, replace } = setupDirtyDoc() vi.mocked(computeVersionToken).mockResolvedValue("v2") await expect(diffViewProvider.saveChanges(false, 0)).rejects.toThrow("Stale version") expect(safeWriteText).not.toHaveBeenCalled() - expect(document.revert).toHaveBeenCalledWith({ save: false }) + expect(replace).toHaveBeenCalledWith(expect.anything(), "disk content") + expect(document.save).not.toHaveBeenCalled() }) it("fails a deleted-after-read saveChanges with the re-read remediation", async () => { @@ -1102,11 +1113,13 @@ describe("DiffViewProvider", () => { Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }), ) + const { document } = setupDirtyDoc() await diffViewProvider.saveChanges(false, 0) expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function), }) + expect(document.save).toHaveBeenCalled() }) it("fails closed when the owning task has been collected", async () => { From 529c830251b2a645d074d12273fdeed7e2ea033c Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 17 Oct 2026 12:39:18 +0800 Subject: [PATCH 41/79] fix(s4b): do not save the document after the guarded publish The guarded publish replaces the file through an atomic rename, so the file has changed externally by the time saveChanges would call updatedDocument.save(): VS Code raises its save-conflict confirmation, which never resolves unattended - the e2e-mock apply_diff and write_to_file suites timed out on it at 29208b727. The buffer and the file hold the same bytes after a successful publish, so the editor's external-change reconciliation clears the dirty flag on its own; the rejection path already rolls the buffer back with an editor edit. The publish path must not touch document.save() at all (pinned). --- src/integrations/editor/DiffViewProvider.ts | 10 ++++++---- .../editor/__tests__/DiffViewProvider.spec.ts | 12 ++++++------ 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index cf4dc4a846d..d1497e5ccd5 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -370,10 +370,12 @@ export class DiffViewProvider { }) throw error } - // The guarded publish already wrote the buffer's bytes; save() only - // re-syncs the editor's dirty flag over identical content - it carries - // the guard's verdict, it does not bypass the guard. - await updatedDocument.save() + // Deliberately no updatedDocument.save() here: the guarded publish + // replaced the file through an atomic rename, so the file changed + // externally and a save would raise VS Code's save-conflict + // confirmation (which hangs unattended flows). The buffer and the file + // hold the same bytes, so the editor's external-change reconciliation + // clears the dirty flag on its own. } // Stop tracking touches and cancel any pending scroll-to-diff before any diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 12e52da54c8..53baa7667f1 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -1051,9 +1051,10 @@ describe("DiffViewProvider", () => { expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function), }) - // The guard wrote the buffer bytes; save() only re-syncs the dirty - // flag over identical content, and no rollback edit is made. - expect(document.save).toHaveBeenCalled() + // The guard wrote the buffer bytes through an atomic rename; calling + // save() over that external change would raise the save-conflict + // confirmation, so the publish path must not save the document. + expect(document.save).not.toHaveBeenCalled() expect(replace).not.toHaveBeenCalled() // Clean save: no userEdits behavior change. expect(result.userEdits).toBeUndefined() @@ -1107,19 +1108,18 @@ describe("DiffViewProvider", () => { }) it("creates an unobserved file when the saveChanges target is absent", async () => { - setupDirtyDoc() + const { document } = setupDirtyDoc() mockTask.observationRegistry.clear() vi.mocked(fs.access).mockRejectedValue( Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }), ) - const { document } = setupDirtyDoc() await diffViewProvider.saveChanges(false, 0) expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { preCommitVerify: expect.any(Function), }) - expect(document.save).toHaveBeenCalled() + expect(document.save).not.toHaveBeenCalled() }) it("fails closed when the owning task has been collected", async () => { From 0e143148f7c28d575e0e0bf50772563c3d666355 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 17 Oct 2026 13:03:59 +0800 Subject: [PATCH 42/79] fix(s4b): record the diff-open observation the guarded saveChanges CAS needs The diff-view save flows (write_to_file, apply_diff's diff-view branch, edit/search_replace/apply_patch) never recorded an observation, and open() itself creates the empty file for new targets. The saveChanges guard therefore rejected every accepted diff: unobserved + existing target -> "read the file first" (e2e-mock apply_diff and write_to_file timed out in the API retry loop at 0d13c318e). open() now records the on-disk version token right where it reads the original content (or creates the empty file), so the diff view IS the read for the CAS: the guarded publish checks against exactly what the user reviewed, and a change between opening the diff and accepting it fails as stale. Regression tests pin the token capture, the created-file CAS publish, and the open-to-accept stale case (NC: exactly these three fail without the observation). --- src/integrations/editor/DiffViewProvider.ts | 10 +++ .../editor/__tests__/DiffViewProvider.spec.ts | 71 +++++++++++++++++++ 2 files changed, 81 insertions(+) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index d1497e5ccd5..15fb6295f5b 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -15,6 +15,7 @@ import { import { createDirectoriesForFile } from "../../utils/fs" import { arePathsEqual, getReadablePath } from "../../utils/path" +import { computeVersionToken } from "../../utils/versionToken" import { formatResponse } from "../../core/prompts/responses" import { diagnosticsToProblemsString, getNewDiagnostics } from "../diagnostics" import { Task } from "../../core/task/Task" @@ -134,6 +135,15 @@ export class DiffViewProvider { if (!fileExists) { await fs.writeFile(absolutePath, "") } + // The diff view is the read for the guarded-write contract (epic #1375, + // #1400): record the on-disk version token for exactly what the user is + // about to review, so saveChanges' guarded publish CAS-checks against it. + // A change between opening the diff and accepting it fails the guard as + // stale instead of silently overwriting the newer content. + const openTask = this.taskRef.deref() + if (openTask) { + openTask.observationRegistry.observe(absolutePath, await computeVersionToken(absolutePath)) + } // If the file was already open, close it (must happen after showing the // diff view since if it's the only tab the column will close). diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 53baa7667f1..52f10b14c69 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -1042,6 +1042,33 @@ describe("DiffViewProvider", () => { diffViewProvider["restorePreviewTabs"] = vi.fn().mockResolvedValue(undefined) return { document, replace } } + // Stub the VS Code surface open() needs so the diff editor resolves + // immediately: the visible editor list, showTextDocument, and the + // document/editor change events the open-wait polls. + const stubDiffEditorOpen = (fsPath: string) => { + const editor = { + document: { + uri: { fsPath, scheme: "file" }, + getText: vi.fn().mockReturnValue(""), + lineCount: 0, + }, + selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } }, + edit: vi.fn().mockResolvedValue(true), + revealRange: vi.fn(), + } + // Structural test doubles for the visible-editor surface; the repo's + // vscode.d.ts has no constructor to build real editors from. + vi.mocked(vscode.window).visibleTextEditors = [editor as unknown as vscode.TextEditor] + vi.mocked(vscode.window.showTextDocument).mockResolvedValue(editor as unknown as vscode.TextEditor) + vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => { + setTimeout( + () => callback({ uri: { fsPath, scheme: "file" } } as unknown as vscode.TextDocument), + 0, + ) + return { dispose: vi.fn() } + }) + vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() }) + } it("publishes the dirty buffer through the guarded write and resyncs without a second write", async () => { const { document, replace } = setupDirtyDoc() @@ -1122,6 +1149,50 @@ describe("DiffViewProvider", () => { expect(document.save).not.toHaveBeenCalled() }) + it("records the on-disk version token when the diff opens (the read for the CAS)", async () => { + mockTask.observationRegistry.clear() + diffViewProvider.editType = "modify" + vi.mocked(computeVersionToken).mockResolvedValue("tok-open") + + stubDiffEditorOpen(`${mockCwd}/test.ts`) + await diffViewProvider.open("test.ts") + + expect(mockTask.observationRegistry.get(`${mockCwd}/test.ts`)?.version).toBe("tok-open") + }) + + it("publishes a diff-flow-created file through the CAS (regression: e2e write_to_file)", async () => { + mockTask.observationRegistry.clear() + diffViewProvider.editType = "create" + vi.mocked(computeVersionToken).mockResolvedValue("tok-empty") + + stubDiffEditorOpen(`${mockCwd}/test.ts`) + await diffViewProvider.open("test.ts") + const { document, replace } = setupDirtyDoc() + + await diffViewProvider.saveChanges(false, 0) + + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { + preCommitVerify: expect.any(Function), + }) + expect(replace).not.toHaveBeenCalled() + expect(document.save).not.toHaveBeenCalled() + }) + + it("fails as stale when the file changed between opening the diff and accepting it", async () => { + mockTask.observationRegistry.clear() + diffViewProvider.editType = "modify" + vi.mocked(computeVersionToken).mockResolvedValueOnce("tok-open").mockResolvedValueOnce("tok-newer") + + stubDiffEditorOpen(`${mockCwd}/test.ts`) + await diffViewProvider.open("test.ts") + const { document, replace } = setupDirtyDoc() + + await expect(diffViewProvider.saveChanges(false, 0)).rejects.toThrow("Stale version") + + expect(safeWriteText).not.toHaveBeenCalled() + expect(replace).toHaveBeenCalledWith(expect.anything(), "disk content") + expect(document.save).not.toHaveBeenCalled() + }) it("fails closed when the owning task has been collected", async () => { setupDirtyDoc() diffViewProvider["taskRef"] = { deref: () => undefined } as unknown as WeakRef From 3f4b6ac4108f55614be825cc4f0a9b7a8bee1fec Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 17 Oct 2026 13:14:32 +0800 Subject: [PATCH 43/79] fix(s4b): carry rolled-back user edits in the rejection remediation A rejected guarded publish rolls the editor buffer back so no dirty buffer survives (a retry's open() would otherwise save it through an unguarded save), but that rollback discarded the user's buffer edits and the error carried no trace of them. Compute the same userEdits patch the success path computes and append it to the rejection message before the rollback clears the buffer, so the retry can merge the edits back in (CR thread 4301051494). Also assert the userEdits patch content, not just its presence, in the divergence test (CR thread 4301051484). NC: pinning the patch computation to undefined fails exactly the new remediation test. --- src/integrations/editor/DiffViewProvider.ts | 25 ++++++++++++++++--- .../editor/__tests__/DiffViewProvider.spec.ts | 17 ++++++++++++- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 15fb6295f5b..110dc5fff06 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -366,8 +366,21 @@ export class DiffViewProvider { } catch (error: unknown) { // The guard rejected the publish: roll the editor buffer back to the // content the diff started from - the file on disk is untouched - so no - // unsaved buffer survives a rejected publish, then surface the - // remediation to the tool layer. + // unsaved buffer survives a rejected publish (a retry's open() would + // otherwise save a dirty buffer through an unguarded save). The user's + // buffer edits are exposed in the rejection remediation BEFORE the + // rollback clears them, so the retry can merge them back in. + const newContentEOL = this.newContent.includes("\r\n") ? "\r\n" : "\n" + const normalizedEditedContent = editedContent.replace(/\r\n|\n/g, newContentEOL) + const normalizedNewContent = this.newContent.replace(/\r\n|\n/g, newContentEOL) + const lostUserEdits = + normalizedEditedContent === normalizedNewContent + ? undefined + : formatResponse.createPrettyPatch( + this.relPath.toPosix(), + normalizedNewContent, + normalizedEditedContent, + ) const editor = this.activeDiffEditor const rollback = this.originalContent ?? "" const fullRange = updatedDocument.validateRange( @@ -378,7 +391,13 @@ export class DiffViewProvider { await editor.edit((builder) => { builder.replace(fullRange, rollback) }) - throw error + const guardMessage = error instanceof Error ? error.message : String(error) + throw new Error( + lostUserEdits + ? `${guardMessage}\n\nThe rolled-back buffer carried user edits; merge them into the retry:` + + `\n${lostUserEdits}` + : guardMessage, + ) } // Deliberately no updatedDocument.save() here: the guarded publish // replaced the file through an atomic rename, so the file changed diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 52f10b14c69..4af730921a9 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -1095,9 +1095,24 @@ describe("DiffViewProvider", () => { expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content with user tweak", { preCommitVerify: expect.any(Function), }) - expect(result.userEdits).toBeDefined() + expect(result.userEdits).toContain("new content with user tweak") }) + it("exposes rolled-back user edits in the rejection remediation", async () => { + setupDirtyDoc("new content with user tweak") + mockTask.observationRegistry.clear() + + const error = await diffViewProvider.saveChanges(false, 0).then( + () => undefined, + (e: unknown) => e as Error, + ) + + expect(error?.message).toContain("File already exists at /mock/cwd/test.ts") + // The rollback discards the buffer's user edits, so the remediation + // must carry them for the retry to merge. + expect(error?.message).toContain("user edits") + expect(error?.message).toContain("new content with user tweak") + }) it("rejects an unobserved saveChanges to an existing file and rolls the buffer back", async () => { const { document, replace } = setupDirtyDoc() mockTask.observationRegistry.clear() From 63a98568f289100c6944a1c03eda981edc6d96c5 Mon Sep 17 00:00:00 2001 From: dsh-agent Date: Thu, 22 Oct 2026 02:49:09 +0800 Subject: [PATCH 44/79] fix(diffview): capture the version token before reading the original content The token was computed after the originalContent read, so a change landing between the read and the token was folded into both: the snapshot the user reviewed and the token the publish CAS-checked against agreed with each other but not with what the user actually saw. The token is now captured first for an existing file; a file created by the diff flow still computes its token after the empty file exists. Test: the original-content read flips the token stub, so a token taken after the read would observe the newer value; the assertion pins the pre-read token. --- src/integrations/editor/DiffViewProvider.ts | 13 +++++++++++- .../editor/__tests__/DiffViewProvider.spec.ts | 21 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 110dc5fff06..b6491ce827e 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -121,6 +121,12 @@ export class DiffViewProvider { // after editing to see if cline needs to fix anything. this.preDiagnostics = vscode.languages.getDiagnostics() + // Capture the on-disk version token for the content the user is about to + // review BEFORE reading it: computing it afterwards would fold a concurrent + // change into both the snapshot and the token, so the guarded publish would + // accept a state the user never reviewed. + const observedVersionToken = fileExists ? await computeVersionToken(absolutePath) : undefined + if (fileExists) { this.originalContent = await fs.readFile(absolutePath, "utf-8") } else { @@ -142,7 +148,12 @@ export class DiffViewProvider { // stale instead of silently overwriting the newer content. const openTask = this.taskRef.deref() if (openTask) { - openTask.observationRegistry.observe(absolutePath, await computeVersionToken(absolutePath)) + // A file created by this diff flow has no pre-read token: compute it now, + // after the empty file exists, so the publish CAS-checks what it created. + openTask.observationRegistry.observe( + absolutePath, + observedVersionToken ?? (await computeVersionToken(absolutePath)), + ) } // If the file was already open, close it (must happen after showing the diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 4af730921a9..363edcfabdf 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -1175,6 +1175,27 @@ describe("DiffViewProvider", () => { expect(mockTask.observationRegistry.get(`${mockCwd}/test.ts`)?.version).toBe("tok-open") }) + it("captures the version token before reading the original content", async () => { + // A change between the read and the token computation would otherwise be + // folded into both the snapshot and the token, so the guarded publish + // would accept content the user never reviewed. Pinning the order makes + // the CAS cover exactly the reviewed bytes. + mockTask.observationRegistry.clear() + diffViewProvider.editType = "modify" + vi.mocked(computeVersionToken).mockResolvedValue("tok-before") + // The original-content read changes the on-disk version: a token taken + // after the read would observe "tok-after". + vi.mocked(fs.readFile).mockImplementationOnce(async () => { + vi.mocked(computeVersionToken).mockResolvedValue("tok-after") + return "disk content" + }) + + stubDiffEditorOpen(`${mockCwd}/test.ts`) + await diffViewProvider.open("test.ts") + + expect(mockTask.observationRegistry.get(`${mockCwd}/test.ts`)?.version).toBe("tok-before") + }) + it("publishes a diff-flow-created file through the CAS (regression: e2e write_to_file)", async () => { mockTask.observationRegistry.clear() diffViewProvider.editType = "create" From 295215567393baaff6cf919a307efcd12280d5b5 Mon Sep 17 00:00:00 2001 From: dsh-agent Date: Thu, 22 Oct 2026 03:00:17 +0800 Subject: [PATCH 45/79] chore(guarded-write): mark the test-only chain reset as internal The production dead-code check (knip --production) reports resetChain as an unused export because only tests reset the per-path chains. An @internal tag is the supported mechanism for a test-only export. --- src/core/tools/guardedWrite.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index cbfd1b22eeb..008bc852d41 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -453,6 +453,9 @@ export async function guardedWrite( /** * Reset the per-path tail-promise chains (test hook). + * + * @internal Test-only: production code never resets the chains, so the production + * dead-code check must not report this export as unused. */ export function resetChain(): void { pendingChains.clear() From c5be3763867be2bbd39c10a677d8a5ecced8e87a Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:14:57 +0800 Subject: [PATCH 46/79] test(core): double fs/promises stat for the guarded-read wiring This branch stats around the tool read so the guarded publish is authorized against the version the diff was computed from. The merged upstream spec mocked only readFile, so every case died on "default.stat is not a function" before reaching the failure reporting under test (35 failures cleared). The stat double matches applyDiffTool.guardedWrite.spec.ts and the reporting assertions are unchanged. Also drop the explicit any on the mocked unlink parameter in safeWriteJson.test.ts. --- .../tools/__tests__/applyDiffTool.failureReporting.spec.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/core/tools/__tests__/applyDiffTool.failureReporting.spec.ts b/src/core/tools/__tests__/applyDiffTool.failureReporting.spec.ts index 7c372645d6e..3ebd2e00f5d 100644 --- a/src/core/tools/__tests__/applyDiffTool.failureReporting.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.failureReporting.spec.ts @@ -15,6 +15,11 @@ vi.mock("@roo-code/telemetry", () => ({ vi.mock("fs/promises", () => ({ default: { readFile: vi.fn().mockResolvedValue(""), + // ApplyDiffTool stats around its read so the guarded publish is authorized against the + // version the diff was computed from; one shared stats object means the file did not + // change underneath the read. This spec is about failure reporting, but the read still + // runs before the diff strategy is asked. + stat: vi.fn().mockResolvedValue({ dev: 1n, ino: 2n, size: 22n, mtimeNs: 100n, ctimeNs: 100n }), }, })) From 27cda88944a46060bc5961c0a1eb3c268fe6414f Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:53:20 +0800 Subject: [PATCH 47/79] fix(tools): fail apply_diff stale and pin the read result in stat-failure tests - apply_diff: after the diff view opens, compare its recorded baseline with the content this tool diffed against. open() re-reads the file, so a change that lands between the two reads would be guarded against the newer baseline while the save publishes content derived from the older one, silently overwriting that change. On a mismatch, revert the diff view and fail the tool stale. - read_file tests: assert the pushed result is the file content ("File: ") and not an "Error:" replacement in the four stat-failure tests, not merely that pushToolResult ran. --- src/core/tools/ApplyDiffTool.ts | 17 +++++++ .../applyDiffTool.guardedWrite.spec.ts | 50 ++++++++++++++++++- src/core/tools/__tests__/readFileTool.spec.ts | 22 ++++++-- 3 files changed, 84 insertions(+), 5 deletions(-) diff --git a/src/core/tools/ApplyDiffTool.ts b/src/core/tools/ApplyDiffTool.ts index 0160c571b9d..011ecbb7081 100644 --- a/src/core/tools/ApplyDiffTool.ts +++ b/src/core/tools/ApplyDiffTool.ts @@ -219,6 +219,23 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> { // Show diff view before asking for approval task.diffViewProvider.editType = "modify" await task.diffViewProvider.open(relPath) + // The diff above was computed against this tool's own read, but open() re-reads + // the file and records that newer text as the save baseline. If the file changed + // between the two reads, saveChanges() would guard the newer baseline while + // publishing content derived from the older one, silently overwriting the write + // that landed in between. Fail closed instead: nothing is saved until the model + // re-reads and reapplies against the current content. + if (task.diffViewProvider.originalContent !== originalContent) { + task.consecutiveMistakeCount++ + task.recordToolError("apply_diff") + const staleError = `The file ${relPath} changed after it was read for this diff, so the diff was not applied. Read the file again and reapply the diff to its current content.` + await task.say("error", staleError) + task.didToolFailInCurrentTurn = true + await task.diffViewProvider.revertChanges() + task.processQueuedMessages() + pushToolResult(staleError) + return + } await task.diffViewProvider.update(diffResult.content, true) task.diffViewProvider.scrollToFirstDiff() diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts index 29a676df203..5f0e3974e57 100644 --- a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -61,6 +61,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { | "providerRef" | "fileContextTracker" | "observationRegistry" + | "didToolFailInCurrentTurn" > let mockSaveDirectly: MockedFunction<(...args: unknown[]) => Promise> let mockAskApproval: MockedFunction<(...args: unknown[]) => Promise> @@ -102,6 +103,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { say: vi.fn().mockResolvedValue(undefined), processQueuedMessages: vi.fn(), didEditFile: false, + didToolFailInCurrentTurn: false, api: { getModel: () => ({ id: "claude-sonnet-4-5" }), } as unknown as Task["api"], @@ -311,7 +313,11 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { // registry, so the read must not leave a token behind for a later write_to_file // to spend on an unrelated overwrite. const diffViewStub = mockTask.diffViewProvider as unknown as Record - diffViewStub.open = vi.fn().mockResolvedValue(undefined) + // open() records the text it read; an unchanged file yields the same content the + // tool diffed against, so the stale-base guard lets the save through. + diffViewStub.open = vi.fn().mockImplementation(async () => { + diffViewStub.originalContent = "original file content\n" + }) diffViewStub.update = vi.fn().mockResolvedValue(undefined) diffViewStub.scrollToFirstDiff = vi.fn() diffViewStub.saveChanges = vi.fn().mockResolvedValue({ @@ -340,4 +346,46 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { expect(mockSaveDirectly).not.toHaveBeenCalled() expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) }) + + it("refuses to save when the file changed between the read and the diff view opening", async () => { + // The diff was computed against "original file content\n", but another writer + // replaced the file before open() re-read it. Saving would publish the older diff + // over that change while the guard checked the newer baseline. + const diffViewStub = mockTask.diffViewProvider as unknown as Record + diffViewStub.open = vi.fn().mockImplementation(async () => { + diffViewStub.originalContent = "written by another process\n" + }) + diffViewStub.update = vi.fn().mockResolvedValue(undefined) + diffViewStub.scrollToFirstDiff = vi.fn() + diffViewStub.revertChanges = vi.fn().mockResolvedValue(undefined) + diffViewStub.saveChanges = vi.fn().mockResolvedValue({ + newProblemsMessage: "", + userEdits: undefined, + finalContent: "new content", + }) + mockTask.providerRef = { + deref: vi.fn().mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + diagnosticsEnabled: true, + writeDelayMs: 1000, + experiments: {}, + }), + }), + } as unknown as Task["providerRef"] + + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(diffViewStub.update).not.toHaveBeenCalled() + expect(diffViewStub.saveChanges).not.toHaveBeenCalled() + expect(diffViewStub.revertChanges).toHaveBeenCalled() + expect(mockTask.didToolFailInCurrentTurn).toBe(true) + expect(mockPushToolResult).toHaveBeenCalledWith( + expect.stringContaining("changed after it was read for this diff"), + ) + }) }) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index ace686f3bfe..e569c49fb09 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -1923,7 +1923,9 @@ describe("ReadFileTool", () => { expect(reg.size).toBe(0) // The read still succeeds — a stat failure never fails the read. expect(mockTask.didToolFailInCurrentTurn).toBe(false) - expect(callbacks.pushToolResult).toHaveBeenCalled() + // The pushed result is the file content, not an error substituted for it. + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("File: stat-fail.ts")) + expect(callbacks.pushToolResult).not.toHaveBeenCalledWith(expect.stringContaining("Error")) }) it("leaves the target unobserved without failing the read when the post-read stat fails", async () => { @@ -1956,7 +1958,11 @@ describe("ReadFileTool", () => { expect(observeSpy).not.toHaveBeenCalled() expect(reg.size).toBe(0) expect(mockTask.didToolFailInCurrentTurn).toBe(false) - expect(callbacks.pushToolResult).toHaveBeenCalled() + // The pushed result is the file content, not an error substituted for it. + expect(callbacks.pushToolResult).toHaveBeenCalledWith( + expect.stringContaining("File: post-stat-fail.ts"), + ) + expect(callbacks.pushToolResult).not.toHaveBeenCalledWith(expect.stringContaining("Error")) }) it("legacy format: does not observe when the file mutates between the pre-read and post-read stats", async () => { @@ -2022,7 +2028,11 @@ describe("ReadFileTool", () => { expect(observeSpy).not.toHaveBeenCalled() expect(reg.size).toBe(0) expect(mockTask.didToolFailInCurrentTurn).toBe(false) - expect(callbacks.pushToolResult).toHaveBeenCalled() + // The pushed result is the file content, not an error substituted for it. + expect(callbacks.pushToolResult).toHaveBeenCalledWith( + expect.stringContaining("File: legacy-stat-fail.ts"), + ) + expect(callbacks.pushToolResult).not.toHaveBeenCalledWith(expect.stringContaining("Error")) }) it("legacy format: leaves the target unobserved when the post-read stat fails", async () => { const mockTask = createMockTask({ @@ -2059,7 +2069,11 @@ describe("ReadFileTool", () => { expect(observeSpy).not.toHaveBeenCalled() expect(reg.size).toBe(0) expect(mockTask.didToolFailInCurrentTurn).toBe(false) - expect(callbacks.pushToolResult).toHaveBeenCalled() + // The pushed result is the file content, not an error substituted for it. + expect(callbacks.pushToolResult).toHaveBeenCalledWith( + expect.stringContaining("File: legacy-post-stat-fail.ts"), + ) + expect(callbacks.pushToolResult).not.toHaveBeenCalledWith(expect.stringContaining("Error")) }) it("two separate Task-owned registries are independent", async () => { const regA = new ObservationRegistry() From 57393812d5b53c4af4f50d424d1c51f0e57b0c62 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:29:57 +0800 Subject: [PATCH 48/79] test(tools): give the failure-reporting fixture the save baseline open() records The stale-base guard compares the content apply_diff diffed against with diffViewProvider.originalContent, which open() sets from its own read. The failure-reporting fixture stubbed open() as a no-op that left originalContent at "", so every case that reached the diff-view branch was rejected as stale and never reported its block counts. The fixture's open() now reads through the same fs mock the tool reads through and records that text, which is what production does when the file has not changed between the two reads. The guard is unchanged: it is still proven by "refuses to save when the file changed between the read and the diff view opening", which overrides open() with a different content. --- .../applyDiffTool.failureReporting.spec.ts | 34 ++++++++++++------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/src/core/tools/__tests__/applyDiffTool.failureReporting.spec.ts b/src/core/tools/__tests__/applyDiffTool.failureReporting.spec.ts index 3ebd2e00f5d..269550057a7 100644 --- a/src/core/tools/__tests__/applyDiffTool.failureReporting.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.failureReporting.spec.ts @@ -73,6 +73,27 @@ describe("ApplyDiffTool failure reporting", () => { mockAskApproval = vi.fn().mockResolvedValue(true) mockHandleError = vi.fn().mockResolvedValue(undefined) + // The diff-view double mirrors the one behaviour execute now depends on: open() reads the + // file and records that text as the save baseline. Reading through the same fs mock the + // tool reads through keeps the fixture's base consistent, which is what the stale-base + // guard compares; a fixture that leaves originalContent at "" or from another read would + // report a stale base that never happened. Stale-base itself is covered by + // applyDiffTool.guardedWrite.spec.ts, which overrides open() with a different content. + const diffViewProviderStub = { + editType: undefined as "create" | "modify" | undefined, + originalContent: "" as string | undefined, + open: vi.fn(async () => { + diffViewProviderStub.originalContent = String(await vi.mocked(fs.readFile)(testFilePath as never)) + }), + update: vi.fn().mockResolvedValue(undefined), + reset: vi.fn().mockResolvedValue(undefined), + revertChanges: vi.fn().mockResolvedValue(undefined), + saveChanges: vi.fn().mockResolvedValue(undefined), + saveDirectly: vi.fn().mockResolvedValue(undefined), + scrollToFirstDiff: vi.fn(), + pushToolWriteResult: vi.fn().mockResolvedValue("Changes successfully applied."), + } + // Only the provider, edit tracking, and diff-view members used by execute are needed. mockTask = { cwd: "/workspace", @@ -91,18 +112,7 @@ describe("ApplyDiffTool failure reporting", () => { }), }), }, - diffViewProvider: { - editType: undefined, - originalContent: "", - open: vi.fn().mockResolvedValue(undefined), - update: vi.fn().mockResolvedValue(undefined), - reset: vi.fn().mockResolvedValue(undefined), - revertChanges: vi.fn().mockResolvedValue(undefined), - saveChanges: vi.fn().mockResolvedValue(undefined), - saveDirectly: vi.fn().mockResolvedValue(undefined), - scrollToFirstDiff: vi.fn(), - pushToolWriteResult: vi.fn().mockResolvedValue("Changes successfully applied."), - }, + diffViewProvider: diffViewProviderStub as unknown as Task["diffViewProvider"], fileContextTracker: { trackFileContext: vi.fn().mockResolvedValue(undefined) }, say: vi.fn().mockResolvedValue(undefined), ask: vi.fn().mockResolvedValue(undefined), From 874f7d1e33051ec4cb51d52b040c23ba2d766ac2 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 4 Nov 2026 06:41:45 +0800 Subject: [PATCH 49/79] test(tools): assert the file body in the stat-failure read tests The four stat-failure read tests checked the File: header and the absence of an Error, so a result that carried the header and no body would still pass. They now assert the mocked read body as well, which is what the surrounding comment already claimed. readFileTool.spec passes, eslint --max-warnings=0 exit 0. --- src/core/tools/__tests__/readFileTool.spec.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index e569c49fb09..9c7a6e6b5f5 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -1925,6 +1925,7 @@ describe("ReadFileTool", () => { expect(mockTask.didToolFailInCurrentTurn).toBe(false) // The pushed result is the file content, not an error substituted for it. expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("File: stat-fail.ts")) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("test content")) expect(callbacks.pushToolResult).not.toHaveBeenCalledWith(expect.stringContaining("Error")) }) @@ -1962,6 +1963,7 @@ describe("ReadFileTool", () => { expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.stringContaining("File: post-stat-fail.ts"), ) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("test content")) expect(callbacks.pushToolResult).not.toHaveBeenCalledWith(expect.stringContaining("Error")) }) @@ -2032,6 +2034,7 @@ describe("ReadFileTool", () => { expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.stringContaining("File: legacy-stat-fail.ts"), ) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("test content")) expect(callbacks.pushToolResult).not.toHaveBeenCalledWith(expect.stringContaining("Error")) }) it("legacy format: leaves the target unobserved when the post-read stat fails", async () => { @@ -2073,6 +2076,7 @@ describe("ReadFileTool", () => { expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.stringContaining("File: legacy-post-stat-fail.ts"), ) + expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("test content")) expect(callbacks.pushToolResult).not.toHaveBeenCalledWith(expect.stringContaining("Error")) }) it("two separate Task-owned registries are independent", async () => { From b4da9062ed4eafd639f8a7325032028a9fa7d5d5 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:31:27 +0800 Subject: [PATCH 50/79] test(task): cover observation-registry isolation at the Task layer The pre-merge gate is right that the registry was only covered in isolation: the changed Task behaviour is that each real Task constructs its own registry, and nothing asserted that. The new spec builds two real Task instances with startTask: false, checks both start empty, observes a path through the first and asserts the second stays empty. Control: giving Task a shared static registry makes it fail with 'expected true to be false'; restored byte-identically. --- .../__tests__/taskObservationRegistry.spec.ts | 259 ++++++++++++++++++ 1 file changed, 259 insertions(+) create mode 100644 src/core/task/__tests__/taskObservationRegistry.spec.ts diff --git a/src/core/task/__tests__/taskObservationRegistry.spec.ts b/src/core/task/__tests__/taskObservationRegistry.spec.ts new file mode 100644 index 00000000000..6573183e174 --- /dev/null +++ b/src/core/task/__tests__/taskObservationRegistry.spec.ts @@ -0,0 +1,259 @@ +import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker" +// npx vitest run core/task/__tests__/flushPendingToolResultsToHistory.spec.ts + +import * as os from "os" +import * as path from "path" +import * as vscode from "vscode" + +import type { GlobalState, ProviderSettings } from "@roo-code/types" +import { TelemetryService } from "@roo-code/telemetry" + +import { Task } from "../Task" +import { ClineProvider } from "../../webview/ClineProvider" +import { ContextProxy } from "../../config/ContextProxy" +import { providerIdentifiers } from "@roo-code/types/provider-identifiers" + +// Mock delay before any imports that might use it +vi.mock("delay", () => ({ + __esModule: true, + default: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("execa", () => ({ + execa: vi.fn(), +})) + +vi.mock("../../../utils/safeWriteJson", () => ({ + safeWriteJson: vi.fn().mockResolvedValue(undefined), +})) + +vi.mock("fs/promises", async (importOriginal) => { + const actual = (await importOriginal()) as Record + const mockFunctions = { + mkdir: vi.fn().mockResolvedValue(undefined), + writeFile: vi.fn().mockResolvedValue(undefined), + readFile: vi.fn().mockResolvedValue("[]"), + unlink: vi.fn().mockResolvedValue(undefined), + rmdir: vi.fn().mockResolvedValue(undefined), + } + + return { + ...actual, + ...mockFunctions, + default: mockFunctions, + } +}) + +const { mockPWaitFor } = vi.hoisted(() => { + return { mockPWaitFor: vi.fn().mockImplementation(async () => Promise.resolve()) } +}) + +vi.mock("p-wait-for", () => ({ + default: mockPWaitFor, +})) + +vi.mock("vscode", () => { + const mockDisposable = { dispose: vi.fn() } + const mockEventEmitter = { event: vi.fn(), fire: vi.fn() } + const mockTextDocument = { uri: { fsPath: "/mock/workspace/path/file.ts" } } + const mockTextEditor = { document: mockTextDocument } + const mockTab = { input: { uri: { fsPath: "/mock/workspace/path/file.ts" } } } + const mockTabGroup = { tabs: [mockTab] } + + return { + TabInputTextDiff: vi.fn(), + CodeActionKind: { + QuickFix: { value: "quickfix" }, + RefactorRewrite: { value: "refactor.rewrite" }, + }, + window: { + createTextEditorDecorationType: vi.fn().mockReturnValue({ + dispose: vi.fn(), + }), + visibleTextEditors: [mockTextEditor], + tabGroups: { + all: [mockTabGroup], + close: vi.fn(), + onDidChangeTabs: vi.fn(() => ({ dispose: vi.fn() })), + }, + showErrorMessage: vi.fn(), + }, + workspace: { + workspaceFolders: [ + { + uri: { fsPath: "/mock/workspace/path" }, + name: "mock-workspace", + index: 0, + }, + ], + createFileSystemWatcher: vi.fn(() => ({ + onDidCreate: vi.fn(() => mockDisposable), + onDidDelete: vi.fn(() => mockDisposable), + onDidChange: vi.fn(() => mockDisposable), + dispose: vi.fn(), + })), + fs: { + stat: vi.fn().mockResolvedValue({ type: 1 }), + }, + onDidSaveTextDocument: vi.fn(() => mockDisposable), + getConfiguration: vi.fn(() => ({ get: (_key: string, defaultValue: unknown) => defaultValue })), + }, + env: { + uriScheme: "vscode", + language: "en", + }, + EventEmitter: vi.fn().mockImplementation(function () { + return mockEventEmitter + }), + Disposable: { + from: vi.fn(), + }, + TabInputText: vi.fn(), + } +}) + +vi.mock("../../mentions", () => ({ + parseMentions: vi.fn().mockImplementation((text) => { + return Promise.resolve({ text: `processed: ${text}`, mode: undefined, contentBlocks: [] }) + }), + openMention: vi.fn(), + getLatestTerminalOutput: vi.fn(), +})) + +vi.mock("../../../integrations/misc/extract-text", () => ({ + extractTextFromFile: vi.fn().mockResolvedValue("Mock file content"), +})) + +vi.mock("../../environment/getEnvironmentDetails", () => ({ + getEnvironmentDetails: vi.fn().mockResolvedValue(""), +})) + +vi.mock("../../ignore/RooIgnoreController") + +vi.mock("../../condense", async (importOriginal) => { + const actual = (await importOriginal()) as Record + return { + ...actual, + summarizeConversation: vi.fn().mockResolvedValue({ + messages: [{ role: "user", content: [{ type: "text", text: "continued" }], ts: Date.now() }], + summary: "summary", + cost: 0, + newContextTokens: 1, + }), + } +}) + +vi.mock("../../../utils/storage", () => ({ + getTaskDirectoryPath: vi + .fn() + .mockImplementation((globalStoragePath, taskId) => Promise.resolve(`${globalStoragePath}/tasks/${taskId}`)), + getSettingsDirectoryPath: vi + .fn() + .mockImplementation((globalStoragePath) => Promise.resolve(`${globalStoragePath}/settings`)), +})) + +vi.mock("../../../utils/fs", () => ({ + fileExistsAtPath: vi.fn().mockReturnValue(false), +})) + +describe("Task observation registry isolation", () => { + let mockProvider: ClineProvider + let mockApiConfig: ProviderSettings + let mockOutputChannel: vscode.OutputChannel + let mockExtensionContext: vscode.ExtensionContext + + beforeEach(() => { + if (!TelemetryService.hasInstance()) { + TelemetryService.createInstance([]) + } + + const storageUri = { + fsPath: path.join(os.tmpdir(), "test-storage"), + } + + mockExtensionContext = { + globalState: { + get: vi.fn().mockImplementation((_key: keyof GlobalState) => undefined), + update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()), + keys: vi.fn().mockReturnValue([]), + }, + globalStorageUri: storageUri, + workspaceState: { + get: vi.fn().mockImplementation((_key) => undefined), + update: vi.fn().mockImplementation((_key, _value) => Promise.resolve()), + keys: vi.fn().mockReturnValue([]), + }, + secrets: { + get: vi.fn().mockImplementation((_key) => Promise.resolve(undefined)), + store: vi.fn().mockImplementation((_key, _value) => Promise.resolve()), + delete: vi.fn().mockImplementation((_key) => Promise.resolve()), + }, + extensionUri: { + fsPath: "/mock/extension/path", + }, + extension: { + packageJSON: { + version: "1.0.0", + }, + }, + } as unknown as vscode.ExtensionContext + + mockOutputChannel = { + name: "test-output", + replace: vi.fn(), + appendLine: vi.fn(), + append: vi.fn(), + clear: vi.fn(), + show: vi.fn(), + hide: vi.fn(), + dispose: vi.fn(), + } + + mockProvider = new ClineProvider( + mockExtensionContext, + mockOutputChannel, + "sidebar", + new ContextProxy(mockExtensionContext), + new WebviewFocusTracker(), + ) + + mockApiConfig = { + apiProvider: providerIdentifiers.anthropic, + apiModelId: "claude-3-5-sonnet-20241022", + apiKey: "test-api-key", + } + + mockProvider.postMessageToWebview = vi.fn().mockResolvedValue(undefined) + mockProvider.postStateToWebview = vi.fn().mockResolvedValue(undefined) + mockProvider.postStateToWebviewWithoutTaskHistory = vi.fn().mockResolvedValue(undefined) + mockProvider.updateTaskHistory = vi.fn().mockResolvedValue(undefined) + }) + + it("keeps two real Task instances' observation registries independent", async () => { + const first = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "first task", + startTask: false, + }) + const second = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "second task", + startTask: false, + }) + + // Both start empty, and observing through one task must not reach the other. + expect(first.observationRegistry.size).toBe(0) + expect(second.observationRegistry.size).toBe(0) + + first.observationRegistry.observe("/shared/file.ts", "1:2:3:4:5") + + expect(first.observationRegistry.has("/shared/file.ts")).toBe(true) + expect(second.observationRegistry.has("/shared/file.ts")).toBe(false) + expect(second.observationRegistry.size).toBe(0) + + await first.abortTask(true).catch(() => undefined) + await second.abortTask(true).catch(() => undefined) + }) +}) From 5bac54a503b6ed0dd4dd2a67bacd058a94b0e95d Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:33:41 +0800 Subject: [PATCH 51/79] fix(file-safety): retry and retain a backup whose cleanup failed The success path unlinked the backup once and swallowed the failure, so a transient EBUSY or a scanner holding the file left the backup in the workspace for good, with nothing left pointing at it. Cleanup now retries a bounded number of times and, if it still fails, keeps the path in a pending set that flushPendingBackupRemovals retries on a later write. New test: every unlink fails during the write (retried, path retained), then a flush clears it once the filesystem lets go. Control: dropping the retention makes the flush return 0 and the test fails. safeWriteText.spec 35 passed, tsc --noEmit 0 errors. --- .../__tests__/safeWriteText.spec.ts | 22 +++++++++- src/services/file-safety/safeWriteText.ts | 40 ++++++++++++++++--- 2 files changed, 56 insertions(+), 6 deletions(-) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index b6b33e4371c..2b62ac76ba5 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -4,7 +4,7 @@ import { execFile } from "child_process" import type { ChildProcess } from "child_process" import * as path from "path" -import { safeWriteText } from "../safeWriteText" +import { flushPendingBackupRemovals, safeWriteText } from "../safeWriteText" // Full mock for fs/promises — all methods are vi.fn() stubs vi.mock("fs/promises", () => ({ @@ -253,6 +253,26 @@ describe("safeWriteText", () => { expect(fs.rmdir).toHaveBeenCalledWith(expect.stringContaining(".file-safety-staging")) }) + it("retains a backup whose cleanup failed and clears it on the next flush", async () => { + const targetPath = "/tmp/test-dir/retry-target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + // Every unlink attempt fails during the write, so the path has to be kept rather than + // abandoned - that is the difference between a retry and an orphan. + vi.mocked(fs.unlink).mockRejectedValue(new Error("EBUSY")) + + await safeWriteText(targetPath, "data", { backup: true, platform: "linux" }) + + const backupPaths = vi + .mocked(fs.unlink) + .mock.calls.map(([candidate]) => String(candidate)) + .filter((candidate) => candidate.includes("safeWriteText.bak_")) + expect(backupPaths.length).toBeGreaterThan(1) // retried before giving up + + // A later cleanup, once the filesystem lets go, must clear the retained path. + vi.mocked(fs.unlink).mockResolvedValue(undefined) + await expect(flushPendingBackupRemovals()).resolves.toBe(1) + }) it("a post-commit backup cleanup failure is non-fatal: the target stays committed and no temp is left behind", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index d135f040604..559c22271bb 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -6,6 +6,38 @@ import { execFile } from "child_process" /** * Options for safeWriteText atomic text publish primitive. */ +// Backups whose removal failed. The path is kept, not abandoned: the next write retries it, so a +// transient EBUSY or a scanner holding the file does not leave the backup in the workspace for good. +const PENDING_BACKUP_REMOVALS = new Set() + +async function _removeBackupWithRetry(backupPath: string, attempts = 3): Promise { + for (let attempt = 0; attempt < attempts; attempt++) { + try { + await fs.unlink(backupPath) + PENDING_BACKUP_REMOVALS.delete(backupPath) + return true + } catch { + if (attempt < attempts - 1) { + await new Promise((resolve) => setTimeout(resolve, 25 * (attempt + 1))) + } + } + } + + PENDING_BACKUP_REMOVALS.add(backupPath) + return false +} + +/** Retry the backup removals an earlier write could not finish. Best-effort; returns how many cleared. */ +export async function flushPendingBackupRemovals(): Promise { + let cleared = 0 + for (const backupPath of [...PENDING_BACKUP_REMOVALS]) { + if (await _removeBackupWithRetry(backupPath)) { + cleared += 1 + } + } + return cleared +} + export interface SafeWriteTextOptions { /** * When true, preserve the old-file semantics: copy the target to a backup and @@ -348,11 +380,9 @@ export async function safeWriteText(filePath: string, content: string, options?: // -- Step 6 (backup:true): delete backup on success ----------- if (releaseBackupOnSuccess && backupPath) { - try { - await fs.unlink(backupPath) - } catch { - // non-fatal — orphaned backup is acceptable - } + // A cleanup failure must not abandon the path: retry, and if it still fails keep it for the + // next write to clear instead of leaving an orphan nobody owns. + await _removeBackupWithRetry(backupPath) } // The staging sub-directory only exists to hold this write's temp file. Once the From 2a37d7e8095383abb728b172a87cde9ee1702668 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Fri, 6 Nov 2026 00:38:43 +0800 Subject: [PATCH 52/79] fix(file-safety): retry retained backups at the start of the next write The retained set only helped if something flushed it, and knip was right that nothing called it: the flush is now the first thing a write does, so a backup left behind by a transient failure is cleared by whichever write touches the primitive next instead of waiting for a caller that never comes. safeWriteText.spec 35 passed, tsc --noEmit 0 errors, eslint --max-warnings=0 exit 0. --- src/services/file-safety/safeWriteText.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index 559c22271bb..1e04ee3baff 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -201,6 +201,10 @@ export async function resolvePublishTarget(absoluteFilePath: string): Promise { const absoluteFilePath = path.resolve(filePath) + // A write is the natural place to retry backups an earlier one could not remove: the failure + // that left them behind is usually transient, and this keeps them owned instead of orphaned. + await flushPendingBackupRemovals() + // Resolve the symlink referent (see resolvePublishTarget). const targetPath = await resolvePublishTarget(absoluteFilePath) const dirPath = path.dirname(targetPath) From 6cd95679c88417ba679275aebccc136c1509dc36 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 8 Nov 2026 05:17:20 +0800 Subject: [PATCH 53/79] fix(file-safety): treat an already-gone backup as removed, not as work to re-register _removeBackupWithRetry caught every unlink failure with a binding-less catch, so it could not tell a busy file from a missing one. A backup that is already gone is the outcome the cleanup was after - someone deleted the retained file, or a second flush is iterating a snapshot of the pending set that another flush has already cleared - but the helper retried it three times and then added the path back to the set, and safeWriteText awaits flushPendingBackupRemovals() before it does anything else, so every later write paid 25 + 50 ms of retry sleeps on a file that cannot come back. Bind the error, treat ENOENT as the removal having happened, and share one code reader with the symlink resolution that already discriminated on ENOENT rather than duplicating its guard. Publish order, the acknowledgement step and the backup naming are untouched; only the cleanup of an already-absent backup changes, and if maintainers settle the wider write-path question the other way this helper can move with it. Measured before the implementation, on the two new cases only: 2 failed | 35 passed (37), reporting 'expected 3 to be 1' for the unlink count and 'expected [1, 0] to deeply equal [1, 1]' for the concurrent flush pair - the second is the race this fix exists for: over one snapshot of the set the flush that won deleted the path and returned 1 while the loser exhausted its attempts against an ENOENT it had caused itself and re-registered the path. After: safeWriteText.spec.ts 37 passed (37), services/file-safety 37 passed (37), core/tools 33 files 797 passed | 5 skipped (802); pnpm --dir src run lint exits 0 with the eslint content cache deleted first; tsc --noEmit -p . emits no diagnostics; prettier --check passes on both files. Neither file has an eslint-suppressions entry, and the prune probe left the registry at 288 file keys and was restored to its HEAD bytes so this commit carries no registry churn. Both blobs are LF-only before and after (449 and 820 newlines at HEAD, 459 and 883 now, zero CR bytes). Co-Authored-By: Claude Opus 4.8 --- .../__tests__/safeWriteText.spec.ts | 63 +++++++++++++++++++ src/services/file-safety/safeWriteText.ts | 22 +++++-- 2 files changed, 79 insertions(+), 6 deletions(-) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index 2b62ac76ba5..b56d4371ed0 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -54,6 +54,15 @@ function _stagingDir(dir: string): string { } // Minimal Stats stand-in: the SUT only reads `.mode` from it. +// Counts unlinks that targeted a backup path, so a retry loop cannot hide inside a +// total unlink count that also covers the staging temp and the DACL dump. +function _backupUnlinkCalls(): number { + return vi + .mocked(fs.unlink) + .mock.calls.map(([candidate]) => String(candidate)) + .filter((candidate) => candidate.includes("safeWriteText.bak_")).length +} + function _stats(mode: number): fsSync.Stats { const s = Object.create(fsSync.Stats.prototype) as fsSync.Stats Object.assign(s, { mode }) @@ -273,6 +282,60 @@ describe("safeWriteText", () => { vi.mocked(fs.unlink).mockResolvedValue(undefined) await expect(flushPendingBackupRemovals()).resolves.toBe(1) }) + it("treats a backup that is already gone as removed rather than re-registering it for every later write", async () => { + const targetPath = "/tmp/test-dir/enoent-target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + // The backup disappears between the commit and the cleanup, so every unlink reports + // ENOENT - the outcome the cleanup was after. Retrying it treats a missing file as + // work, and the 25 + 50 ms of retry sleep is then paid on every later write, because + // safeWriteText flushes the pending set before it does anything else. + vi.mocked(fs.unlink).mockRejectedValue( + Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }), + ) + + await safeWriteText(targetPath, "data", { backup: true, platform: "linux" }) + + // One attempt on the backup, not three. + expect(_backupUnlinkCalls()).toBe(1) + // Nothing is left pending: an already-removed backup is done, not owed. + await expect(flushPendingBackupRemovals()).resolves.toBe(0) + + // A later write to the same target attempts its own cleanup once and never revisits + // the path that is already gone. + await safeWriteText(targetPath, "data2", { backup: true, platform: "linux" }) + expect(_backupUnlinkCalls()).toBe(2) + }) + + it("does not re-register a backup path that a concurrent flush already removed", async () => { + const targetPath = "/tmp/test-dir/race-target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + // A scanner holds the backup for the whole write, so the path is retained at the end + // of step 6 - the state two flushes can then race over. + vi.mocked(fs.unlink).mockRejectedValue(new Error("EBUSY")) + await safeWriteText(targetPath, "data", { backup: true, platform: "linux" }) + + // Two flushes iterate the same snapshot of the pending set. The first unlink succeeds + // and removes the file, so every attempt the losing flush makes afterwards reports + // ENOENT for a path it is still holding in its own iteration. + let unlinkAttempts = 0 + vi.mocked(fs.unlink).mockImplementation(async () => { + unlinkAttempts += 1 + if (unlinkAttempts === 1) { + return undefined + } + throw Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }) + }) + const cleared = await Promise.all([flushPendingBackupRemovals(), flushPendingBackupRemovals()]) + expect(cleared).toEqual([1, 1]) + + // The path must not be back in the set: with unlink working again there is nothing + // left for a later write to clear. + vi.mocked(fs.unlink).mockResolvedValue(undefined) + await expect(flushPendingBackupRemovals()).resolves.toBe(0) + }) + it("a post-commit backup cleanup failure is non-fatal: the target stays committed and no temp is left behind", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index 1e04ee3baff..4292fd3c965 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -10,13 +10,27 @@ import { execFile } from "child_process" // transient EBUSY or a scanner holding the file does not leave the backup in the workspace for good. const PENDING_BACKUP_REMOVALS = new Set() +function _errorCode(error: unknown): string | undefined { + return typeof error === "object" && error !== null && "code" in error + ? (error as { code?: string }).code + : undefined +} + async function _removeBackupWithRetry(backupPath: string, attempts = 3): Promise { for (let attempt = 0; attempt < attempts; attempt++) { try { await fs.unlink(backupPath) PENDING_BACKUP_REMOVALS.delete(backupPath) return true - } catch { + } catch (error: unknown) { + // A backup that is already gone is the outcome this cleanup was after: someone deleted + // the retained file, or a second flush is iterating a snapshot of the set that another + // flush has already cleared. Treating that as work retries a file that cannot come back + // and re-adds its path, so every later write pays the retry sleeps on it. + if (_errorCode(error) === "ENOENT") { + PENDING_BACKUP_REMOVALS.delete(backupPath) + return true + } if (attempt < attempts - 1) { await new Promise((resolve) => setTimeout(resolve, 25 * (attempt + 1))) } @@ -343,11 +357,7 @@ export async function safeWriteText(filePath: string, content: string, options?: } releaseBackupOnSuccess = true } catch (err: unknown) { - const code = - typeof err === "object" && err !== null && "code" in err - ? (err as { code?: string }).code - : undefined - if (code !== "ENOENT") throw err + if (_errorCode(err) !== "ENOENT") throw err } } From 4f7cd0049e4e3313c22fbe8ab40e02173d0686b1 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 8 Nov 2026 05:27:26 +0800 Subject: [PATCH 54/79] fix(file-safety): hand a backup whose failure-path removal fails to the next write The drop itself is correct: at the point a write fails after the backup was copied, the target has not been published, so the backup is a copy of content the target still holds rather than the only copy of anything. What was wrong is how the drop is attempted. It called fs.unlink once with a swallowing catch, and when that single attempt failed the path was never handed to anyone - the only writers of PENDING_BACKUP_REMOVALS are _removeBackupWithRetry itself, and the only production caller of flushPendingBackupRemovals is safeWriteText's own opening line - so a failed cleanup left a backup beside the target that nothing in this module could ever find again. The intent stays 'remove it'; only the failure of the removal changes: retry it, and if it still fails, register the path so a later write finishes the job. The option doc and this site's comment now say that, and the step 3a comment no longer claims 'no backup is taken' when preCommitVerify runs, because step 3 has already copied the target by then (a verifier rejection still moves nothing - the commit rename never runs). Measured before the implementation: 1 failed | 37 passed (38), reporting 'expected 1 to be 3' for the unlink attempts on the backup path. The other half of the claim - that nothing owned the path - was measured on the shipped shape beforehand with a throwaway probe against this same head: an isolated preCommitVerify failure with every unlink rejecting gave copyFileCalls=1, renameCalls=0, backupUnlinkCalls=1 and flushPendingBackupRemovals() resolving 0, i.e. one attempt and no owner. After: safeWriteText.spec.ts 38 passed (38), services/file-safety 38 passed (38), core/tools 33 files 797 passed | 5 skipped (802). A full services sweep with the change reads 11 failed | 2264 passed | 13 skipped (2288) against 11 failed | 2263 passed | 13 skipped (2287) at the untouched head 93bf0b506, and the extra 2 in the first sweep run were ShadowCheckpointService cases that pass 42 of 42 when run alone at the head and with the change: load-dependent flake in another service, not this unit. The 11 baseline failures are marketplace, rules and code-index parser cases that fail at the head too. pnpm --dir src run lint exits 0 with the eslint content cache deleted first; tsc --noEmit -p . emits no diagnostics; prettier --check passes on both files; neither file has an eslint-suppressions entry and the prune probe left the registry at 288 file keys and was restored byte-for-byte, so this commit carries no registry churn. Publish order, the acknowledgement step and the backup naming are untouched; if maintainers settle the wider write-path question the other way, this helper moves with it. Co-Authored-By: Claude Opus 4.8 --- .../__tests__/safeWriteText.spec.ts | 26 +++++++++++++++++++ src/services/file-safety/safeWriteText.ts | 23 +++++++++++----- 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index b56d4371ed0..0d6055df211 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -450,6 +450,32 @@ describe("safeWriteText", () => { expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_")) }) + it("hands a backup whose failure-path removal could not complete to a later write", async () => { + const targetPath = "/tmp/test-dir/verify-fail.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + // The verifier runs after step 3 has copied the target to the backup, and every unlink + // fails, so the intended drop cannot complete. The path must then be owned by a later + // write rather than forgotten beside the target with nothing pointing at it. + const verify = vi.fn(async () => { + throw new Error("Stale version at commit time") + }) + vi.mocked(fs.unlink).mockRejectedValue(new Error("EBUSY")) + + await expect( + safeWriteText(targetPath, "data", { backup: true, platform: "linux", preCommitVerify: verify }), + ).rejects.toThrow("Stale version at commit time") + + // Retried rather than given up after one attempt. + expect(_backupUnlinkCalls()).toBe(3) + // Owned: once the filesystem lets go, a flush clears exactly that retained path. + vi.mocked(fs.unlink).mockResolvedValue(undefined) + await expect(flushPendingBackupRemovals()).resolves.toBe(1) + // The drop is still the intent, so nothing was committed and the pre-write content is + // still at the target path: no rename happened at all. + expect(fs.rename).not.toHaveBeenCalled() + }) + it("backup:true when target does not exist: no backup created, just commit", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index 4292fd3c965..e9490e555de 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -56,7 +56,11 @@ export interface SafeWriteTextOptions { /** * When true, preserve the old-file semantics: copy the target to a backup and * fsync the copy before the commit, delete the backup after a successful commit, - * and drop the backup on failure. The target is never moved, so a failed write + * and on failure try to remove the backup too - the copy is of content the target + * still holds, so it is clutter rather than the only copy, and it is not what a + * failed write is meant to leave behind. A removal that itself fails hands the path + * to the next write instead of abandoning it, so the clutter does not end up with no + * owner. The target is never moved, so a failed write * leaves the pre-write content at the target path instead of rolling anything * back. When false (default) the atomic rename simply replaces * the target -- crash-safe window is zero. @@ -363,7 +367,8 @@ export async function safeWriteText(filePath: string, content: string, options?: // -- Step 3a: pre-commit verification ------------------------- // Runs before the commit rename so a rejection leaves the target untouched - - // no backup is taken and nothing is moved yet. + // nothing is moved yet. The backup copy has already been made by step 3 when + // backup is on, and the failure path below removes it. if (options?.preCommitVerify) { await options.preCommitVerify(targetPath) } @@ -423,11 +428,15 @@ export async function safeWriteText(filePath: string, content: string, options?: if (backupPath && releaseBackupOnSuccess) { // Nothing to restore: the backup is a copy, so the target still holds whatever // the commit left there - before the commit that is the pre-write content, and - // after it the published content. Either way the copy has served its purpose - // and must not be left beside the target where no caller can find it. The old - // design renamed the target away and back, which could itself fail and leave - // persisted state missing at its expected path. - await fs.unlink(backupPath).catch(() => {}) + // after it the published content. Either way the copy has served its purpose and + // the intent is to remove it: the target still holds what the copy holds, so a + // leftover is clutter rather than the only copy of anything. What must not happen + // is clutter with no owner - one best-effort unlink that fails leaves a backup + // beside the target that nothing in this module can ever find again - so the + // removal is retried and, if it still fails, the path goes to the pending set for + // a later write to finish. The old design renamed the target away and back, which + // could itself fail and leave persisted state missing at its expected path. + await _removeBackupWithRetry(backupPath) backupPath = null } From 6004a76ca5b08f312b9d6619e9f5e49f04617ba6 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 8 Nov 2026 05:33:28 +0800 Subject: [PATCH 55/79] test(file-safety): assert the retained backup, and drain the pending set per case The cleanup-failure case asserted that the backup unlink happened and that nothing else moved, but it never asserted the state the failure actually produces: after three exhausted attempts the path is in PENDING_BACKUP_REMOVALS, and that is what the failure path is for. Its mock also rejected only once, so the helper's own second attempt succeeded and nothing was ever retained - the case could not have detected a missing retention at all. The mock now rejects for the whole attempt, the case asserts the retries and asserts that a flush afterwards clears exactly one path, and the comment no longer calls an orphaned backup "the documented acceptable outcome": the option doc promises a removal attempt and, since the previous commit, an owner for a removal that fails. The three commit-side assertions stay - one commit rename, no rename away from the committed target, and no unlink of anything temp-shaped - and the rename-count assertion that had been written twice now stands once, with the second slot filled by the assertion it was standing in for. The pending set is module state rather than per-case state, so an afterEach drains it through the exported flush with unlink made to succeed, which needs no new production surface. Measured: with a case inserted ahead of this one that retains and never flushes, and the drain commented out, this case fails "expected 6 to be 3" - its own write flushes the predecessor's retained path, paying 25 + 50 ms of retry sleeps on a path it never created, and then adds its own three attempts. The same two-case selection with the drain re-enabled reads 2 passed | 37 skipped (39). Without the inserted case the file reads 38 passed (38) either way, because every case in this file that can retain also flushes what it retains - the drain is what keeps that true of the next case that forgets to. Each of the five affected cases also passes alone under -t (1 passed | 37 skipped) and the whole file passes in declaration order (38 passed), so no case here depends on which cases ran before it. Test-only change: 24 added, 9 removed in safeWriteText.spec.ts, no source change. pnpm --dir src run lint exits 0 with the eslint content cache deleted first; tsc --noEmit -p . emits no diagnostics; prettier --check passes; core/tools reads 33 files 797 passed | 5 skipped (802) unchanged; the file has no eslint-suppressions entry and the prune probe left the registry at 288 file keys and was restored byte-for-byte. Co-Authored-By: Claude Opus 4.8 --- .../__tests__/safeWriteText.spec.ts | 33 ++++++++++++++----- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index 0d6055df211..ec88f8d46f2 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -89,6 +89,15 @@ describe("safeWriteText", () => { ) }) + // PENDING_BACKUP_REMOVALS is module state, not per-case state: a case whose write retains a + // backup hands that path to the next case's write, which then unlinks a path it never created. + // Draining through the exported flush with unlink made to succeed empties the set without + // reaching for a private symbol, so no case here depends on which cases ran before it. + afterEach(async () => { + vi.mocked(fs.unlink).mockResolvedValue(undefined) + await flushPendingBackupRemovals() + }) + describe("staging and cleanup", () => { it("creates a temp file in the staging dir, fsyncs it, renames to target, and cleans up on success", async () => { const targetPath = "/tmp/test-dir/target.txt" @@ -336,14 +345,15 @@ describe("safeWriteText", () => { await expect(flushPendingBackupRemovals()).resolves.toBe(0) }) - it("a post-commit backup cleanup failure is non-fatal: the target stays committed and no temp is left behind", async () => { + it("a post-commit backup cleanup failure is non-fatal: the target stays committed and the path is handed to a later write", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) vi.mocked(fsSync.openSync).mockReturnValue(1) - // The post-commit backup unlink (SUT step 6) fails — the write must - // still succeed; an orphaned backup is the documented acceptable - // outcome, so the failure is swallowed instead of rolling back. - vi.mocked(fs.unlink).mockRejectedValueOnce(new Error("EPERM")) + // The post-commit backup unlink (SUT step 6) fails for the whole attempt. The write + // still succeeds: the failure is swallowed rather than rolled back, and the path is + // retained for a later write rather than abandoned. Rejecting once would let the + // helper's own second attempt succeed and the retention would never be observable. + vi.mocked(fs.unlink).mockRejectedValue(new Error("EPERM")) await safeWriteText(targetPath, "data", { backup: true, platform: "linux" }) @@ -352,16 +362,21 @@ describe("safeWriteText", () => { expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath) expect(fs.rename).toHaveBeenCalledTimes(1) - // the failing cleanup was the post-commit backup unlink + // the failing cleanup was the post-commit backup unlink, retried to exhaustion expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.bak_")) + expect(_backupUnlinkCalls()).toBe(3) - // no rollback rename: the backup is a copy, so nothing is renamed back over - // the committed target. - expect(fs.rename).toHaveBeenCalledTimes(1) + // no rollback rename: nothing was ever renamed away from the committed target + expect(fs.rename).not.toHaveBeenCalledWith(targetPath, expect.anything()) // the staging temp was already committed by the rename; nothing // temp-shaped is unlinked afterwards expect(fs.unlink).not.toHaveBeenCalledWith(expect.stringContaining("safeWriteText_")) + + // retention is the outcome this failure produces and it is observable: with the + // filesystem let go, a flush clears exactly the one path this write left behind + vi.mocked(fs.unlink).mockResolvedValue(undefined) + await expect(flushPendingBackupRemovals()).resolves.toBe(1) }) }) From 173982c77bd687857a2b815ea4c8cf0f952701e2 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 8 Nov 2026 07:01:23 +0800 Subject: [PATCH 56/79] fix(file-safety): answer the guarded-write review rows on links, target mode and backup retention Three answers on the guarded write path, each pinned by a case that fails without the fix: - resolvePublishTarget: realpath answers ENOENT both for a name that does not exist yet and for a symlink whose referent is gone. Only the first may fall back to the link path; a dangling link is now refused instead of being replaced, which is what the file's own contract block already said. - The generated staging file is created with openSync's mode, which the umask narrows. The caller-staged branch already corrected it with fchmodSync on the open fd; the generated branch now does the same, so both publish paths carry the target's mode rather than the creation mask. - When the cleanup unlink inside the backup-creation catch itself fails, the path now goes through _removeBackupWithRetry and the pending-removal set instead of fs.unlink(...).catch(() => {}), so the retained backup is retried and a later flush can clear it rather than being swallowed. Tests first, then the fixes: the three new cases in the "publication guards" describe each failed against the old behaviour, and the publication and verification-order cases now compare invocationCallOrder across write, fsync, close and rename (and write, fsync and verify) so the durability contract is asserted as an order and not only as a set of calls. 2 files changed, +118 -8 (from git diff --cached --numstat in the same run as this commit) --- .../__tests__/safeWriteText.spec.ts | 95 ++++++++++++++++++- src/services/file-safety/safeWriteText.ts | 31 ++++-- 2 files changed, 118 insertions(+), 8 deletions(-) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index ec88f8d46f2..8d821df7227 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -15,6 +15,7 @@ vi.mock("fs/promises", () => ({ rename: vi.fn(), unlink: vi.fn(), realpath: vi.fn(), + lstat: vi.fn(), rmdir: vi.fn(), })) @@ -63,6 +64,13 @@ function _backupUnlinkCalls(): number { .filter((candidate) => candidate.includes("safeWriteText.bak_")).length } +// A symlink stand-in: only isSymbolicLink and mode are read by safeWriteText. +function _lstatLike(mode: number, symbolic: boolean): fsSync.Stats { + const s = Object.create(fsSync.Stats.prototype) as fsSync.Stats + Object.assign(s, { mode, isSymbolicLink: () => symbolic }) + return s +} + function _stats(mode: number): fsSync.Stats { const s = Object.create(fsSync.Stats.prototype) as fsSync.Stats Object.assign(s, { mode }) @@ -77,6 +85,11 @@ describe("safeWriteText", () => { // After resetAllMocks, vi.fn() returns undefined — restore promise defaults. vi.mocked(fs.mkdir).mockResolvedValue(undefined) vi.mocked(fs.access).mockResolvedValue(undefined) + // lstat answers ENOENT for a name that does not exist yet, which is the default + // condition of the create-if-absent cases; the dangling-symlink case overrides it. + vi.mocked(fs.lstat).mockRejectedValue( + Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }), + ) vi.mocked(fs.rename).mockResolvedValue(undefined) vi.mocked(fs.unlink).mockResolvedValue(undefined) // Existing-target default: a regular 0o644 file. @@ -211,6 +224,17 @@ describe("safeWriteText", () => { // the temp file was fully closed before the commit rename expect(vi.mocked(fsSync.closeSync).mock.calls[0][0]).toBe(1) expect(fs.rename).toHaveBeenCalled() + + // ... and in that order: everything above counts calls, so a commit rename that + // ran before the file fsync would satisfy every assertion here. Compare call order + // across the four steps the durability contract is about. + const writeOrder = vi.mocked(fsSync.writeSync).mock.invocationCallOrder[0] + const fsyncOrder = vi.mocked(fsSync.fsyncSync).mock.invocationCallOrder[0] + const closeOrder = vi.mocked(fsSync.closeSync).mock.invocationCallOrder[0] + const renameOrder = vi.mocked(fs.rename).mock.invocationCallOrder[0] + expect(writeOrder).toBeLessThan(fsyncOrder) + expect(fsyncOrder).toBeLessThan(closeOrder) + expect(closeOrder).toBeLessThan(renameOrder) }) }) @@ -266,7 +290,19 @@ describe("safeWriteText", () => { // The verifier runs after staging and fsync but before the rename, so the target // was never moved and the staged content was cleaned up. expect(verify).toHaveBeenCalledWith(targetPath) - expect(fs.rename).not.toHaveBeenCalled() + // Order is the contract here, not the call: the verifier must run after the staged + // file is written and fsynced. The other half - that it ran before the commit rename + // - is the rename assertion below, because a rejected verification never renames. + // Both sides of the comparison have to exist before they are compared: a verifier + // that runs too early never stages anything, and that must read as a failed call + // assertion rather than as a comparison against undefined. + expect(fsSync.writeSync).toHaveBeenCalledTimes(1) + expect(fsSync.fsyncSync).toHaveBeenCalled() + const stagedWriteOrder = vi.mocked(fsSync.writeSync).mock.invocationCallOrder[0] + const stagedFsyncOrder = vi.mocked(fsSync.fsyncSync).mock.invocationCallOrder[0] + const verifyOrder = verify.mock.invocationCallOrder[0] + expect(stagedWriteOrder).toBeLessThan(stagedFsyncOrder) + expect(stagedFsyncOrder).toBeLessThan(verifyOrder) expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_")) expect(fs.rmdir).toHaveBeenCalledWith(expect.stringContaining(".file-safety-staging")) }) @@ -921,4 +957,61 @@ describe("safeWriteText", () => { expect(fs.rename).not.toHaveBeenCalled() }) }) + + // These three cases each pin one answer that the code currently gets wrong: what lstat + // says when realpath says ENOENT, what mode the generated staging file is published + // with, and who owns a backup whose cleanup unlink itself failed. + describe("publication guards: dangling links, target mode and retained backups", () => { + it("rejects a write whose target is a symlink with no referent instead of replacing the link", async () => { + const linkPath = "/tmp/test-dir/link.txt" + // realpath answers ENOENT both for a name that does not exist yet and for a symlink + // whose referent is gone. lstat is what tells the two apart, and the documented + // contract is that only an absent target may fall back to the link path. + vi.mocked(fs.realpath).mockRejectedValue( + Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }), + ) + vi.mocked(fs.lstat).mockResolvedValue(_lstatLike(0o777, true)) + + await expect(safeWriteText(linkPath, "data", { platform: "linux" })).rejects.toThrow(/dangling symlink/) + expect(fs.rename).not.toHaveBeenCalled() + }) + it("fixes the generated staging file's mode with fchmod so the umask cannot narrow it", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + // A permissive target: the generated staging file must be published with the same + // mode rather than the creation mask the process happens to run under. + vi.mocked(fsSync.statSync).mockReturnValue(_stats(0o664)) + vi.mocked(fsSync.openSync).mockReturnValue(1) + + await safeWriteText(targetPath, "new data", { platform: "linux" }) + + // The open argument is not the outcome - openSync's mode is subject to the umask - + // so assert the call that fixes the mode on the descriptor, and that it lands + // between the open and the fsync. + expect(fsSync.fchmodSync).toHaveBeenCalledWith(1, 0o664) + const openOrder = vi.mocked(fsSync.openSync).mock.invocationCallOrder[0] + const chmodOrder = vi.mocked(fsSync.fchmodSync).mock.invocationCallOrder[0] + const fsyncOrder = vi.mocked(fsSync.fsyncSync).mock.invocationCallOrder[0] + expect(openOrder).toBeLessThan(chmodOrder) + expect(chmodOrder).toBeLessThan(fsyncOrder) + }) + it("keeps a backup whose creation cleanup failed for a later write to clear", async () => { + const targetPath = "/tmp/test-dir/target.txt" + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + vi.mocked(fsSync.openSync).mockReturnValue(1) + vi.mocked(fs.copyFile).mockRejectedValue(new Error("EXDEV: cross-device copy not permitted")) + vi.mocked(fs.unlink).mockRejectedValue(new Error("EBUSY: resource busy or locked")) + + await expect(safeWriteText(targetPath, "data", { backup: true, platform: "linux" })).rejects.toThrow( + "EXDEV: cross-device copy not permitted", + ) + + // The cleanup unlink failed, so the path must still be owned: it goes through the + // same retry loop as every other backup removal - three attempts - and a later + // flush has to be able to clear it instead of leaving it beside the target. + expect(_backupUnlinkCalls()).toBe(3) + vi.mocked(fs.unlink).mockResolvedValue(undefined) + await expect(flushPendingBackupRemovals()).resolves.toBe(1) + }) + }) }) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index e9490e555de..f6def97cf44 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -206,12 +206,18 @@ async function _restoreDaclWindows(dirPath: string, dumpPath: string, execFileRu * across filesystems fails with EXDEV. */ export async function resolvePublishTarget(absoluteFilePath: string): Promise { - return fs.realpath(absoluteFilePath).catch((error: unknown) => { - const code = - typeof error === "object" && error !== null && "code" in error - ? (error as { code?: string }).code - : undefined - if (code !== "ENOENT") throw error + return fs.realpath(absoluteFilePath).catch(async (error: unknown) => { + if (_errorCode(error) !== "ENOENT") { + throw error + } + // realpath answers ENOENT for two different worlds: a name that does not exist + // yet, and a symlink whose referent is gone. lstat tells them apart, and only the + // first may fall back to the link path - writing through the second would let the + // commit rename replace the link with a regular file where a link used to stand. + const linkState = await fs.lstat(absoluteFilePath).catch(() => null) + if (linkState?.isSymbolicLink()) { + throw new Error(`Cannot write through a dangling symlink at ${absoluteFilePath}: its target does not exist`) + } return absoluteFilePath }) } @@ -259,6 +265,12 @@ export async function safeWriteText(filePath: string, content: string, options?: // directory under a fresh name would put back under tempPath. The retry this // branch used to carry therefore could only fail a second time. const fd = fsSync.openSync(tempPath, "w", targetMode) + // open()'s mode argument is subject to the process umask, so asking for the + // target's mode at creation is not the same as publishing it: a 0o664 target under + // a 0o022 umask would come out 0o644. The chmod on the open descriptor is what + // fixes the mode we asked for - the same reason the caller-staged branch below + // fchmods rather than trusting its own open mode. + fsSync.fchmodSync(fd, targetMode) try { // Loop until every byte is written: writeSync can report a short // (partial) write, and publishing a truncated staging file would @@ -355,7 +367,12 @@ export async function safeWriteText(filePath: string, content: string, options?: } } catch (backupError: unknown) { // A half-written backup is worse than none: it looks like a restore source. - await fs.unlink(backupPath).catch(() => {}) + // The half-made backup has to go, but a failed unlink here must not orphan it: + // this is the only cleanup this path performs and nulling backupPath below would + // also hide the path from the rollback cleanup, so it goes through the same + // three-strike removal every other backup removal uses - which keeps the path in + // PENDING_BACKUP_REMOVALS for a later write to clear when this unlink fails. + await _removeBackupWithRetry(backupPath) backupPath = null throw backupError } From 176a3887a2df70cecf77c845d4011d0a083102fe Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 8 Nov 2026 07:01:33 +0800 Subject: [PATCH 57/79] fix(editor): stop saveDirectly from saving a document that may hold user edits In the openFile === false path saveDirectly opened the document and, whenever it reported itself dirty, called document.save(). VS Code hands back the already-open instance of that file, so a dirty flag there can mean the user has unsaved edits in that buffer: saving it flushes that stale buffer over the bytes the guarded write just published. It also meant a test could pass by stubbing a document that saves itself. The document is still opened - it is what lets a later openFile === true call find the instance and reveal it - but it is no longer saved on this path, which is the same reason saveChanges publishes a dirty buffer through the guard instead of saving it. The new case stubs a document reporting isDirty and asserts the guarded write ran, the document was opened and document.save() was not. 2 files changed, +31 -6 (from git diff --cached --numstat in the same run as this commit) --- src/integrations/editor/DiffViewProvider.ts | 14 ++++++----- .../editor/__tests__/DiffViewProvider.spec.ts | 23 +++++++++++++++++++ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index b6491ce827e..761aa77a66a 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -1263,12 +1263,14 @@ export class DiffViewProvider { }) } else { // Just open the document in memory to trigger diagnostics without showing it - const doc = await vscode.workspace.openTextDocument(vscode.Uri.file(absolutePath)) - - // Save the document to ensure VSCode recognizes it as saved and triggers diagnostics - if (doc.isDirty) { - await doc.save() - } + await vscode.workspace.openTextDocument(vscode.Uri.file(absolutePath)) + + // A dirty document here carries unsaved user edits: VS Code hands back the + // existing instance rather than a fresh one. Saving it now would flush that stale + // buffer over the bytes the guarded write just published, which is the same reason + // saveChanges publishes a dirty buffer through the guard instead of saving it. The + // buffer is left to the user's own save; the document is still open, so diagnostics + // run against it either way. // Force a small delay to ensure diagnostics are triggered await new Promise((resolve) => setTimeout(resolve, 100)) diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 363edcfabdf..cd7bd6b7e0c 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -874,6 +874,29 @@ describe("DiffViewProvider", () => { expect(vscode.window.showTextDocument).not.toHaveBeenCalled() }) + it("does not save an in-memory document that already holds unsaved user edits", async () => { + // VS Code hands back the existing document instance, so the one this branch + // receives can carry unsaved user edits. Saving it would flush that stale buffer + // over the bytes the guarded write just published - the rule saveChanges follows + // for the same reason. The double is a structural cast: vscode.d.ts offers no + // constructor for a TextDocument. + const save = vi.fn().mockResolvedValue(undefined) + vi.mocked(vscode.workspace.openTextDocument).mockResolvedValue({ + isDirty: true, + save, + uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" }, + } as unknown as vscode.TextDocument) + + await diffViewProvider.saveDirectly("test.ts", "new content", false, false, 0) + + const { safeWriteText } = await import("../../../services/file-safety/safeWriteText") + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { + preCommitVerify: expect.any(Function), + }) + expect(vscode.workspace.openTextDocument).toHaveBeenCalled() + expect(save).not.toHaveBeenCalled() + }) + it("should skip diagnostics when diagnosticsEnabled is false", async () => { const mockDelay = vi.mocked(delay) mockDelay.mockClear() From 8592d67885eb0ffefd905e307e77052a4b8966a8 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 8 Nov 2026 09:21:13 +0800 Subject: [PATCH 58/79] fix(file-safety): propagate a failed target lstat and only remove a backup this call created resolvePublishTarget swallowed every lstat error and read it as "the name does not exist yet". That is the one guess the surrounding code exists to avoid: an absent name may fall back to the link path, a dangling link may not, and an unreadable target tells us nothing. EIO/EACCES from lstat now stop the write instead of letting the commit rename replace a link with a regular file where a link used to stand. The backup seed open was paired with an unconditional removal. An exclusive open that throws EEXIST means the generated name already belongs to another write, and this call was removing that file - its only cleanup - before failing. Removal is now gated on a flag set immediately after the open succeeds, kept separate from the success-path release flag. A half-made copy is still removed exactly as before. Both fixes are pinned by tests written against the previous implementation: with the old file at f6def97cf447 the two new cases fail (promise resolved instead of rejecting; one unlink against a path this write never created), with the new file 43/43 pass. Gates, on the pinned runtime node v22.23.4 (.tmp-node22) where the suites ran: focused spec 43/43; vitest services 5 failed/1646 passed (the 5 are the known rules.spec symlink EPERM cases, identical at the parent); vitest misc 2113 passed; vitest core 4351 passed; full src suite 45 failed/12809 passed at this commit vs 45 failed/12807 passed at the parent with an identical FAIL-set (dist_assets 40 + rules.spec 5), so 45 known-local and nothing head-only. tsc --noEmit clean, knip --treat-config-hints-as-errors clean, eslint --max-warnings=0 clean with .eslintcache cleared after the last prettier write, prettier --check clean, src/eslint-suppressions.json unchanged from the parent blob cb6575a316. Co-Authored-By: Claude --- .../__tests__/safeWriteText.spec.ts | 47 +++++++++++++++++++ src/services/file-safety/safeWriteText.ts | 35 ++++++++++++-- 2 files changed, 79 insertions(+), 3 deletions(-) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index 8d821df7227..2cb6feded8d 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -501,6 +501,32 @@ describe("safeWriteText", () => { expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_")) }) + // Written before the fix: the seed open is where a taken backup name is discovered, and today + // the catch beside it removes the path whether or not this call created it. + it("leaves a backup name it did not create alone when the exclusive seed open finds it taken", async () => { + const targetPath = "/tmp/test-dir/target.txt" + const eexist = Object.assign(new Error("EEXIST: file already exists"), { code: "EEXIST" }) + vi.mocked(fs.realpath).mockResolvedValue(targetPath) + // The "wx" open on a .bak_ name is the seed, and it is the only place this flow can + // discover that the generated name is already owned by another write. Failing it there + // means this call created nothing, so it has no business removing anything. + vi.mocked(fsSync.openSync).mockImplementation(function (pathArg: unknown, flagArg?: unknown) { + if (flagArg === "wx" && String(pathArg).includes("safeWriteText.bak_")) { + throw eexist + } + return 1 + }) + + await expect(safeWriteText(targetPath, "data", { backup: true, platform: "linux" })).rejects.toEqual( + expect.objectContaining({ code: "EEXIST" }), + ) + + // Not one unlink attempt against a backup path: three strikes would mean it treated a + // file it never made as its own to throw away. + expect(_backupUnlinkCalls()).toBe(0) + expect(fs.copyFile).not.toHaveBeenCalled() + expect(fs.rename).not.toHaveBeenCalled() + }) it("hands a backup whose failure-path removal could not complete to a later write", async () => { const targetPath = "/tmp/test-dir/verify-fail.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) @@ -975,6 +1001,27 @@ describe("safeWriteText", () => { await expect(safeWriteText(linkPath, "data", { platform: "linux" })).rejects.toThrow(/dangling symlink/) expect(fs.rename).not.toHaveBeenCalled() }) + // Written before the fix: today lstat's failure is swallowed and read as "the name is + // absent", which is the one guess that must not be made here. + it("propagates a non-ENOENT lstat failure instead of treating the target as absent", async () => { + const linkPath = "/tmp/test-dir/link.txt" + // realpath answers ENOENT for an absent name and for a dangling link alike; lstat is + // what tells the two apart. If lstat itself cannot answer, the code does not know which + // world it is in, and guessing "absent" lets the commit rename replace a link with a + // regular file where a link used to stand. An unreadable target has to stop the write. + vi.mocked(fs.realpath).mockRejectedValue( + Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }), + ) + vi.mocked(fs.lstat).mockRejectedValue(Object.assign(new Error("EIO: i/o error"), { code: "EIO" })) + + await expect(safeWriteText(linkPath, "data", { platform: "linux" })).rejects.toEqual( + expect.objectContaining({ code: "EIO" }), + ) + + // Stopped before the write, not merely reported: nothing was created and nothing moved. + expect(fs.mkdir).not.toHaveBeenCalled() + expect(fs.rename).not.toHaveBeenCalled() + }) it("fixes the generated staging file's mode with fchmod so the umask cannot narrow it", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index f6def97cf44..1de2e5769df 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -214,7 +214,18 @@ export async function resolvePublishTarget(absoluteFilePath: string): Promise null) + const linkState = await fs.lstat(absoluteFilePath).catch((error: unknown) => { + // ENOENT is the only lstat answer that means "this name does not exist yet" - + // the one world that may fall back to the link path. Any other failure leaves us + // unable to tell an absent name from a dangling link, and the guess that has to be + // avoided is the permissive one: writing on through the link path would let the + // commit rename replace a link with a regular file where a link used to stand. + // An unreadable target stops the write instead. + if (_errorCode(error) !== "ENOENT") { + throw error + } + return null + }) if (linkState?.isSymbolicLink()) { throw new Error(`Cannot write through a dangling symlink at ${absoluteFilePath}: its target does not exist`) } @@ -338,6 +349,10 @@ export async function safeWriteText(filePath: string, content: string, options?: } try { + // Ownership of the backup path is decided by the exclusive open below, not by picking a + // name: an open that throws EEXIST means the name already belongs to another write, and + // this attempt may then remove nothing. Declared outside that try so its catch can see it. + let backupSeeded = false // -- Step 3 (backup:true): durable copy target -> backup ---- if (options?.backup) { try { @@ -354,6 +369,11 @@ export async function safeWriteText(filePath: string, content: string, options?: // the chmod afterwards is what clears a copied read-only attribute on Windows // and keeps a backup of a permissive file private. const seedFd = fsSync.openSync(backupPath, "wx", 0o600) + // Ownership of the backup path begins here, at the moment this call + // creates the file - not at the moment it picks a name. An exclusive open + // that throws EEXIST means the name belongs to another write, and nothing + // below may treat that file as this attempt's to throw away. + backupSeeded = true fsSync.closeSync(seedFd) await fs.copyFile(targetPath, backupPath) await fs.chmod(backupPath, 0o600) @@ -371,8 +391,17 @@ export async function safeWriteText(filePath: string, content: string, options?: // this is the only cleanup this path performs and nulling backupPath below would // also hide the path from the rollback cleanup, so it goes through the same // three-strike removal every other backup removal uses - which keeps the path in - // PENDING_BACKUP_REMOVALS for a later write to clear when this unlink fails. - await _removeBackupWithRetry(backupPath) + // Only a backup this call actually opened is ours to remove. If the exclusive + // seed open threw EEXIST the name was already another write's, and removing it + // here would throw away somebody else's restore source - which is the only + // cleanup this path performs, so nothing later would. A half-made copy still + // goes through the same three-strike removal every other backup removal uses, + // which keeps the path in PENDING_BACKUP_REMOVALS for a later write to clear + // when an unlink of our own copy fails. + + if (backupSeeded) { + await _removeBackupWithRetry(backupPath) + } backupPath = null throw backupError } From 1a069228a26fe1ebd3c64f105ae5684d180d5d5c Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 8 Nov 2026 09:55:02 +0800 Subject: [PATCH 59/79] fix(file-safety): hand a caller-staged temp file back when target resolution refuses to guess resolvePublishTarget runs above safeWriteText's guarded region, so the rollback unlink below it is unreachable from a resolution refusal. A caller that staged its own temp file (safeWriteJson) was left holding it, against step 8 of the documented contract ("On failure: drop the backup copy; clean up temp + dump"). The refusal is the one the previous commit added - it made a non-ENOENT lstat answer throw instead of guessing "absent" - so this leak is exposed by that change rather than pre-existing in this shape. Measured on the pinned runtime node v22.23.4 (.tmp-node22): with the implementation byte-identical to the parent blob 1de2e5769df1 the new case fails 1/44 (the caller's staged path is never unlinked); with the fix 44/44. vitest.services.config.ts 1647 passed with the same five rules.spec symlink failures as the parent; vitest.misc.config.ts 2113 passed; vitest.core.config.ts 4351 passed. Default-config full src suite 47 failed / 12808 passed: the FAIL-set is the known 45 (dist_assets 40 + rules.spec 5) plus 1 ShadowCheckpointService and 2 extension.spec cases that are timeout-shaped (a 20000ms test timeout appears in the log) and sit in files with zero file-safety imports (git grep exit 1 in each). A first attempt of the same command on the same box reported 68 failed with 21 further Task.spec failures that were absent on the re-run, so those are load, not diff; the dist_assets enumeration makes the default-config totals move between runs, which is why the FAIL-set rather than the totals is the invariant quoted here. tsc --noEmit and knip --treat-config-hints-as-errors clean on box node v25.9.0; eslint --max-warnings=0 clean with .eslintcache deleted after the last prettier write; prettier --check 1 before --write and 0 after; src/eslint-suppressions.json left at the parent blob cb6575a3165b. Co-Authored-By: Claude --- .../__tests__/safeWriteText.spec.ts | 23 +++++++++++++++++++ src/services/file-safety/safeWriteText.ts | 14 ++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index 2cb6feded8d..fa0b5a9b343 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -1022,6 +1022,29 @@ describe("safeWriteText", () => { expect(fs.mkdir).not.toHaveBeenCalled() expect(fs.rename).not.toHaveBeenCalled() }) + it("hands a caller-staged temp file back when target resolution refuses to guess", async () => { + const linkPath = "/tmp/test-dir/link.txt" + const callerTemp = "/tmp/test-dir/.staging/caller-staged.tmp" + // safeWriteJson stages its temp file beside the resolved path before calling this + // function. A refusal before the guarded region must hand that file back: step 8 of + // the documented contract says a failed write cleans up temp + dump, and resolution + // sits above the region that owns the staged file. + vi.mocked(fs.realpath).mockRejectedValue( + Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }), + ) + vi.mocked(fs.lstat).mockRejectedValue(Object.assign(new Error("EIO: i/o error"), { code: "EIO" })) + + await expect(safeWriteText(linkPath, "data", { platform: "linux", tempPath: callerTemp })).rejects.toEqual( + expect.objectContaining({ code: "EIO" }), + ) + + // The caller's staged file is the only temp this call could have leaked, and it is + // removed; nothing was created and nothing moved. + expect(fs.unlink).toHaveBeenCalledWith(callerTemp) + expect(_backupUnlinkCalls()).toBe(0) + expect(fs.mkdir).not.toHaveBeenCalled() + expect(fs.rename).not.toHaveBeenCalled() + }) it("fixes the generated staging file's mode with fchmod so the umask cannot narrow it", async () => { const targetPath = "/tmp/test-dir/target.txt" vi.mocked(fs.realpath).mockResolvedValue(targetPath) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index 1de2e5769df..6f1911efe07 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -241,7 +241,19 @@ export async function safeWriteText(filePath: string, content: string, options?: await flushPendingBackupRemovals() // Resolve the symlink referent (see resolvePublishTarget). - const targetPath = await resolvePublishTarget(absoluteFilePath) + let targetPath: string + try { + targetPath = await resolvePublishTarget(absoluteFilePath) + } catch (error) { + // A caller that staged its own temp file (safeWriteJson) owns it until the guarded + // region below takes over. Resolution sits above that region, so a refusal here never + // reaches the rollback unlink: without this the staged file is left on disk, against + // the documented cleanup contract (step 8: on failure clean up temp + dump). + if (options?.tempPath) { + await fs.unlink(options.tempPath).catch(() => {}) + } + throw error + } const dirPath = path.dirname(targetPath) // Ensure parent directory exists (mirrors safeWriteJson behaviour). From abc6b20ddb98bb8073deb74a5b28cef07dc7067e Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 8 Nov 2026 10:22:45 +0800 Subject: [PATCH 60/79] fix(file-safety): hand back a caller-staged temp file when directory setup fails Directory setup (mkdir + access) sits above the guarded region exactly like target resolution does, so a refusal there never reaches the rollback unlink inside the region. With a caller-supplied tempPath - which is how safeWriteJson stages its own temp file - the staged file was left on disk and the documented cleanup contract (step 8: on failure clean up temp + dump) was broken for that path too. Control on pinned node v22.23.4 (.tmp-node22): the two new cases against the parent impl blob 6f1911efe07fd (the parent blob verified by git hash-object) give 2 failed / 44 passed - the staged file is never unlinked; with the guard the file is 46/46. Logs 1408-dir-cleanup-cases-against-prefix-impl- node22.log and 1408-focused-fixed-r201.log. Gates: focused spec 46/46 and vitest.services.config.ts green on pinned v22.23.4 (the services shard is the only shard that executes this spec - src/package.json routes services/** there, so core+misc alone would never run it); tsc --noEmit and knip clean on box node v25.9.0; eslint --prune-suppressions --max-warnings=0 clean on both touched files with .eslintcache cleared after the last prettier write; prettier --check 1 before --write (my comment lines) and 0 after; src/eslint-suppressions.json left at the parent blob. Co-Authored-By: Claude --- .../__tests__/safeWriteText.spec.ts | 38 +++++++++++++++++++ src/services/file-safety/safeWriteText.ts | 16 ++++++-- 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index fa0b5a9b343..b91554ab32d 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -1083,5 +1083,43 @@ describe("safeWriteText", () => { vi.mocked(fs.unlink).mockResolvedValue(undefined) await expect(flushPendingBackupRemovals()).resolves.toBe(1) }) + it("hands a caller-staged temp file back when the parent directory cannot be prepared", async () => { + const callerTemp = "/tmp/caller-staged-dir.tmp" + vi.mocked(fs.realpath).mockImplementation(async (p: unknown) => String(p)) + vi.mocked(fs.lstat).mockRejectedValue( + Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }), + ) + vi.mocked(fs.mkdir).mockRejectedValueOnce( + Object.assign(new Error("EACCES: permission denied, mkdir '/tmp/test-dir'"), { code: "EACCES" }), + ) + + await expect( + safeWriteText("/tmp/test-dir/target.txt", "payload", { tempPath: callerTemp, platform: "linux" }), + ).rejects.toThrow("EACCES") + + // Directory setup sits above the guarded region, same as target resolution: the + // rollback unlink cannot be reached from here, so the staged file has to be handed + // back by the same cleanup the refusal path uses. + expect(fs.unlink).toHaveBeenCalledWith(callerTemp) + expect(_backupUnlinkCalls()).toBe(0) + }) + + it("hands a caller-staged temp file back when the prepared directory fails access check", async () => { + const callerTemp = "/tmp/caller-staged-access.tmp" + vi.mocked(fs.realpath).mockImplementation(async (p: unknown) => String(p)) + vi.mocked(fs.lstat).mockRejectedValue( + Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }), + ) + vi.mocked(fs.access).mockRejectedValueOnce( + Object.assign(new Error("EACCES: permission denied, access '/tmp/test-dir'"), { code: "EACCES" }), + ) + + await expect( + safeWriteText("/tmp/test-dir/target.txt", "payload", { tempPath: callerTemp, platform: "linux" }), + ).rejects.toThrow("EACCES") + + expect(fs.unlink).toHaveBeenCalledWith(callerTemp) + expect(_backupUnlinkCalls()).toBe(0) + }) }) }) diff --git a/src/services/file-safety/safeWriteText.ts b/src/services/file-safety/safeWriteText.ts index 6f1911efe07..ecb6e327522 100644 --- a/src/services/file-safety/safeWriteText.ts +++ b/src/services/file-safety/safeWriteText.ts @@ -256,9 +256,19 @@ export async function safeWriteText(filePath: string, content: string, options?: } const dirPath = path.dirname(targetPath) - // Ensure parent directory exists (mirrors safeWriteJson behaviour). - await fs.mkdir(dirPath, { recursive: true }) - await fs.access(dirPath) + // Ensure parent directory exists (mirrors safeWriteJson behaviour). Setup sits above the + // guarded region just like target resolution, so a failure here has to hand a + // caller-staged temp file back the same way: the rollback unlink inside the region is + // unreachable from a mkdir or access refusal. + try { + await fs.mkdir(dirPath, { recursive: true }) + await fs.access(dirPath) + } catch (error) { + if (options?.tempPath) { + await fs.unlink(options.tempPath).catch(() => {}) + } + throw error + } // Create the staging directory only when we generate the temp file there; // callers supplying their own tempPath (e.g. safeWriteJson) must not be left From ddd91192fa24b1e0e7fd753b277efdeabdce96b3 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Mon, 9 Nov 2026 03:48:05 +0800 Subject: [PATCH 61/79] test(file-safety): assert a directory-setup refusal stops before the write The two caller-staged setup-refusal tests asserted only the hand-back - fs.unlink with the caller's temp and no backup unlinks - so nothing pinned that the write never started. Measured with a fall-through mutant at 0c07c5b09 (the setup catch records the refusal instead of throwing and rethrows after the commit rename): the spec as it stands here is 46/46 green, which is the row's claim in run form. The added assertions on fsSync.openSync, fsSync.mkdirSync and fs.rename turn that same mutant red (2 failed | 44 passed, at the openSync rows of the two setup tests) and are green against the head source (46/46). The target-resolution refusal test already asserted fs.mkdir and fs.rename were untouched; its openSync twin completes the convention for all three refusals above the guarded region. Answers review thread 4477041800's sibling shape on this series; test-only. --- .../file-safety/__tests__/safeWriteText.spec.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/services/file-safety/__tests__/safeWriteText.spec.ts b/src/services/file-safety/__tests__/safeWriteText.spec.ts index b91554ab32d..b5dfb042bfd 100644 --- a/src/services/file-safety/__tests__/safeWriteText.spec.ts +++ b/src/services/file-safety/__tests__/safeWriteText.spec.ts @@ -1044,6 +1044,9 @@ describe("safeWriteText", () => { expect(_backupUnlinkCalls()).toBe(0) expect(fs.mkdir).not.toHaveBeenCalled() expect(fs.rename).not.toHaveBeenCalled() + // Same convention as the two directory-setup tests below, extended to the sync write step: + // this refusal happens before any of the write work. + expect(fsSync.openSync).not.toHaveBeenCalled() }) it("fixes the generated staging file's mode with fchmod so the umask cannot narrow it", async () => { const targetPath = "/tmp/test-dir/target.txt" @@ -1102,6 +1105,13 @@ describe("safeWriteText", () => { // back by the same cleanup the refusal path uses. expect(fs.unlink).toHaveBeenCalledWith(callerTemp) expect(_backupUnlinkCalls()).toBe(0) + // Directory setup sits above the guarded region, so a refusal here has to stop before any + // write work: a failure that fell through into the write would still hand the staged file + // back and still throw EACCES, and only the absence of the write tells those two shapes + // apart. + expect(fsSync.openSync).not.toHaveBeenCalled() + expect(fsSync.mkdirSync).not.toHaveBeenCalled() + expect(fs.rename).not.toHaveBeenCalled() }) it("hands a caller-staged temp file back when the prepared directory fails access check", async () => { @@ -1120,6 +1130,13 @@ describe("safeWriteText", () => { expect(fs.unlink).toHaveBeenCalledWith(callerTemp) expect(_backupUnlinkCalls()).toBe(0) + // Directory setup sits above the guarded region, so a refusal here has to stop before any + // write work: a failure that fell through into the write would still hand the staged file + // back and still throw EACCES, and only the absence of the write tells those two shapes + // apart. + expect(fsSync.openSync).not.toHaveBeenCalled() + expect(fsSync.mkdirSync).not.toHaveBeenCalled() + expect(fs.rename).not.toHaveBeenCalled() }) }) }) From db582baee88efd53672818ed38ba3689a0a79e08 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Mon, 9 Nov 2026 04:36:14 +0800 Subject: [PATCH 62/79] test(tools): drive the guardedWrite double's abort through requestAbort Task.abort became a get-only accessor on main. 5319fe91fb0c ("refactor(task): read abort and abortReason from run-state latches", landed 2026-11-08T16:18:32Z) declares main's Task.ts:3582 as 'get abort(): boolean { return abort(this.runState) }' fed by runState.ts:188, with requestAbort as the write surface. compile typechecks the checkout CI produces, which is refs/pull/1408/merge - main plus this branch - and in that tree this file's two 'task.abort = true' lines are assignments to a getter, even though they are legal against this branch's Task, which still carries the mutable field at Task.ts:397. The failing step was 'Check types' (pnpm check-types, exit 2) with 'Check formatting' and 'Lint' green ahead of it, and the whole diagnostic set was: core/tools/__tests__/guardedWrite.spec.ts(745,9): error TS2540: Cannot assign to 'abort' because it is a core/tools/__tests__/guardedWrite.spec.ts(759,9): error TS2540: Cannot assign to 'abort' because it is a The parent 0c07c5b097 ran the same step as a cache miss with zero TS errors because its merge ref predated the 16:18 landing, so the file and its lines are unchanged between the clean run and the red one. The double now carries requestAbort and both rows call it rather than writing the field, because that is the entry point production calls and it does not depend on which of the two Task shapes the tree happens to carry. guardedWrite.ts:420 reads task.abort and nothing in this file asserts abandoned, so the double's method sets the flag guardedWrite consults and carries abandoned only to match the method it replaces; the comment at :63-77 names the accessor and the kernel line so the next reader does not have to rediscover the split between the two trees. Control. With the double's requestAbort changed so it no longer sets the flag, the file is 2 failed | 40 passed (42): 'does not publish a queued write after the issuing task is disposed' red at spec.ts:763 with 'promise resolved "undefined" instead of rejecting', and 'refuses an already-cancelled task's write before any I/O' red at spec.ts:775 with 'expected [Function] to throw error matching /was cancelled/'. So both rows still prove the cancellation they name rather than trusting the call's name. Against the shipped source the file is 42 passed (42) in the branch tree and 42 passed (42) in the merged tree, and safeWriteText is 46 passed (46) in both. Typecheck in both directions, because that is the proof this class of red needs. tsc --noEmit in the merged tree before the change exits 2 with exactly the two TS2540 errors above; after the change it exits 0 with no diagnostics. tsc --noEmit in the branch tree exits 0 before and after, which is precisely why a branch-tree typecheck cannot catch this: the property is mutable in that tree by construction. The merged tree used here is git merge-tree of main 5319fe91fb0c and this branch - tree c7ee6aee6525, conflict-free - checked out into a scratch worktree with the usual node_modules junctions, which is the content CI's merge ref holds. +21/-6 in this one spec file - 7 executable lines, 14 comment lines, no blank lines, no production file touched. Measured with .tmp-node22 node v22.23.4. eslint --prune-suppressions --max-warnings=0 on the file exits 0 with src/eslint-suppressions.json restored byte-for-byte, and repo-root prettier --check on the file exits 0. --- src/core/tools/__tests__/guardedWrite.spec.ts | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index ccd53563891..a6087a09d4a 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -62,14 +62,29 @@ interface MockTaskOptions { /** * Minimal structural Task: guardedWrite reads task.cwd, task.observationRegistry and - * task.abort (the flag Task.dispose() sets). The real Task constructor needs the - * full provider machinery, so a single documented double cast stands in for the class. + * task.abort. The real Task constructor needs the full provider machinery, so a single + * documented double cast stands in for the class. + * + * The double carries requestAbort rather than letting a test write the flag, because that + * is the surface Task uses to set it: requestAbort on this branch's Task.ts:3591, and on + * main's Task.ts:3594, where abort itself is a get-only accessor fed by the run-state + * kernel (run-state/runState.ts:188). Writing task.abort from a test still compiles + * against this branch's Task and stops compiling against main's, which is the difference + * the merged-tree typecheck sees; calling the same entry point production calls does not + * depend on which of the two shapes the tree carries. abandoned is carried only so the + * method matches the one it replaces - nothing here asserts it, and guardedWrite.ts:420 + * reads only abort. */ function createMockTask(options: MockTaskOptions = {}): Task { const task = { cwd: options.cwd ?? WORKSPACE, observationRegistry: options.observationRegistry ?? new ObservationRegistry(), abort: false, + abandoned: false, + requestAbort(isAbandoned: boolean): void { + this.abandoned = isAbandoned === true + this.abort = true + }, } return task as unknown as Task } @@ -737,12 +752,12 @@ describe("guardedWrite (S4a, epic #1375)", () => { const first = guardedWrite(task, "queued.txt", "first", "create") const second = guardedWrite(task, "queued.txt", "second", "create") // Let the first link enter the publish (the chain runs on microtasks) before the - // disposal lands: Task.dispose() sets task.abort while the second write is still - // queued behind it. + // cancellation lands: an aborted task carries the flag guardedWrite consults, and + // the second write is still queued behind the first at that point. await new Promise(function (resolve) { setImmediate(resolve) }) - task.abort = true + task.requestAbort(false) releaseFirst() await first await expect(second).rejects.toThrow(/was cancelled/) @@ -756,7 +771,7 @@ describe("guardedWrite (S4a, epic #1375)", () => { it("refuses an already-cancelled task's write before any I/O", async () => { const task = createMockTask() - task.abort = true + task.requestAbort(false) await expect(guardedWrite(task, "gone.txt", "x", "create")).rejects.toThrow(/was cancelled/) expect(mockedSafeWriteText).not.toHaveBeenCalled() expect(mockedFsAccess).not.toHaveBeenCalled() From bbedf8bb15f66d531c8390fdbbe954c0823e8224 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:56:15 +0800 Subject: [PATCH 63/79] test(tools): drive the guarded-write cancellation double through Task's own requestAbort The double in guardedWrite.spec.ts set abort and abandoned itself, so the two "cancellation while queued" rows kept passing on the double's own copy of the logic: deleting the flag write at Task.ts:3595 changed no row in this file (measured: 42 passed against the mutated Task with the head-shaped file). The stand-in now stands on Task.prototype with only the fields the constructor would have initialized, so requestAbort is the class's own method and the run-state kernel it drives is the production one. With that shape the same deletion fails both rows (2 failed, 40 passed), and the unmutated run still passes 42 of 42. The flag contract was already pinned on a real Task elsewhere: the same mutation fails 2 rows of core/task/__tests__/Task.run-shadow.spec.ts (2 failed, 14 passed). What this closes is the combination - a queued guarded write cancelled through production requestAbort - which is what review thread 4507759199 asked for. Controls measured on this head: - tsc --noEmit -p src/tsconfig.json: 0 errors with the change, 0 errors at head. - Sensitivity probe: task.runState = 12345 in this file reports TS2322 at :108, so the file is inside the typecheck rather than skipped by a tsconfig glob. - eslint --max-warnings=0 on the changed file: 0 messages, 0 warnings; eslint-suppressions json untouched, so no count rises. - prettier --check on the file: clean. - Real Task construction cost, for the record: the smallest spec on this branch that builds one (Task.abort-reason-race.spec.ts) carries 12 vi.mock blocks and a 34-line provider double; this file mocks fs/promises down to three functions, so the prototype stand-in is the narrowest shape that still runs the production method. --- src/core/tools/__tests__/guardedWrite.spec.ts | 69 ++++++++++++------- 1 file changed, 46 insertions(+), 23 deletions(-) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index a6087a09d4a..292fbe90694 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -18,7 +18,9 @@ import { resolvePublishTarget, safeWriteText } from "../../../services/file-safe import { computeVersionToken } from "../../../utils/versionToken" import { acquireFileLock } from "../../../utils/fileLock" import { ObservationRegistry } from "../../task/observationRegistry" -import type { Task } from "../../task/Task" +import { Task } from "../../task/Task" +import { initialRunState, type RunState } from "../../task/run-state/runState" +import type { RunRejection } from "../../task/run-state/runStateShadow" // -- Mocks ------------------------------------------------------------------- @@ -61,31 +63,52 @@ interface MockTaskOptions { } /** - * Minimal structural Task: guardedWrite reads task.cwd, task.observationRegistry and - * task.abort. The real Task constructor needs the full provider machinery, so a single - * documented double cast stands in for the class. + * Task stand-in that runs the production cancellation path instead of re-implementing it. * - * The double carries requestAbort rather than letting a test write the flag, because that - * is the surface Task uses to set it: requestAbort on this branch's Task.ts:3591, and on - * main's Task.ts:3594, where abort itself is a get-only accessor fed by the run-state - * kernel (run-state/runState.ts:188). Writing task.abort from a test still compiles - * against this branch's Task and stops compiling against main's, which is the difference - * the merged-tree typecheck sees; calling the same entry point production calls does not - * depend on which of the two shapes the tree carries. abandoned is carried only so the - * method matches the one it replaces - nothing here asserts it, and guardedWrite.ts:420 - * reads only abort. + * guardedWrite reads three things off the task - cwd, observationRegistry and abort + * (src/core/tools/guardedWrite.ts:407, :413, :420) - and building a real Task needs the full + * provider machinery: the smallest spec on this branch that does it, + * src/core/task/__tests__/Task.abort-reason-race.spec.ts, carries 12 vi.mock blocks and a + * 34-line provider double (:88-121) for exactly that reason. So this stands on Task.prototype + * and supplies only the values the constructor would have initialized. requestAbort is then + * the class's own method: the flag write at Task.ts:3595 and the run-state kernel it drives + * (Task.ts:3591-3597, driveRunEvent at :3609-3630 over runState and runRejections) are + * production code rather than a re-implementation in the double, so the cancellation rows + * below fail when requestAbort stops setting abort. That is the gap the hand-written setter + * this replaced left open - with that setter, deleting the assignment at Task.ts:3595 changed + * no row in this file. + * + * Nothing here depends on which spelling of abort the tree carries. cwd is an accessor on + * Task.prototype (Task.ts:6487), so it is shadowed with an own property instead of assigned; + * abort and abandoned are left to production - undefined until requestAbort runs, which reads + * the same as false at the truthy check in guardedWrite.ts:420 - because that call site reads + * only abort, while main reads both flags from the kernel latches + * (src/core/task/run-state/runState.ts:188, :190) and exposes abort as a get-only accessor + * (main's Task.ts:3582), where a test that wrote the field would not compile. */ + +/** The fields Task's constructor initializes that this stand-in has to supply by hand. */ +interface TaskDoubleFields { + cwd?: string + observationRegistry?: ObservationRegistry + runState?: RunState + runRejections?: RunRejection[] +} + function createMockTask(options: MockTaskOptions = {}): Task { - const task = { - cwd: options.cwd ?? WORKSPACE, - observationRegistry: options.observationRegistry ?? new ObservationRegistry(), - abort: false, - abandoned: false, - requestAbort(isAbandoned: boolean): void { - this.abandoned = isAbandoned === true - this.abort = true - }, - } + // Object.create is untyped in this lib: its signature takes no type argument, so the shape + // comes from the structural type above rather than from a generic parameter. + const task: TaskDoubleFields = Object.create(Task.prototype) + Object.defineProperty(task, "cwd", { + value: options.cwd ?? WORKSPACE, + writable: true, + configurable: true, + }) + task.observationRegistry = options.observationRegistry ?? new ObservationRegistry() + task.runState = initialRunState + task.runRejections = [] + // The stand-in covers only the members guardedWrite touches; Task's own surface is wider and + // no constructor runs here, so the double assertion stands in for that gap. return task as unknown as Task } From 94ca5fcf47e7542fb358da07c2e07cb5c5abd353 Mon Sep 17 00:00:00 2001 From: "user.email" <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:04:48 +0800 Subject: [PATCH 64/79] fix(apply-diff): refuse the direct save a stale observation would authorize The focus-disruption save records its observation only when the tool's own read produced a version token. When that read straddled a write no token exists, yet an earlier read's observation still authorizes the guarded publish, so a diff built from mid-flight content overwrites the target on another read's authority. Refuse that save. When nothing is observed the read still continues and the unobserved-edit guard's own remediation answers, which is what the stat-failure rows already lock. Answers review root PRRT_kwDOSK-bwM61KUmx (src/core/tools/ApplyDiffTool.ts:208). Control row: "refuses the direct save when the read produced no token and an earlier observation would authorize it" - exit 1 at df1047b5 with "expected \"vi.fn()\" to not be called at all, but actually been called 1 times", exit 0 here (11 passed). --- src/core/tools/ApplyDiffTool.ts | 12 +++++ .../applyDiffTool.guardedWrite.spec.ts | 45 +++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/src/core/tools/ApplyDiffTool.ts b/src/core/tools/ApplyDiffTool.ts index 011ecbb7081..6afa77224c4 100644 --- a/src/core/tools/ApplyDiffTool.ts +++ b/src/core/tools/ApplyDiffTool.ts @@ -203,6 +203,18 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> { // the task-wide registry. task.diffViewProvider.editType = "modify" task.diffViewProvider.originalContent = originalContent + if (readVersionToken === undefined && task.observationRegistry.has(absolutePath)) { + // This read straddled a write (or one of its stats failed), so it produced no token + // of its own, yet an earlier read left this path observed. Publishing now would let + // that other read's token authorize an overwrite of content this tool never + // verified - the failure the unobserved-edit guard exists to stop, reached through a + // registry entry the guard has no reason to distrust. Fail closed. When nothing is + // observed the read still continues and the guard's own remediation answers, which + // is the behavior the stat-failure rows in applyDiffTool.guardedWrite.spec.ts lock. + throw new Error( + `The file ${relPath} changed while it was being read for this diff, so nothing was saved. Read the file again and reapply the diff against the current content.`, + ) + } if (readVersionToken !== undefined) { task.observationRegistry.observe(absolutePath, readVersionToken) } diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts index 5f0e3974e57..c64a1ea450d 100644 --- a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -193,6 +193,51 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { ) }) + it("refuses the direct save when the read produced no token and an earlier observation would authorize it", async () => { + // The reviewer's scenario: an earlier read left this path observed, so the guarded + // publish would find a token to compare against, while the read that built *this* + // diff straddled a write and produced no token of its own. Saving now publishes + // content this tool never observed at a version it can verify, authorized by an + // observation that belongs to a different read. + const absolutePath = path.resolve("/workspace/project", "src/thing.ts") + const earlierToken = "7:4242:1234:1700000000123456789:1700000000789999999" + mockTask.observationRegistry.observe(absolutePath, earlierToken) + + const statMock = vi.mocked((await import("fs/promises")).default.stat) + statMock + .mockResolvedValueOnce({ + dev: 7n, + ino: 4242n, + size: 1234n, + mtimeNs: 1n, + ctimeNs: 2n, + } as unknown as BigIntStats) + .mockResolvedValueOnce({ + dev: 7n, + ino: 4242n, + size: 9999n, + mtimeNs: 3n, + ctimeNs: 4n, + } as unknown as BigIntStats) + + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(mockSaveDirectly).not.toHaveBeenCalled() + const [reportedWhere, reportedError] = mockHandleError.mock.calls[0] ?? [] + expect(reportedWhere).toBe("applying diff") + expect(reportedError instanceof Error ? reportedError.message : "").toContain("changed while it was being read") + expect(vi.mocked(mockTask.diffViewProvider.reset)).toHaveBeenCalled() + expect(mockTask.didEditFile).toBe(false) + expect(mockPushToolResult).not.toHaveBeenCalledWith("Saved file") + // The earlier read's observation is left alone: this row is about not publishing on + // its authority, not about retiring it. + expect(mockTask.observationRegistry.get(absolutePath)?.version).toBe(earlierToken) + }) it("does not observe when the file changes underneath the read", async () => { // Only the fields versionTokenOfStat reads; a full BigIntStats cannot be built // against the mocked fs, so the double assertion is the narrowest option. From fa492398426659ca5691620c7daf45f562367b6e Mon Sep 17 00:00:00 2001 From: "user.email" <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:08:34 +0800 Subject: [PATCH 65/79] fix(apply-diff): retire the abandoned read's observation after a stale rejection open() re-reads the file and records that newer version as the save baseline (src/integrations/editor/DiffViewProvider.ts:149-157). When apply_diff then rejects the diff as stale, the rollback retires the editor buffer but the observation stayed current, so a later write_to_file - focus-disruption save enabled - could publish on a read this tool had abandoned. ObservationRegistry gains a per-path forget so the stale flow drops exactly that path; clear() would have stripped observations that belong to other files. Answers review root PRRT_kwDOSK-bwM61KUm3 (src/core/tools/ApplyDiffTool.ts:238). Controls and their exits at the tree this replaces (b49fa5d02ff0): - src/core/task/__tests__/observationRegistry.spec.ts "forget drops one path and leaves every other path observed" - exit 1, TypeError: "reg.forget is not a function"; exit 0 here (14 passed). - src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts "retires the diff view observation for this path when it rejects a stale diff" - exit 1, "expected true to be false // Object.is equality"; exit 0 here (12 passed). applyDiffTool.failureReporting.spec.ts also re-run green (35 passed). --- .../__tests__/observationRegistry.spec.ts | 13 +++++ src/core/task/observationRegistry.ts | 12 +++++ src/core/tools/ApplyDiffTool.ts | 6 +++ .../applyDiffTool.guardedWrite.spec.ts | 47 +++++++++++++++++++ 4 files changed, 78 insertions(+) diff --git a/src/core/task/__tests__/observationRegistry.spec.ts b/src/core/task/__tests__/observationRegistry.spec.ts index 7286cc79bba..14b4e71a9a3 100644 --- a/src/core/task/__tests__/observationRegistry.spec.ts +++ b/src/core/task/__tests__/observationRegistry.spec.ts @@ -38,6 +38,19 @@ describe("ObservationRegistry", () => { expect(reg.has("/y.ts")).toBe(false) }) + it("forget drops one path and leaves every other path observed", () => { + const reg = new ObservationRegistry() + reg.observe("/x.ts", "t1") + reg.observe("/y.ts", "t2") + + expect(reg.forget("/x.ts")).toBe(true) + expect(reg.has("/x.ts")).toBe(false) + expect(reg.get("/y.ts")?.version).toBe("t2") + expect(reg.size).toBe(1) + + // Forgetting a path nobody observed reports rather than throws. + expect(reg.forget("/z.ts")).toBe(false) + }) it("size reflects the number of observed entries", () => { const reg = new ObservationRegistry() expect(reg.size).toBe(0) diff --git a/src/core/task/observationRegistry.ts b/src/core/task/observationRegistry.ts index b3b7a719871..539a5cb3a61 100644 --- a/src/core/task/observationRegistry.ts +++ b/src/core/task/observationRegistry.ts @@ -56,6 +56,18 @@ export class ObservationRegistry { return this.entries.has(absolutePath) } + /** + * Drop the observation for one path, leaving every other path observed. + * + * A tool that abandons its own read - a stale diff it will not save - must not leave + * that read's version token behind as authority for some later write. Retiring the + * whole registry would strip observations that belong to other files and to other + * tasks' work, so the removal is per path. Reports whether an entry was removed. + */ + forget(absolutePath: string): boolean { + return this.entries.delete(absolutePath) + } + clear(): void { this.entries.clear() } diff --git a/src/core/tools/ApplyDiffTool.ts b/src/core/tools/ApplyDiffTool.ts index 6afa77224c4..9935fd9858c 100644 --- a/src/core/tools/ApplyDiffTool.ts +++ b/src/core/tools/ApplyDiffTool.ts @@ -244,6 +244,12 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> { await task.say("error", staleError) task.didToolFailInCurrentTurn = true await task.diffViewProvider.revertChanges() + // The rollback retires the editor buffer, but open() had already recorded the + // newer on-disk version as this flow's observation (DiffViewProvider.ts:149-157). + // Leaving it current would let a later write - write_to_file with the + // focus-disruption save - publish on a read this tool abandoned, so retire that + // path only; other files keep what their own reads recorded. + task.observationRegistry.forget(absolutePath) task.processQueuedMessages() pushToolResult(staleError) return diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts index c64a1ea450d..19e0728f64b 100644 --- a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -433,4 +433,51 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { expect.stringContaining("changed after it was read for this diff"), ) }) + it("retires the diff view observation for this path when it rejects a stale diff", async () => { + // open() re-reads the file and records that newer version as the save baseline + // (src/integrations/editor/DiffViewProvider.ts:149-157). When the tool then rejects + // the diff as stale, the rollback retires the buffer but leaves that observation + // current, and a later write_to_file - focus-disruption save enabled - can spend it + // on an overwrite the model never read. Retiring it must not retire other paths. + const absolutePath = path.resolve("/workspace/project", "src/thing.ts") + const otherPath = path.resolve("/workspace/project", "src/other.ts") + mockTask.observationRegistry.observe(otherPath, "7:4242:1234:1700000000123456789:1700000000789999999") + + const diffViewStub = mockTask.diffViewProvider as unknown as Record + diffViewStub.open = vi.fn().mockImplementation(async () => { + diffViewStub.originalContent = "written by another process\n" + // What production open() does after re-reading the file: observe the newer token. + mockTask.observationRegistry.observe(absolutePath, "7:4242:1234:1700000000123456799:1700000000789000001") + }) + diffViewStub.update = vi.fn().mockResolvedValue(undefined) + diffViewStub.scrollToFirstDiff = vi.fn() + diffViewStub.revertChanges = vi.fn().mockResolvedValue(undefined) + diffViewStub.saveChanges = vi.fn().mockResolvedValue({ + newProblemsMessage: "", + userEdits: undefined, + finalContent: "new content", + }) + mockTask.providerRef = { + deref: vi.fn().mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + diagnosticsEnabled: true, + writeDelayMs: 1000, + experiments: {}, + }), + }), + } as unknown as Task["providerRef"] + + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(diffViewStub.update).not.toHaveBeenCalled() + expect(diffViewStub.saveChanges).not.toHaveBeenCalled() + expect(diffViewStub.revertChanges).toHaveBeenCalled() + expect(mockTask.observationRegistry.has(absolutePath)).toBe(false) + expect(mockTask.observationRegistry.has(otherPath)).toBe(true) + }) }) From 478c10750d9a88e83e86228eb67d047892701730 Mon Sep 17 00:00:00 2001 From: "user.email" <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:11:19 +0800 Subject: [PATCH 66/79] test(guarded-write): bind the FIFO chain to blocked publishes and a pending reset MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three review asks on src/core/tools/__tests__/guardedWrite.spec.ts were about assertions this file did not carry, so they are landed as executable rows rather than as code: - a third write is now queued behind a *blocked* second write on the same path, which the shipped eviction row (two rapid writes behind an idle tail) does not cover. - the independence row now holds the first path's publish open and requires the second path to settle while it is held, releasing the gate in finally. As shipped it ran both writes against a writer that resolves immediately, so a single global queue passed it. - a pending-link row: resetChain() runs while a publish is in flight and the later write must reach safeWriteText anyway, which is detachment rather than ordering. Answers review roots PRRT_kwDOSK-bwM61KUmV, 607 (…61KUml) and PRRT_kwDOSK-bwM61KUmq. These rows bind behavior the head already had, so their controls are negations of that behavior, run against src/core/tools/guardedWrite.ts as it stands at 6b7d45ee63 with the probe reverted before commit: - PROBE N1 (enqueue ignores any pending tail): row "keeps a third write queued behind a blocked second write on the same path" exit 1 - "expected [ 'start:second', 'start:third', …(1) ] to deeply equal [ 'start:second' ]". - PROBE N2 (one queue for every path): row "writes on different paths are independent (no cross-path serialization)" exit 1 - "Test timed out in 20000ms." - PROBE N3 (resetChain does nothing): row "detaches a pending link so a later write runs while the blocked one is still held" exit 1 - "Test timed out in 20000ms." With the implementation as shipped the file is exit 0: Tests 44 passed (44). --- src/core/tools/__tests__/guardedWrite.spec.ts | 110 +++++++++++++++++- 1 file changed, 109 insertions(+), 1 deletion(-) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index 292fbe90694..79af6b30fba 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -469,6 +469,46 @@ describe("guardedWrite (S4a, epic #1375)", () => { expect(mockedSafeWriteText).toHaveBeenCalledTimes(3) }) + it("keeps a third write queued behind a blocked second write on the same path", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("queue.txt"), "v1") + mockedComputeVersionToken.mockResolvedValue("v1") + const task = createMockTask({ observationRegistry: reg }) + + // Settle one write first so its chain entry is evicted with it: the three writes + // below are submitted to a chain that was just emptied, which is the state the ask + // is about - links enqueued while a publish is already in flight, not links queued + // behind an idle tail. + await guardedWrite(task, "queue.txt", "first", "update") + + const order: string[] = [] + let releaseSecond: () => void = () => {} + const secondHeld = new Promise((resolve) => { + releaseSecond = resolve + }) + mockedSafeWriteText.mockImplementation(async (_path: string, content: string) => { + order.push("start:" + content) + if (content === "second") { + // Hold only the second publication: the third write must not reach + // safeWriteText until this one settles. + await secondHeld + } + order.push("end:" + content) + }) + + const p2 = guardedWrite(task, "queue.txt", "second", "update") + const p3 = guardedWrite(task, "queue.txt", "third", "update") + + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(order).toEqual(["start:second"]) + + releaseSecond() + await Promise.all([p2, p3]) + + expect(order).toEqual(["start:second", "end:second", "start:third", "end:third"]) + // Three publishes: the settled first write plus the two queued behind it. + expect(mockedSafeWriteText).toHaveBeenCalledTimes(3) + }) it("writes on different paths are independent (no cross-path serialization)", async () => { const reg = new ObservationRegistry() reg.observe(abs("a.txt"), "v1") @@ -476,10 +516,37 @@ describe("guardedWrite (S4a, epic #1375)", () => { mockedComputeVersionToken.mockResolvedValue("v1") const task = createMockTask({ observationRegistry: reg }) + const order: string[] = [] + let releaseFirst: () => void = () => {} + const firstHeld = new Promise((resolve) => { + releaseFirst = resolve + }) + mockedSafeWriteText.mockImplementation(async (_path: string, content: string) => { + order.push("start:" + content) + if (content === "a") { + // Hold only the first path publish open. The chains are keyed per absolute + // path, so the second path must reach its publish anyway; a single global + // queue would leave b.txt waiting here and the await below would time out. + await firstHeld + } + order.push("end:" + content) + }) + const p1 = guardedWrite(task, "a.txt", "a", "update") const p2 = guardedWrite(task, "b.txt", "b", "update") - await Promise.all([p1, p2]) + try { + // The second path settles while the first is still inside safeWriteText. + await p2 + expect(order).toEqual(["start:a", "start:b", "end:b"]) + } finally { + // Release the held gate on every exit path, including an assertion failure + // above, so a failing row cannot leave the chain blocked for the next one. + releaseFirst() + await p1 + } + + expect(order).toEqual(["start:a", "start:b", "end:b", "end:a"]) expect(mockedSafeWriteText).toHaveBeenCalledTimes(2) }) }) @@ -636,6 +703,47 @@ describe("guardedWrite (S4a, epic #1375)", () => { preCommitVerify: expect.any(Function), }) }) + it("detaches a pending link so a later write runs while the blocked one is still held", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("pending.txt"), "v1") + mockedComputeVersionToken.mockResolvedValue("v1") + const task = createMockTask({ observationRegistry: reg }) + + const order: string[] = [] + let releaseFirst: () => void = () => {} + const firstHeld = new Promise((resolve) => { + releaseFirst = resolve + }) + mockedSafeWriteText.mockImplementation(async (_path: string, content: string) => { + order.push("start:" + content) + if (content === "held") { + await firstHeld + } + order.push("end:" + content) + }) + + // A publish is in flight on this path's chain at the moment resetChain() runs. + const p1 = guardedWrite(task, "pending.txt", "held", "update") + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(order).toEqual(["start:held"]) + + resetChain() + + try { + // Detachment is the assertion: the abandoned tail may not hold the new write, + // so the fresh write must reach its publish and settle while the held link is + // still inside safeWriteText. A resetChain() that did nothing would leave this + // await behind the held link and time out. + await guardedWrite(task, "pending.txt", "fresh", "update") + expect(order).toEqual(["start:held", "start:fresh", "end:fresh"]) + } finally { + releaseFirst() + await p1 + } + + expect(order).toEqual(["start:held", "start:fresh", "end:fresh", "end:held"]) + expect(mockedSafeWriteText).toHaveBeenCalledTimes(2) + }) }) describe("atomicity of the guard check and publish", () => { From 9adcbc93eda8609333fe1d0720b1ec9269c50005 Mon Sep 17 00:00:00 2001 From: easonLiangWorldedtech Date: Sun, 29 Nov 2026 05:02:58 +0800 Subject: [PATCH 67/79] fix(tools): re-adjudicate the s4b rebase onto main's evolved architecture The engine's auto-merge dropped or duplicated pieces of main's evolved composition: - dropped the task-double's `as unknown as Task` cast (WeakRef is stricter on main now), - duplicated the ObservationRegistry import+field in Task.ts (same signature as #1394's dedupe commit), - duplicated `import { t }`-class lines in specs, - omitted the now-required ToolCallbacks.toolCallId at 20 guarded-write spec call sites, - and left main's (not this branch's) versionToken/safeWriteJson/observation-registry picks in place, their later self-converging picks already subsumed by main (dropped: versionToken A1 family, safeWriteJson internals, eslint-suppressions additions main already earned back). Main's BigInt versionToken and lock/recovery safeWriteJson stay as-is. Battery: src tsc clean against own packages, eslint 0 over 25 changed files, prettier 0, guarded-write vitest 70/70. --- src/core/task/Task.ts | 2 - .../applyDiffTool.guardedWrite.spec.ts | 8 + .../__tests__/applyPatchTool.execute.spec.ts | 12 + src/core/tools/__tests__/readFileTool.spec.ts | 2 + src/eslint-suppressions.json | 1305 +++++++++++++++++ .../editor/__tests__/DiffViewProvider.spec.ts | 3 +- 6 files changed, 1328 insertions(+), 4 deletions(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 1a71726d641..e2e25ef93da 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -108,7 +108,6 @@ import { restoreTodoListForTask } from "../tools/UpdateTodoListTool" import { FileContextTracker } from "../context-tracking/FileContextTracker" import { ObservationRegistry } from "./observationRegistry" import { RooIgnoreController } from "../ignore/RooIgnoreController" -import { ObservationRegistry } from "./observationRegistry" import { RooProtectedController } from "../protect/RooProtectedController" import { type AssistantMessageContent, presentAssistantMessage } from "../assistant-message" import { DispatchState, type PendingWork } from "./dispatchState" @@ -314,7 +313,6 @@ export class Task extends EventEmitter implements TaskLike { readonly parentTask: Task | undefined = undefined readonly taskNumber: number readonly workspacePath: string - readonly observationRegistry = new ObservationRegistry() /** * The mode associated with this task. Persisted across sessions diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts index 19e0728f64b..61a3a8bd85c 100644 --- a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -141,6 +141,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(mockSaveDirectly).toHaveBeenCalledWith( @@ -164,6 +165,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(mockHandleError).toHaveBeenCalledWith("applying diff", guardError) @@ -176,6 +178,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) // The focus-disruption save has no diff view to observe the file, so the tool read @@ -262,6 +265,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) // A read that straddled a write proves nothing about the current version, so no @@ -295,6 +299,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) // Both stat calls must be consumed: beforeEach only clears call history, so a @@ -332,6 +337,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(mockSaveDirectly).not.toHaveBeenCalled() @@ -347,6 +353,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(mockSaveDirectly).not.toHaveBeenCalled() @@ -385,6 +392,7 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(diffViewStub.saveChanges).toHaveBeenCalled() diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index d341d3b0f13..56f9d094556 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -230,6 +230,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(mockSaveDirectly).toHaveBeenCalledWith( @@ -250,6 +251,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) // The hunk read doubles as the S2 observation (ReadFileTool contract): @@ -276,6 +278,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(mockTask.observationRegistry.has(path.resolve("/workspace/project", "src/thing.ts"))).toBe(false) @@ -309,6 +312,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) // A stat failure is not evidence the file changed and not a reason to abort the @@ -337,6 +341,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("Failed to process patch")) @@ -353,6 +358,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(mockPushToolResult).toHaveBeenCalledWith("Changes were rejected by the user.") @@ -388,6 +394,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(diffViewStub.saveChanges).toHaveBeenCalled() @@ -402,6 +409,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(mockSaveDirectly).toHaveBeenCalledWith( @@ -422,6 +430,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(mockSaveDirectly).toHaveBeenCalledWith( @@ -446,6 +455,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) // The destination saveDirectly is the guarded publish for a move: a failure there @@ -467,6 +477,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(mockHandleError).toHaveBeenCalledWith("apply patch", guardError) @@ -485,6 +496,7 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, + toolCallId: "test-call", }) expect(mockHandleError).toHaveBeenCalledWith("apply patch", guardError) diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 9c7a6e6b5f5..329c0f4a920 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -12,6 +12,8 @@ * - Output structure formatting */ +import type { LegacyReadFileParams } from "@roo-code/types" +import type { Stats } from "fs" import os from "os" import path from "path" import * as vscode from "vscode" diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index 185d3a9d6a2..e07b00bd6a9 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -1,2 +1,1307 @@ +{ + "api/providers/__tests__/anthropic-vertex.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 31 + } + }, + "api/providers/__tests__/anthropic.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 7 + } + }, + "api/providers/__tests__/base-openai-compatible-provider-timeout.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "api/providers/__tests__/base-openai-compatible-provider.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/providers/__tests__/base-provider.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "api/providers/__tests__/bedrock-custom-arn.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 12 + } + }, + "api/providers/__tests__/bedrock-error-handling.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 7 + } + }, + "api/providers/__tests__/bedrock-inference-profiles.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 27 + } + }, + "api/providers/__tests__/bedrock-native-tools.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 19 + } + }, + "api/providers/__tests__/bedrock-reasoning.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/providers/__tests__/bedrock.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 37 + } + }, + "api/providers/__tests__/deepseek.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 12 + } + }, + "api/providers/__tests__/gemini-handler.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 18 + } + }, + "api/providers/__tests__/gemini.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 33 + } + }, + "api/providers/__tests__/kenari.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/providers/__tests__/kimi-code.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/providers/__tests__/lite-llm.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 26 + } + }, + "api/providers/__tests__/mimo.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 18 + } + }, + "api/providers/__tests__/minimax.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/providers/__tests__/moonshot.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 22 + } + }, + "api/providers/__tests__/native-ollama.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 21 + } + }, + "api/providers/__tests__/openai-codex-native-tool-calls.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 22 + } + }, + "api/providers/__tests__/openai-codex.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 16 + } + }, + "api/providers/__tests__/openai-native-tools.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 14 + } + }, + "api/providers/__tests__/openai-native-usage.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 25 + } + }, + "api/providers/__tests__/openai-native.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 74 + } + }, + "api/providers/__tests__/openai-timeout.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "api/providers/__tests__/openai.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "api/providers/__tests__/opencode-go.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "api/providers/__tests__/openrouter.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 34 + } + }, + "api/providers/__tests__/qwen-code-native-tools.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/providers/__tests__/sambanova.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/providers/__tests__/unbound.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "api/providers/__tests__/vercel-ai-gateway.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/providers/__tests__/vertex.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "api/providers/__tests__/zai.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/providers/anthropic-vertex.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "api/providers/anthropic.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/providers/base-openai-compatible-provider.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 6 + } + }, + "api/providers/base-provider.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "api/providers/bedrock.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 32 + } + }, + "api/providers/deepseek.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/providers/fetchers/__tests__/kenari.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/providers/fetchers/__tests__/kimi-code.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/providers/fetchers/__tests__/lmstudio.test.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "api/providers/fetchers/__tests__/modelEndpointCache.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 9 + } + }, + "api/providers/fetchers/__tests__/moonshot.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/providers/fetchers/__tests__/ollama.test.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 9 + } + }, + "api/providers/fetchers/__tests__/opencode-go.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/providers/fetchers/__tests__/openrouter.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/providers/fetchers/__tests__/vercel-ai-gateway.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/providers/fetchers/__tests__/zoo-gateway.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 8 + } + }, + "api/providers/fetchers/litellm.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/providers/gemini.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "api/providers/lite-llm.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 6 + } + }, + "api/providers/mimo.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "api/providers/moonshot.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/providers/native-ollama.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/providers/openai-codex.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 31 + } + }, + "api/providers/openai-native.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 27 + } + }, + "api/providers/openai.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/providers/openrouter.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 6 + } + }, + "api/providers/poe.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/providers/requesty.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "api/providers/unbound.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "api/providers/utils/__tests__/error-handler.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 35 + } + }, + "api/providers/utils/__tests__/image-generation.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 17 + } + }, + "api/providers/utils/__tests__/timeout-config.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/providers/utils/error-handler.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 7 + } + }, + "api/providers/xai.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "api/transform/__tests__/ai-sdk.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "api/transform/__tests__/anthropic-filter.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 6 + } + }, + "api/transform/__tests__/bedrock-converse-format.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "api/transform/__tests__/gemini-format.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "api/transform/__tests__/mistral-format.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/transform/__tests__/model-params.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 8 + } + }, + "api/transform/__tests__/openai-format.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 49 + } + }, + "api/transform/__tests__/r1-format.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 8 + } + }, + "api/transform/__tests__/reasoning.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/transform/__tests__/responses-api-input.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/transform/__tests__/zai-format.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "api/transform/ai-sdk.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/transform/bedrock-converse-format.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "api/transform/cache-strategy/__tests__/cache-strategy.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 17 + } + }, + "api/transform/caching/__tests__/gemini.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/transform/gemini-format.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "api/transform/openai-format.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 7 + } + }, + "api/transform/r1-format.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "api/transform/responses-api-input.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 6 + } + }, + "api/transform/responses-api-stream.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "api/transform/zai-format.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "core/assistant-message/NativeToolCallParser.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/assistant-message/__tests__/presentAssistantMessage-custom-tool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "core/assistant-message/__tests__/presentAssistantMessage-images.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 14 + } + }, + "core/assistant-message/__tests__/presentAssistantMessage-unknown-tool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 8 + } + }, + "core/assistant-message/presentAssistantMessage.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "core/auto-approval/__tests__/AutoApprovalHandler.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/checkpoints/__tests__/checkpoint.test.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "core/checkpoints/index.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/condense/__tests__/condense.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "core/condense/__tests__/foldedFileContext.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 10 + } + }, + "core/condense/__tests__/index.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 24 + } + }, + "core/config/ContextProxy.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/config/CustomModesManager.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "core/config/ProviderSettingsManager.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "core/config/__tests__/ContextProxy.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "core/config/__tests__/CustomModesManager.exportImportSlugChange.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "core/config/__tests__/CustomModesManager.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 12 + } + }, + "core/config/__tests__/CustomModesManager.yamlEdgeCases.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/context-management/__tests__/context-management.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/context-tracking/__tests__/FileContextTracker.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "core/context/context-management/__tests__/context-error-handling.test.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/context/context-management/context-error-handling.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/diff/stats.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/environment/__tests__/getEnvironmentDetails.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/ignore/__tests__/RooIgnoreController.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/mentions/index.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/mentions/processUserContentMentions.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/message-manager/index.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 21 + } + }, + "core/message-manager/index.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/prompts/__tests__/add-custom-instructions.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/prompts/__tests__/get-prompt-component.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/prompts/__tests__/responses-rooignore.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 6 + } + }, + "core/prompts/__tests__/system-prompt.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "core/prompts/sections/__tests__/custom-instructions-global.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 18 + } + }, + "core/prompts/sections/__tests__/custom-instructions.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 55 + } + }, + "core/prompts/tools/__tests__/filter-tools-for-mode.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 14 + } + }, + "core/prompts/tools/native-tools/__tests__/converters.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/prompts/tools/native-tools/__tests__/read_file.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "core/task-persistence/__tests__/TaskHistoryStore.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "core/task-persistence/__tests__/importRooTaskHistory.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/task-persistence/__tests__/taskMessages.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/task-persistence/apiMessages.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/task/Task.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 17 + } + }, + "core/task/__tests__/Task.dispose.test.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "core/task/__tests__/Task.persistence.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 8 + } + }, + "core/task/__tests__/Task.sticky-profile-race.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "core/task/__tests__/Task.throttle.test.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 24 + } + }, + "core/task/__tests__/apiConversationHistory.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 23 + } + }, + "core/task/__tests__/ask-clear-approval-buttons.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 18 + } + }, + "core/task/__tests__/ask-queued-message-drain.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 17 + } + }, + "core/task/__tests__/flushPendingToolResultsToHistory.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 14 + } + }, + "core/task/__tests__/grace-retry-errors.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "core/task/__tests__/grounding-sources.test.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "core/task/__tests__/native-tools-filtering.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "core/task/__tests__/new-task-isolation.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/task/__tests__/reasoning-preservation.test.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 20 + } + }, + "core/task/__tests__/task-tool-history.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "core/task/apiConversationHistory.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 8 + } + }, + "core/tools/BaseTool.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/tools/CodebaseSearchTool.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/tools/GenerateImageTool.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/tools/NewTaskTool.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/tools/ReadFileTool.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "core/tools/ToolRepetitionDetector.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/tools/UpdateTodoListTool.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/tools/UseMcpToolTool.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "core/tools/__tests__/ReadCommandOutputTool.test.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 16 + } + }, + "core/tools/__tests__/askFollowupQuestionTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 20 + } + }, + "core/tools/__tests__/attemptCompletionTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 11 + } + }, + "core/tools/__tests__/editFileTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "core/tools/__tests__/editTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/tools/__tests__/executeCommand.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 10 + } + }, + "core/tools/__tests__/executeCommandTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 8 + } + }, + "core/tools/__tests__/generateImageTool.test.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 9 + } + }, + "core/tools/__tests__/listFilesTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 10 + } + }, + "core/tools/__tests__/mcpServerRestriction.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 6 + } + }, + "core/tools/__tests__/newTaskTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 26 + } + }, + "core/tools/__tests__/readFileTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 96 + } + }, + "core/tools/__tests__/runSlashCommandTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/tools/__tests__/searchReplaceTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/tools/__tests__/skillTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "core/tools/__tests__/updateTodoListTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/tools/__tests__/useMcpToolTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 21 + } + }, + "core/tools/__tests__/validateToolUse.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/tools/__tests__/writeToFileTool.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "core/tools/helpers/toolResultFormatting.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/tools/validateToolUse.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "core/webview/ClineProvider.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 7 + } + }, + "core/webview/__tests__/ClineProvider.apiHandlerRebuild.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 34 + } + }, + "core/webview/__tests__/ClineProvider.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 195 + } + }, + "core/webview/__tests__/ClineProvider.sticky-mode.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 27 + } + }, + "core/webview/__tests__/ClineProvider.sticky-profile.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 15 + } + }, + "core/webview/__tests__/ClineProvider.taskHistory.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 12 + } + }, + "core/webview/__tests__/diagnosticsHandler.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 7 + } + }, + "core/webview/__tests__/messageEnhancer.test.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 8 + } + }, + "core/webview/__tests__/skillsMessageHandler.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/webview/__tests__/telemetrySettingsTracking.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "core/webview/__tests__/webviewMessageHandler.cloudAuth.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "core/webview/__tests__/webviewMessageHandler.delete.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 9 + } + }, + "core/webview/__tests__/webviewMessageHandler.edit.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/webview/__tests__/webviewMessageHandler.importRooHistory.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 13 + } + }, + "core/webview/__tests__/webviewMessageHandler.readFileContent.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/webview/__tests__/webviewMessageHandler.routerModels.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 56 + } + }, + "core/webview/__tests__/webviewMessageHandler.searchFiles.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "core/webview/__tests__/webviewMessageHandler.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 35 + } + }, + "core/webview/messageEnhancer.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "core/webview/webviewMessageHandler.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "services/__tests__/zoo-code-auth.test.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "services/checkpoints/__tests__/ShadowCheckpointService.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "services/code-index/__tests__/config-manager.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "services/code-index/__tests__/manager.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 84 + } + }, + "services/code-index/__tests__/orchestrator.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 23 + } + }, + "services/code-index/__tests__/service-factory.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 43 + } + }, + "services/code-index/embedders/__tests__/bedrock.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 7 + } + }, + "services/code-index/embedders/__tests__/gemini.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "services/code-index/embedders/__tests__/mistral.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "services/code-index/embedders/__tests__/ollama.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "services/code-index/embedders/__tests__/openai-compatible-rate-limit.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 15 + } + }, + "services/code-index/embedders/__tests__/openai-compatible.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 28 + } + }, + "services/code-index/embedders/__tests__/openai.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 10 + } + }, + "services/code-index/embedders/__tests__/openrouter.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "services/code-index/embedders/__tests__/vercel-ai-gateway.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "services/code-index/embedders/bedrock.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "services/code-index/embedders/ollama.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "services/code-index/embedders/openai-compatible.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "services/code-index/embedders/openai.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "services/code-index/embedders/openrouter.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "services/code-index/interfaces/vector-store.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "services/code-index/orchestrator.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "services/code-index/processors/__tests__/file-watcher.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 24 + } + }, + "services/code-index/processors/__tests__/parser.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 22 + } + }, + "services/code-index/processors/__tests__/scanner.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 26 + } + }, + "services/code-index/processors/file-watcher.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "services/code-index/processors/scanner.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "services/code-index/semble/__tests__/provider.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 12 + } + }, + "services/code-index/semble/__tests__/semble-cli.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "services/code-index/semble/__tests__/semble-downloader.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 61 + } + }, + "services/code-index/semble/provider.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "services/code-index/semble/semble-cli.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "services/code-index/shared/__tests__/validation-helpers.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "services/code-index/shared/validation-helpers.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "services/code-index/vector-store/__tests__/qdrant-client.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 87 + } + }, + "services/code-index/vector-store/qdrant-client.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "services/glob/__tests__/gitignore-integration.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "services/glob/__tests__/gitignore-test.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "services/glob/__tests__/list-files-limit.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 6 + } + }, + "services/glob/__tests__/list-files.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 22 + } + }, + "services/marketplace/MarketplaceManager.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "services/marketplace/SimpleInstaller.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 7 + } + }, + "services/marketplace/__tests__/MarketplaceManager.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "services/marketplace/__tests__/SimpleInstaller.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 17 + } + }, + "services/marketplace/__tests__/marketplace-setting-check.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "services/mcp/McpHub.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 7 + } + }, + "services/mcp/McpOAuthClientProvider.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "services/mcp/McpServerManager.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "services/mcp/__tests__/McpHub.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 150 + } + }, + "services/mcp/__tests__/McpOAuthClientProvider.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 18 + } + }, + "services/mcp/__tests__/SecretStorageService.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "services/mcp/utils/__tests__/oauth.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 9 + } + }, + "services/mcp/utils/callbackServer.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "services/mcp/utils/oauth.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "services/mdm/__tests__/MdmService.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 5 + } + }, + "services/ripgrep/__tests__/diagnostic.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 1 + } + }, + "services/roo-config/__tests__/index.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 20 + } + }, + "services/roo-config/index.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "services/rules/__tests__/rules.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "services/search/__tests__/file-search.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 3 + } + }, + "services/skills/__tests__/SkillsManager.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } + }, + "services/tree-sitter/__tests__/helpers.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 4 + } + }, + "services/tree-sitter/__tests__/markdownParser.spec.ts": { + "@typescript-eslint/no-explicit-any": { + "count": 2 + } } } diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index cd7bd6b7e0c..885b9c852ae 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -15,7 +15,6 @@ import { safeWriteText } from "../../../services/file-safety/safeWriteText" import { ObservationRegistry } from "../../../core/task/observationRegistry" import { createDirectoriesForFile } from "../../../utils/fs" import { acquireFileLock } from "../../../utils/fileLock" -import type { Task } from "../../../core/task/Task" // Mock delay vi.mock("delay", () => ({ @@ -256,7 +255,7 @@ describe("DiffViewProvider", () => { }), }), }, - } + } as unknown as Task diffViewProvider = new DiffViewProvider(mockCwd, mockTask) // Mock the necessary properties and methods From 28e95d6379fc411f48df20a488b8bcfa44d4f3e2 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:43:53 +0800 Subject: [PATCH 68/79] fix(1408): drop the unused catch binding in the two read paths (lint gate) The guarded-write wiring wrapped each read in `catch (error)` while the body reports a fixed message built from the path, so the binding was never read and compile's lint step failed on both files: 'error' is defined but never used. Main already uses the optional catch binding at these two sites; the files now match it, and no suppression was added or removed. Co-authored-by: Claude --- src/core/tools/EditTool.ts | 2 +- src/core/tools/SearchReplaceTool.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/core/tools/EditTool.ts b/src/core/tools/EditTool.ts index 49596e9cc53..ec412e9c02e 100644 --- a/src/core/tools/EditTool.ts +++ b/src/core/tools/EditTool.ts @@ -110,7 +110,7 @@ export class EditTool extends BaseTool<"edit"> { readVersionToken = preReadToken } } - } catch (error) { + } catch { task.consecutiveMistakeCount++ task.recordToolError("edit") const errorMessage = `Failed to read file '${relPath}'. Please verify file permissions and try again.` diff --git a/src/core/tools/SearchReplaceTool.ts b/src/core/tools/SearchReplaceTool.ts index 3faf1630973..06665d976e0 100644 --- a/src/core/tools/SearchReplaceTool.ts +++ b/src/core/tools/SearchReplaceTool.ts @@ -115,7 +115,7 @@ export class SearchReplaceTool extends BaseTool<"search_replace"> { readVersionToken = preReadToken } } - } catch (error) { + } catch { task.consecutiveMistakeCount++ task.recordToolError("search_replace") const errorMessage = `Failed to read file '${relPath}'. Please verify file permissions and try again.` From 15940326f6e149bf9f6e1a336018e5615b7ac256 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:58:55 +0800 Subject: [PATCH 69/79] chore(1408): prune the suppression count the lint gate reports as leftover With the unused catch bindings gone, lint over src exited 2 on "There are suppressions left that do not occur anymore": the recorded count for @typescript-eslint/no-explicit-any in core/tools/__tests__/readFileTool.spec.ts stood one above what the file contains. Pruned by hand (96 -> 95) so the suppressions file keeps its committed formatting; eslint over the whole workspace and prettier --check both pass and no count increased. Co-authored-by: Claude --- src/eslint-suppressions.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index e07b00bd6a9..dae44f79ece 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -841,7 +841,7 @@ }, "core/tools/__tests__/readFileTool.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 96 + "count": 95 } }, "core/tools/__tests__/runSlashCommandTool.spec.ts": { From f4473d38ebfd78fa85036139e108adfa49362ebf Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:47:36 +0800 Subject: [PATCH 70/79] fix(apply-diff): retire the observation when the rollback itself rejects The stale rejection on the diff-view branch retires this path's observation so a later write cannot spend the newer token open() recorded. It ran after revertChanges(), which saves, unlinks and rmdirs: a rollback that rejected skipped the retirement, the error reached the catch at src/core/tools/ApplyDiffTool.ts:345-347, and the reset() there does not touch the registry, so the abandoned read's token stayed current for the next guarded write to this path. The retirement now runs in finally - it happens on both exit paths and the rollback failure still reaches handleError unchanged. The focus-disruption observation row moves inside the save. A guarded save consults the registry when saveDirectly runs, so the publish is held open on a gate and the registry is sampled from inside the double; sampling only after execute returned passed with the observe placed after the save, where the guard had already refused for want of a token. Answers review roots PRRT_kwDOSK-bwM62-xcF (src/core/tools/ApplyDiffTool.ts:252) and PRRT_kwDOSK-bwM69JXAx (src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts:188). Controls, run with the production file as it stands at 15940326f6 and the probe reverted before commit: - "retires the observation even when the rollback itself rejects" - exit 1, "expected true to be false // Object.is equality"; exit 0 here (13 passed). - PROBE (observe moved after saveDirectly): "records the version the diff was computed against before the guarded save runs" - exit 1, "expected [ undefined ] to deeply equal [ Array(1) ]"; exit 0 with the observe where it belongs. --- src/core/tools/ApplyDiffTool.ts | 20 ++-- .../applyDiffTool.guardedWrite.spec.ts | 97 +++++++++++++++++-- 2 files changed, 103 insertions(+), 14 deletions(-) diff --git a/src/core/tools/ApplyDiffTool.ts b/src/core/tools/ApplyDiffTool.ts index 9935fd9858c..f05965b6eb5 100644 --- a/src/core/tools/ApplyDiffTool.ts +++ b/src/core/tools/ApplyDiffTool.ts @@ -243,13 +243,19 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> { const staleError = `The file ${relPath} changed after it was read for this diff, so the diff was not applied. Read the file again and reapply the diff to its current content.` await task.say("error", staleError) task.didToolFailInCurrentTurn = true - await task.diffViewProvider.revertChanges() - // The rollback retires the editor buffer, but open() had already recorded the - // newer on-disk version as this flow's observation (DiffViewProvider.ts:149-157). - // Leaving it current would let a later write - write_to_file with the - // focus-disruption save - publish on a read this tool abandoned, so retire that - // path only; other files keep what their own reads recorded. - task.observationRegistry.forget(absolutePath) + try { + await task.diffViewProvider.revertChanges() + } finally { + // The rollback retires the editor buffer, but open() had already recorded the + // newer on-disk version as this flow's observation (DiffViewProvider.ts:149-157). + // Leaving it current would let a later write - write_to_file with the + // focus-disruption save - publish on a read this tool abandoned, so retire that + // path only; other files keep what their own reads recorded. It runs in finally + // because a rollback that itself rejects (revertChanges saves, unlinks and rmdirs) + // must not leave that newer token in the task-wide registry for the next guarded + // write to spend; the original error still reaches handleError unchanged. + task.observationRegistry.forget(absolutePath) + } task.processQueuedMessages() pushToolResult(staleError) return diff --git a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts index 61a3a8bd85c..b769ce3a422 100644 --- a/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts +++ b/src/core/tools/__tests__/applyDiffTool.guardedWrite.spec.ts @@ -173,19 +173,51 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { expect(mockTask.didEditFile).toBe(false) expect(mockPushToolResult).not.toHaveBeenCalledWith("Saved file") }) - it("records the version the diff was computed against so the guarded edit is authorized", async () => { - await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { + it("records the version the diff was computed against before the guarded save runs", async () => { + // Path instruction: check the behavior while the call is still pending. A real guarded save + // reads the registry the moment saveDirectly runs, so the publish is held open on a gate + // and the registry is sampled from inside the double. Sampling only after execute returned + // would still pass if the observation moved to after the save, where the guard would + // already have refused for want of a token. + const absolutePath = path.resolve("/workspace/project", "src/thing.ts") + let releaseSave: () => void = () => {} + const saveHeld = new Promise((resolve) => { + releaseSave = resolve + }) + const versionsAtPublish: (string | undefined)[] = [] + mockSaveDirectly.mockImplementation(async () => { + versionsAtPublish.push(mockTask.observationRegistry.get(absolutePath)?.version) + await saveHeld + return { newProblemsMessage: "", userEdits: undefined, finalContent: "new content" } + }) + + const running = tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-call", }) - // The focus-disruption save has no diff view to observe the file, so the tool read - // itself must leave an observation for the version the hunks were computed against - - // otherwise saveDirectly("edit") rejects with "File not read yet". - const observed = mockTask.observationRegistry.get(path.resolve("/workspace/project", "src/thing.ts")) - expect(observed?.version).toBe("7:4242:1234:1700000000123456789:1700000000789999999") + try { + await vi.waitFor(() => { + if (versionsAtPublish.length === 0) { + throw new Error("the guarded save has not been entered yet") + } + }) + // The focus-disruption save has no diff view to observe the file, so the tool read + // itself must leave an observation for the version the hunks were computed against - + // otherwise saveDirectly("edit") rejects with "File not read yet". + expect(versionsAtPublish).toEqual(["7:4242:1234:1700000000123456789:1700000000789999999"]) + } finally { + // Release the held publish on every exit path so a failing row cannot hang the suite. + releaseSave() + await running + } + + expect(versionsAtPublish).toHaveLength(1) + expect(mockTask.observationRegistry.get(absolutePath)?.version).toBe( + "7:4242:1234:1700000000123456789:1700000000789999999", + ) expect(mockSaveDirectly).toHaveBeenCalledWith( "src/thing.ts", "modified file content\n", @@ -488,4 +520,55 @@ describe("ApplyDiffTool.execute - guarded write (S4b, epic #1375)", () => { expect(mockTask.observationRegistry.has(absolutePath)).toBe(false) expect(mockTask.observationRegistry.has(otherPath)).toBe(true) }) + + it("retires the observation even when the rollback itself rejects", async () => { + // The stale rejection retires this path inside a finally. A rollback that rejects - + // revertChanges saves, unlinks and rmdirs, any of which can throw - used to skip it, and + // reset() in the catch does not touch the registry, so the newer token open() recorded + // stayed current: the next guarded write to this path passed its version check and could + // publish content this tool never diffed. + const absolutePath = path.resolve("/workspace/project", "src/thing.ts") + const rollbackError = new Error("Failed to save the reverted document") + + const diffViewStub = mockTask.diffViewProvider as unknown as Record + diffViewStub.open = vi.fn().mockImplementation(async () => { + diffViewStub.originalContent = "written by another process\n" + // What production open() does after re-reading the file: observe the newer token. + mockTask.observationRegistry.observe(absolutePath, "7:4242:1234:1700000000123456799:1700000000789000001") + }) + diffViewStub.update = vi.fn().mockResolvedValue(undefined) + diffViewStub.scrollToFirstDiff = vi.fn() + diffViewStub.revertChanges = vi.fn().mockRejectedValue(rollbackError) + diffViewStub.saveChanges = vi.fn().mockResolvedValue({ + newProblemsMessage: "", + userEdits: undefined, + finalContent: "new content", + }) + mockTask.providerRef = { + deref: vi.fn().mockReturnValue({ + getState: vi.fn().mockResolvedValue({ + diagnosticsEnabled: true, + writeDelayMs: 1000, + experiments: {}, + }), + }), + } as unknown as Task["providerRef"] + + await tool.execute({ path: "src/thing.ts", diff: "unified diff" }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-tool-call-id", + }) + + expect(diffViewStub.revertChanges).toHaveBeenCalled() + // The finally ran despite the rollback rejecting: nothing is left for the next guarded + // write on this path to spend. + expect(mockTask.observationRegistry.has(absolutePath)).toBe(false) + // The rollback failure reaches the handler unchanged, and nothing is reported as saved. + expect(mockHandleError).toHaveBeenCalledWith("applying diff", rollbackError) + expect(mockSaveDirectly).not.toHaveBeenCalled() + expect(mockPushToolResult).not.toHaveBeenCalled() + expect(vi.mocked(mockTask.diffViewProvider.reset)).toHaveBeenCalled() + }) }) From b1a8e09bdb281606b5f66559459a0e8c5786e2b1 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:47:49 +0800 Subject: [PATCH 71/79] fix(apply-patch): refuse the publish an older observation would authorize The same-file update publish now follows the rule this pull states for apply_diff: a read that yields no version token may not lean on an older observation. When the hunk read straddled a write - or either of its stats failed - nothing was recorded, yet an earlier read could still leave the path observed. guardedWrite picks its guard from the entry it finds and has no reason to distrust it, so with the disk back on that earlier token replaceIfVersion accepted content derived from the transient read; the create kind does not help, because an observed path that still exists takes the CAS branch. The tool refuses it and tells the model to re-read and reapply, as apply_diff does. With nothing observed the patch still runs and the guard's own remediation answers, which the stat-failure rows already lock. Adds the row the thread asked for - a prior observation with mismatched read stats - and moves the hunk-observe row inside the publish for the same reason as the apply_diff row. Answers review root PRRT_kwDOSK-bwM69JXAz (src/core/tools/__tests__/applyPatchTool.execute.spec.ts:270). Controls, run with src/core/tools/ApplyPatchTool.ts as it stands at 15940326f6 and the probe reverted before commit: - "update: refuses the publish when the read left no token and an earlier observation would authorize it" - exit 1, "expected \"vi.fn()\" to not be called at all, but actually been called 1 times" on saveDirectly(..., "create"); exit 0 here (15 passed). - PROBE (observe moved after saveDirectly): "update: observes the hunk read before the guarded publish runs" - exit 1, "expected [ undefined ] to deeply equal [ Array(1) ]". --- src/core/tools/ApplyPatchTool.ts | 11 +++ .../__tests__/applyPatchTool.execute.spec.ts | 82 +++++++++++++++++-- 2 files changed, 86 insertions(+), 7 deletions(-) diff --git a/src/core/tools/ApplyPatchTool.ts b/src/core/tools/ApplyPatchTool.ts index 220c07ae144..ad11e85905a 100644 --- a/src/core/tools/ApplyPatchTool.ts +++ b/src/core/tools/ApplyPatchTool.ts @@ -481,6 +481,17 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> { // that consumes it, so a failed patch, a rejection, and the diff-view // branch leave no token in the task-wide registry. const readToken = readTokens.get(absolutePath) + if (readToken === undefined && task.observationRegistry.has(absolutePath)) { + // This hunk read straddled a write (or one of its stats failed), so it left no token of + // its own, yet an earlier read left this path observed. The create-style publish below + // would then CAS against that other read's token - guardedWrite trusts the entry it finds, + // so nothing stops content this tool never verified from landing. Fail closed the way + // apply_diff does. With nothing observed the patch still runs and the guard's own + // remediation answers, which is what the stat-failure rows lock. + throw new Error( + `The file ${relPath} changed while it was being read for this patch, so nothing was saved. Read the file again and reapply the patch against the current content.`, + ) + } if (readToken !== undefined) { task.observationRegistry.observe(absolutePath, readToken) } diff --git a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts index 56f9d094556..07cb080f881 100644 --- a/src/core/tools/__tests__/applyPatchTool.execute.spec.ts +++ b/src/core/tools/__tests__/applyPatchTool.execute.spec.ts @@ -246,19 +246,51 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { expect(mockHandleError).not.toHaveBeenCalled() }) - it("update: observes the hunk read so the guarded publish is not unobserved", async () => { - await tool.execute({ patch: updatePatch }, mockTask as Task, { + it("update: observes the hunk read before the guarded publish runs", async () => { + // Path instruction: check the behavior while the call is still pending. The guard reads + // the registry the moment saveDirectly runs, so the publish is held open on a gate and + // the registry is sampled from inside the double; sampling only after execute returned + // would also pass if the observe moved to after the save, where a real guard had + // already refused the unobserved write. + const absolutePath = path.resolve("/workspace/project", "src/thing.ts") + let releaseSave: () => void = () => {} + const saveHeld = new Promise((resolve) => { + releaseSave = resolve + }) + const versionsAtPublish: (string | undefined)[] = [] + mockSaveDirectly.mockImplementation(async () => { + versionsAtPublish.push(mockTask.observationRegistry.get(absolutePath)?.version) + await saveHeld + return { newProblemsMessage: "", userEdits: undefined, finalContent: "new content" } + }) + + const running = tool.execute({ patch: updatePatch }, mockTask as Task, { askApproval: mockAskApproval, handleError: mockHandleError, pushToolResult: mockPushToolResult, toolCallId: "test-call", }) - // The hunk read doubles as the S2 observation (ReadFileTool contract): - // stable pre/post stats record the version token, so the in-place modify - // publish is not rejected as an unobserved write. - const observed = mockTask.observationRegistry.get(path.resolve("/workspace/project", "src/thing.ts")) - expect(observed?.version).toBe("7:4242:1234:1700000000123456789:1700000000789999999") + try { + await vi.waitFor(() => { + if (versionsAtPublish.length === 0) { + throw new Error("the guarded publish has not been entered yet") + } + }) + // The hunk read doubles as the S2 observation (ReadFileTool contract): + // stable pre/post stats record the version token, so the in-place modify + // publish is not rejected as an unobserved write. + expect(versionsAtPublish).toEqual(["7:4242:1234:1700000000123456789:1700000000789999999"]) + } finally { + // Release the held publish on every exit path so a failing row cannot hang the suite. + releaseSave() + await running + } + + expect(versionsAtPublish).toHaveLength(1) + expect(mockTask.observationRegistry.get(absolutePath)?.version).toBe( + "7:4242:1234:1700000000123456789:1700000000789999999", + ) }) it("update: does not observe when the pre- and post-read tokens disagree", async () => { @@ -285,6 +317,42 @@ describe("ApplyPatchTool.execute - guarded write (S4b, epic #1375)", () => { expect(mockHandleError).toHaveBeenCalledWith("apply patch", guardError) }) + it("update: refuses the publish when the read left no token and an earlier observation would authorize it", async () => { + // The row's scenario, which no row here covered: the hunk read straddled a write so it + // recorded nothing, while an earlier read still left this path observed. guardedWrite + // consults the entry it finds and does not know which read produced it, so with the + // disk back on the earlier token (the stat double reports that version on every other + // call) replaceIfVersion would have accepted content derived from the transient read. + // The tool has to refuse it: the guard alone is not the backstop here. + const absolutePath = path.resolve("/workspace/project", "src/thing.ts") + const earlierToken = "7:4242:1234:1700000000123456789:1700000000789999999" + mockTask.observationRegistry.observe(absolutePath, earlierToken) + + const statMock = mockedFsPromises.default.stat + statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 1234n, mtimeNs: 1n, ctimeNs: 2n }) + statMock.mockResolvedValueOnce({ dev: 7n, ino: 4242n, size: 9999n, mtimeNs: 3n, ctimeNs: 4n }) + + await tool.execute({ patch: updatePatch }, mockTask as Task, { + askApproval: mockAskApproval, + handleError: mockHandleError, + pushToolResult: mockPushToolResult, + toolCallId: "test-call", + }) + + // Nothing reached the publish primitive, so the file is untouched. + expect(mockSaveDirectly).not.toHaveBeenCalled() + expect(mockTask.didEditFile).toBe(false) + expect(mockPushToolResult).not.toHaveBeenCalledWith("Saved file") + const [reportedWhere, reportedError] = mockHandleError.mock.calls[0] ?? [] + expect(reportedWhere).toBe("apply patch") + expect(reportedError instanceof Error ? reportedError.message : "").toContain( + "changed while it was being read for this patch", + ) + // The earlier read's observation stays: this row is about not publishing on its + // authority, not about retiring it. + expect(mockTask.observationRegistry.get(absolutePath)?.version).toBe(earlierToken) + }) + it.each(["pre-read", "post-read"])( "update: continues the hunk read and records no observation when the %s stat fails", async (which) => { From aca45b7b7b6d3756ad1ecba231785d6691539cac Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:48:01 +0800 Subject: [PATCH 72/79] test(guarded-write): gate the FIFO rows instead of timing them Two rows proved their ordering with a timer hop or an unbounded await, which is what the two review asks named. The third-write row waited on setTimeout(0) before asserting the successor had not published; it now polls until the second publish is inside the double, so the assertion is read while the call is pending rather than after a guessed hop. The cross-path independence row awaited the second write directly, so the global queue it rules out would have shown up as a suite timeout; it now races that await against a 200 ms gate-held timer, clears the timer, and releases the held publish in finally on every exit path. Answers review roots PRRT_kwDOSK-bwM61KUmV (src/core/tools/__tests__/guardedWrite.spec.ts:467) and PRRT_kwDOSK-bwM61KUml (src/core/tools/__tests__/guardedWrite.spec.ts:550). The behavior is already shipped, so the controls are negations of it, run against src/core/tools/guardedWrite.ts as it stands at 15940326f6 with the probe reverted before commit: - PROBE N1 (enqueue ignores any pending tail): "keeps a third write queued behind a blocked second write on the same path" - exit 1, "expected [ 'start:second', 'start:third', ... ] to deeply equal [ 'start:second' ]". - PROBE N2 (one queue for every path): "writes on different paths are independent (no cross-path serialization)" - exit 1, "expected 'gate-held' to be 'second-settled'" - the named failure the earlier version of this row could only report as "Test timed out in 20000ms." With guardedWrite.ts untouched the file is exit 0: Tests 44 passed (44). --- src/core/tools/__tests__/guardedWrite.spec.ts | 29 ++++++++++++++++--- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index 79af6b30fba..5fecdf0571d 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -499,7 +499,16 @@ describe("guardedWrite (S4a, epic #1375)", () => { const p2 = guardedWrite(task, "queue.txt", "second", "update") const p3 = guardedWrite(task, "queue.txt", "third", "update") - await new Promise((resolve) => setTimeout(resolve, 0)) + // Poll on the gate, not on a fixed timer: the fact to prove is about a pending call, and + // a bare macrotask hop would fail as a flake rather than as a named assertion if the + // chain ever needed another turn to reach the publish. + await vi.waitFor(() => { + if (order.length === 0) { + throw new Error("the second write has not reached its publish yet") + } + }) + // The third write is already enqueued behind the held second one and has not reached + // safeWriteText: a chain that dropped the waiting successor would publish it here. expect(order).toEqual(["start:second"]) releaseSecond() @@ -526,7 +535,8 @@ describe("guardedWrite (S4a, epic #1375)", () => { if (content === "a") { // Hold only the first path publish open. The chains are keyed per absolute // path, so the second path must reach its publish anyway; a single global - // queue would leave b.txt waiting here and the await below would time out. + // queue would leave b.txt waiting here, and the bounded race below then reports + // a held gate instead of a pass. await firstHeld } order.push("end:" + content) @@ -536,8 +546,19 @@ describe("guardedWrite (S4a, epic #1375)", () => { const p2 = guardedWrite(task, "b.txt", "b", "update") try { - // The second path settles while the first is still inside safeWriteText. - await p2 + // The second path settles while the first is still inside safeWriteText. The wait is + // bounded by a race rather than by the suite timeout: one global queue would leave + // b.txt waiting behind the held gate, and that is the difference between a named + // assertion failure and a row that hangs. + let holdTimer: ReturnType | undefined + const outcome = await Promise.race([ + p2.then(() => "second-settled" as const), + new Promise<"gate-held">((resolve) => { + holdTimer = setTimeout(() => resolve("gate-held"), 200) + }), + ]) + clearTimeout(holdTimer) + expect(outcome).toBe("second-settled") expect(order).toEqual(["start:a", "start:b", "end:b"]) } finally { // Release the held gate on every exit path, including an assertion failure From 75ee343d4c854a506ae6c04aba803f0b0ec9dd5e Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:37:18 +0800 Subject: [PATCH 73/79] fix(read-file): record whether each read handed over the whole file The registry already carries a completeness flag and its own docstring says a guarded full-file replacement consults it, but nothing ever set it: every production observe() call passed two arguments, so the default said a read that returned lines 10 to 12 of a 400-line file had handed over the file. A read_file that returned a slice, an indentation block, a legacy line range, or a view the 2000-line limit cut short now records what the model actually got, on both the native and the legacy path, and passes it as an argument instead of leaving it to the default. Completeness means every line of the file was handed over. processTextFile reports it alongside the output - a reader that reports truncation, or ranges that skip or stop short of the last line, is a partial view - and the legacy path derives it from the ranges it selected or the limit it hit. readCoversWholeFile merges the 1-based ranges the readers report so adjacent or contiguous selections still count as full coverage, and treats an empty file as covered because there was nothing there to withhold. Part of review 6100859777 (Persistence Integrity, ask 1). No thread was opened on it, so this commit is the answer; the write-side gate that consumes this lands beside it. Control, run against src/core/tools/ReadFileTool.ts as it stands at aca45b7b7b with the new rows in place and the production change reverted before commit: - "hands the completeness to observe as an argument instead of leaning on the default" - exit 1, "expected [ 'C:\test\workspace\slice.txt', ...(1) ] to have a length of 3 but got 2". - the eight partial-view rows (slice with an offset, limit truncation, an indentation block that leaves lines out, ranges with a gap, ranges the reader also reported as truncated, three legacy range rows and the legacy limit row) - exit 1 each, "expected true to be false // Object.is equality": the registry default answered for them. With the production change in place the file is exit 0: Tests 110 passed (110). --- src/core/tools/ReadFileTool.ts | 73 +++++- src/core/tools/__tests__/readFileTool.spec.ts | 233 +++++++++++++++++- 2 files changed, 292 insertions(+), 14 deletions(-) diff --git a/src/core/tools/ReadFileTool.ts b/src/core/tools/ReadFileTool.ts index 1a89b42c08e..21024a6f093 100644 --- a/src/core/tools/ReadFileTool.ts +++ b/src/core/tools/ReadFileTool.ts @@ -69,6 +69,33 @@ interface FileResult { entry?: InternalFileEntry } +/** + * Whether the ranges a reader reported together span every line of the file. + * + * A range list that skips a line, or a selection the reader stopped short, leaves the + * model holding part of the file, and the observation must not claim it holds all of + * it. Ranges are 1-based and inclusive, as the readers report them. An empty file is + * covered by any selection: there is nothing there to withhold. + */ +function readCoversWholeFile(includedRanges: [number, number][], totalLines: number): boolean { + if (totalLines === 0) { + return true + } + + let coveredThrough = 0 + for (const [start, end] of [...includedRanges].sort((a, b) => a[0] - b[0])) { + if (start > coveredThrough + 1) { + return false + } + coveredThrough = Math.max(coveredThrough, end) + if (coveredThrough >= totalLines) { + return true + } + } + + return false +} + // ─── Tool Implementation ────────────────────────────────────────────────────── export class ReadFileTool extends BaseTool<"read_file"> { @@ -222,11 +249,13 @@ export class ReadFileTool extends BaseTool<"read_file"> { const preReadStats = await fs.stat(fullPath, { bigint: true }).catch(() => undefined) const buffer = await fs.readFile(fullPath) const fileContent = buffer.toString("utf-8") - const result = this.processTextFile(fileContent, entry) + const processed = this.processTextFile(fileContent, entry) await task.fileContextTracker.trackFileContext(relPath, "read_tool" as RecordSource) - // A2 (plan #33 / epic #1375): record the observed on-disk version for the future write guard. + // A2 (plan #33 / epic #1375): record the observed on-disk version for the future write guard, + // together with whether this read handed over the whole file (completeness comes from + // the mode processing above, not from a guess at the caller's parameters). // The token is captured before AND after the read; the target is observed only // when both match — a mutation between the two stats means the content the model // received is not the on-disk state, and observing it would let a later write @@ -236,12 +265,12 @@ export class ReadFileTool extends BaseTool<"read_file"> { if (preReadStats && postReadStats) { const preReadToken = versionTokenOfStat(preReadStats) if (preReadToken === versionTokenOfStat(postReadStats)) { - task.observationRegistry.observe(fullPath, preReadToken) + task.observationRegistry.observe(fullPath, preReadToken, processed.complete) } } updateFileResult(relPath, { - nativeContent: `File: ${relPath}\n${result}`, + nativeContent: `File: ${relPath}\n${processed.output}`, }) } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error) @@ -285,8 +314,13 @@ export class ReadFileTool extends BaseTool<"read_file"> { /** * Process a text file according to the requested mode. + * + * The second field says whether the view handed to the model is the whole file. A slice, + * an indentation block, or a read the line limit cut short gives only part of it, and + * the read's observation has to carry that: a partial view authorizes targeted edits + * on what the model saw, not a full-file replacement. */ - private processTextFile(content: string, entry: InternalFileEntry): string { + private processTextFile(content: string, entry: InternalFileEntry): { output: string; complete: boolean } { const mode = entry.mode || "slice" if (mode === "indentation") { @@ -319,7 +353,10 @@ export class ReadFileTool extends BaseTool<"read_file"> { output += `\n\nIncluded ranges: ${rangeStr} (total: ${result.totalLines} lines)` } - return output + return { + output, + complete: !result.wasTruncated && readCoversWholeFile(result.includedRanges, result.totalLines), + } } // Slice mode (default): simple offset/limit reading @@ -346,7 +383,10 @@ export class ReadFileTool extends BaseTool<"read_file"> { output = "Note: File is empty" } - return output + return { + output, + complete: !result.wasTruncated && readCoversWholeFile(result.includedRanges, result.totalLines), + } } /** @@ -800,9 +840,14 @@ export class ReadFileTool extends BaseTool<"read_file"> { // Handle line ranges if specified let content: string + // Whether this read handed over the whole file, recorded with the observation below: + // a line range that leaves lines out, or a default read the line limit cut short, + // authorizes targeted edits but not a full-file replacement. + let readIsComplete: boolean if (entry.lineRanges && entry.lineRanges.length > 0) { const lines = rawContent.split("\n") const selectedLines: string[] = [] + const coveredRanges: [number, number][] = [] for (const range of entry.lineRanges) { // Convert to 0-based index, ranges are 1-based inclusive @@ -812,12 +857,16 @@ export class ReadFileTool extends BaseTool<"read_file"> { for (let i = startIdx; i <= endIdx; i++) { selectedLines.push(`${i + 1} | ${lines[i]}`) } + coveredRanges.push([startIdx + 1, endIdx + 1]) } content = selectedLines.join("\n") + readIsComplete = readCoversWholeFile(coveredRanges, lines.length) } else { // Read with default limits using slice mode const result = readWithSlice(rawContent, 0, DEFAULT_LINE_LIMIT) content = result.content + readIsComplete = + !result.wasTruncated && readCoversWholeFile(result.includedRanges, result.totalLines) if (result.wasTruncated) { content += `\n\n[File truncated: showing ${result.returnedLines} of ${result.totalLines} total lines]` } @@ -829,15 +878,15 @@ export class ReadFileTool extends BaseTool<"read_file"> { await task.fileContextTracker.trackFileContext(relPath, "read_tool") // A2 (plan #33 / epic #1375): mirror the native path — record the observed - // on-disk version so legacy-format reads also feed the future write guard. - // Observe only when the pre-read and post-read tokens match (a mutation between - // them means the returned content is not the on-disk state). A stat failure - // leaves the target unobserved and never fails the read. + // on-disk version and this read's completeness so legacy-format reads also feed + // the future write guard. Observe only when the pre-read and post-read tokens + // match (a mutation between them means the returned content is not the on-disk + // state). A stat failure leaves the target unobserved and never fails the read. const postReadStats = await fs.stat(fullPath, { bigint: true }).catch(() => undefined) if (preReadStats && postReadStats) { const preReadToken = versionTokenOfStat(preReadStats) if (preReadToken === versionTokenOfStat(postReadStats)) { - task.observationRegistry.observe(fullPath, preReadToken) + task.observationRegistry.observe(fullPath, preReadToken, readIsComplete) } } } catch (error) { diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 329c0f4a920..986c84ac64b 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -12,7 +12,7 @@ * - Output structure formatting */ -import type { LegacyReadFileParams } from "@roo-code/types" +import type { LegacyReadFileParams, ReadFileToolParams } from "@roo-code/types" import type { Stats } from "fs" import os from "os" import path from "path" @@ -26,7 +26,11 @@ import { ObservationRegistry } from "../../task/observationRegistry" import { formatResponse } from "../../prompts/responses" import { validateImageForProcessing, processImageFile, isSupportedImageFormat } from "../helpers/imageHelpers" import { extractTextFromFile, getSupportedBinaryFormats } from "../../../integrations/misc/extract-text" -import { readWithIndentation, readWithSlice } from "../../../integrations/misc/indentation-reader" +import { + readWithIndentation, + readWithSlice, + type IndentationReadResult, +} from "../../../integrations/misc/indentation-reader" // ─── Mocks ──────────────────────────────────────────────────────────────────── @@ -1805,6 +1809,231 @@ describe("ReadFileTool", () => { expect(obs!.version).toBe(calledVersion) }) + /** + * Runs one native read through a given reader result and reports the completeness the + * tool handed to observe. The readers are mocked here, so each row states the view the + * model got and says nothing about the host filesystem. + */ + async function completenessOfNativeRead( + params: ReadFileToolParams, + readerResult: IndentationReadResult, + ): Promise { + const reg = new ObservationRegistry() + const mockTask = createMockTask({ observationRegistry: reg }) + const callbacks = createMockCallbacks() + const observeSpy = vi.spyOn(reg, "observe") + + if ("mode" in params && params.mode === "indentation") { + mockedReadWithIndentation.mockReturnValue(readerResult) + } else { + mockedReadWithSlice.mockReturnValue(readerResult) + } + + await readFileTool.execute(params, mockTask as unknown as Task, callbacks) + expect(observeSpy).toHaveBeenCalledTimes(1) + const calledPath = observeSpy.mock.calls[0]?.[0] + return calledPath === undefined ? undefined : reg.get(calledPath)?.complete + } + + it("passes completeness explicitly, and a whole-file slice read reports complete", async () => { + const view: IndentationReadResult = { + content: "1 | a\n2 | b", + returnedLines: 2, + totalLines: 2, + wasTruncated: false, + includedRanges: [[1, 2]], + } + await expect(completenessOfNativeRead({ path: "whole.txt" }, view)).resolves.toBe(true) + }) + + it("hands the completeness to observe as an argument instead of leaning on the default", async () => { + const reg = new ObservationRegistry() + const mockTask = createMockTask({ observationRegistry: reg }) + const observeSpy = vi.spyOn(reg, "observe") + + await readFileTool.execute( + { path: "slice.txt", offset: 10 }, + mockTask as unknown as Task, + createMockCallbacks(), + ) + + expect(observeSpy).toHaveBeenCalledTimes(1) + // Three arguments: path, version token, and the completeness of the view the model + // got. Two would mean the registry default decided the answer. + expect(observeSpy.mock.calls[0]).toHaveLength(3) + }) + + it("records an incomplete observation for a read that started past the first line", async () => { + const view: IndentationReadResult = { + content: "10 | j\n11 | k", + returnedLines: 2, + totalLines: 20, + wasTruncated: true, + includedRanges: [[10, 11]], + } + await expect(completenessOfNativeRead({ path: "slice.txt", offset: 10, limit: 2 }, view)).resolves.toBe( + false, + ) + }) + + it("records an incomplete observation for a whole-file read the line limit cut short", async () => { + const view: IndentationReadResult = { + content: "1 | a\n2 | b", + returnedLines: 2, + totalLines: 5, + wasTruncated: true, + includedRanges: [[1, 2]], + } + await expect(completenessOfNativeRead({ path: "cut.txt" }, view)).resolves.toBe(false) + }) + + it("records a complete observation for an indentation block that covers the whole file", async () => { + const view: IndentationReadResult = { + content: "1 | class Foo {", + returnedLines: 9, + totalLines: 9, + wasTruncated: false, + includedRanges: [[1, 9]], + } + await expect( + completenessOfNativeRead( + { path: "flat.ts", mode: "indentation", indentation: { anchor_line: 1 } }, + view, + ), + ).resolves.toBe(true) + }) + + it("records an incomplete observation for an indentation block that leaves lines out", async () => { + const view: IndentationReadResult = { + content: "3 | method() {", + returnedLines: 2, + totalLines: 9, + wasTruncated: false, + includedRanges: [[3, 4]], + } + await expect( + completenessOfNativeRead( + { path: "block.ts", mode: "indentation", indentation: { anchor_line: 3 } }, + view, + ), + ).resolves.toBe(false) + }) + + it("records an incomplete observation when the ranges skip a line although they end at the last one", async () => { + const view: IndentationReadResult = { + content: "1 | a", + returnedLines: 8, + totalLines: 9, + wasTruncated: false, + includedRanges: [ + [1, 4], + [6, 9], + ], + } + await expect( + completenessOfNativeRead( + { path: "gaps.ts", mode: "indentation", indentation: { anchor_line: 1 } }, + view, + ), + ).resolves.toBe(false) + }) + + it("records an incomplete observation when the reader reports full coverage it also truncated", async () => { + // The ranges alone would read as complete; the truncation the reader reports names the + // line that was withheld, so both halves have to answer. + const view: IndentationReadResult = { + content: "1 | a", + returnedLines: 9, + totalLines: 9, + wasTruncated: true, + includedRanges: [[1, 9]], + } + await expect( + completenessOfNativeRead( + { path: "told.txt", mode: "indentation", indentation: { anchor_line: 1 } }, + view, + ), + ).resolves.toBe(false) + }) + + it("records a complete observation for an empty file: nothing was withheld", async () => { + const view: IndentationReadResult = { + content: "", + returnedLines: 0, + totalLines: 0, + wasTruncated: false, + includedRanges: [], + } + await expect(completenessOfNativeRead({ path: "empty.txt" }, view)).resolves.toBe(true) + }) + + /** + * Runs one legacy-format (multi-file, line-range) read and reports the completeness it + * recorded. The content is handed over as text because that branch slices it directly + * instead of going through the mocked reader. + */ + async function completenessOfLegacyRead( + fileEntry: LegacyReadFileParams["files"][number], + fileContent: string, + ): Promise { + const reg = new ObservationRegistry() + const mockTask = createMockTask({ observationRegistry: reg }) + const callbacks = createMockCallbacks() + const observeSpy = vi.spyOn(reg, "observe") + mockedFsReadFile.mockResolvedValue(fileContent) + + const legacyParams: LegacyReadFileParams = { files: [fileEntry], _legacyFormat: true } + await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) + + expect(observeSpy).toHaveBeenCalledTimes(1) + const calledPath = observeSpy.mock.calls[0]?.[0] + return calledPath === undefined ? undefined : reg.get(calledPath)?.complete + } + + it("records a complete observation for legacy ranges that cover every line", async () => { + await expect( + completenessOfLegacyRead({ path: "legacy.txt", lineRanges: [{ start: 1, end: 3 }] }, "l1\nl2\nl3"), + ).resolves.toBe(true) + }) + + it("records a complete observation for adjacent legacy ranges that together cover every line", async () => { + await expect( + completenessOfLegacyRead( + { + path: "legacy.txt", + lineRanges: [ + { start: 1, end: 2 }, + { start: 3, end: 3 }, + ], + }, + "l1\nl2\nl3", + ), + ).resolves.toBe(true) + }) + + it("records an incomplete observation for a legacy range that leaves the head of the file out", async () => { + await expect( + completenessOfLegacyRead({ path: "legacy.txt", lineRanges: [{ start: 2, end: 3 }] }, "l1\nl2\nl3"), + ).resolves.toBe(false) + }) + + it("records an incomplete observation for a legacy range that stops short of the last line", async () => { + await expect( + completenessOfLegacyRead({ path: "legacy.txt", lineRanges: [{ start: 1, end: 2 }] }, "l1\nl2\nl3"), + ).resolves.toBe(false) + }) + + it("records an incomplete observation for a legacy read the line limit cut short", async () => { + mockedReadWithSlice.mockReturnValue({ + content: "1 | l1", + returnedLines: 1, + totalLines: 9, + wasTruncated: true, + includedRanges: [[1, 1]], + }) + await expect(completenessOfLegacyRead({ path: "legacy.txt" }, "l1")).resolves.toBe(false) + }) + it("a failed read (absent path) leaves the registry size 0 and does not throw", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), From f9f88157f445fa3df9f5afe98c2d88064131110b Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:40:19 +0800 Subject: [PATCH 74/79] fix(guarded-write): refuse a full-file replacement over a partial read A create/update over a path that was read and is still there replaces the whole file, so the observation behind it has to cover the whole file. Before this, a read_file of lines 10-12 of a 300-line file left a matching token in the registry and replaceIfVersion accepted a write whose content the model had composed against 3 of those 300 lines: the CAS check compares bytes-on-disk to the token, not the model's knowledge, so it says nothing about the 297 lines being discarded. The guard now refuses that and asks for a full read, in the same remediation family as the stale-version and deleted-after-read answers. Two cases stay as they were, deliberately. An edit-style publish writes lines computed against the current file, not a view the model is holding, so it is not gated. And an observed target that vanished after the read is not a replacement of anything observed: the absence check keeps the delete-after-read remediation answering for it, and it is paid for only on the partial-read path - a create reaching this branch was already shown to exist by the branch above, so the complete-read path performs no extra I/O and no existing row changes its mock call counts. Part of review 6100859777 (Persistence Integrity, asks 2 and 3); no thread was opened on it. The regression lives at the guard layer because that is the narrowest layer that fails for it: src/core/tools/writeToFileTool.spec.ts doubles DiffViewProvider.saveDirectly, so the publish never runs through the real guard there and a row in that file could not show "must not publish". Controls, run against src/core/tools/guardedWrite.ts as it stands at 75ee343d4c with the new rows in place and the production change reverted before commit: - "refuses to overwrite a file the model only read part of - nothing published" - exit 1, "AssertionError: promise resolved \"undefined\" instead of rejecting": without the gate the write ran the publish path and resolved. - "refuses a create that lands on an existing file read only in part" - same failure, same exit. The four rows beside them (complete read publishes, targeted edit publishes, vanished target keeps the delete-after-read answer, create recreates a vanished target) pass either way, so the two failures name the gate and not the fixtures. With the gate in place the file is exit 0: Tests 50 passed (50), 44 of them pre-existing. --- src/core/tools/__tests__/guardedWrite.spec.ts | 101 ++++++++++++++++++ src/core/tools/guardedWrite.ts | 25 ++++- 2 files changed, 124 insertions(+), 2 deletions(-) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index 5fecdf0571d..5a3964d40ad 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -292,6 +292,107 @@ describe("guardedWrite (S4a, epic #1375)", () => { }) }) + describe("full-file replacement over a partial read", () => { + it("refuses to overwrite a file the model only read part of - nothing published", async () => { + const reg = new ObservationRegistry() + // read_file answered with a slice of a larger file: the token still matches, so the + // only thing standing between this write and the lines the model never saw is the + // completeness the read recorded. + reg.observe(abs("doc.txt"), "v1", false) + const task = createMockTask({ observationRegistry: reg }) + mockedFsAccess.mockResolvedValue(undefined) + mockedComputeVersionToken.mockResolvedValue("v1") + + await expect(guardedWrite(task, "doc.txt", "the whole file, rewritten", "update")).rejects.toThrow( + "File was read only in part -- " + + abs("doc.txt") + + " was last read as a slice, a line range or a truncated view, and this write replaces the whole file; read the file in full, then retry.", + ) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + // Refusing must not spend the read either: the model re-reads in full and retries with + // the same token, so the observation stays as the read left it. + expect(reg.get(abs("doc.txt"))).toMatchObject({ version: "v1", complete: false }) + }) + + it("refuses a create that lands on an existing file read only in part", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("doc.txt"), "v1", false) + const task = createMockTask({ observationRegistry: reg }) + // The target is still there, so this create is a full-file replacement too. + mockedFsAccess.mockResolvedValue(undefined) + mockedComputeVersionToken.mockResolvedValue("v1") + + await expect(guardedWrite(task, "doc.txt", "whole file", "create")).rejects.toThrow( + "File was read only in part -- " + abs("doc.txt"), + ) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) + + it("publishes the same write when the read covered the whole file", async () => { + // Same fixture, complete read: the partial flag is what the guard consults, not the + // kind or the mere fact of an observation. + const reg = new ObservationRegistry() + reg.observe(abs("doc.txt"), "v1") + const task = createMockTask({ observationRegistry: reg }) + mockedFsAccess.mockResolvedValue(undefined) + mockedComputeVersionToken.mockResolvedValue("v1") + + await guardedWrite(task, "doc.txt", "the whole file, rewritten", "update") + + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "the whole file, rewritten", { + preCommitVerify: expect.any(Function), + }) + expect(reg.get(abs("doc.txt"))?.complete).toBe(true) + }) + + it("leaves a targeted edit alone: an edit is not a replacement of an observed view", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("code.ts"), "v1", false) + const task = createMockTask({ observationRegistry: reg }) + mockedComputeVersionToken.mockResolvedValue("v1") + + await guardedWrite(task, "code.ts", "lines the edit produced", "edit") + + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("code.ts"), "lines the edit produced", { + preCommitVerify: expect.any(Function), + }) + // The publish wrote the whole file, so what the registry now describes is that file: + // it records what was published, not how much of the earlier read the model saw. + // (Whether a later full-file write should be gated on the model's own read is an + // open product question, not something this row decides.) + expect(reg.get(abs("code.ts"))).toMatchObject({ version: "v1", complete: true }) + }) + + it("lets a vanished partially-read target reach the version guard that answers for it", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("gone.txt"), "v1", false) + const task = createMockTask({ observationRegistry: reg }) + // Nothing observed is on disk any more, so this is not a replacement of a partial + // view: the delete-after-read remediation is the accurate one. + mockedFsAccess.mockRejectedValue({ code: "ENOENT" }) + mockedComputeVersionToken.mockRejectedValue({ code: "ENOENT" }) + + await expect(guardedWrite(task, "gone.txt", "next", "update")).rejects.toThrow( + "File was deleted after it was read", + ) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) + + it("lets a create recreate a partially-read target that vanished", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("gone.txt"), "v1", false) + const task = createMockTask({ observationRegistry: reg }) + mockedFsAccess.mockRejectedValue({ code: "ENOENT" }) + mockedComputeVersionToken.mockResolvedValue("v2") + + await guardedWrite(task, "gone.txt", "recreated", "create") + + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("gone.txt"), "recreated", { + preCommitVerify: expect.any(Function), + }) + }) + }) + describe("edit", () => { it("fails read-first when the file was never observed - nothing published, no I/O", async () => { const task = createMockTask() diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index 008bc852d41..8364131900d 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -387,10 +387,16 @@ export async function assertWithinCanonicalRoot(cwd: string, absolutePath: strin * * 1. Resolves the absolute path against task.cwd. * 2. Consults the task's S2 observation registry to pick the guard: + * - unobserved + edit: unobservedEditGuard; * - unobserved + create/update: createIfAbsent (rejects if it exists); + * - observed + edit: replaceIfVersion on the read-time token. A targeted edit + * publishes lines computed against the current file rather than replacing a + * view the model is holding, so the read's completeness does not gate it; * - observed + create on a file that vanished after the read: recreate; - * - observed otherwise: replaceIfVersion (CAS on the S1 version token); - * - unobserved + edit: unobservedEditGuard. + * - observed otherwise: replaceIfVersion (CAS on the S1 version token), and a + * full-file replacement of a target that is still there needs an observation of + * the whole file: a read that covered only part of it is refused with a + * read-it-in-full remediation instead of publishing over the lines off-screen. * 3. Runs the chosen guard on the per-path FIFO chain so concurrent writes to * the same path are deterministically ordered. */ @@ -438,6 +444,21 @@ export async function guardedWrite( // after the read recreates it. publishedVersion = await createIfAbsent(absolutePath, content, task.cwd) } else { + // Full-file replacement. The model is holding the whole file as its write's + // content, so it needs the whole file as its authority: a read that stopped at a + // slice, a line range or the line limit leaves the lines off-screen uncared for, + // and publishing over them silently deletes content nobody observed. + // + // A target that has since vanished is not a replacement of anything observed, so + // the version check below keeps answering for it -- hence the absence check, which + // is paid for only on this partial-read path (a "create" reaching here was already + // shown to exist by the branch above, so it short-circuits). + if (!obs.complete && (kind === "create" || !(await fileIsAbsent(absolutePath)))) { + throw new GuardRejectedError( + `File was read only in part -- ${absolutePath} was last read as a slice, a line range or a truncated view, and this write replaces the whole file; read the file in full, then retry.`, + absolutePath, + ) + } // Otherwise the version recorded at read time must still match the // on-disk token. publishedVersion = await replaceIfVersion(absolutePath, obs.version, content, task.cwd) From c7267350bc263ab8f1e51dd1a02528847d470557 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:41:53 +0800 Subject: [PATCH 75/79] docs(observation-registry): match the docstring to what the code actually enforces The header promised a completeness check that gated a full-file replacement, and the observe doc added an obligation no caller carried: it said a caller whose read is internal to a targeted edit must carry the model's prior completeness so its own read cannot upgrade a partial one. Nothing in the tree does that, and the sentence could not fail, so it was a claim rather than a contract. After the two commits beside this one the flag is enforced in one place, and the prose now says only what is true there: - complete describes whether the delivery this observation was recorded for covers every line of the file. It is not a claim that the model has seen, or still remembers, every line. - Only the full-file replacement consults it: kind create or update on a path that was observed and is still on disk (src/core/tools/guardedWrite.ts:456). A targeted edit is not gated, and no other production code reads the flag. - A publish re-observes with complete = true (src/core/tools/guardedWrite.ts:471) because the file on disk is then the content that write carried: the record describes the file the edit produced, not the model's memory of an earlier partial read. Part of review 6100859777 (Persistence Integrity, ask 4); no thread was opened on it. No row tests a comment, and the behavior the prose now describes is pinned by the rows added in f9f88157f4 - including the edit row, which fails if a publish stops recording what it published. --- src/core/task/observationRegistry.ts | 40 +++++++++++++++++----------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/src/core/task/observationRegistry.ts b/src/core/task/observationRegistry.ts index 539a5cb3a61..be5baccbf94 100644 --- a/src/core/task/observationRegistry.ts +++ b/src/core/task/observationRegistry.ts @@ -1,13 +1,16 @@ /** * Per-task file observation registry (upstream epic #1375, phase A2). * - * Each Task owns its own instance so parent and subtask observations are - * independent. The S4 guarded-write will compare these versions against the - * token recomputed pre-write to detect stale reads or file replacement. + * Each Task owns its own instance so parent and subtask observations are independent. * - * Pure in-memory — zero I/O, no dependencies. The S4 guarded-write consults - * these observations for the version check and for the completeness check that - * gates a full-file replacement. + * Pure in-memory — zero I/O, no dependencies. The guarded write (src/core/tools/guardedWrite.ts) + * consults these observations twice: + * - every write compares `version` against the token it recomputes under its own lock, which is + * how a stale read or a file replacement is detected; + * - a full-file replacement — kind "create" or "update" landing on a path that was observed and + * is still on disk (src/core/tools/guardedWrite.ts:456) — additionally requires `complete`. + * A targeted edit (kind "edit") is not gated on completeness, and no other production code reads + * the flag: it exists for that one decision. */ export interface FileObservation { @@ -16,10 +19,13 @@ export interface FileObservation { /** Millisecond timestamp when the observation was recorded. */ observedAt: number /** - * Whether the read that produced this observation returned the complete - * file. A slice, line-range, truncated, or indentation-block read returns - * only a view of the file; such an observation authorizes targeted edits - * on the view the model saw, but never a full-file replacement. + * Whether what this observation was recorded for covers every line of the file. + * + * A slice, line-range, truncated or indentation-block read hands over a view rather than the + * file and records false. The flag describes the coverage of that delivery and nothing more: it + * is not a claim that the model has seen, or still remembers, every line of the file. Only the + * full-file replacement consults it — that write replaces lines the model cannot see from a + * partial view, so it needs an observation of the whole file to be allowed at all. */ complete: boolean } @@ -34,12 +40,14 @@ export class ObservationRegistry { /** * Record an observation for a file at its absolute path. * - * Re-observing replaces the entry with a fresh observedAt timestamp, the - * new version token, and the read's completeness. `complete` defaults to - * true for callers that read the whole file themselves (spec doubles, - * WriteToFileTool). A caller whose read is internal to a targeted edit must - * carry the model's prior completeness instead, so the tool's own read cannot - * upgrade a partial read into authority for a full-file replacement. + * Re-observing replaces the entry with a fresh observedAt timestamp, the new version token, + * and this delivery's completeness. + * + * `complete` defaults to true because the callers that lean on the default read or publish the + * whole file. After a guarded publish the file on disk is exactly the content that write carried, + * so recording true there describes the file the write produced (src/core/tools/guardedWrite.ts:471) + * - it says nothing about how much of an earlier read the model was shown. read_file is the + * caller that passes false, on both of its paths, whenever it handed over only a view. */ observe(absolutePath: string, version: string, complete: boolean = true): void { if (this.retired) { From 59cfaa9cc32aa760c1d6b8e60421c23375f167bf Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:21:13 +0800 Subject: [PATCH 76/79] fix(guarded-write): read the observation before the validation await guardedWrite took its observation snapshot after `await assertWithinCanonicalRoot`, which yields while it inspects the filesystem. A peer write that publishes in that window refreshes the registry, so the waiting write read the peer's version token, its compare-and-swap matched that token, and content that was never issued against the peer's file replaced the peer's content - the lost update the version token exists to prevent, arriving through the guard's own await instead of through the per-path queue. The completeness flag moved the same way: a peer read covering the whole file could replace a partial observation before the completeness gate ran, letting a full-file replacement through a guard that was looking at a slice. The snapshot is taken with the resolved path, before the first await. It is a map lookup with no I/O, so no inspection moves earlier and the containment check still rejects before any guarded write happens. Review thread: src/core/tools/guardedWrite.ts:419 (Major / Data Integrity). Tests: new describe "the observation is read when the write is issued" - - a peer publish that lands while validation is held now rejects the first write stale and publishes nothing (one publish in total, the peer's token still recorded); - a write held in validation with no peer publish still publishes. Control (tests unchanged, only the ordering reverted; corpse kept): exit 1, 1 failed | 53 passed - AssertionError: promise resolved "undefined" instead of rejecting variant: results/1408r3-variantA-read-after-await.ts log: results/wt6-1408r3-control-A.txt Gates at this commit: eslint . --ext=ts --max-warnings=0 exit 0 (suppression leaves 261, none added, none rising); check-types exit 0; prettier --check . exit 0; vitest core/tools/__tests__/guardedWrite.spec.ts 52 passed (50 pre-existing + 2 new), the seven guarded-write consumer suites plus taskObservationRegistry 220 passed across the 8 core files, DiffViewProvider.spec 93 passed - 0 failures. --- src/core/tools/__tests__/guardedWrite.spec.ts | 72 +++++++++++++++++++ src/core/tools/guardedWrite.ts | 27 ++++--- 2 files changed, 91 insertions(+), 8 deletions(-) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index 5a3964d40ad..8fde921b7f9 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -393,6 +393,78 @@ describe("guardedWrite (S4a, epic #1375)", () => { }) }) + describe("the observation is read when the write is issued", () => { + it("rejects a write whose validation window a peer publish landed in - stale, nothing published", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("doc.txt"), "v1") + const task = createMockTask({ observationRegistry: reg }) + // A stand-in for the disk: the version token follows the bytes, so a publish moves it, + // and replaceIfVersion hands the moved token back for the registry to record. + let diskVersion = "v1" + mockedComputeVersionToken.mockImplementation(async () => diskVersion) + mockedSafeWriteText.mockImplementation(async (_path: string, _content: string) => { + // The commit-time verifier has its own describe; this row is about the check that + // runs before the queue, so the double only has to do what a publish does to the token. + diskVersion = "v2" + }) + mockedFsAccess.mockResolvedValue(undefined) + // Hold the canonical-root check open: it is the await that yields, so a peer can + // publish while this write sits in it. mockImplementationOnce takes only the first + // call, which is this write's realpath of task.cwd. + let releaseValidation: () => void = () => {} + const held = new Promise((resolve) => { + releaseValidation = resolve + }) + const realpathSpy = vi.mocked(fs.realpath) + realpathSpy.mockImplementationOnce(() => held.then(() => WORKSPACE)) + + const first = guardedWrite(task, "doc.txt", "prepared against v1", "update") + await vi.waitFor(() => { + expect(realpathSpy).toHaveBeenCalledTimes(1) + }) + // The peer is not queued behind this write - the write has not reached the per-path + // queue yet - so it publishes and refreshes the registry out from under it. + await guardedWrite(task, "doc.txt", "the peer content", "update") + expect(reg.get(abs("doc.txt"))?.version).toBe("v2") + + releaseValidation() + // This write was issued against v1, so v1 is the state it has to answer for: the peer + // makes it stale. Reading the observation after the await instead would hand it the + // peer's own token, the compare-and-swap would pass, and the peer's content would be + // replaced by a write that was never issued against it. + await expect(first).rejects.toThrow( + "Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.", + ) + expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) + expect(reg.get(abs("doc.txt"))?.version).toBe("v2") + }) + + it("publishes when nothing publishes while the validation is held", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("doc.txt"), "v1") + const task = createMockTask({ observationRegistry: reg }) + mockedComputeVersionToken.mockResolvedValue("v1") + mockedFsAccess.mockResolvedValue(undefined) + let releaseValidation: () => void = () => {} + const held = new Promise((resolve) => { + releaseValidation = resolve + }) + const realpathSpy = vi.mocked(fs.realpath) + realpathSpy.mockImplementationOnce(() => held.then(() => WORKSPACE)) + + const write = guardedWrite(task, "doc.txt", "new content", "update") + await vi.waitFor(() => { + expect(realpathSpy).toHaveBeenCalledTimes(1) + }) + releaseValidation() + + await expect(write).resolves.toBeUndefined() + expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "new content", { + preCommitVerify: expect.any(Function), + }) + }) + }) + describe("edit", () => { it("fails read-first when the file was never observed - nothing published, no I/O", async () => { const task = createMockTask() diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index 8364131900d..1f7766a639e 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -385,8 +385,10 @@ export async function assertWithinCanonicalRoot(cwd: string, absolutePath: strin /** * Guarded write entry point. * - * 1. Resolves the absolute path against task.cwd. - * 2. Consults the task's S2 observation registry to pick the guard: + * 1. Resolves the absolute path against task.cwd and snapshots the observation from the + * task's S2 registry BEFORE the containment check's await, so a peer publish cannot + * move the version token or the completeness flag out from under an issued write. + * 2. Picks the guard from that snapshot: * - unobserved + edit: unobservedEditGuard; * - unobserved + create/update: createIfAbsent (rejects if it exists); * - observed + edit: replaceIfVersion on the read-time token. A targeted edit @@ -407,17 +409,26 @@ export async function guardedWrite( kind: GuardedWriteKind = "update", ): Promise { const absolutePath = resolveAbsolutePath(task, relPathOrAbsolute) + // Snapshot the observation when the write is issued, not when its link runs, and + // not across an await. The registry read is a map lookup with no I/O, so it costs + // nothing to take it before the containment check; the await below is a filesystem + // inspection that yields, and a peer write can publish and refresh the registry in + // that window. An observation taken after it would carry the PEER's version token, + // this write's compare-and-swap would match it, and content that was never issued + // against the peer's file would replace it - the lost update the token exists to + // prevent, arriving through the guard's own await instead of through the queue. + // The completeness flag moves the same way: a peer read that covers the whole file + // can replace a partial observation while this write is parked, and a write must not + // inherit completeness it was not issued with. A refresh after a publish must not + // retroactively validate a second write that was issued against the pre-publish + // state: two concurrent writes to one path still have exactly one winner. + const obs = task.observationRegistry.get(absolutePath) + // The approval and .rooignore decisions were made on the workspace // spelling; verify the canonical target before any guarded I/O so a ".." // escape or a symlinked ancestor cannot publish outside the workspace. await assertWithinCanonicalRoot(task.cwd, absolutePath) - // Snapshot the observation when the write is issued, not when its link runs. - // A refresh after a publish must not retroactively validate a second write that - // was issued against the pre-publish state: two concurrent writes to one path - // still have exactly one winner. - const obs = task.observationRegistry.get(absolutePath) - return enqueue(absolutePath, async () => { // The link can reach the head of the queue long after the task that issued it is // gone (panel closed, task switched, abort landed while another write held the From 9d84046be9f12c3747f0d4962cf9a75a0a66fe98 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:21:50 +0800 Subject: [PATCH 77/79] fix(guarded-write): report an inspection failure instead of blaming the read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The completeness gate asks whether the observed target is still on disk, and it asked that of fileIsAbsent, which answers "not absent" for every failure that is not ENOENT. A denied inspection (EACCES, EIO) is not evidence that the target is there, and this gate has no later check to defer to, so a write ended in "File was read only in part -- ... read the file in full, then retry" for a file the guard had not managed to inspect at all: the remediation sent the model to re-read while the real condition was a permission failure. Before this gate existed the same failure surfaced from replaceIfVersion, which rethrows a non-ENOENT inspection error verbatim - the gate took that report away rather than adding a guarantee. The gate now asks the stricter question: ENOENT is absent, anything else is rethrown unchanged. The create path keeps its own answer - there a denial means "not absent" and defers to the version guard, which re-checks under the write lock - so the two strictness rules are separated on purpose rather than unified, and pinned apart below. Review thread: src/core/tools/guardedWrite.ts:456 (Minor / Functional Correctness). Tests: - "answers an inspection failure with the error itself, not with a verdict about the read": rejects with the raw EACCES object, publishes nothing, and leaves the observation as the read left it, because a failed inspection is not a guard verdict. - "keeps deferring a denied create-path check to the guard's own answer": a create whose access check is denied still gets the completeness refusal, so the stricter gate does not reach back into the create fallback (the complete-read twin of this row, "defers to the version guard when the access check is denied (not ENOENT)", is untouched). Control (tests unchanged, only the gate's question reverted; corpse kept): exit 1, 1 failed | 53 passed - AssertionError: expected GuardRejectedError: File was read only in… { path: '…' } to be Error: EACCES: permission denied, access … { code: '…' } // Object.is equality variant: results/1408r3-variantB-tolerant-gate.ts log: results/wt6-1408r3-control-B.txt Gates at this commit: eslint . --ext=ts --max-warnings=0 exit 0 (suppression leaves 261, none added, none rising); check-types exit 0; prettier --check . exit 0; vitest core/tools/__tests__/guardedWrite.spec.ts 54 passed (50 pre-existing + 4 new), the 8 core files 222 passed, DiffViewProvider.spec 93 passed - 0 failures. --- src/core/tools/__tests__/guardedWrite.spec.ts | 38 +++++++++++++++++++ src/core/tools/guardedWrite.ts | 29 +++++++++++++- 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index 8fde921b7f9..705db6749f4 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -391,6 +391,44 @@ describe("guardedWrite (S4a, epic #1375)", () => { preCommitVerify: expect.any(Function), }) }) + it("answers an inspection failure with the error itself, not with a verdict about the read", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("locked.txt"), "v1", false) + const task = createMockTask({ observationRegistry: reg }) + // The completeness gate asks one question: is the observed target still there. A denied + // inspection does not answer it, and the write the gate stands in front of would have + // propagated this same error, so the error is what the caller has to receive - not a + // remediation that sends the model to re-read a file the guard never inspected. + const failure = Object.assign(new Error("EACCES: permission denied, access '" + abs("locked.txt") + "'"), { + code: "EACCES", + }) + mockedFsAccess.mockRejectedValue(failure) + mockedComputeVersionToken.mockResolvedValue("v1") + + await expect(guardedWrite(task, "locked.txt", "the whole file, rewritten", "update")).rejects.toBe(failure) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + // A failed inspection is not a guard verdict either: the read is still the model's to use. + expect(reg.get(abs("locked.txt"))).toMatchObject({ version: "v1", complete: false }) + }) + + it("keeps deferring a denied create-path check to the guard's own answer", async () => { + // The two absence questions have different strictness on purpose, so the create path's + // own answer has to survive the gate's stricter one. The create branch treats a denial + // as "not absent" and defers to the version guard - pinned for a complete read by + // "defers to the version guard when the access check is denied (not ENOENT)" above - and + // on a partial read the guard's answer for a target that has not gone is the + // completeness refusal. This row pins that the refusal still wins here rather than the + // gate's stricter rule reaching back into the create branch. + const reg = new ObservationRegistry() + reg.observe(abs("locked.txt"), "v1", false) + const task = createMockTask({ observationRegistry: reg }) + mockedFsAccess.mockRejectedValue({ code: "EACCES" }) + + await expect(guardedWrite(task, "locked.txt", "whole file", "create")).rejects.toThrow( + "File was read only in part -- " + abs("locked.txt"), + ) + expect(mockedSafeWriteText).not.toHaveBeenCalled() + }) }) describe("the observation is read when the write is issued", () => { diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index 1f7766a639e..1a326974b5b 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -144,6 +144,28 @@ async function fileIsAbsent(absolutePath: string): Promise { } } +/** + * The same question as fileIsAbsent, answered only from evidence about the target, for + * the callers that turn the answer into a guard verdict. "A denial says nothing" is a + * usable answer when the fallback is a publish that re-checks the file under the write + * lock - that is the create path, which defers to the version guard. It is not usable + * here: the completeness gate has no later check to defer to, so swallowing EACCES or + * EIO would replace the error the guarded publish was about to propagate with a refusal + * that sends the model to re-read a file the guard never managed to inspect. ENOENT is + * the only denial that means absent; every other one is rethrown unchanged. + */ +async function fileIsAbsentStrict(absolutePath: string): Promise { + try { + await fs.access(absolutePath) + return false + } catch (error: unknown) { + if (errorCode(error) === "ENOENT") { + return true + } + throw error + } +} + /** * Publish content only if the target file does not exist. * @@ -463,8 +485,11 @@ export async function guardedWrite( // A target that has since vanished is not a replacement of anything observed, so // the version check below keeps answering for it -- hence the absence check, which // is paid for only on this partial-read path (a "create" reaching here was already - // shown to exist by the branch above, so it short-circuits). - if (!obs.complete && (kind === "create" || !(await fileIsAbsent(absolutePath)))) { + // shown to exist by the branch above, so it short-circuits). The check is the + // strict one: an inspection that fails for a reason other than absence is rethrown + // rather than turned into a verdict about the read, because this gate has no later + // check to defer it to. + if (!obs.complete && (kind === "create" || !(await fileIsAbsentStrict(absolutePath)))) { throw new GuardRejectedError( `File was read only in part -- ${absolutePath} was last read as a slice, a line range or a truncated view, and this write replaces the whole file; read the file in full, then retry.`, absolutePath, From a5567e3c2d5f7dc1ba4f4e73967dff80908e5bd8 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:59:46 +0800 Subject: [PATCH 78/79] fix(diff-view): keep the file's byte-order mark through the guarded publish The diff flow strips byte-order marks from everything it writes into the diff buffer (every editor write goes through stripAllBOMs), but it reads the file raw (fs.readFile utf-8), so originalContent carries a mark the buffer never has. saveChanges then handed the buffer's text to the guard verbatim: for a UTF-8-sig file the published bytes had no leading U+FEFF, so the guarded rename published a file that was not the file the diff started from - a UTF-8-sig reader folds the first real character into the encoding signature. The mirror asymmetry sat in the guard-rejection rollback, which wrote the raw originalContent into a buffer that every other path of this class keeps BOM-free (revertChanges writes stripped text): a rejected save left a mark in the buffer that a later publish would then copy a second time. The rule is stated once, at the publish boundary. contentWithOriginalBOM copies the mark the original carried - none stays none, and a buffer that already carries one is not marked twice - and the rollback strips, matching every other buffer state this class writes. The buffer stays BOM-free everywhere else, so a mark is applied exactly once per publish. Review finding: "Preserve the original UTF-8 BOM on the diff-view publish path" (Persistence Integrity, review 6101103933 at head 9d84046be9). Tool-authored publishes are untouched: saveDirectly is called by the write and edit tools with content those tools composed, not with a buffer this class stripped. Tests: four rows in the guarded saveChanges describe - - a file whose original carried U+FEFF publishes U+FEFF + the buffer text; - a buffer that already carries the mark publishes exactly one mark; - a file that had no mark publishes none: the rule copies, it never invents; - a rejected publish rolls the buffer back to the stripped original text. Controls (tests unchanged, one production rule reverted at a time; corpses kept): - publish rule reverted: exit 1, 1 failed | 96 passed - AssertionError: ... to be called with arguments [ '/mock/cwd/test.ts', ... ] - "\uFEFFnew content" (expected) + "new content" (received) results/bom-1408-control-P.txt, variant results/bom-1408-variantP-no-publish-rule.ts - rollback strip reverted: exit 1, 1 failed | 96 passed - AssertionError: ... to be called with arguments [ Anything, 'disk content' ] - "disk content" (expected) + "\uFEFFdisk content" (received) results/bom-1408-control-R.txt, variant results/bom-1408-variantR-raw-rollback.ts The comment at the no-save-after-publish decision is corrected in the same commit: after the restore the file holds the buffer's text plus the mark the original carried while the buffer itself is untouched, so external-change reconciliation - not a save - is what clears the dirty flag, and the assumption that the editor tracks the mark with the document's encoding is named as an assumption because unit doubles cannot exercise that bookkeeping. Gates at this commit (local, not pushed): eslint . --ext=ts --max-warnings=0 exit 0 (suppression leaves 261, none added, none rising; per-file --prune-suppressions run on both changed files, exit 0 each); check-types exit 0; prettier --check . exit 0 - prettier removed one blank line I had left before a closing brace, the only reformat, and the suites were re-run against the formatted content. vitest integrations/editor/__tests__/DiffViewProvider.spec.ts 97 passed (93 pre-existing + 4 new); whole misc project 2578 passed | 13 skipped | 0 failed; the eight saveDirectly-consumer core specs 243 passed | 5 skipped | 0 failed. --- src/integrations/editor/DiffViewProvider.ts | 44 +++++++++++++-- .../editor/__tests__/DiffViewProvider.spec.ts | 56 +++++++++++++++++++ 2 files changed, 95 insertions(+), 5 deletions(-) diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 761aa77a66a..94c75c49ec2 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -372,8 +372,11 @@ export class DiffViewProvider { // unreachable and the write cannot be guarded. throw new Error("Cannot guard the write: the owning task is no longer available") } + // The buffer is BOM-free by construction; the file it replaces may not be, so + // the bytes handed to the guard carry whatever mark the original carried. + const publishContent = this.contentWithOriginalBOM(editedContent) try { - await guardedWrite(guardTask, this.relPath, editedContent, "update") + await guardedWrite(guardTask, this.relPath, publishContent, "update") } catch (error: unknown) { // The guard rejected the publish: roll the editor buffer back to the // content the diff started from - the file on disk is untouched - so no @@ -393,7 +396,10 @@ export class DiffViewProvider { normalizedEditedContent, ) const editor = this.activeDiffEditor - const rollback = this.originalContent ?? "" + // Stripped, like every other buffer state this class writes (revertChanges does + // the same): the buffer this rollback lands in is BOM-free, and handing it the raw + // original would put a mark back that the publish rule above would then copy again. + const rollback = this.stripAllBOMs(this.originalContent ?? "") const fullRange = updatedDocument.validateRange( // Whole-document range: lineCount is one past the last line, so this // covers every byte the buffer holds. @@ -413,9 +419,13 @@ export class DiffViewProvider { // Deliberately no updatedDocument.save() here: the guarded publish // replaced the file through an atomic rename, so the file changed // externally and a save would raise VS Code's save-conflict - // confirmation (which hangs unattended flows). The buffer and the file - // hold the same bytes, so the editor's external-change reconciliation - // clears the dirty flag on its own. + // confirmation (which hangs unattended flows). The file now holds the + // buffer's text plus the mark the original carried, and the buffer itself + // is untouched, so external-change reconciliation - not a save - is what + // clears the dirty flag. That reconciliation has to treat the mark as part + // of the document's encoding rather than of its text; these unit doubles + // cannot exercise the editor's own bookkeeping, so it is named as the + // assumption it is. } // Stop tracking touches and cancel any pending scroll-to-diff before any @@ -1175,6 +1185,30 @@ export class DiffViewProvider { return result } + /** + * Put back the byte-order mark the file on disk carried, for the text about to be + * published over it. + * + * Every write this flow makes into the diff buffer goes through stripAllBOMs, so the + * buffer - and the text the guard receives - is BOM-free even when the file being + * replaced opened with a mark. Publishing that text unchanged drops the mark, and a + * UTF-8-sig reader folds the first real character into the encoding signature, so the + * published file is not the file the diff started from. The buffer stays BOM-free + * everywhere else (revertChanges and the streamed edits both strip) and the publish + * boundary is where the mark is restored, so the rule is applied once. It copies the + * mark the original had - none stays none - and does nothing when the buffer already + * carries one, which keeps a file from gaining a second signature. + */ + private contentWithOriginalBOM(editedContent: string): string { + const original = this.originalContent ?? "" + if (!original.startsWith("\uFEFF") || editedContent.startsWith("\uFEFF")) { + return editedContent + } + // The same run of marks stripAllBOMs would have removed, so a file that opened with + // more than one does not end up with fewer than it started with. + return original.slice(0, original.length - this.stripAllBOMs(original).length) + editedContent + } + async reset(): Promise { // Dispose touch listeners and cancel any pending deferred scroll BEFORE any // async editor manipulation. closeAllDiffViews() awaits tab-close operations, diff --git a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts index 885b9c852ae..85e7c43b6b4 100644 --- a/src/integrations/editor/__tests__/DiffViewProvider.spec.ts +++ b/src/integrations/editor/__tests__/DiffViewProvider.spec.ts @@ -1260,6 +1260,62 @@ describe("DiffViewProvider", () => { ) expect(safeWriteText).not.toHaveBeenCalled() }) + it("keeps the byte-order mark the file on disk had when publishing the buffer", async () => { + // Every write this flow makes into the diff buffer is BOM-stripped, so publishing + // the buffer verbatim would publish a file without the mark the original had: a + // UTF-8-sig reader folds the first real character into the encoding signature. + // The buffer stays BOM-free and the publish boundary puts the mark back. + setupDirtyDoc("new content") + diffViewProvider["originalContent"] = "\uFEFFdisk content" + + await diffViewProvider.saveChanges(false, 0) + + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "\uFEFFnew content", { + preCommitVerify: expect.any(Function), + }) + }) + + it("does not mark twice when the buffer already carries the byte-order mark", async () => { + // A mark the user or the editor put back into the buffer is already the mark the + // publish needs; adding another would put two signatures on one file. + setupDirtyDoc("\uFEFFnew content") + diffViewProvider["originalContent"] = "\uFEFFdisk content" + + await diffViewProvider.saveChanges(false, 0) + + const published = String(vi.mocked(safeWriteText).mock.calls[0][1]) + expect(published.startsWith("\uFEFF")).toBe(true) + expect(published.split("\uFEFF").length - 1).toBe(1) + }) + + it("publishes no byte-order mark when the file on disk had none", async () => { + // The rule copies the original's mark; it never invents one, so the common case + // is untouched. + setupDirtyDoc("new content") + diffViewProvider["originalContent"] = "disk content" + + await diffViewProvider.saveChanges(false, 0) + + expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content", { + preCommitVerify: expect.any(Function), + }) + }) + + it("rolls the buffer back without the byte-order mark on a rejected publish", async () => { + // A rejected publish leaves the file untouched, and every other buffer state this + // class produces is BOM-free - revertChanges writes stripped text - so the rollback + // has to strip the mark too. Writing the raw original here would leave a mark in + // the buffer that the publish rule would then copy a second time. + const { document, replace } = setupDirtyDoc() + diffViewProvider["originalContent"] = "\uFEFFdisk content" + mockTask.observationRegistry.clear() + + await expect(diffViewProvider.saveChanges(false, 0)).rejects.toThrow( + "File already exists at /mock/cwd/test.ts and was not read before this write -- read the file first, then retry.", + ) + expect(replace).toHaveBeenCalledWith(expect.anything(), "disk content") + expect(document.save).not.toHaveBeenCalled() + }) }) }) }) From 8c16a46676d817cd02ab4192391a06f53a8a4727 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:33:51 +0800 Subject: [PATCH 79/79] fix(guarded-write): keep the prior completeness when an edit publishes The post-publish refresh recorded the published token and let the completeness flag default to true, so a targeted edit issued against a partial read left the registry claiming a whole-file observation. The next full-file replacement then passed the completeness gate on an authority the model never had - the loss the gate exists to refuse. Only a full-file replacement earns a whole-file observation: its published content is now the file. A targeted edit publishes lines computed against the current file, so the refresh carries forward the completeness the write was issued with. Tests: the row the review named now expects the retained complete:false, and a new row runs a partial read, then an edit, then a full update write and expects that write to be refused with the read-it-in-full remediation. Both rows were red before the production change (exit 1, 2 failed | 53 passed) with AssertionError: expected { version: 'v1', ... } to match object { version: 'v1', complete: false }. Controls, production only with the tests as committed, each awaited and the working bytes hash-checked back to the committed sha afterwards: - 1408-variantA-publish-resets-complete.ts (the old refresh): exactly those 2 rows red, 2 failed | 53 passed - 1408-control-A-reset-true.txt. - 1408-variantB-publish-never-claims-complete.ts (no publish ever claims completeness): the created-file flow goes red instead - records the published token so a later write needs no re-read - 1 failed | 54 passed - 1408-control-B-never-claims.txt. So both halves of the rule are load-bearing. After restoring the committed bytes the suite is green again: 55 passed - 1408-tests-after-controls.txt. Docstrings revised to match the code: the ObservationRegistry header and observe() now state which completeness a publish records and why; FileObservation.complete names the two ways the flag is recorded; the guarded-write entry point documents the refresh as step 4. Two drifted line citations in the registry header (guardedWrite.ts:456 and :471) now point at the gate at :496 and the refresh at :521. The diff-view read doc states that its whole-file completeness is earned by the read above it rather than assumed. Gates at this state: eslint over src exit 0; per-file prune-suppressions on all four files exit 0 with the suppression table unchanged; prettier --write reports all four unchanged and prettier --check over the repo exit 0; cold check-types with zero tsbuildinfo files exit 0 with no type errors; vitest for guardedWrite plus its nine consumer suites 347 passed, 0 failed, and the diff-view spec under the misc config 97 passed, 0 failed. --- src/core/task/observationRegistry.ts | 25 ++++++++++---- src/core/tools/__tests__/guardedWrite.spec.ts | 34 ++++++++++++++++--- src/core/tools/guardedWrite.ts | 17 +++++++++- src/integrations/editor/DiffViewProvider.ts | 8 +++-- 4 files changed, 70 insertions(+), 14 deletions(-) diff --git a/src/core/task/observationRegistry.ts b/src/core/task/observationRegistry.ts index be5baccbf94..1609d6364e9 100644 --- a/src/core/task/observationRegistry.ts +++ b/src/core/task/observationRegistry.ts @@ -8,9 +8,14 @@ * - every write compares `version` against the token it recomputes under its own lock, which is * how a stale read or a file replacement is detected; * - a full-file replacement — kind "create" or "update" landing on a path that was observed and - * is still on disk (src/core/tools/guardedWrite.ts:456) — additionally requires `complete`. + * is still on disk (src/core/tools/guardedWrite.ts:496) — additionally requires `complete`. * A targeted edit (kind "edit") is not gated on completeness, and no other production code reads * the flag: it exists for that one decision. + * + * A publish re-observes the path it wrote, and it records the completeness its own kind earns: a + * full-file replacement produced the whole file, so it records true, while a targeted edit only + * published lines, so it carries the previous value forward (src/core/tools/guardedWrite.ts:521) + * rather than claiming a whole-file read the model never had. */ export interface FileObservation { @@ -26,6 +31,10 @@ export interface FileObservation { * is not a claim that the model has seen, or still remembers, every line of the file. Only the * full-file replacement consults it — that write replaces lines the model cannot see from a * partial view, so it needs an observation of the whole file to be allowed at all. + * + * A publish records the flag too, and only ever from its own kind: a full-file replacement holds + * the whole file it just wrote, a targeted edit carries forward whatever the observation it was + * issued with said. */ complete: boolean } @@ -43,11 +52,15 @@ export class ObservationRegistry { * Re-observing replaces the entry with a fresh observedAt timestamp, the new version token, * and this delivery's completeness. * - * `complete` defaults to true because the callers that lean on the default read or publish the - * whole file. After a guarded publish the file on disk is exactly the content that write carried, - * so recording true there describes the file the write produced (src/core/tools/guardedWrite.ts:471) - * - it says nothing about how much of an earlier read the model was shown. read_file is the - * caller that passes false, on both of its paths, whenever it handed over only a view. + * `complete` defaults to true because the callers that lean on the default either read the whole + * file or published it: guardedWrite records true after a full-file replacement, because the file + * on disk is then exactly the content that write carried (src/core/tools/guardedWrite.ts:521). + * Neither claim says anything about how much of an earlier read the model was shown. On a + * targeted edit guardedWrite passes the flag explicitly instead: the edit published lines + * computed against the current file rather than replacing a view, so it carries forward the + * completeness it was issued with, and a partial read followed by an edit still refuses a later + * full-file replacement. read_file is the caller that passes false, on both of its paths, + * whenever it handed over only a view. */ observe(absolutePath: string, version: string, complete: boolean = true): void { if (this.retired) { diff --git a/src/core/tools/__tests__/guardedWrite.spec.ts b/src/core/tools/__tests__/guardedWrite.spec.ts index 705db6749f4..bd1ff7e0c0a 100644 --- a/src/core/tools/__tests__/guardedWrite.spec.ts +++ b/src/core/tools/__tests__/guardedWrite.spec.ts @@ -356,11 +356,35 @@ describe("guardedWrite (S4a, epic #1375)", () => { expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("code.ts"), "lines the edit produced", { preCommitVerify: expect.any(Function), }) - // The publish wrote the whole file, so what the registry now describes is that file: - // it records what was published, not how much of the earlier read the model saw. - // (Whether a later full-file write should be gated on the model's own read is an - // open product question, not something this row decides.) - expect(reg.get(abs("code.ts"))).toMatchObject({ version: "v1", complete: true }) + // The edit published lines, not the file. Completeness describes what the model was shown, so + // the refresh carries the value the edit was issued with instead of claiming a whole-file + // read the model never had: the next full-file replacement still has to earn its way past + // the completeness gate, which is the row added below. + expect(reg.get(abs("code.ts"))).toMatchObject({ version: "v1", complete: false }) + }) + + it("refuses a full-file write that follows an edit issued against a partial read", async () => { + const reg = new ObservationRegistry() + reg.observe(abs("code.ts"), "v1", false) + const task = createMockTask({ observationRegistry: reg }) + mockedComputeVersionToken.mockResolvedValue("v1") + // The target stays on disk, so the write that follows is a full-file replacement. + mockedFsAccess.mockResolvedValue(undefined) + + await guardedWrite(task, "code.ts", "lines the edit produced", "edit") + + // The edit was allowed: a targeted edit is gated on the version token, not on completeness. + expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) + expect(reg.get(abs("code.ts"))).toMatchObject({ version: "v1", complete: false }) + + // The model still holds the file only as far as the partial read showed it, so the whole-file + // replacement is refused on the completeness the edit carried forward, rather than accepted + // because an edit happened to publish. + await expect(guardedWrite(task, "code.ts", "the whole file, rewritten", "update")).rejects.toThrow( + "File was read only in part -- " + abs("code.ts"), + ) + // Only the edit published. + expect(mockedSafeWriteText).toHaveBeenCalledTimes(1) }) it("lets a vanished partially-read target reach the version guard that answers for it", async () => { diff --git a/src/core/tools/guardedWrite.ts b/src/core/tools/guardedWrite.ts index 1a326974b5b..685cc221f9c 100644 --- a/src/core/tools/guardedWrite.ts +++ b/src/core/tools/guardedWrite.ts @@ -423,6 +423,10 @@ export async function assertWithinCanonicalRoot(cwd: string, absolutePath: strin * read-it-in-full remediation instead of publishing over the lines off-screen. * 3. Runs the chosen guard on the per-path FIFO chain so concurrent writes to * the same path are deterministically ordered. + * 4. Records the published token under the completeness the write was entitled to: a + * full-file replacement records a whole-file observation, a targeted edit keeps the + * completeness it was issued with, so an edit landing on a partial read cannot make a + * later whole-file replacement look authorised. */ export async function guardedWrite( task: Task, @@ -504,7 +508,18 @@ export async function guardedWrite( // later guarded write must compare against it rather than the read-time (or, // for a created file, missing) token, which is what the result message // "you do not need to re-read the file" promises. - task.observationRegistry.observe(absolutePath, publishedVersion) + // + // Completeness travels with the write that published, and the two kinds differ. A + // full-file replacement leaves the disk holding exactly the content this write carried, + // so recording a whole-file observation there describes the file the write produced. A + // targeted edit publishes lines computed against the current file rather than replacing + // a view, so it carries no whole-file authority: refreshing to true here would hand the + // next full-file replacement an observation of the whole file the model was never shown, + // which is exactly what the gate above this line refuses. The snapshot the write was + // issued against is therefore the value an edit publish carries forward - the same + // reason a peer read must not lend completeness to a write parked in the queue. + const publishedComplete = kind === "edit" ? (obs?.complete ?? false) : true + task.observationRegistry.observe(absolutePath, publishedVersion, publishedComplete) }) } diff --git a/src/integrations/editor/DiffViewProvider.ts b/src/integrations/editor/DiffViewProvider.ts index 94c75c49ec2..09823fe9ea7 100644 --- a/src/integrations/editor/DiffViewProvider.ts +++ b/src/integrations/editor/DiffViewProvider.ts @@ -144,8 +144,12 @@ export class DiffViewProvider { // The diff view is the read for the guarded-write contract (epic #1375, // #1400): record the on-disk version token for exactly what the user is // about to review, so saveChanges' guarded publish CAS-checks against it. - // A change between opening the diff and accepting it fails the guard as - // stale instead of silently overwriting the newer content. + // The read above took the whole file, so this observation is a whole-file + // one: the default completeness is what that read earned rather than an + // assumption, and saveChanges publishes it back as a full-file replacement + // (kind "update"), so the publish-side refresh keeps the same claim. A change + // between opening the diff and accepting it fails the guard as stale instead + // of silently overwriting the newer content. const openTask = this.taskRef.deref() if (openTask) { // A file created by this diff flow has no pre-read token: compute it now,