@causyne/agent 1.20.91 → 1.20.94

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.
Files changed (46) hide show
  1. package/package.json +1 -1
  2. package/src/agentLoop.js +116 -26
  3. package/src/agentLoop.ts +121 -26
  4. package/src/contextManager.js +2 -0
  5. package/src/decideTools.js +9 -0
  6. package/src/decideTools.ts +9 -0
  7. package/src/decisionPolicy.js +119 -1
  8. package/src/decisionPolicy.ts +129 -1
  9. package/src/historyPruner.js +16 -1
  10. package/src/historyPruner.ts +13 -1
  11. package/src/sandbox.js +33 -7
  12. package/src/skills/skillResourceSafety.js +70 -0
  13. package/src/skills/skillResourceSafety.ts +77 -0
  14. package/src/smartToolsUse.js +28 -11
  15. package/src/smartToolsUse.ts +34 -11
  16. package/src/taskShape.js +28 -13
  17. package/src/taskShape.ts +31 -12
  18. package/src/tools/codeSearcher.js +349 -210
  19. package/src/tools/codeSearcher.ts +408 -0
  20. package/src/tools/codebaseSearch.js +182 -68
  21. package/src/tools/codebaseSearch.ts +221 -0
  22. package/src/tools/deferredMcpSearch.js +94 -40
  23. package/src/tools/deferredMcpSearch.ts +89 -30
  24. package/src/tools/fsFind.js +180 -115
  25. package/src/tools/fsFind.ts +228 -0
  26. package/src/tools/fsList.js +149 -69
  27. package/src/tools/fsList.ts +224 -0
  28. package/src/tools/fsSearch.js +192 -189
  29. package/src/tools/fsSearch.ts +241 -0
  30. package/src/tools/readNativeSkill.js +34 -42
  31. package/src/tools/readNativeSkill.ts +38 -36
  32. package/src/tools/searchRelevance.js +70 -0
  33. package/src/tools/searchRelevance.ts +72 -0
  34. package/src/tools/toolSelfRepair.js +56 -20
  35. package/src/tools/toolSelfRepair.ts +58 -19
  36. package/src/tools/walkerSafety.js +445 -0
  37. package/src/tools/walkerSafety.ts +516 -0
  38. package/src/tui/composerGeometry.js +45 -0
  39. package/src/tui/composerGeometry.ts +80 -0
  40. package/src/tui/homeView.js +10 -6
  41. package/src/tui/homeView.ts +10 -6
  42. package/src/tui/lineEditor.js +8 -0
  43. package/src/tui/prompt.js +9 -4
  44. package/src/userSkills.js +183 -203
  45. package/src/userSkills.ts +301 -0
  46. package/src/userSkills.d.ts +0 -26
@@ -1,5 +1,6 @@
1
1
  import { sessionBanner, type BannerInfo } from './banner.js';
2
2
  import { centerRows } from './layout.js';
3
+ import { fitHomeContent } from './composerGeometry.js';
3
4
  import { panelRows } from './overlay.js';
4
5
 
5
6
  export interface PlacedView {
@@ -74,17 +75,20 @@ export function placeHome(
74
75
  const available = Math.max(1, Math.floor(height));
75
76
  const logo = centerRows(sessionBanner(info, columns, { height: available }), columns).rows;
76
77
  const spacer = available >= 25 ? 2 : 1;
77
- const required = logo.length + spacer + promptRows.length;
78
+ // When the window is short, preserve the composer and editing caret first.
79
+ // The logo yields height; it must never push a wrapped draft off-screen.
80
+ const fitted = fitHomeContent(logo, promptRows, available, caretRow, spacer);
81
+ const required = fitted.logoRows.length + fitted.spacer + fitted.promptRows.length;
78
82
  const top = Math.max(0, Math.floor((available - required) / 2));
79
83
  const rows = [
80
84
  ...Array<string>(top).fill(''),
81
- ...logo,
82
- ...Array<string>(spacer).fill(''),
83
- ...promptRows
85
+ ...fitted.logoRows,
86
+ ...Array<string>(fitted.spacer).fill(''),
87
+ ...fitted.promptRows
84
88
  ];
85
89
  return {
86
- rows: rows.slice(0, available),
87
- caretRow: Math.min(available - 1, top + logo.length + spacer + Math.max(0, caretRow)),
90
+ rows,
91
+ caretRow: top + fitted.logoRows.length + fitted.spacer + fitted.caretRow,
88
92
  caretCol: Math.max(0, Math.min(caretCol, columns - 2))
89
93
  };
90
94
  }
@@ -376,6 +376,14 @@ export class LineEditor {
376
376
  while (pos <= line.length) {
377
377
  if (pos === line.length) {
378
378
  if (isCurrentLine && pos === this.col && !placed) {
379
+ // An exact-width final row has no cell after its last glyph.
380
+ // Move the caret onto an empty continuation row instead of
381
+ // positioning it outside the editing surface. Preserve text.
382
+ if (used >= budget && pos > 0) {
383
+ rows.push(row);
384
+ row = prefix;
385
+ used = 0;
386
+ }
379
387
  cursorRow = rows.length;
380
388
  cursorCol = prefixWidth + used;
381
389
  placed = true;
package/src/tui/prompt.js CHANGED
@@ -24,6 +24,7 @@ import { PromptHistory } from './history.js';
24
24
  import { FileIndex, suggest, applyCompletion, detectTrigger, renderPicker, MAX_VISIBLE } from './completion.js';
25
25
  import { paint, dim, bold, GLYPHS, terminalWidth, HAS_COLOR } from './theme.js';
26
26
  import { barBlock, GUTTER } from './block.js';
27
+ import { composerGeometry } from './composerGeometry.js';
27
28
  import { visibleWidth, truncate, wrapBlock, shortenHome, safeDisplay, stripAnsi } from './text.js';
28
29
  import { pickExample, fitHints } from './banner.js';
29
30
  import { panelRows } from './overlay.js';
@@ -1603,10 +1604,14 @@ export class ChatPrompt {
1603
1604
  // surface you are writing INTO. Every row of the block is inset by the same
1604
1605
  // gutter, so the caret column is a constant rather than a special case for
1605
1606
  // row 0 — which is also one fewer thing for erase() to get wrong.
1606
- const boxWidth = Math.max(20, width - 1);
1607
- const inset = visibleWidth(GLYPHS.bar) + GUTTER;
1608
- const inner = Math.max(8, boxWidth - inset);
1609
- const layout = this.editor.render(inner, '');
1607
+ // Reserve one editor cell for the caret. The left bar and gutter are
1608
+ // consumed by barBlock; the remaining full-width body is not all editable.
1609
+ // This prevents a full sentence from placing the cursor beyond the fill.
1610
+ const { boxWidth, inset, editorWidth } = composerGeometry(
1611
+ width, visibleWidth(GLYPHS.barHeavy || GLYPHS.bar), GUTTER
1612
+ );
1613
+ const inner = editorWidth;
1614
+ const layout = this.editor.render(editorWidth, '');
1610
1615
 
1611
1616
  // Scroll the editor internally rather than growing without bound: keep a
1612
1617
  // window of MAX_PROMPT_ROWS that always contains the caret.
package/src/userSkills.js CHANGED
@@ -1,51 +1,43 @@
1
-
2
-
3
- import fs from 'fs';
4
- import os from 'os';
5
- import path from 'path';
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
6
3
  import { causyneHome } from './utils/paths.js';
7
- import { assertSkillTreeSafe } from './skills/skillResourceSafety.js';
8
-
4
+ import { assertSkillFileSafe, assertSkillTreeSafe, writeSkillFileSafely } from './skills/skillResourceSafety.js';
9
5
  // Bounds. Every one of these protects the context window, which is the resource
10
6
  // a skill library actually spends.
11
7
  export const MAX_USER_SKILLS = 200;
12
8
  export const MAX_SKILL_BYTES = 32 * 1024;
13
9
  export const MAX_DESCRIPTION = 400;
14
-
15
10
  // A skill id and a domain are path segments. Lowercase, digits and hyphens is
16
11
  // the whole alphabet — which makes traversal, drive letters, device names,
17
12
  // leading dots and spaces unrepresentable rather than merely filtered.
18
13
  const SEGMENT = /^[a-z0-9][a-z0-9-]{0,63}$/;
19
-
20
14
  // Windows reserves these as device names. A directory called `con` or `aux`
21
15
  // cannot be created there, and `nul` silently discards what is written to it —
22
16
  // so a skill named after one would work on the author's Mac and fail, or vanish,
23
17
  // for a Windows user. Vision section 3: never assume the developer's own OS.
24
18
  const RESERVED = new Set([
25
- 'con', 'prn', 'aux', 'nul',
26
- ...Array.from({ length: 9 }, (_, index) => `com${index + 1}`),
27
- ...Array.from({ length: 9 }, (_, index) => `lpt${index + 1}`)
19
+ 'con', 'prn', 'aux', 'nul',
20
+ ...Array.from({ length: 9 }, (_, index) => `com${index + 1}`),
21
+ ...Array.from({ length: 9 }, (_, index) => `lpt${index + 1}`)
28
22
  ]);
29
-
30
23
  export function userSkillsRoot() {
31
- return path.join(causyneHome(), 'skills');
24
+ return path.join(causyneHome(), 'skills');
32
25
  }
33
-
34
26
  /** Is this a usable path segment? Returns a reason when it is not. */
35
27
  export function validateSegment(value, what = 'name') {
36
- const text = String(value == null ? '' : value);
37
- if (!text) return `${what} is required`;
38
- if (!SEGMENT.test(text)) {
39
- return `${what} must be lowercase letters, digits and hyphens, starting with a letter or digit `
40
- + `(got ${JSON.stringify(text.slice(0, 40))})`;
41
- }
42
- if (RESERVED.has(text)) {
43
- return `${what} ${JSON.stringify(text)} is a reserved device name on Windows — `
44
- + 'a skill by that name would fail there. Pick another.';
45
- }
46
- return null;
28
+ const text = String(value == null ? '' : value);
29
+ if (!text)
30
+ return `${what} is required`;
31
+ if (!SEGMENT.test(text)) {
32
+ return `${what} must be lowercase letters, digits and hyphens, starting with a letter or digit `
33
+ + `(got ${JSON.stringify(text.slice(0, 40))})`;
34
+ }
35
+ if (RESERVED.has(text)) {
36
+ return `${what} ${JSON.stringify(text)} is a reserved device name on Windows — `
37
+ + 'a skill by that name would fail there. Pick another.';
38
+ }
39
+ return null;
47
40
  }
48
-
49
41
  /**
50
42
  * Read `domain` and `name` out of a `domain/name` id.
51
43
  *
@@ -53,46 +45,45 @@ export function validateSegment(value, what = 'name') {
53
45
  * guessed split is how a traversal segment reaches a join().
54
46
  */
55
47
  export function parseSkillId(id) {
56
- const parts = String(id == null ? '' : id).split('/');
57
- if (parts.length !== 2) {
58
- return { error: 'skill id must be "domain/name", for example team/release-checklist' };
59
- }
60
- const [domain, name] = parts;
61
- const domainError = validateSegment(domain, 'domain');
62
- if (domainError) return { error: domainError };
63
- const nameError = validateSegment(name, 'skill name');
64
- if (nameError) return { error: nameError };
65
- return { domain, name };
48
+ const parts = String(id == null ? '' : id).split('/');
49
+ if (parts.length !== 2) {
50
+ return { error: 'skill id must be "domain/name", for example team/release-checklist' };
51
+ }
52
+ const [domain = '', name = ''] = parts;
53
+ const domainError = validateSegment(domain, 'domain');
54
+ if (domainError)
55
+ return { error: domainError };
56
+ const nameError = validateSegment(name, 'skill name');
57
+ if (nameError)
58
+ return { error: nameError };
59
+ return { domain, name };
66
60
  }
67
-
68
61
  /** Strip control characters and collapse a description onto one line. */
69
62
  function cleanDescription(value) {
70
- return String(value == null ? '' : value)
71
- // eslint-disable-next-line no-control-regex
72
- .replace(/[\x00-\x1f\x7f]/g, ' ')
73
- .replace(/\s+/g, ' ')
74
- .trim()
75
- .slice(0, MAX_DESCRIPTION);
63
+ return String(value == null ? '' : value)
64
+ // eslint-disable-next-line no-control-regex
65
+ .replace(/[\x00-\x1f\x7f]/g, ' ')
66
+ .replace(/\s+/g, ' ')
67
+ .trim()
68
+ .slice(0, MAX_DESCRIPTION);
76
69
  }
77
-
78
70
  /** Remove control bytes from a body while keeping newlines and tabs. */
79
71
  function cleanBody(value) {
80
- // eslint-disable-next-line no-control-regex
81
- return String(value == null ? '' : value).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
72
+ // eslint-disable-next-line no-control-regex
73
+ return String(value == null ? '' : value).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
82
74
  }
83
-
84
75
  function parseFrontmatter(content) {
85
- const match = content.match(/^---\n([\s\S]*?)\n---/);
86
- if (!match) return {};
87
- const block = match[1];
88
- const name = block.match(/^name:\s*(.+)$/m);
89
- const description = block.match(/^description:\s*(.+)$/m);
90
- return {
91
- name: name ? name[1].trim() : '',
92
- description: description ? description[1].trim() : ''
93
- };
76
+ const match = content.match(/^---\n([\s\S]*?)\n---/);
77
+ if (!match)
78
+ return {};
79
+ const block = match[1] ?? '';
80
+ const name = block.match(/^name:\s*(.+)$/m);
81
+ const description = block.match(/^description:\s*(.+)$/m);
82
+ return {
83
+ name: name?.[1] ? name[1].trim() : '',
84
+ description: description?.[1] ? description[1].trim() : ''
85
+ };
94
86
  }
95
-
96
87
  /**
97
88
  * Every user skill on disk, validated.
98
89
  *
@@ -100,85 +91,90 @@ function parseFrontmatter(content) {
100
91
  * must not stop a session from starting. Returns { skills, problems }.
101
92
  */
102
93
  export function loadUserSkills(root = userSkillsRoot()) {
103
- const skills = [];
104
- const problems = [];
105
-
106
- let domains;
107
- try {
108
- if (!fs.existsSync(root)) return { skills, problems };
109
- domains = fs.readdirSync(root, { withFileTypes: true })
110
- .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
111
- .map((entry) => entry.name);
112
- } catch (e) {
113
- return { skills, problems: [`could not read ${root}: ${e.message}`] };
114
- }
115
-
116
- for (const domain of domains) {
117
- if (validateSegment(domain, 'domain')) {
118
- problems.push(`skipped domain ${JSON.stringify(domain)}: not a valid name`);
119
- continue;
120
- }
121
- let names;
94
+ const skills = [];
95
+ const problems = [];
96
+ let domains;
122
97
  try {
123
- names = fs.readdirSync(path.join(root, domain), { withFileTypes: true })
124
- .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
125
- .map((entry) => entry.name);
126
- } catch (e) { continue; }
127
-
128
- for (const name of names) {
129
- if (skills.length >= MAX_USER_SKILLS) {
130
- problems.push(`stopped at ${MAX_USER_SKILLS} skills — the rest were not loaded`);
131
- return { skills, problems };
132
- }
133
- if (validateSegment(name, 'skill name')) {
134
- problems.push(`skipped ${domain}/${name}: not a valid name`);
135
- continue;
136
- }
137
-
138
- const file = path.join(root, domain, name, 'SKILL.md');
139
- let content;
140
- try {
141
- assertSkillTreeSafe(root, domain, name);
142
- // Refuse a symlink outright: it is the one way a file inside this
143
- // directory can point at something outside it.
144
- const stat = fs.lstatSync(file);
145
- if (!stat.isFile()) { problems.push(`skipped ${domain}/${name}: not a regular file`); continue; }
146
- if (stat.size > MAX_SKILL_BYTES) {
147
- problems.push(`skipped ${domain}/${name}: ${(stat.size / 1024).toFixed(0)} KB exceeds the `
148
- + `${MAX_SKILL_BYTES / 1024} KB limit — a skill this large would crowd out the task`);
149
- continue;
98
+ if (!fs.existsSync(root))
99
+ return { skills, problems };
100
+ domains = fs.readdirSync(root, { withFileTypes: true })
101
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
102
+ .map((entry) => entry.name);
103
+ }
104
+ catch (e) {
105
+ const msg = e instanceof Error ? e.message : String(e);
106
+ return { skills, problems: [`could not read ${root}: ${msg}`] };
107
+ }
108
+ for (const domain of domains) {
109
+ if (validateSegment(domain, 'domain')) {
110
+ problems.push(`skipped domain ${JSON.stringify(domain)}: not a valid name`);
111
+ continue;
112
+ }
113
+ let names;
114
+ try {
115
+ names = fs.readdirSync(path.join(root, domain), { withFileTypes: true })
116
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
117
+ .map((entry) => entry.name);
118
+ }
119
+ catch {
120
+ continue;
121
+ }
122
+ for (const name of names) {
123
+ if (skills.length >= MAX_USER_SKILLS) {
124
+ problems.push(`stopped at ${MAX_USER_SKILLS} skills — the rest were not loaded`);
125
+ return { skills, problems };
126
+ }
127
+ if (validateSegment(name, 'skill name')) {
128
+ problems.push(`skipped ${domain}/${name}: not a valid name`);
129
+ continue;
130
+ }
131
+ const file = path.join(root, domain, name, 'SKILL.md');
132
+ let content;
133
+ try {
134
+ assertSkillTreeSafe(root, domain, name);
135
+ // Refuse a symlink outright: it is the one way a file inside this
136
+ // directory can point at something outside it.
137
+ const stat = fs.lstatSync(file);
138
+ if (stat.isSymbolicLink() || !stat.isFile()) {
139
+ problems.push(`skipped ${domain}/${name}: not a regular file`);
140
+ continue;
141
+ }
142
+ if (stat.size > MAX_SKILL_BYTES) {
143
+ problems.push(`skipped ${domain}/${name}: ${(stat.size / 1024).toFixed(0)} KB exceeds the `
144
+ + `${MAX_SKILL_BYTES / 1024} KB limit — a skill this large would crowd out the task`);
145
+ continue;
146
+ }
147
+ content = fs.readFileSync(file, 'utf8');
148
+ }
149
+ catch {
150
+ continue;
151
+ }
152
+ const meta = parseFrontmatter(content);
153
+ const description = cleanDescription(meta.description);
154
+ if (!description) {
155
+ problems.push(`skipped ${domain}/${name}: no description in the frontmatter — `
156
+ + 'the description is how the agent decides when the skill applies');
157
+ continue;
158
+ }
159
+ skills.push({
160
+ domain,
161
+ id: name,
162
+ name: meta.name || name,
163
+ description,
164
+ content: cleanBody(content),
165
+ source: 'user',
166
+ path: file
167
+ });
150
168
  }
151
- content = fs.readFileSync(file, 'utf8');
152
- } catch (e) { continue; }
153
-
154
- const meta = parseFrontmatter(content);
155
- const description = cleanDescription(meta.description);
156
- if (!description) {
157
- problems.push(`skipped ${domain}/${name}: no description in the frontmatter — `
158
- + 'the description is how the agent decides when the skill applies');
159
- continue;
160
- }
161
-
162
- skills.push({
163
- domain,
164
- id: name,
165
- name: meta.name || name,
166
- description,
167
- content: cleanBody(content),
168
- source: 'user',
169
- path: file
170
- });
171
169
  }
172
- }
173
- return { skills, problems };
170
+ return { skills, problems };
174
171
  }
175
-
176
172
  /** The starting point a new skill is written from. */
177
- export function skillTemplate(domain, name, description = '') {
178
- const title = name.split('-').map((word) => word[0].toUpperCase() + word.slice(1)).join(' ');
179
- return `---
173
+ export function skillTemplate(_domain, name, description = '') {
174
+ const title = name.split('-').map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
175
+ return `---
180
176
  name: ${name}
181
- description: ${description || `TODO — one line: what this does, and WHEN to reach for it.`}
177
+ description: ${description || 'TODO — one line: what this does, and WHEN to reach for it.'}
182
178
  ---
183
179
 
184
180
  # ${title}
@@ -197,7 +193,6 @@ description: ${description || `TODO — one line: what this does, and WHEN to re
197
193
  - How to confirm the whole thing worked.
198
194
  `;
199
195
  }
200
-
201
196
  /**
202
197
  * Write a user skill to disk.
203
198
  *
@@ -205,81 +200,66 @@ description: ${description || `TODO — one line: what this does, and WHEN to re
205
200
  * replace a skill someone spent time on.
206
201
  */
207
202
  export function writeUserSkill({ domain, name, content, overwrite = false }, root = userSkillsRoot()) {
208
- const domainError = validateSegment(domain, 'domain');
209
- if (domainError) return { ok: false, error: domainError };
210
- const nameError = validateSegment(name, 'skill name');
211
- if (nameError) return { ok: false, error: nameError };
212
-
213
- const body = cleanBody(content);
214
- if (Buffer.byteLength(body, 'utf8') > MAX_SKILL_BYTES) {
215
- return { ok: false, error: `skill exceeds the ${MAX_SKILL_BYTES / 1024} KB limit` };
216
- }
217
-
218
- const meta = parseFrontmatter(body);
219
- if (!cleanDescription(meta.description)) {
220
- return {
221
- ok: false,
222
- error: "the frontmatter needs a `description:` line — it is what the agent reads to decide whether the skill applies, so a skill without one can never be selected"
223
- };
224
- }
225
-
226
- const directory = path.join(root, domain, name);
227
- const file = path.join(directory, 'SKILL.md');
228
-
229
- // Belt and braces: the resolved path must still be inside the root after every
230
- // segment has been joined. Validation above already makes this unreachable.
231
- const resolvedRoot = path.resolve(root);
232
- const resolvedFile = path.resolve(file);
233
- if (resolvedFile !== resolvedRoot && !resolvedFile.startsWith(resolvedRoot + path.sep)) {
234
- return { ok: false, error: 'refusing to write outside the skills directory' };
235
- }
236
-
237
- if (!overwrite && fs.existsSync(file)) {
238
- return { ok: false, error: `${domain}/${name} already exists — pass overwrite to replace it` };
239
- }
240
-
241
- try {
242
- // Causyne Skills Safety v1: lexical path checks do not stop an existing
243
- // symlinked parent directory from redirecting a skill write elsewhere.
244
- assertSkillTreeSafe(root, domain, name, true);
245
- fs.mkdirSync(directory, { recursive: true });
246
- assertSkillTreeSafe(root, domain, name);
247
- const nofollow = typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
248
- const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | nofollow
249
- | (overwrite ? fs.constants.O_TRUNC : fs.constants.O_EXCL);
250
- const fd = fs.openSync(file, flags, 0o600);
203
+ const domainError = validateSegment(domain, 'domain');
204
+ if (domainError)
205
+ return { ok: false, error: domainError };
206
+ const nameError = validateSegment(name, 'skill name');
207
+ if (nameError)
208
+ return { ok: false, error: nameError };
209
+ const body = cleanBody(content);
210
+ if (Buffer.byteLength(body, 'utf8') > MAX_SKILL_BYTES) {
211
+ return { ok: false, error: `skill exceeds the ${MAX_SKILL_BYTES / 1024} KB limit` };
212
+ }
213
+ const meta = parseFrontmatter(body);
214
+ if (!cleanDescription(meta.description)) {
215
+ return {
216
+ ok: false,
217
+ error: "the frontmatter needs a `description:` line — it is what the agent reads to decide whether the skill applies, so a skill without one can never be selected"
218
+ };
219
+ }
220
+ const directory = path.join(root, domain, name);
221
+ const file = path.join(directory, 'SKILL.md');
222
+ // Belt and braces: the resolved path must still be inside the root after every
223
+ // segment has been joined. Validation above already makes this unreachable.
224
+ const resolvedRoot = path.resolve(root);
225
+ const resolvedFile = path.resolve(file);
226
+ if (resolvedFile !== resolvedRoot && !resolvedFile.startsWith(resolvedRoot + path.sep)) {
227
+ return { ok: false, error: 'refusing to write outside the skills directory' };
228
+ }
229
+ if (!overwrite && fs.existsSync(file)) {
230
+ return { ok: false, error: `${domain}/${name} already exists — pass overwrite to replace it` };
231
+ }
251
232
  try {
252
- if (!fs.fstatSync(fd).isFile()) throw new Error('SKILL.md must be a regular file');
253
- fs.writeFileSync(fd, body, 'utf8');
254
- } finally {
255
- fs.closeSync(fd);
233
+ // Causyne Skills Safety v1: lexical path checks do not stop an existing
234
+ // symlinked parent directory or SKILL.md symlink from redirecting writes.
235
+ const writtenPath = writeSkillFileSafely(root, domain, name, 'SKILL.md', body, overwrite);
236
+ return { ok: true, path: writtenPath };
237
+ }
238
+ catch (e) {
239
+ const msg = e instanceof Error ? e.message : String(e);
240
+ return { ok: false, error: `could not write ${file}: ${msg}` };
256
241
  }
257
- } catch (e) {
258
- return { ok: false, error: `could not write ${file}: ${e.message}` };
259
- }
260
- return { ok: true, path: file };
261
242
  }
262
-
263
243
  /** Remove a user skill. Compiled skills are not removable — they are the build. */
264
244
  export function deleteUserSkill(domain, name, root = userSkillsRoot()) {
265
- const domainError = validateSegment(domain, 'domain');
266
- if (domainError) return { ok: false, error: domainError };
267
- const nameError = validateSegment(name, 'skill name');
268
- if (nameError) return { ok: false, error: nameError };
269
-
270
- const directory = path.join(root, domain, name);
271
- if (!fs.existsSync(path.join(directory, 'SKILL.md'))) {
272
- return { ok: false, error: `${domain}/${name} is not a user skill` };
273
- }
274
- try {
275
- assertSkillTreeSafe(root, domain, name);
276
- const skillFile = fs.lstatSync(path.join(directory, 'SKILL.md'));
277
- if (skillFile.isSymbolicLink() || !skillFile.isFile()) {
278
- throw new Error('SKILL.md must be a regular file');
245
+ const domainError = validateSegment(domain, 'domain');
246
+ if (domainError)
247
+ return { ok: false, error: domainError };
248
+ const nameError = validateSegment(name, 'skill name');
249
+ if (nameError)
250
+ return { ok: false, error: nameError };
251
+ const directory = path.join(root, domain, name);
252
+ if (!fs.existsSync(path.join(directory, 'SKILL.md'))) {
253
+ return { ok: false, error: `${domain}/${name} is not a user skill` };
254
+ }
255
+ try {
256
+ assertSkillTreeSafe(root, domain, name);
257
+ assertSkillFileSafe(path.join(directory, 'SKILL.md'), false);
258
+ fs.rmSync(directory, { recursive: true, force: true });
259
+ }
260
+ catch (e) {
261
+ const msg = e instanceof Error ? e.message : String(e);
262
+ return { ok: false, error: `could not remove ${directory}: ${msg}` };
279
263
  }
280
- fs.rmSync(directory, { recursive: true, force: true });
281
- } catch (e) {
282
- return { ok: false, error: `could not remove ${directory}: ${e.message}` };
283
- }
284
- return { ok: true, path: directory };
264
+ return { ok: true, path: directory };
285
265
  }