@causyne/agent 1.20.100 → 1.20.104

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,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
+ };
@@ -1,7 +1,46 @@
1
- import { exec } from 'child_process';
2
- import os from 'os';
1
+ import { execFile } from 'node:child_process';
2
+ import os from 'node:os';
3
3
  import { currentToolAutonomyMode } from '../approvalPolicy.js';
4
4
 
5
+ /**
6
+ * Parse the documented Git subcommand syntax without invoking a shell.
7
+ * Quoted commit messages and filenames are preserved as single arguments.
8
+ */
9
+ export function parseGitArguments(raw) {
10
+ if (typeof raw !== 'string' || !raw.trim()) throw new Error('A Git subcommand is required.');
11
+ const argv = [];
12
+ let token = '';
13
+ let quote = null;
14
+ let started = false;
15
+ for (let i = 0; i < raw.length; i++) {
16
+ const char = raw.charAt(i);
17
+ const next = raw.charAt(i + 1);
18
+ if (char === '\\' && quote !== "'" && next && /[\\\s"'\\]/.test(next)) {
19
+ token += next;
20
+ started = true;
21
+ i++;
22
+ continue;
23
+ }
24
+ if (char === '"' || char === "'") {
25
+ if (!quote) { quote = char; started = true; continue; }
26
+ if (quote === char) { quote = null; continue; }
27
+ }
28
+ if (!quote && /[;&|><`$()\r\n]/.test(char)) {
29
+ throw new Error('Git commands must contain one subcommand, without shell operators or substitution.');
30
+ }
31
+ if (!quote && /\s/.test(char)) {
32
+ if (started) { argv.push(token); token = ''; started = false; }
33
+ continue;
34
+ }
35
+ token += char;
36
+ started = true;
37
+ }
38
+ if (quote) throw new Error('Unterminated quote in Git command.');
39
+ if (started) argv.push(token);
40
+ if (!argv.length) throw new Error('A Git subcommand is required.');
41
+ return argv;
42
+ }
43
+
5
44
  export const gitExec = {
6
45
  schema: {
7
46
  name: 'gitOp',
@@ -16,39 +55,40 @@ export const gitExec = {
16
55
  }
17
56
  },
18
57
  async execute(args) {
19
- const cwd = (args.cwd || process.cwd()).replace(/^~\//, os.homedir() + '/');
20
- let cmdString = args.command;
21
-
22
- // Phase 5 AGI Upgrade: Boundary Conditions
23
- if (cmdString.includes('-i') || cmdString.includes('interactive')) {
24
- return { success: false, error: 'Interactive workflows (e.g., rebase -i) are strictly forbidden in AGI automation. Use precise non-interactive commands.' };
25
- }
26
-
27
- if ((cmdString.includes('push -f') || cmdString.includes('push --force') || cmdString.includes('branch -D'))
28
- && currentToolAutonomyMode() === undefined) {
58
+ const cwd = String(args?.cwd || process.cwd()).replace(/^~\//, os.homedir() + '/');
59
+ let argv;
60
+ try {
61
+ argv = parseGitArguments(args?.command);
62
+ } catch (error) {
63
+ return { success: false, error: error.message };
64
+ }
65
+
66
+ const subcommand = argv[0];
67
+ if (subcommand === 'rebase' && argv.some(arg => arg === '-i' || arg === '--interactive')) {
68
+ return { success: false, error: 'Interactive Git rebase is not supported. Use precise non-interactive commands.' };
69
+ }
70
+ const forcingPush = subcommand === 'push' && argv.slice(1).some(arg => arg === '-f' || arg === '--force' || arg.startsWith('--force-with-lease'));
71
+ const forcingBranch = subcommand === 'branch' && argv.includes('-D');
72
+ if ((forcingPush || forcingBranch) && currentToolAutonomyMode() === undefined) {
29
73
  return { success: false, error: 'Destructive Git action requires the agent session approval and sandbox policy.' };
30
74
  }
31
75
 
32
- const command = `git ${cmdString}`;
33
-
34
- return new Promise((resolve) => {
35
- exec(command, { cwd, maxBuffer: 5 * 1024 * 1024 }, (error, stdout, stderr) => {
76
+ return new Promise(resolve => {
77
+ // Never use a shell here: gitOp is a structured tool, not an arbitrary shell.
78
+ execFile('git', argv, { cwd, maxBuffer: 5 * 1024 * 1024 }, (error, stdout, stderr) => {
36
79
  const fullOutput = (stdout || '') + '\n' + (stderr || '');
37
-
38
- // Phase 5 AGI Upgrade: Autonomous Conflict Detection
39
80
  if (fullOutput.includes('CONFLICT (content): Merge conflict')) {
40
- resolve({
41
- success: false,
42
- error: `[AUTONOMOUS CONFLICT DETECTED]\nGit merge conflict occurred. DO NOT PANIC.\n1. Use fs.read to read the conflicted files.\n2. Analyze the <<<<<<< HEAD markers.\n3. Use fs.edit to surgically resolve the conflict.\n4. Run git add and git commit.`,
43
- output: fullOutput
81
+ resolve({
82
+ success: false,
83
+ error: '[AUTONOMOUS CONFLICT DETECTED] Git merge conflict occurred. Inspect conflicted files, resolve exact markers and verify before continuing.',
84
+ output: fullOutput
44
85
  });
45
86
  return;
46
87
  }
47
-
48
88
  if (error) {
49
89
  resolve({ success: false, output: stdout, error: stderr || error.message, exitCode: error.code });
50
90
  } else {
51
- resolve({ success: true, output: stdout || stderr, exitCode: 0 });
91
+ resolve({ success: true, output: stdout || stderr, exitCode: 0 });
52
92
  }
53
93
  });
54
94
  });
@@ -1,107 +1,119 @@
1
- import fs from 'fs/promises';
2
- import os from 'os';
3
-
4
- // Phase 3 AGI Upgrade: Fast Levenshtein Distance for Fuzzy Matching
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
- const matrix = Array(a.length + 1).fill(null).map(() => Array(b.length + 1).fill(null));
7
-
8
- for (let i = 0; i <= a.length; i++) matrix[i][0] = i;
9
- for (let j = 0; j <= b.length; j++) matrix[0][j] = j;
10
-
11
- for (let i = 1; i <= a.length; i++) {
12
- for (let j = 1; j <= b.length; j++) {
13
- const indicator = a[i - 1] === b[j - 1] ? 0 : 1;
14
- matrix[i][j] = Math.min(
15
- matrix[i - 1][j] + 1, // deletion
16
- matrix[i][j - 1] + 1, // insertion
17
- matrix[i - 1][j - 1] + indicator // substitution
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
- const dist = getLevenshteinDistance(original, match);
26
- const maxLen = Math.max(original.length, match.length);
27
- if (maxLen === 0) return 100;
28
- return ((maxLen - dist) / maxLen) * 100;
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 multiEdit = {
32
- schema: {
33
- name: 'MultiEdit',
34
- description: 'Make multiple edits to a single file atomically. Replaces old_string with new_string. If exact match fails, uses fuzzy matching (requires 90% confidence). Includes atomic rollback.',
35
- parameters: {
36
- type: 'object',
37
- properties: {
38
- file_path: { type: 'string' },
39
- edits: {
40
- type: 'array',
41
- items: {
32
+ schema: {
33
+ name: 'MultiEdit',
34
+ description: 'Make multiple edits to a single file atomically. Replaces old_string with new_string. If exact match fails, uses fuzzy matching (requires 90% confidence). Includes atomic rollback.',
35
+ parameters: {
42
36
  type: 'object',
43
37
  properties: {
44
- old_string: { type: 'string' },
45
- new_string: { type: 'string' }
38
+ file_path: { type: 'string' },
39
+ edits: {
40
+ type: 'array',
41
+ items: {
42
+ type: 'object',
43
+ properties: {
44
+ old_string: { type: 'string' },
45
+ new_string: { type: 'string' }
46
+ },
47
+ required: ['old_string', 'new_string']
48
+ },
49
+ minItems: 1
50
+ }
46
51
  },
47
- required: ['old_string', 'new_string']
48
- },
49
- minItems: 1
50
- }
51
- },
52
- required: ['file_path', 'edits']
53
- }
54
- },
55
- async execute(args) {
56
- try {
57
- const target = args.file_path.replace(/^~\//, os.homedir() + '/');
58
- let originalContent = await fs.readFile(target, 'utf8');
59
- let workingContent = originalContent; // Phase 3 AGI Upgrade: Atomic Rollback prep
60
-
61
- let replacements = 0;
62
- for (let i = 0; i < args.edits.length; i++) {
63
- const edit = args.edits[i];
64
-
65
- // Try exact match first
66
- if (workingContent.includes(edit.old_string)) {
67
- workingContent = workingContent.replace(edit.old_string, edit.new_string);
68
- replacements++;
69
- continue;
52
+ required: ['file_path', 'edits']
70
53
  }
71
-
72
- // Phase 3 AGI Upgrade: Fuzzy Match Fallback
73
- // Find the best sliding window match (simplified for performance: split by line, scan chunks)
74
- const lines = workingContent.split('\n');
75
- const oldLines = edit.old_string.split('\n');
76
- let bestMatch = null;
77
- let highestConfidence = 0;
78
-
79
- for (let j = 0; j <= lines.length - oldLines.length; j++) {
80
- const chunk = lines.slice(j, j + oldLines.length).join('\n');
81
- const conf = calculateConfidence(edit.old_string, chunk);
82
- if (conf > highestConfidence) {
83
- highestConfidence = conf;
84
- bestMatch = chunk;
85
- }
54
+ },
55
+ async execute(args) {
56
+ try {
57
+ if (!args || typeof args !== 'object') {
58
+ return { success: false, error: 'MultiEdit requires an object with file_path and edits array.' };
59
+ }
60
+ if (typeof args.file_path !== 'string' || !args.file_path.trim()) {
61
+ return { success: false, error: 'MultiEdit requires a non-empty string file_path.' };
62
+ }
63
+ if (!Array.isArray(args.edits) || args.edits.length === 0) {
64
+ return { success: false, error: 'MultiEdit requires a non-empty edits array.' };
65
+ }
66
+ const rawPath = args.file_path.trim();
67
+ const target = rawPath.startsWith('~/') || rawPath.startsWith('~\\')
68
+ ? path.join(os.homedir(), rawPath.slice(2))
69
+ : path.resolve(rawPath);
70
+ const originalContent = await fs.readFile(target, 'utf8');
71
+ let workingContent = originalContent;
72
+ let replacements = 0;
73
+ for (let i = 0; i < args.edits.length; i++) {
74
+ const edit = args.edits[i];
75
+ if (!edit || typeof edit.old_string !== 'string' || typeof edit.new_string !== 'string') {
76
+ return {
77
+ success: false,
78
+ error: `ATOMIC ROLLBACK: Edit index ${i} is missing valid old_string or new_string. Rollback complete.`
79
+ };
80
+ }
81
+ // Try exact match first
82
+ if (workingContent.includes(edit.old_string)) {
83
+ workingContent = workingContent.replace(edit.old_string, edit.new_string);
84
+ replacements++;
85
+ continue;
86
+ }
87
+ // Fuzzy Match Fallback
88
+ const lines = workingContent.split('\n');
89
+ const oldLines = edit.old_string.split('\n');
90
+ let bestMatch = null;
91
+ let highestConfidence = 0;
92
+ for (let j = 0; j <= lines.length - oldLines.length; j++) {
93
+ const chunk = lines.slice(j, j + oldLines.length).join('\n');
94
+ const conf = calculateConfidence(edit.old_string, chunk);
95
+ if (conf > highestConfidence) {
96
+ highestConfidence = conf;
97
+ bestMatch = chunk;
98
+ }
99
+ }
100
+ if (highestConfidence >= 90 && bestMatch) {
101
+ workingContent = workingContent.replace(bestMatch, edit.new_string);
102
+ replacements++;
103
+ }
104
+ else {
105
+ return {
106
+ success: false,
107
+ 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.`
108
+ };
109
+ }
110
+ }
111
+ // Commit the transaction atomically
112
+ atomicWriteFileSync(target, workingContent, { encoding: 'utf8' });
113
+ return { success: true, output: `Transaction Success: ${replacements} atomic edits applied to ${args.file_path}` };
86
114
  }
87
-
88
- if (highestConfidence >= 90 && bestMatch) {
89
- workingContent = workingContent.replace(bestMatch, edit.new_string);
90
- replacements++;
91
- } else {
92
- // Atomic Rollback
93
- return {
94
- success: false,
95
- 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.`
96
- };
115
+ catch (e) {
116
+ return { success: false, error: e instanceof Error ? e.message : String(e) };
97
117
  }
98
- }
99
-
100
- // Commit the transaction
101
- await fs.writeFile(target, workingContent, 'utf8');
102
- return { success: true, output: `Transaction Success: ${replacements} atomic edits applied to ${args.file_path}` };
103
- } catch (e) {
104
- return { success: false, error: e.message };
105
118
  }
106
- }
107
119
  };
@@ -0,0 +1,145 @@
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 MultiEditItem {
7
+ old_string: string;
8
+ new_string: string;
9
+ }
10
+
11
+ export interface MultiEditArgs {
12
+ file_path: string;
13
+ edits: MultiEditItem[];
14
+ }
15
+
16
+ export interface MultiEditResult {
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 multiEdit = {
51
+ schema: {
52
+ name: 'MultiEdit',
53
+ description: 'Make multiple edits to a single file atomically. Replaces old_string with new_string. If exact match fails, uses fuzzy matching (requires 90% confidence). Includes atomic rollback.',
54
+ parameters: {
55
+ type: 'object',
56
+ properties: {
57
+ file_path: { type: 'string' },
58
+ edits: {
59
+ type: 'array',
60
+ items: {
61
+ type: 'object',
62
+ properties: {
63
+ old_string: { type: 'string' },
64
+ new_string: { type: 'string' }
65
+ },
66
+ required: ['old_string', 'new_string']
67
+ },
68
+ minItems: 1
69
+ }
70
+ },
71
+ required: ['file_path', 'edits']
72
+ }
73
+ },
74
+
75
+ async execute(args: MultiEditArgs): Promise<MultiEditResult> {
76
+ try {
77
+ if (!args || typeof args !== 'object') {
78
+ return { success: false, error: 'MultiEdit requires an object with file_path and edits array.' };
79
+ }
80
+ if (typeof args.file_path !== 'string' || !args.file_path.trim()) {
81
+ return { success: false, error: 'MultiEdit requires a non-empty string file_path.' };
82
+ }
83
+ if (!Array.isArray(args.edits) || args.edits.length === 0) {
84
+ return { success: false, error: 'MultiEdit requires a non-empty edits array.' };
85
+ }
86
+
87
+ const rawPath = args.file_path.trim();
88
+ const target = rawPath.startsWith('~/') || rawPath.startsWith('~\\')
89
+ ? path.join(os.homedir(), rawPath.slice(2))
90
+ : path.resolve(rawPath);
91
+
92
+ const originalContent = await fs.readFile(target, 'utf8');
93
+ let workingContent = originalContent;
94
+ let replacements = 0;
95
+
96
+ for (let i = 0; i < args.edits.length; i++) {
97
+ const edit = args.edits[i];
98
+ if (!edit || typeof edit.old_string !== 'string' || typeof edit.new_string !== 'string') {
99
+ return {
100
+ success: false,
101
+ error: `ATOMIC ROLLBACK: Edit index ${i} is missing valid old_string or new_string. Rollback complete.`
102
+ };
103
+ }
104
+
105
+ // Try exact match first
106
+ if (workingContent.includes(edit.old_string)) {
107
+ workingContent = workingContent.replace(edit.old_string, edit.new_string);
108
+ replacements++;
109
+ continue;
110
+ }
111
+
112
+ // Fuzzy Match Fallback
113
+ const lines = workingContent.split('\n');
114
+ const oldLines = edit.old_string.split('\n');
115
+ let bestMatch: string | null = null;
116
+ let highestConfidence = 0;
117
+
118
+ for (let j = 0; j <= lines.length - oldLines.length; j++) {
119
+ const chunk = lines.slice(j, j + oldLines.length).join('\n');
120
+ const conf = calculateConfidence(edit.old_string, chunk);
121
+ if (conf > highestConfidence) {
122
+ highestConfidence = conf;
123
+ bestMatch = chunk;
124
+ }
125
+ }
126
+
127
+ if (highestConfidence >= 90 && bestMatch) {
128
+ workingContent = workingContent.replace(bestMatch, edit.new_string);
129
+ replacements++;
130
+ } else {
131
+ return {
132
+ success: false,
133
+ 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.`
134
+ };
135
+ }
136
+ }
137
+
138
+ // Commit the transaction atomically
139
+ atomicWriteFileSync(target, workingContent, { encoding: 'utf8' });
140
+ return { success: true, output: `Transaction Success: ${replacements} atomic edits applied to ${args.file_path}` };
141
+ } catch (e: unknown) {
142
+ return { success: false, error: e instanceof Error ? e.message : String(e) };
143
+ }
144
+ }
145
+ };
@@ -84,14 +84,18 @@ function renderMarkdown(text, width) {
84
84
  continue;
85
85
  }
86
86
  if (inFence) {
87
- lines.push(paint('accent', ' ' + truncate(line, width - 2, '')));
87
+ for (const codeRow of wrapBlock(' ' + line, Math.max(8, width), { hang: 0 })) {
88
+ lines.push(paint('accent', codeRow));
89
+ }
88
90
  continue;
89
91
  }
90
92
 
91
93
  const heading = line.match(/^(#{1,6})\s+(.*)$/);
92
94
  if (heading) {
93
95
  lines.push('');
94
- lines.push(bold(paint('ink', heading[2])));
96
+ for (const headingRow of wrap(heading[2], Math.max(8, width))) {
97
+ lines.push(bold(paint('ink', headingRow)));
98
+ }
95
99
  continue;
96
100
  }
97
101
 
@@ -138,8 +142,10 @@ function renderMarkdown(text, width) {
138
142
 
139
143
  const tableRow = line.match(/^\s*\|(.+)\|\s*$/);
140
144
  if (tableRow) {
141
- const cells = tableRow[1].split('|').map(c => inline(c.trim()));
142
- lines.push(' ' + cells.join(paint('muted', ' │ ')));
145
+ const cells = tableRow[1].split('|').map(c => c.trim());
146
+ for (const tableLine of wrapBlock(' ' + cells.join(' │ '), Math.max(8, width), { hang: 0 })) {
147
+ lines.push(inline(tableLine));
148
+ }
143
149
  continue;
144
150
  }
145
151
 
@@ -824,9 +830,11 @@ export class ChatRenderer {
824
830
 
825
831
  formatAssistantMessage(content, { streaming = false } = {}) {
826
832
  const width = this.measure();
827
- this.write();
833
+ // The frame already ends with a blank separator. A leading blank row on the
834
+ // first assistant response leaves a visible void in compact chat view.
828
835
  this.write(`${paint('agent', GLYPHS.arrow)} ${bold(paint('agent', 'Causyne'))}${streaming ? ' ' + dim('…') : ''}`);
829
- for (const line of renderMarkdown(content, width - 2)) {
836
+ // Reserve the transcript's three-column inset and final safety cell.
837
+ for (const line of renderMarkdown(content, Math.max(8, width - 4))) {
830
838
  this.write(line ? ' ' + line : '');
831
839
  }
832
840
  this.write();