dsh-awesome-optimizer 0.0.0-stage → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,289 @@
1
+ import { createHash } from 'node:crypto';
2
+ import z from '@deepseek-ai/schemastery';
3
+ import { HarnessError, createUserMessage } from '@deepseek-ai/dsh-llm';
4
+ import { ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline';
5
+ import { normalizePath } from './runtime-policy.js';
6
+
7
+ export const RECOVERY_SOURCE = 'optimizer-write-recovery';
8
+ export const RETRY_TOOL = 'retry_failed_write';
9
+ export const PAIRING_ERROR = 'invalid escalation: justification is only valid together with sandbox_permissions';
10
+ const MIN_BYTES = 8 * 1024;
11
+ const MAX_BYTES = 1024 * 1024;
12
+ const READ_ONLY = new Set(['read', 'read_image', 'read_batch', 'glob', 'grep', 'skill']);
13
+
14
+ export const FailureRecoveryConfig = z.object({
15
+ enabled: z.boolean().default(true),
16
+ maxAttempts: z.number().step(1).min(1).max(1).default(1)
17
+ });
18
+
19
+ /**
20
+ * Structured finite recovery record abstraction.
21
+ */
22
+ export class RecoveryRecord {
23
+ constructor({
24
+ owner,
25
+ callId,
26
+ rootCallId,
27
+ toolName = 'write',
28
+ args,
29
+ definition,
30
+ turn = 1,
31
+ step = 0,
32
+ category = 'pairing-error',
33
+ maxAttempts = 1
34
+ }) {
35
+ this.owner = owner;
36
+ this.callId = callId;
37
+ this.rootCallId = rootCallId;
38
+ this.toolName = toolName;
39
+ this.args = { file_path: args.file_path, content: args.content };
40
+ this.targetPath = normalizePath(args.file_path);
41
+ this.argHash = createHash('sha256').update((args.file_path ?? '') + '|' + (args.content ?? '')).digest('hex').slice(0, 16);
42
+ this.definition = definition;
43
+ this.turn = turn;
44
+ this.step = step;
45
+ this.category = category;
46
+ this.attempts = 0;
47
+ this.maxAttempts = maxAttempts;
48
+ this.notified = false;
49
+ this.invalidatedReason = null;
50
+ this.createdAt = Date.now();
51
+ }
52
+
53
+ isValid(agent, currentTurn, currentDefinition) {
54
+ if (this.invalidatedReason) return false;
55
+ if (this.owner !== agent) return false;
56
+ if (this.turn !== currentTurn) return false;
57
+ if (this.attempts >= this.maxAttempts) return false;
58
+ if (currentDefinition && this.definition !== currentDefinition) return false;
59
+ return true;
60
+ }
61
+
62
+ invalidate(reason) {
63
+ if (!this.invalidatedReason) {
64
+ this.invalidatedReason = reason;
65
+ }
66
+ }
67
+
68
+ consume() {
69
+ this.attempts++;
70
+ if (this.attempts >= this.maxAttempts) {
71
+ this.invalidate('attempt-exceeded');
72
+ }
73
+ }
74
+ }
75
+
76
+ const eligible = (exec, result) => {
77
+ const args = exec.arguments;
78
+ return exec.parent === undefined && exec.name === 'write' && !exec.signal.aborted
79
+ && result.isError && result.error.message === PAIRING_ERROR
80
+ && args && typeof args.file_path === 'string' && args.file_path.trim().length > 0
81
+ && typeof args.content === 'string' && typeof args.justification === 'string'
82
+ && args.justification.trim().length > 0 && args.sandbox_permissions === undefined
83
+ && Object.keys(args).every(key => ['file_path', 'content', 'justification'].includes(key))
84
+ && Buffer.byteLength(args.content, 'utf8') >= MIN_BYTES
85
+ && Buffer.byteLength(args.content, 'utf8') <= MAX_BYTES;
86
+ };
87
+
88
+ /** Keep only a reference to the latest unexecuted native write in this turn. */
89
+ export function applyFailureRecovery(ctx, { enabled = true, maxAttempts = 1 } = {}) {
90
+ if (!enabled) return null;
91
+ const attemptsLimit = Math.min(1, Math.max(1, Math.floor(Number.isFinite(maxAttempts) ? maxAttempts : 1)));
92
+ const states = new WeakMap();
93
+ const candidates = new Map();
94
+ const pipeline = new ToolExecutionPipeline(ctx);
95
+
96
+ const getStats = session => {
97
+ const s = session && states.get(session);
98
+ return s ? { ...s.stats } : { attempted: 0, succeeded: 0, failed: 0, invalidated: 0 };
99
+ };
100
+
101
+ const getRecord = session => {
102
+ return session ? states.get(session)?.record : undefined;
103
+ };
104
+
105
+ const service = { getRecord, getStats };
106
+
107
+ ctx.on('session/event', (session, event) => {
108
+ if (event.type === 'turn/start') {
109
+ states.set(session, {
110
+ turn: event.data.turn,
111
+ step: 0,
112
+ rootResults: 0,
113
+ concluded: false,
114
+ record: undefined,
115
+ stats: { attempted: 0, succeeded: 0, failed: 0, invalidated: 0 }
116
+ });
117
+ }
118
+ const state = states.get(session);
119
+ if (!state) return;
120
+ if (event.type === 'turn/end') {
121
+ if (state.record) {
122
+ state.record.invalidate('turn-end');
123
+ state.stats.invalidated++;
124
+ state.record = undefined;
125
+ }
126
+ }
127
+ if (event.type === 'working-directory/change') {
128
+ if (state.record) {
129
+ state.record.invalidate('cwd-change');
130
+ state.stats.invalidated++;
131
+ state.record = undefined;
132
+ }
133
+ }
134
+ if (event.type === 'step/start') {
135
+ state.step = event.data.step ?? state.step;
136
+ state.rootResults = 0;
137
+ state.concluded = false;
138
+ }
139
+ if (event.type === 'user/message' && event.data.source?.kind === RECOVERY_SOURCE
140
+ && event.data.source.callId === state.record?.callId) {
141
+ state.record.notified = true;
142
+ }
143
+ });
144
+
145
+ ctx.on('tools/pre-execute', async (exec, next) => {
146
+ if (exec.parent === undefined && exec.agent && exec.name !== RETRY_TOOL && !READ_ONLY.has(exec.name)) {
147
+ const state = states.get(exec.agent.session);
148
+ if (state?.record) {
149
+ state.record.invalidate('mutating-tool');
150
+ state.stats.invalidated++;
151
+ state.record = undefined;
152
+ }
153
+ }
154
+ return next();
155
+ });
156
+
157
+ ctx.on('tools/execute', async (exec, next) => {
158
+ const result = await next();
159
+ if (exec.agent && eligible(exec, result)) {
160
+ candidates.set(exec.token, ctx.tools.executable('write', exec.agent, exec.toolSet));
161
+ }
162
+ return result;
163
+ });
164
+
165
+ ctx.on('tools/result', (exec, result) => {
166
+ const definition = candidates.get(exec.token);
167
+ candidates.delete(exec.token);
168
+ if (!exec.agent || exec.parent !== undefined) return;
169
+ const state = states.get(exec.agent.session);
170
+ if (!state) return;
171
+ state.rootResults++;
172
+ state.concluded ||= result.concludesTurn === true;
173
+ if (!definition || !eligible(exec, result)) return;
174
+ state.record = new RecoveryRecord({
175
+ owner: exec.agent,
176
+ callId: exec.callId,
177
+ rootCallId: exec.rootCallId,
178
+ toolName: 'write',
179
+ args: exec.arguments,
180
+ definition,
181
+ turn: state.turn,
182
+ step: state.step,
183
+ category: 'pairing-error',
184
+ maxAttempts: attemptsLimit
185
+ });
186
+ });
187
+
188
+ ctx.on('agent/pre-step', async ({ agent, step, signal, messages }, next) => {
189
+ const decision = await next();
190
+ if (decision.kind !== 'enter' || signal.aborted) return decision;
191
+ if (decision.messages.length === 0 && (step === 1 || messages.length > 0)) return decision;
192
+ const state = states.get(agent.session);
193
+ const record = state?.record;
194
+ if (!record || record.owner !== agent || record.notified) return decision;
195
+ if (decision.messages.length === 0 && (state.rootResults === 0 || state.concluded)) return decision;
196
+ const notice = createUserMessage({
197
+ content: [{
198
+ type: 'text',
199
+ text: [
200
+ `The large write in call ${JSON.stringify(record.callId)} failed because justification was supplied without sandbox_permissions.`,
201
+ `To retry the same file path and exact content under current permissions, call ${RETRY_TOOL} with {"call_id":${JSON.stringify(record.callId)}}. Only the invalid justification is removed; do not generate the content again.`,
202
+ 'This reference is valid only in this turn until a subsequent potentially mutating tool call, and can be attempted once. Retry only if the write is still required. All current tool policies and cancellation checks still apply.'
203
+ ].join('\n')
204
+ }],
205
+ source: {
206
+ kind: RECOVERY_SOURCE,
207
+ form: 'notice',
208
+ summary: 'Reuse a rejected large write without generating its contents again.',
209
+ callId: record.callId
210
+ }
211
+ });
212
+ return { ...decision, messages: [...decision.messages, notice] };
213
+ }, { prepend: true });
214
+
215
+ ctx.tools.register({
216
+ name: RETRY_TOOL,
217
+ description: 'Retry the latest large write rejected for an unpaired justification, using its original call ID and exact contents. Removes only that invalid justification. Current permissions apply; consumes the reference once.',
218
+ parameters: {
219
+ type: 'object',
220
+ additionalProperties: false,
221
+ required: ['call_id'],
222
+ properties: {
223
+ call_id: { type: 'string', description: 'Original failed write call ID supplied by the recovery notice.' }
224
+ }
225
+ },
226
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] },
227
+ async execute(args, exec) {
228
+ exec.signal.throwIfAborted();
229
+ const state = exec.agent && states.get(exec.agent.session);
230
+ const record = state?.record;
231
+ if (!args || typeof args.call_id !== 'string' || Object.keys(args).length !== 1
232
+ || !record || record.owner !== exec.agent || record.callId !== args.call_id) {
233
+ throw new Error('No matching recoverable write in this turn. Use the normal write tool if still needed.');
234
+ }
235
+ if (!record.isValid(exec.agent, state.turn)) {
236
+ throw new Error('No matching recoverable write in this turn. Use the normal write tool if still needed.');
237
+ }
238
+ state.record = undefined;
239
+ if (ctx.tools.executable('write', exec.agent, exec.toolSet) !== record.definition) {
240
+ record.invalidate('tool-definition-change');
241
+ if (state) state.stats.invalidated++;
242
+ throw new Error('The original write tool is no longer admitted. The recovery reference has expired.');
243
+ }
244
+ record.consume();
245
+ if (state) state.stats.attempted++;
246
+ const subCallId = `${exec.callId}:write-recovery`;
247
+ const log = { rootCallId: exec.rootCallId, parentCallId: exec.callId, subCallId, name: 'write', arguments: record.args };
248
+ exec.agent.session.append('tool/ptc-dispatch-start', log);
249
+ const prepared = await pipeline.prepare({
250
+ callId: subCallId,
251
+ rootCallId: exec.rootCallId,
252
+ parent: exec.token,
253
+ name: 'write',
254
+ arguments: record.args,
255
+ agent: exec.agent,
256
+ toolSet: exec.toolSet,
257
+ signal: exec.signal
258
+ });
259
+ const outcome = prepared.kind === 'dispatch' ? await pipeline.dispatch(prepared.exec) : prepared;
260
+ const result = await pipeline.complete(prepared.exec, outcome);
261
+ exec.agent.session.append('tool/ptc-dispatch', {
262
+ ...log,
263
+ isError: result.isError,
264
+ content: result.content,
265
+ ...(result.error?.info ? { error: result.error.info } : {}),
266
+ ...(result.meta === undefined ? {} : { meta: result.meta })
267
+ });
268
+ for (const context of result.additionalContexts ?? []) exec.deferContext(context);
269
+ if (result.isError) {
270
+ if (state) state.stats.failed++;
271
+ throw new HarnessError(result.error.message, result.error.info?.code ?? 'WRITE_RECOVERY_FAILED');
272
+ }
273
+ if (state) state.stats.succeeded++;
274
+ if (result.concludesTurn) exec.concludeTurn();
275
+ return result.content.filter(block => block.type === 'text').map(block => block.text).join('\n');
276
+ }
277
+ }, { when: ({ agent }) => ctx.tools.get('write', agent) !== undefined });
278
+
279
+ return service;
280
+ }
281
+
282
+ export const name = 'agent-optimizer-failure-recovery';
283
+ export const inject = ['tools'];
284
+ export const Config = FailureRecoveryConfig;
285
+ export function apply(ctx, config = {}) {
286
+ const service = applyFailureRecovery(ctx, FailureRecoveryConfig(config));
287
+ if (service) ctx.provide('failureRecovery', service);
288
+ }
289
+ export default { name, inject, Config, apply };
@@ -0,0 +1,44 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type z from '@deepseek-ai/schemastery';
3
+
4
+ export type FileMutationPolicyMode = 'off' | 'observe' | 'enforce';
5
+
6
+ export interface FileMutationPolicyOptions {
7
+ mode?: FileMutationPolicyMode;
8
+ minLargeWriteBytes?: number;
9
+ reminderLimit?: number;
10
+ allowFullReplacement?: (exec: any, normalizedPath: string) => boolean;
11
+ }
12
+
13
+ export interface FileMutationPolicySummary {
14
+ largeWriteViolations: number;
15
+ largeWritesBlocked: number;
16
+ fullReplacementsAllowed: number;
17
+ editsCount: number;
18
+ observedFiles: number;
19
+ createdFiles: number;
20
+ }
21
+
22
+ export declare const MUTATION_SOURCE: 'optimizer-file-mutation-policy';
23
+ export declare const FileMutationPolicyConfig: z<FileMutationPolicyOptions>;
24
+ export declare function fileExists(filePath?: string | null, cwd?: string, fsService?: any, signal?: AbortSignal): Promise<boolean>;
25
+
26
+ export declare class FileMutationPolicyManager {
27
+ readonly config: FileMutationPolicyOptions;
28
+ fsService?: any;
29
+ workingDirectory?: any;
30
+ constructor(config?: FileMutationPolicyOptions, fsService?: any, workingDirectory?: any);
31
+ onTurnStart(session: unknown, turn: number): void;
32
+ onTurnEnd(session: unknown): void;
33
+ onCwdChange(session: unknown, newCwd: string): void;
34
+ evaluateToolExecution(session: unknown, exec: any, toolsService?: any, fsService?: any): Promise<any>;
35
+ recordResult(session: unknown, exec: any, result: any): void;
36
+ getSummary(session: unknown, turn?: number): FileMutationPolicySummary;
37
+ }
38
+
39
+ export declare function applyFileMutationPolicy(ctx: Context, rawConfig?: FileMutationPolicyOptions): FileMutationPolicyManager | null;
40
+ export declare const name: string;
41
+ export declare const Config: z<FileMutationPolicyOptions>;
42
+ export declare function apply(ctx: Context, config?: FileMutationPolicyOptions): void;
43
+ declare const plugin: { name: typeof name; Config: typeof Config; apply: typeof apply };
44
+ export default plugin;
@@ -0,0 +1,298 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import z from '@deepseek-ai/schemastery';
4
+ import { normalizePath } from './runtime-policy.js';
5
+
6
+ export const MUTATION_SOURCE = 'optimizer-file-mutation-policy';
7
+
8
+ export const FileMutationPolicyConfig = z.object({
9
+ mode: z.union(['off', 'observe', 'enforce']).default('observe'),
10
+ minLargeWriteBytes: z.number().step(1).min(1).default(8192),
11
+ reminderLimit: z.number().step(1).min(1).default(1),
12
+ allowFullReplacement: z.any()
13
+ });
14
+
15
+ /**
16
+ * Check safely whether a file path exists via ctx.fs backend if available,
17
+ * falling back to local filesystem check.
18
+ */
19
+ export async function fileExists(filePath, cwd = '', fsService, signal) {
20
+ if (!filePath || typeof filePath !== 'string') return false;
21
+ if (fsService && typeof fsService.resolve === 'function') {
22
+ try {
23
+ const target = await fsService.resolve(filePath, { cwd, signal });
24
+ if (typeof fsService.stat === 'function') {
25
+ const info = await fsService.stat(target, signal);
26
+ return info !== undefined;
27
+ }
28
+ return target !== undefined;
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+ try {
34
+ const resolved = path.isAbsolute(filePath) ? filePath : path.resolve(cwd || process.cwd(), filePath);
35
+ return fs.existsSync(resolved);
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Manager tracking file reads, writes, and enforcing edit vs write constraints.
43
+ */
44
+ export class FileMutationPolicyManager {
45
+ constructor(config = {}, fsService, workingDirectory) {
46
+ this.config = FileMutationPolicyConfig(config);
47
+ this.fsService = fsService;
48
+ this.workingDirectory = workingDirectory;
49
+ this.sessionStates = new WeakMap();
50
+ }
51
+
52
+ #createTurnState(turn, cwd = '') {
53
+ return {
54
+ turn,
55
+ cwd,
56
+ observedFiles: new Set(),
57
+ knownExistingFiles: new Set(),
58
+ createdFiles: new Set(),
59
+ pendingCreates: new Map(),
60
+ largeWriteViolations: 0,
61
+ largeWritesBlocked: 0,
62
+ fullReplacementsAllowed: 0,
63
+ editsCount: 0,
64
+ records: []
65
+ };
66
+ }
67
+
68
+ stateFor(session, turn) {
69
+ if (!session) return null;
70
+ let state = this.sessionStates.get(session);
71
+ const targetTurn = turn ?? state?.turn ?? 1;
72
+ if (!state || state.turn !== targetTurn) {
73
+ state = this.#createTurnState(targetTurn, state?.cwd ?? '');
74
+ this.sessionStates.set(session, state);
75
+ }
76
+ return state;
77
+ }
78
+
79
+ onTurnStart(session, turn) {
80
+ const existing = this.sessionStates.get(session);
81
+ this.sessionStates.set(session, this.#createTurnState(turn, existing?.cwd ?? ''));
82
+ }
83
+
84
+ onTurnEnd(session) {
85
+ const state = this.sessionStates.get(session);
86
+ state?.pendingCreates.clear();
87
+ }
88
+
89
+ onCwdChange(session, newCwd) {
90
+ const state = this.sessionStates.get(session);
91
+ if (!state) return;
92
+ state.cwd = newCwd;
93
+ state.observedFiles.clear();
94
+ state.knownExistingFiles.clear();
95
+ state.createdFiles.clear();
96
+ state.pendingCreates.clear();
97
+ }
98
+
99
+ async evaluateToolExecution(session, exec, toolsService, fsService = this.fsService) {
100
+ if (this.config.mode === 'off' || !session || !exec) {
101
+ return { allowed: true, reason: 'policy-off' };
102
+ }
103
+ const state = this.stateFor(session);
104
+ if (!state) return { allowed: true, reason: 'no-state' };
105
+
106
+ if (exec.parent !== undefined) {
107
+ return { allowed: true, reason: 'nested-ptc-call' };
108
+ }
109
+
110
+ if (exec.name === 'retry_failed_write') {
111
+ return { allowed: true, reason: 'recovery-tool' };
112
+ }
113
+
114
+ if (exec.name !== 'write') {
115
+ return { allowed: true, reason: 'not-write' };
116
+ }
117
+
118
+ const args = exec.arguments ?? {};
119
+ const targetPath = typeof args.file_path === 'string' ? args.file_path : '';
120
+ const normPath = normalizePath(targetPath, state.cwd);
121
+ const content = typeof args.content === 'string' ? args.content : '';
122
+ const byteLength = Buffer.byteLength(content, 'utf8');
123
+
124
+ if (state.createdFiles.has(normPath)) {
125
+ return { allowed: true, reason: 'created-in-this-turn' };
126
+ }
127
+
128
+ const createPending = [...state.pendingCreates.values()].includes(normPath);
129
+ const existsInBackend = await fileExists(targetPath, state.cwd, fsService, exec.signal);
130
+ const knownExisting = state.knownExistingFiles.has(normPath) || existsInBackend;
131
+ if (!knownExisting && !createPending) {
132
+ state.pendingCreates.set(exec.callId, normPath);
133
+ return { allowed: true, reason: 'target-does-not-exist' };
134
+ }
135
+
136
+ if (byteLength < this.config.minLargeWriteBytes) {
137
+ return { allowed: true, reason: 'below-size-threshold' };
138
+ }
139
+
140
+ if (toolsService && toolsService.get && toolsService.get('edit', exec.agent) === undefined) {
141
+ return { allowed: true, reason: 'no-edit-available' };
142
+ }
143
+
144
+ let hostApprovedReplacement = false;
145
+ try {
146
+ hostApprovedReplacement = typeof this.config.allowFullReplacement === 'function'
147
+ && this.config.allowFullReplacement(exec, normPath) === true;
148
+ } catch {
149
+ // Never convert a host callback exception into a loop crash.
150
+ }
151
+ if (hostApprovedReplacement) {
152
+ state.fullReplacementsAllowed++;
153
+ return { allowed: true, reason: 'host-approved-replacement' };
154
+ }
155
+
156
+ state.largeWriteViolations++;
157
+ const violation = {
158
+ callId: exec.callId,
159
+ targetPath: normPath,
160
+ byteLength,
161
+ code: 'LARGE_WRITE_EXISTING_FILE',
162
+ reason: 'target is known existing and the call appears to replace the whole file',
163
+ nextAction: 'use edit with an exact unique match, or use the host-approved full-replacement path',
164
+ retryable: false
165
+ };
166
+ state.records.push(violation);
167
+
168
+ if (this.config.mode === 'enforce') {
169
+ state.largeWritesBlocked++;
170
+ return {
171
+ allowed: false,
172
+ ...violation
173
+ };
174
+ }
175
+
176
+ return {
177
+ allowed: true,
178
+ ...violation
179
+ };
180
+ }
181
+
182
+ recordResult(session, exec, result) {
183
+ if (!session || !exec) return;
184
+ const state = this.stateFor(session);
185
+ if (!state) return;
186
+
187
+ const args = exec.arguments ?? {};
188
+ if (exec.name === 'write') {
189
+ const pendingPath = state.pendingCreates.get(exec.callId);
190
+ state.pendingCreates.delete(exec.callId);
191
+ if (result && !result.isError && pendingPath) state.createdFiles.add(pendingPath);
192
+ } else if (result?.isError) {
193
+ return;
194
+ } else if (exec.name === 'edit') {
195
+ state.editsCount++;
196
+ if (typeof args.file_path === 'string') {
197
+ const filePath = normalizePath(args.file_path, state.cwd);
198
+ state.observedFiles.add(filePath);
199
+ state.knownExistingFiles.add(filePath);
200
+ }
201
+ } else if (['read', 'read_image'].includes(exec.name)) {
202
+ if (typeof args.file_path === 'string') {
203
+ const filePath = normalizePath(args.file_path, state.cwd);
204
+ state.observedFiles.add(filePath);
205
+ state.knownExistingFiles.add(filePath);
206
+ }
207
+ } else if (exec.name === 'read_batch' && Array.isArray(args.files)) {
208
+ for (const item of args.files) {
209
+ if (typeof item?.file_path === 'string') {
210
+ const filePath = normalizePath(item.file_path, state.cwd);
211
+ state.observedFiles.add(filePath);
212
+ state.knownExistingFiles.add(filePath);
213
+ }
214
+ }
215
+ } else if (['grep', 'glob'].includes(exec.name)) {
216
+ if (typeof args.path === 'string') {
217
+ state.observedFiles.add(normalizePath(args.path, state.cwd));
218
+ }
219
+ }
220
+ }
221
+
222
+ getSummary(session, turn) {
223
+ const state = this.stateFor(session, turn);
224
+ if (!state) {
225
+ return {
226
+ largeWriteViolations: 0,
227
+ largeWritesBlocked: 0,
228
+ fullReplacementsAllowed: 0,
229
+ editsCount: 0,
230
+ observedFiles: 0,
231
+ createdFiles: 0
232
+ };
233
+ }
234
+ return {
235
+ largeWriteViolations: state.largeWriteViolations,
236
+ largeWritesBlocked: state.largeWritesBlocked,
237
+ fullReplacementsAllowed: state.fullReplacementsAllowed,
238
+ editsCount: state.editsCount,
239
+ observedFiles: state.observedFiles.size,
240
+ createdFiles: state.createdFiles.size
241
+ };
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Apply file mutation policy to Cordis context.
247
+ */
248
+ export function applyFileMutationPolicy(ctx, rawConfig = {}) {
249
+ const config = FileMutationPolicyConfig(rawConfig);
250
+ if (config.mode === 'off') return null;
251
+
252
+ const fsService = ctx.get ? ctx.get('fs') : undefined;
253
+ const workingDirectory = ctx.get ? ctx.get('workingDirectory') : undefined;
254
+ const manager = new FileMutationPolicyManager(config, fsService, workingDirectory);
255
+
256
+ ctx.on('session/event', (session, event) => {
257
+ if (event.type === 'turn/start') {
258
+ manager.onTurnStart(session, event.data.turn);
259
+ } else if (event.type === 'turn/end') {
260
+ manager.onTurnEnd(session);
261
+ } else if (event.type === 'working-directory/change') {
262
+ manager.onCwdChange(session, event.data.cwd);
263
+ }
264
+ });
265
+
266
+ ctx.on('tools/pre-execute', async (exec, next) => {
267
+ if (!exec.agent) return next();
268
+ const effectiveFs = (ctx.get ? ctx.get('fs') : undefined) ?? manager.fsService;
269
+ const decision = await manager.evaluateToolExecution(exec.agent.session, exec, ctx.tools, effectiveFs);
270
+ if (!decision.allowed) {
271
+ return {
272
+ kind: 'deny',
273
+ reason: JSON.stringify({
274
+ code: decision.code,
275
+ reason: decision.reason,
276
+ nextAction: decision.nextAction,
277
+ retryable: decision.retryable
278
+ })
279
+ };
280
+ }
281
+ return next();
282
+ });
283
+
284
+ ctx.on('tools/result', (exec, result) => {
285
+ if (!exec.agent) return;
286
+ manager.recordResult(exec.agent.session, exec, result);
287
+ });
288
+
289
+ return manager;
290
+ }
291
+
292
+ export const name = 'agent-optimizer-file-mutation-policy';
293
+ export const Config = FileMutationPolicyConfig;
294
+ export function apply(ctx, config = {}) {
295
+ const manager = applyFileMutationPolicy(ctx, config);
296
+ if (manager) ctx.provide('fileMutationPolicy', manager);
297
+ }
298
+ export default { name, Config, apply };