-
Notifications
You must be signed in to change notification settings - Fork 1.2k
feat(agent-core-v2): guard Edit and Write against stale or unread files #3096
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
sailist
merged 2 commits into
MoonshotAI:main
from
sailist:feat-051-08-19-mtime-staleness-check
Aug 19, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@moonshot-ai/kimi-code": patch | ||
| --- | ||
|
|
||
| Edit and Write now require reading an existing file before modifying it, and reject the write when the file changed on disk since it was last read. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 changes: 10 additions & 0 deletions
10
packages/agent-core-v2/src/features/staleGuard/staleGuard.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| import { createDecorator, type ServiceIdentifier } from '#/_base/di/instantiation'; | ||
|
|
||
| export interface IStaleGuardService { | ||
| readonly _serviceBrand: undefined; | ||
|
|
||
| recordedMtimeMs(path: string): number | undefined; | ||
| } | ||
|
|
||
| export const IStaleGuardService: ServiceIdentifier<IStaleGuardService> = | ||
| createDecorator<IStaleGuardService>('staleGuardService'); |
19 changes: 19 additions & 0 deletions
19
packages/agent-core-v2/src/features/staleGuard/staleGuardFeature.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| import { ScopeActivation } from '#/_base/di/instantiation'; | ||
| import { Feature } from '#/features/feature'; | ||
| import { registerFeature } from '#/features/featureRegistry'; | ||
|
|
||
| import { IStaleGuardService } from './staleGuard'; | ||
| import { StaleGuardService } from './staleGuardService'; | ||
|
|
||
| export class StaleGuardFeature extends Feature { | ||
| static override readonly name = 'staleGuard'; | ||
|
|
||
| constructor() { | ||
| super(); | ||
| this.contributeAgentService(IStaleGuardService, StaleGuardService, { | ||
| activation: ScopeActivation.OnScopeCreated, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| registerFeature(StaleGuardFeature); |
41 changes: 41 additions & 0 deletions
41
packages/agent-core-v2/src/features/staleGuard/staleGuardOps.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| /* oxlint-disable typescript-eslint/no-unsafe-declaration-merging, eslint-plugin-import/namespace -- Event2 class+payload-interface declaration merging is the sanctioned event-declaration idiom. */ | ||
| import { z } from 'zod'; | ||
|
|
||
| import { Event2 } from '#/app/event/event2'; | ||
| import { defineState } from '#/state/state'; | ||
|
|
||
| export type StaleGuardModelState = Map<string, number>; | ||
|
|
||
| const staleGuardRecordedSchema = z.object({ | ||
| path: z.string(), | ||
| mtimeMs: z.number(), | ||
| }); | ||
|
|
||
| export class StaleGuardRecorded extends Event2<z.infer<typeof staleGuardRecordedSchema>> { | ||
| static override readonly type = 'staleGuard.recorded'; | ||
| static override readonly durable = true; | ||
| static override readonly schema = staleGuardRecordedSchema; | ||
| } | ||
| export interface StaleGuardRecorded extends z.infer<typeof staleGuardRecordedSchema> {} | ||
|
|
||
| const staleGuardClearedSchema = z.object({}); | ||
|
|
||
| export class StaleGuardCleared extends Event2<z.infer<typeof staleGuardClearedSchema>> { | ||
| static override readonly type = 'staleGuard.cleared'; | ||
| static override readonly durable = true; | ||
| static override readonly schema = staleGuardClearedSchema; | ||
| } | ||
| export interface StaleGuardCleared extends z.infer<typeof staleGuardClearedSchema> {} | ||
|
|
||
| export const staleGuardKey = defineState( | ||
| 'staleGuard', | ||
| (): StaleGuardModelState => new Map(), | ||
| ).replayable({ | ||
| schema: z.custom<StaleGuardModelState>(), | ||
| }) | ||
| .on(StaleGuardRecorded, (s, e) => { | ||
| s.set(e.path, e.mtimeMs); | ||
| }) | ||
| .on(StaleGuardCleared, (s) => { | ||
| s.clear(); | ||
| }); |
146 changes: 146 additions & 0 deletions
146
packages/agent-core-v2/src/features/staleGuard/staleGuardService.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| import { Disposable } from '#/_base/di/lifecycle'; | ||
| import { IAgentStateService } from '#/agent/state/agentState'; | ||
| import { IAgentRuntimeService } from '#/agent/runtimeBinding/agentRuntime'; | ||
| import { denyToolExecution } from '#/agent/toolExecutor/beforeToolExecuteEvent'; | ||
| import { IAgentToolExecutorService } from '#/agent/toolExecutor/toolExecutor'; | ||
| import type { | ||
| BeforeToolExecuteEvent, | ||
| ToolDidExecuteContext, | ||
| } from '#/agent/toolExecutor/toolHooks'; | ||
| import type { ToolCall } from '#/kosong/contract/message'; | ||
| import type { HostFileStat } from '#/os/interface/hostFileSystem'; | ||
| import { IEventDispatcher } from '#/state/eventDispatcher'; | ||
| import type { ToolAccesses, ToolFileAccessOperation } from '#/tool/toolContract'; | ||
|
|
||
| import { IStaleGuardService } from './staleGuard'; | ||
| import { StaleGuardCleared, StaleGuardRecorded, staleGuardKey } from './staleGuardOps'; | ||
|
|
||
| const WRITE_OPERATIONS: readonly ToolFileAccessOperation[] = ['write', 'readwrite']; | ||
| const READ_OPERATIONS: readonly ToolFileAccessOperation[] = ['read']; | ||
|
|
||
| function accessedFilePath( | ||
| accesses: ToolAccesses | undefined, | ||
| operations: readonly ToolFileAccessOperation[], | ||
| ): string | undefined { | ||
| for (const access of accesses ?? []) { | ||
| if (access.kind === 'file' && operations.includes(access.operation)) return access.path; | ||
| } | ||
| return undefined; | ||
| } | ||
|
|
||
| function stringArg(args: unknown, key: string): string | undefined { | ||
| if (typeof args !== 'object' || args === null) return undefined; | ||
| const value = (args as Record<string, unknown>)[key]; | ||
| return typeof value === 'string' ? value : undefined; | ||
| } | ||
|
|
||
| function callPathArg(call: ToolCall): string | undefined { | ||
| if (typeof call.arguments !== 'string') return undefined; | ||
| try { | ||
| return stringArg(JSON.parse(call.arguments), 'path'); | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| } | ||
|
|
||
| export class StaleGuardService extends Disposable implements IStaleGuardService { | ||
| declare readonly _serviceBrand: undefined; | ||
|
|
||
| constructor( | ||
| @IAgentStateService private readonly states: IAgentStateService, | ||
| @IEventDispatcher private readonly dispatcher: IEventDispatcher, | ||
| @IAgentRuntimeService private readonly runtime: IAgentRuntimeService, | ||
| @IAgentToolExecutorService toolExecutor: IAgentToolExecutorService, | ||
| ) { | ||
| super(); | ||
| this.states.contributeState(staleGuardKey); | ||
| this._register(toolExecutor.onBeforeExecuteTool((event) => this.guardWrite(event))); | ||
| this._register( | ||
| toolExecutor.hooks.onDidExecuteTool.register('staleGuard', async (ctx, next) => { | ||
| await this.observeExecution(ctx); | ||
| await next(); | ||
| }), | ||
| ); | ||
| this._register( | ||
| this.runtime.onDidChange(() => { | ||
| void this.dispatcher.dispatch(new StaleGuardCleared({})); | ||
| }), | ||
| ); | ||
| } | ||
|
|
||
| recordedMtimeMs(path: string): number | undefined { | ||
| return this.states.get(staleGuardKey).get(path); | ||
| } | ||
|
|
||
| private guardWrite(event: BeforeToolExecuteEvent): void { | ||
| const name = event.toolCall.name; | ||
| if (name !== 'Edit' && name !== 'Write') return; | ||
| const path = accessedFilePath(event.execution.accesses, WRITE_OPERATIONS); | ||
| if (path === undefined) return; | ||
| const displayPath = stringArg(event.args, 'path') ?? path; | ||
| if (coveredByEarlierRead(event, displayPath)) return; | ||
| event.waitUntil(async () => { | ||
| const error = await this.checkWritable(path, displayPath); | ||
| return error === undefined ? undefined : { veto: denyToolExecution(error) }; | ||
| }); | ||
| } | ||
|
|
||
| private async observeExecution(ctx: ToolDidExecuteContext): Promise<void> { | ||
| if (ctx.outcome !== 'executed' || ctx.result.isError === true) return; | ||
| const name = ctx.toolCall.name; | ||
| if (name === 'Read') { | ||
| const path = accessedFilePath(ctx.accesses, READ_OPERATIONS); | ||
| if (path !== undefined) await this.recordCurrentMtime(path); | ||
| return; | ||
| } | ||
| if (name === 'Edit' || name === 'Write') { | ||
| const path = accessedFilePath(ctx.accesses, WRITE_OPERATIONS); | ||
| if (path !== undefined) await this.recordCurrentMtime(path); | ||
| } | ||
| } | ||
|
|
||
| private async checkWritable(path: string, displayPath: string): Promise<string | undefined> { | ||
| const stat = await this.statFile(path); | ||
| if (stat === undefined || stat.mtimeMs === undefined) return undefined; | ||
| const recorded = this.recordedMtimeMs(path); | ||
| if (recorded === undefined) { | ||
| return ( | ||
| `"${displayPath}" has not been read by this agent yet. ` + | ||
| 'Read the file before writing to it.' | ||
| ); | ||
| } | ||
| if (recorded !== stat.mtimeMs) { | ||
| return ( | ||
| `"${displayPath}" has been modified on disk since this agent last read it. ` + | ||
| 'Read the file again before writing to it.' | ||
| ); | ||
| } | ||
| return undefined; | ||
| } | ||
|
|
||
| private async recordCurrentMtime(path: string): Promise<void> { | ||
| const stat = await this.statFile(path); | ||
| if (stat?.mtimeMs === undefined) return; | ||
| await this.dispatcher.dispatch(new StaleGuardRecorded({ path, mtimeMs: stat.mtimeMs })); | ||
| } | ||
|
|
||
| private async statFile(path: string): Promise<HostFileStat | undefined> { | ||
| const lease = this.runtime.acquire(['fs']); | ||
| try { | ||
| const stat = await lease.runtime.fs!.stat(path); | ||
| return stat.isFile ? stat : undefined; | ||
| } catch { | ||
| return undefined; | ||
| } finally { | ||
| lease.dispose(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| function coveredByEarlierRead(event: BeforeToolExecuteEvent, rawPath: string): boolean { | ||
| for (const call of event.toolCalls) { | ||
| if (call.id === event.toolCall.id) return false; | ||
| if (call.name === 'Read' && callPathArg(call) === rawPath) return true; | ||
| } | ||
| return false; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The check runs during tool-call preparation rather than immediately before the write.
AgentToolExecutorService.executeprepares every call beforeexecuteBatchstarts any task, so a same-responseReadfollowed byEditis incorrectly rejected as unread; conversely, a file changed after this check while the write waits behind another conflicting call or an approval is overwritten without detection. Run the freshness check inside the scheduler's execution task, after preceding file accesses have completed and directly beforeexecution.execute.Useful? React with 👍 / 👎.