@causyne/agent 1.20.99 → 1.20.103
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/causyne.js +18 -1
- package/package.json +1 -1
- package/src/agentLoop.js +81 -21
- package/src/agentLoop.ts +78 -21
- package/src/autoUpdate.js +4 -4
- package/src/autoUpdate.ts +4 -4
- package/src/cliMode.js +2 -0
- package/src/compiledSkills.d.ts +5 -0
- package/src/launchIntent.js +52 -1
- package/src/launchIntent.ts +56 -1
- package/src/plugins/pluginManager.d.ts +7 -0
- package/src/plugins/pluginSkills.js +1 -0
- package/src/plugins/pluginSkills.ts +1 -0
- package/src/promptMentions.js +1 -1
- package/src/promptMentions.ts +1 -1
- package/src/skills/skillResourceSafety.js +38 -2
- package/src/skills/skillResourceSafety.ts +39 -2
- package/src/skillsManager.js +224 -232
- package/src/skillsManager.ts +354 -0
- package/src/tools/createSkill.js +92 -104
- package/src/tools/createSkill.ts +142 -0
- package/src/tools/fsEdit.js +104 -91
- package/src/tools/fsEdit.ts +144 -0
- package/src/tools/multiEdit.js +105 -93
- package/src/tools/multiEdit.ts +145 -0
- package/src/tools/readNativeSkill.js +2 -1
- package/src/tools/readNativeSkill.ts +2 -1
- package/src/tui/mouseHover.js +0 -4
- package/src/tui/mouseHover.ts +0 -4
- package/src/tui/prompt.js +12 -0
- package/src/tui/stageSurface.js +12 -13
- package/src/userSkills.js +5 -4
- package/src/userSkills.ts +6 -4
- package/src/skillsManager.d.ts +0 -7
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Let the agent write a skill for the user.
|
|
2
|
+
//
|
|
3
|
+
// The compiled library is one library for everybody. The other half of the same
|
|
4
|
+
// idea is that the agent can WRITE one: a user explains their release process
|
|
5
|
+
// once, and it becomes a procedure the agent follows every time afterwards
|
|
6
|
+
// instead of being re-explained every session. That is the difference between a
|
|
7
|
+
// tool that remembers and a tool that does not.
|
|
8
|
+
//
|
|
9
|
+
// The contract is the one every compiled skill already meets — frontmatter with
|
|
10
|
+
// a routing description, numbered steps each closing with a checkable
|
|
11
|
+
// criterion, and a verification section. It is enforced here rather than
|
|
12
|
+
// suggested, because a skill written to a weaker standard than the library is
|
|
13
|
+
// worse than none: it dilutes the index the agent chooses from.
|
|
14
|
+
//
|
|
15
|
+
// Path safety, size limits and sanitising all live in userSkills.js, and this
|
|
16
|
+
// tool cannot reach the filesystem except through it.
|
|
17
|
+
|
|
18
|
+
import {
|
|
19
|
+
parseSkillId, writeUserSkill, userSkillsRoot, MAX_SKILL_BYTES
|
|
20
|
+
} from '../userSkills.js';
|
|
21
|
+
import { invalidateUserSkills } from '../skillsManager.js';
|
|
22
|
+
|
|
23
|
+
export interface CreateSkillArgs {
|
|
24
|
+
skill_id?: string;
|
|
25
|
+
content?: string;
|
|
26
|
+
overwrite?: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface CreateSkillResult {
|
|
30
|
+
success: boolean;
|
|
31
|
+
result?: string;
|
|
32
|
+
error?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Everything the contract requires, reported at once rather than one at a time. */
|
|
36
|
+
function contractProblems(content: string): string[] {
|
|
37
|
+
const problems: string[] = [];
|
|
38
|
+
if (!/^---\r?\n[\s\S]*?\r?\n---/.test(content)) {
|
|
39
|
+
problems.push('missing the `---` frontmatter block at the very top');
|
|
40
|
+
}
|
|
41
|
+
if (!/^description:\s*\S/m.test(content)) {
|
|
42
|
+
problems.push("frontmatter needs a `description:` — it is the ONLY thing the agent reads when deciding whether this skill applies, so write it as \"what this does. Use when …\"");
|
|
43
|
+
}
|
|
44
|
+
if (!/^name:\s*\S/m.test(content)) {
|
|
45
|
+
problems.push('frontmatter needs a `name:`');
|
|
46
|
+
}
|
|
47
|
+
if (!/\*\*Done when:\*\*/.test(content)) {
|
|
48
|
+
problems.push("no step ends with a `**Done when:**` criterion — without one this is a description of a task, not a procedure someone can follow to a known end");
|
|
49
|
+
}
|
|
50
|
+
if (!/##\s+Verification/i.test(content)) {
|
|
51
|
+
problems.push('no `## Verification` section — a skill has to say how to confirm it worked');
|
|
52
|
+
}
|
|
53
|
+
return problems;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export const createSkill = {
|
|
57
|
+
schema: {
|
|
58
|
+
name: 'skill_create',
|
|
59
|
+
description:
|
|
60
|
+
"Write a reusable skill into the user's own skill library so it is available in every future session. Use when the user describes a procedure specific to them — their "
|
|
61
|
+
+ 'deployment steps, their review checklist, their project conventions — that would '
|
|
62
|
+
+ 'otherwise have to be explained again next time. Ask the user before writing one they '
|
|
63
|
+
+ 'did not request. The body must follow the skill contract: frontmatter with name and a '
|
|
64
|
+
+ '"Use when ..." description, numbered steps each ending with a "**Done when:**" line, '
|
|
65
|
+
+ 'and a closing "## Verification" section.',
|
|
66
|
+
parameters: {
|
|
67
|
+
type: 'object',
|
|
68
|
+
properties: {
|
|
69
|
+
skill_id: {
|
|
70
|
+
type: 'string',
|
|
71
|
+
description:
|
|
72
|
+
"Where it lives, as \"domain/name\". Both are lowercase letters, digits and hyphens. Use an existing domain (web, devops, python, testing, security, design, …) when the "
|
|
73
|
+
+ 'skill belongs to one, or a new domain of the user\'s own such as "team" or the '
|
|
74
|
+
+ 'project name. Example: team/release-checklist'
|
|
75
|
+
},
|
|
76
|
+
content: {
|
|
77
|
+
type: 'string',
|
|
78
|
+
description:
|
|
79
|
+
"The complete SKILL.md, starting with the --- frontmatter block. Write the procedure, not an essay: the steps someone would actually take, in order, each with a "
|
|
80
|
+
+ 'checkable "**Done when:**" line, closing with "## Verification".'
|
|
81
|
+
},
|
|
82
|
+
overwrite: {
|
|
83
|
+
type: 'boolean',
|
|
84
|
+
description:
|
|
85
|
+
"Replace an existing skill of the same id. Defaults to false. Only set this when the user has asked for that specific skill to be rewritten."
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
required: ['skill_id', 'content']
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
|
|
92
|
+
execute: async (args: CreateSkillArgs = {}): Promise<CreateSkillResult> => {
|
|
93
|
+
const parsed = parseSkillId(args.skill_id);
|
|
94
|
+
if ('error' in parsed && parsed.error) return { success: false, error: parsed.error };
|
|
95
|
+
if (!parsed.domain || !parsed.name) return { success: false, error: 'Invalid skill id' };
|
|
96
|
+
|
|
97
|
+
const content = typeof args.content === 'string' ? args.content : '';
|
|
98
|
+
if (!content.trim()) {
|
|
99
|
+
return { success: false, error: 'content is required — write the whole SKILL.md' };
|
|
100
|
+
}
|
|
101
|
+
if (Buffer.byteLength(content, 'utf8') > MAX_SKILL_BYTES) {
|
|
102
|
+
return {
|
|
103
|
+
success: false,
|
|
104
|
+
error: `the skill is larger than the ${MAX_SKILL_BYTES / 1024} KB limit. A skill this long `
|
|
105
|
+
+ 'will crowd out the task it is meant to help with — split it, or move the detail into '
|
|
106
|
+
+ 'the step that needs it.'
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const problems = contractProblems(content);
|
|
111
|
+
if (problems.length > 0) {
|
|
112
|
+
return {
|
|
113
|
+
success: false,
|
|
114
|
+
error: 'the skill does not meet the contract:\n'
|
|
115
|
+
+ problems.map((problem) => ` - ${problem}`).join('\n')
|
|
116
|
+
+ '\n\nRewrite it with those fixed and call skill_create again.'
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const written = writeUserSkill({
|
|
121
|
+
domain: parsed.domain,
|
|
122
|
+
name: parsed.name,
|
|
123
|
+
content,
|
|
124
|
+
overwrite: args.overwrite === true
|
|
125
|
+
});
|
|
126
|
+
if (!written.ok) return { success: false, error: written.error ?? 'could not write skill' };
|
|
127
|
+
|
|
128
|
+
// The catalogue is cached; a skill written now must be visible now.
|
|
129
|
+
invalidateUserSkills();
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
success: true,
|
|
133
|
+
result: `Wrote ${parsed.domain}/${parsed.name} to ${written.path}\n\n`
|
|
134
|
+
+ `It is now in the user's library alongside the built-in skills, and it shadows a `
|
|
135
|
+
+ `built-in of the same id. They can see it with /skill mine, read it with `
|
|
136
|
+
+ `/skills ${parsed.domain}/${parsed.name}, and edit the file directly at `
|
|
137
|
+
+ `${userSkillsRoot()}.`
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
export default createSkill;
|
package/src/tools/fsEdit.js
CHANGED
|
@@ -1,105 +1,118 @@
|
|
|
1
|
-
import fs from 'fs/promises';
|
|
2
|
-
import os from 'os';
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { atomicWriteFileSync } from '../infra/atomicWriter.js';
|
|
5
5
|
function getLevenshteinDistance(a, b) {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
6
|
+
const matrix = Array(a.length + 1)
|
|
7
|
+
.fill(null)
|
|
8
|
+
.map(() => Array(b.length + 1).fill(0));
|
|
9
|
+
for (let i = 0; i <= a.length; i++)
|
|
10
|
+
matrix[i][0] = i;
|
|
11
|
+
for (let j = 0; j <= b.length; j++)
|
|
12
|
+
matrix[0][j] = j;
|
|
13
|
+
for (let i = 1; i <= a.length; i++) {
|
|
14
|
+
for (let j = 1; j <= b.length; j++) {
|
|
15
|
+
const indicator = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
16
|
+
matrix[i][j] = Math.min(matrix[i - 1][j] + 1, // deletion
|
|
17
|
+
matrix[i][j - 1] + 1, // insertion
|
|
18
|
+
matrix[i - 1][j - 1] + indicator // substitution
|
|
19
|
+
);
|
|
20
|
+
}
|
|
19
21
|
}
|
|
20
|
-
|
|
21
|
-
return matrix[a.length][b.length];
|
|
22
|
+
return matrix[a.length][b.length];
|
|
22
23
|
}
|
|
23
|
-
|
|
24
24
|
function calculateConfidence(original, match) {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
25
|
+
const dist = getLevenshteinDistance(original, match);
|
|
26
|
+
const maxLen = Math.max(original.length, match.length);
|
|
27
|
+
if (maxLen === 0)
|
|
28
|
+
return 100;
|
|
29
|
+
return ((maxLen - dist) / maxLen) * 100;
|
|
29
30
|
}
|
|
30
|
-
|
|
31
31
|
export const fsEdit = {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
type: 'object',
|
|
37
|
-
properties: {
|
|
38
|
-
path: { type: 'string' },
|
|
39
|
-
edits: {
|
|
40
|
-
type: 'array',
|
|
41
|
-
items: {
|
|
32
|
+
schema: {
|
|
33
|
+
name: 'fs.edit',
|
|
34
|
+
description: 'Surgically edit specific lines/blocks in a file. Employs 90% confidence Levenshtein fuzzy matching if exact match fails.',
|
|
35
|
+
parameters: {
|
|
42
36
|
type: 'object',
|
|
43
37
|
properties: {
|
|
44
|
-
|
|
45
|
-
|
|
38
|
+
path: { type: 'string' },
|
|
39
|
+
edits: {
|
|
40
|
+
type: 'array',
|
|
41
|
+
items: {
|
|
42
|
+
type: 'object',
|
|
43
|
+
properties: {
|
|
44
|
+
searchContent: { type: 'string' },
|
|
45
|
+
replaceContent: { type: 'string' }
|
|
46
|
+
},
|
|
47
|
+
required: ['searchContent', 'replaceContent']
|
|
48
|
+
}
|
|
49
|
+
}
|
|
46
50
|
},
|
|
47
|
-
required: ['
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
},
|
|
51
|
-
required: ['path', 'edits']
|
|
52
|
-
}
|
|
53
|
-
},
|
|
54
|
-
async execute(args) {
|
|
55
|
-
try {
|
|
56
|
-
const target = args.path.replace(/^~\//, os.homedir() + '/');
|
|
57
|
-
let originalContent = await fs.readFile(target, 'utf8');
|
|
58
|
-
let workingContent = originalContent; // Phase 3 AGI Upgrade: Atomic Rollback prep
|
|
59
|
-
|
|
60
|
-
let replacements = 0;
|
|
61
|
-
for (let i = 0; i < args.edits.length; i++) {
|
|
62
|
-
const edit = args.edits[i];
|
|
63
|
-
|
|
64
|
-
// Try exact match first
|
|
65
|
-
if (workingContent.includes(edit.searchContent)) {
|
|
66
|
-
workingContent = workingContent.replace(edit.searchContent, edit.replaceContent);
|
|
67
|
-
replacements++;
|
|
68
|
-
continue;
|
|
51
|
+
required: ['path', 'edits']
|
|
69
52
|
}
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
53
|
+
},
|
|
54
|
+
async execute(args) {
|
|
55
|
+
try {
|
|
56
|
+
if (!args || typeof args !== 'object') {
|
|
57
|
+
return { success: false, error: 'fs_edit requires an object with path and edits array.' };
|
|
58
|
+
}
|
|
59
|
+
if (typeof args.path !== 'string' || !args.path.trim()) {
|
|
60
|
+
return { success: false, error: 'fs_edit requires a non-empty string path.' };
|
|
61
|
+
}
|
|
62
|
+
if (!Array.isArray(args.edits) || args.edits.length === 0) {
|
|
63
|
+
return { success: false, error: 'fs_edit requires a non-empty edits array.' };
|
|
64
|
+
}
|
|
65
|
+
const targetPath = args.path.trim();
|
|
66
|
+
const target = targetPath.startsWith('~/') || targetPath.startsWith('~\\')
|
|
67
|
+
? path.join(os.homedir(), targetPath.slice(2))
|
|
68
|
+
: path.resolve(targetPath);
|
|
69
|
+
const originalContent = await fs.readFile(target, 'utf8');
|
|
70
|
+
let workingContent = originalContent;
|
|
71
|
+
let replacements = 0;
|
|
72
|
+
for (let i = 0; i < args.edits.length; i++) {
|
|
73
|
+
const edit = args.edits[i];
|
|
74
|
+
if (!edit || typeof edit.searchContent !== 'string' || typeof edit.replaceContent !== 'string') {
|
|
75
|
+
return {
|
|
76
|
+
success: false,
|
|
77
|
+
error: `ATOMIC ROLLBACK: Edit index ${i} is missing valid searchContent or replaceContent strings. Rollback complete.`
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
// Try exact match first
|
|
81
|
+
if (workingContent.includes(edit.searchContent)) {
|
|
82
|
+
workingContent = workingContent.replace(edit.searchContent, edit.replaceContent);
|
|
83
|
+
replacements++;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
// Fuzzy Match Fallback
|
|
87
|
+
const lines = workingContent.split('\n');
|
|
88
|
+
const oldLines = edit.searchContent.split('\n');
|
|
89
|
+
let bestMatch = null;
|
|
90
|
+
let highestConfidence = 0;
|
|
91
|
+
for (let j = 0; j <= lines.length - oldLines.length; j++) {
|
|
92
|
+
const chunk = lines.slice(j, j + oldLines.length).join('\n');
|
|
93
|
+
const conf = calculateConfidence(edit.searchContent, chunk);
|
|
94
|
+
if (conf > highestConfidence) {
|
|
95
|
+
highestConfidence = conf;
|
|
96
|
+
bestMatch = chunk;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (highestConfidence >= 90 && bestMatch) {
|
|
100
|
+
workingContent = workingContent.replace(bestMatch, edit.replaceContent);
|
|
101
|
+
replacements++;
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
return {
|
|
105
|
+
success: false,
|
|
106
|
+
error: `ATOMIC ROLLBACK: Edit index ${i} failed. Exact match not found, and fuzzy match confidence was too low (${highestConfidence.toFixed(2)}% < 90%). Previous edits in this batch were rolled back.`
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
// Commit the transaction atomically
|
|
111
|
+
atomicWriteFileSync(target, workingContent, { encoding: 'utf8' });
|
|
112
|
+
return { success: true, output: `Transaction Success: ${replacements} replacement(s) safely applied to ${args.path}` };
|
|
84
113
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
workingContent = workingContent.replace(bestMatch, edit.replaceContent);
|
|
88
|
-
replacements++;
|
|
89
|
-
} else {
|
|
90
|
-
// Atomic Rollback
|
|
91
|
-
return {
|
|
92
|
-
success: false,
|
|
93
|
-
error: `ATOMIC ROLLBACK: Edit index ${i} failed. Exact match not found, and fuzzy match confidence was too low (${highestConfidence.toFixed(2)}% < 90%). Previous edits in this batch were rolled back.`
|
|
94
|
-
};
|
|
114
|
+
catch (e) {
|
|
115
|
+
return { success: false, error: e instanceof Error ? e.message : String(e) };
|
|
95
116
|
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// Commit the transaction
|
|
99
|
-
await fs.writeFile(target, workingContent, 'utf8');
|
|
100
|
-
return { success: true, output: `Transaction Success: ${replacements} replacement(s) safely applied to ${args.path}` };
|
|
101
|
-
} catch (e) {
|
|
102
|
-
return { success: false, error: e.message };
|
|
103
117
|
}
|
|
104
|
-
}
|
|
105
118
|
};
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { atomicWriteFileSync } from '../infra/atomicWriter.js';
|
|
5
|
+
|
|
6
|
+
export interface FsEditItem {
|
|
7
|
+
searchContent: string;
|
|
8
|
+
replaceContent: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface FsEditArgs {
|
|
12
|
+
path: string;
|
|
13
|
+
edits: FsEditItem[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface FsEditResult {
|
|
17
|
+
success: boolean;
|
|
18
|
+
output?: string;
|
|
19
|
+
error?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function getLevenshteinDistance(a: string, b: string): number {
|
|
23
|
+
const matrix: number[][] = Array(a.length + 1)
|
|
24
|
+
.fill(null)
|
|
25
|
+
.map(() => Array(b.length + 1).fill(0));
|
|
26
|
+
|
|
27
|
+
for (let i = 0; i <= a.length; i++) matrix[i]![0] = i;
|
|
28
|
+
for (let j = 0; j <= b.length; j++) matrix[0]![j] = j;
|
|
29
|
+
|
|
30
|
+
for (let i = 1; i <= a.length; i++) {
|
|
31
|
+
for (let j = 1; j <= b.length; j++) {
|
|
32
|
+
const indicator = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
33
|
+
matrix[i]![j] = Math.min(
|
|
34
|
+
matrix[i - 1]![j]! + 1, // deletion
|
|
35
|
+
matrix[i]![j - 1]! + 1, // insertion
|
|
36
|
+
matrix[i - 1]![j - 1]! + indicator // substitution
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return matrix[a.length]![b.length]!;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function calculateConfidence(original: string, match: string): number {
|
|
44
|
+
const dist = getLevenshteinDistance(original, match);
|
|
45
|
+
const maxLen = Math.max(original.length, match.length);
|
|
46
|
+
if (maxLen === 0) return 100;
|
|
47
|
+
return ((maxLen - dist) / maxLen) * 100;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export const fsEdit = {
|
|
51
|
+
schema: {
|
|
52
|
+
name: 'fs.edit',
|
|
53
|
+
description: 'Surgically edit specific lines/blocks in a file. Employs 90% confidence Levenshtein fuzzy matching if exact match fails.',
|
|
54
|
+
parameters: {
|
|
55
|
+
type: 'object',
|
|
56
|
+
properties: {
|
|
57
|
+
path: { type: 'string' },
|
|
58
|
+
edits: {
|
|
59
|
+
type: 'array',
|
|
60
|
+
items: {
|
|
61
|
+
type: 'object',
|
|
62
|
+
properties: {
|
|
63
|
+
searchContent: { type: 'string' },
|
|
64
|
+
replaceContent: { type: 'string' }
|
|
65
|
+
},
|
|
66
|
+
required: ['searchContent', 'replaceContent']
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
required: ['path', 'edits']
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
|
|
74
|
+
async execute(args: FsEditArgs): Promise<FsEditResult> {
|
|
75
|
+
try {
|
|
76
|
+
if (!args || typeof args !== 'object') {
|
|
77
|
+
return { success: false, error: 'fs_edit requires an object with path and edits array.' };
|
|
78
|
+
}
|
|
79
|
+
if (typeof args.path !== 'string' || !args.path.trim()) {
|
|
80
|
+
return { success: false, error: 'fs_edit requires a non-empty string path.' };
|
|
81
|
+
}
|
|
82
|
+
if (!Array.isArray(args.edits) || args.edits.length === 0) {
|
|
83
|
+
return { success: false, error: 'fs_edit requires a non-empty edits array.' };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const targetPath = args.path.trim();
|
|
87
|
+
const target = targetPath.startsWith('~/') || targetPath.startsWith('~\\')
|
|
88
|
+
? path.join(os.homedir(), targetPath.slice(2))
|
|
89
|
+
: path.resolve(targetPath);
|
|
90
|
+
|
|
91
|
+
const originalContent = await fs.readFile(target, 'utf8');
|
|
92
|
+
let workingContent = originalContent;
|
|
93
|
+
let replacements = 0;
|
|
94
|
+
|
|
95
|
+
for (let i = 0; i < args.edits.length; i++) {
|
|
96
|
+
const edit = args.edits[i];
|
|
97
|
+
if (!edit || typeof edit.searchContent !== 'string' || typeof edit.replaceContent !== 'string') {
|
|
98
|
+
return {
|
|
99
|
+
success: false,
|
|
100
|
+
error: `ATOMIC ROLLBACK: Edit index ${i} is missing valid searchContent or replaceContent strings. Rollback complete.`
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Try exact match first
|
|
105
|
+
if (workingContent.includes(edit.searchContent)) {
|
|
106
|
+
workingContent = workingContent.replace(edit.searchContent, edit.replaceContent);
|
|
107
|
+
replacements++;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Fuzzy Match Fallback
|
|
112
|
+
const lines = workingContent.split('\n');
|
|
113
|
+
const oldLines = edit.searchContent.split('\n');
|
|
114
|
+
let bestMatch: string | null = null;
|
|
115
|
+
let highestConfidence = 0;
|
|
116
|
+
|
|
117
|
+
for (let j = 0; j <= lines.length - oldLines.length; j++) {
|
|
118
|
+
const chunk = lines.slice(j, j + oldLines.length).join('\n');
|
|
119
|
+
const conf = calculateConfidence(edit.searchContent, chunk);
|
|
120
|
+
if (conf > highestConfidence) {
|
|
121
|
+
highestConfidence = conf;
|
|
122
|
+
bestMatch = chunk;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (highestConfidence >= 90 && bestMatch) {
|
|
127
|
+
workingContent = workingContent.replace(bestMatch, edit.replaceContent);
|
|
128
|
+
replacements++;
|
|
129
|
+
} else {
|
|
130
|
+
return {
|
|
131
|
+
success: false,
|
|
132
|
+
error: `ATOMIC ROLLBACK: Edit index ${i} failed. Exact match not found, and fuzzy match confidence was too low (${highestConfidence.toFixed(2)}% < 90%). Previous edits in this batch were rolled back.`
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Commit the transaction atomically
|
|
138
|
+
atomicWriteFileSync(target, workingContent, { encoding: 'utf8' });
|
|
139
|
+
return { success: true, output: `Transaction Success: ${replacements} replacement(s) safely applied to ${args.path}` };
|
|
140
|
+
} catch (e: unknown) {
|
|
141
|
+
return { success: false, error: e instanceof Error ? e.message : String(e) };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
};
|