@saydone/dab 0.1.1 → 0.1.2

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 (118) hide show
  1. package/AGENTS.md +7 -0
  2. package/CHANGELOG.md +26 -1
  3. package/CHANGELOG.zh.md +26 -1
  4. package/README.i18n.yaml +8 -8
  5. package/README.md +16 -6
  6. package/README.zh.md +16 -6
  7. package/dist/adapter/claude-code/adapter.js +5 -2
  8. package/dist/adapter/claude-code/adapter.js.map +1 -1
  9. package/dist/adapter/claude-code/adoption.d.ts +58 -0
  10. package/dist/adapter/claude-code/adoption.js +749 -0
  11. package/dist/adapter/claude-code/adoption.js.map +1 -0
  12. package/dist/adapter/claude-code/policy-compile.js +1 -1
  13. package/dist/adapter/claude-code/policy-compile.js.map +1 -1
  14. package/dist/adapter/claude-code/projection.d.ts +1 -0
  15. package/dist/adapter/claude-code/projection.js +7 -1
  16. package/dist/adapter/claude-code/projection.js.map +1 -1
  17. package/dist/adapter/types.d.ts +7 -0
  18. package/dist/cli.js +9 -19
  19. package/dist/cli.js.map +1 -1
  20. package/dist/commands/detect.d.ts +14 -0
  21. package/dist/commands/detect.js +383 -54
  22. package/dist/commands/detect.js.map +1 -1
  23. package/dist/commands/init.d.ts +4 -1
  24. package/dist/commands/init.js +177 -40
  25. package/dist/commands/init.js.map +1 -1
  26. package/dist/commands/normalize.d.ts +53 -0
  27. package/dist/commands/normalize.js +378 -29
  28. package/dist/commands/normalize.js.map +1 -1
  29. package/dist/commands/policy-explain.js +9 -0
  30. package/dist/commands/policy-explain.js.map +1 -1
  31. package/dist/core/diagnostics.d.ts +2 -0
  32. package/dist/core/diagnostics.js +18 -0
  33. package/dist/core/diagnostics.js.map +1 -1
  34. package/dist/core/fs-atomic.d.ts +6 -0
  35. package/dist/core/fs-atomic.js +29 -0
  36. package/dist/core/fs-atomic.js.map +1 -1
  37. package/dist/core/paths.js +29 -6
  38. package/dist/core/paths.js.map +1 -1
  39. package/dist/core/practice-paths.d.ts +73 -0
  40. package/dist/core/practice-paths.js +310 -0
  41. package/dist/core/practice-paths.js.map +1 -0
  42. package/dist/core/skill-marker.d.ts +28 -0
  43. package/dist/core/skill-marker.js +57 -0
  44. package/dist/core/skill-marker.js.map +1 -0
  45. package/dist/core/version-compare.d.ts +8 -0
  46. package/dist/core/version-compare.js +23 -0
  47. package/dist/core/version-compare.js.map +1 -0
  48. package/dist/core/version.d.ts +2 -0
  49. package/dist/core/version.js +13 -0
  50. package/dist/core/version.js.map +1 -0
  51. package/dist/detect/checklist.d.ts +42 -0
  52. package/dist/detect/checklist.js +137 -0
  53. package/dist/detect/checklist.js.map +1 -0
  54. package/dist/detect/checks.d.ts +1 -1
  55. package/dist/detect/checks.js +15 -3
  56. package/dist/detect/checks.js.map +1 -1
  57. package/dist/detect/practice.d.ts +43 -0
  58. package/dist/detect/practice.js +782 -0
  59. package/dist/detect/practice.js.map +1 -0
  60. package/dist/detect/preflight.d.ts +21 -0
  61. package/dist/detect/preflight.js +408 -0
  62. package/dist/detect/preflight.js.map +1 -0
  63. package/dist/docs/config.js +5 -0
  64. package/dist/docs/config.js.map +1 -1
  65. package/dist/init/adoption.d.ts +138 -0
  66. package/dist/init/adoption.js +747 -0
  67. package/dist/init/adoption.js.map +1 -0
  68. package/dist/init/docs-language.d.ts +12 -0
  69. package/dist/init/docs-language.js +110 -0
  70. package/dist/init/docs-language.js.map +1 -0
  71. package/dist/init/managed-skills.d.ts +81 -0
  72. package/dist/init/managed-skills.js +407 -0
  73. package/dist/init/managed-skills.js.map +1 -0
  74. package/dist/init/minimal-source.d.ts +14 -0
  75. package/dist/init/minimal-source.js +42 -0
  76. package/dist/init/minimal-source.js.map +1 -0
  77. package/dist/init/practice-authoring.d.ts +5 -0
  78. package/dist/init/practice-authoring.js +36 -0
  79. package/dist/init/practice-authoring.js.map +1 -0
  80. package/dist/init/practice-docs.d.ts +13 -0
  81. package/dist/init/practice-docs.js +278 -0
  82. package/dist/init/practice-docs.js.map +1 -0
  83. package/dist/init/practice.d.ts +78 -0
  84. package/dist/init/practice.js +528 -0
  85. package/dist/init/practice.js.map +1 -0
  86. package/dist/init/scanner.js +7 -0
  87. package/dist/init/scanner.js.map +1 -1
  88. package/dist/init/skill-templates.d.ts +7 -0
  89. package/dist/init/skill-templates.js +25 -0
  90. package/dist/init/skill-templates.js.map +1 -0
  91. package/dist/init/templates.d.ts +22 -10
  92. package/dist/init/templates.js +32 -88
  93. package/dist/init/templates.js.map +1 -1
  94. package/dist/model/agents-md.js +1 -1
  95. package/dist/model/agents-md.js.map +1 -1
  96. package/dist/model/agents.d.ts +10 -0
  97. package/dist/model/agents.js +110 -86
  98. package/dist/model/agents.js.map +1 -1
  99. package/dist/model/diagnostics-codes.d.ts +1 -0
  100. package/dist/model/diagnostics-codes.js +1 -0
  101. package/dist/model/diagnostics-codes.js.map +1 -1
  102. package/dist/model/facts.js +24 -4
  103. package/dist/model/facts.js.map +1 -1
  104. package/dist/model/project-manifest.js +2 -0
  105. package/dist/model/project-manifest.js.map +1 -1
  106. package/dist/model/schemas.d.ts +30 -1
  107. package/dist/model/schemas.js +8 -1
  108. package/dist/model/schemas.js.map +1 -1
  109. package/dist/model/scope.d.ts +13 -0
  110. package/dist/model/scope.js +57 -0
  111. package/dist/model/scope.js.map +1 -1
  112. package/dist/model/skills.d.ts +10 -0
  113. package/dist/model/skills.js +126 -56
  114. package/dist/model/skills.js.map +1 -1
  115. package/package.json +2 -1
  116. package/skills/dab-architecture-writing/SKILL.md +58 -0
  117. package/skills/dab-decision-notes/SKILL.md +57 -0
  118. package/skills/dab-doc-writing/SKILL.md +58 -0
@@ -0,0 +1,749 @@
1
+ import { constants } from 'node:fs';
2
+ import { copyFile, cp, readdir, readlink, realpath, rename, rm } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path';
4
+ import { randomBytes } from 'node:crypto';
5
+ import { compareStrings } from '../../core/compare.js';
6
+ import { backupPath, ensureDir, lstatOrNull, readTextFile, replaceSymlink, } from '../../core/fs-atomic.js';
7
+ import { assertParentInsideRoot, isPathInside, relativeLink, resolveInside, toPosix, } from '../../core/paths.js';
8
+ import { isAuthoredPathProblem } from '../../core/practice-paths.js';
9
+ import { discoverAgents, validateAgentSource } from '../../model/agents.js';
10
+ import { DiagnosticCodes } from '../../model/diagnostics-codes.js';
11
+ import { getGeneratedTarget } from '../../model/project-manifest.js';
12
+ import { discoverSkills, validateSkillSource } from '../../model/skills.js';
13
+ const AdoptionCodes = {
14
+ contentDiffers: 'adoption.content-differs',
15
+ skillExtraFiles: 'adoption.skill-extra-files',
16
+ nameMismatch: 'adoption.name-mismatch',
17
+ unmanagedSymlink: 'adoption.unmanaged-symlink',
18
+ sourceEscape: 'adoption.source-escape',
19
+ targetEscape: 'adoption.target-escape',
20
+ targetConflict: 'adoption.target-conflict',
21
+ sourceUnreadable: 'adoption.source-unreadable',
22
+ targetUnreadable: 'adoption.target-unreadable',
23
+ applyFailed: 'adoption.apply-failed',
24
+ sourceMissing: 'adoption.source-missing',
25
+ sourceSymlinkEscape: 'adoption.source-symlink-escape',
26
+ targetExists: 'adoption.target-exists',
27
+ targetMissing: 'adoption.target-missing',
28
+ };
29
+ function errorMessage(error) {
30
+ return error instanceof Error ? error.message : String(error);
31
+ }
32
+ async function readDirOrEmpty(dir) {
33
+ try {
34
+ const entries = await readdir(dir, { withFileTypes: true });
35
+ return entries.sort((left, right) => compareStrings(left.name, right.name));
36
+ }
37
+ catch (error) {
38
+ if (error.code === 'ENOENT') {
39
+ return [];
40
+ }
41
+ throw error;
42
+ }
43
+ }
44
+ function relativePath(root, absolute) {
45
+ return toPosix(relative(root, absolute));
46
+ }
47
+ /**
48
+ * DAB owns `.claude` entries one by one. A directory-level symlink would make
49
+ * every entry resolve through it, so it is a conflict instead of a fact.
50
+ */
51
+ async function sourceRootDiagnostic(root, sourceDir, label) {
52
+ const info = await lstatOrNull(sourceDir);
53
+ if (info?.isSymbolicLink() !== true) {
54
+ return undefined;
55
+ }
56
+ return {
57
+ code: AdoptionCodes.unmanagedSymlink,
58
+ severity: 'error',
59
+ message: `${label} is a directory symlink; DAB manages .claude entries one by one`,
60
+ file: relativePath(root, sourceDir),
61
+ hint: 'Replace the directory symlink with a real directory so each entry can be imported.',
62
+ };
63
+ }
64
+ /**
65
+ * Reject sources and targets that escape the adoption root, either through a
66
+ * relative path or through a symlinked parent directory.
67
+ */
68
+ async function pathDiagnostic(root, file, code, label) {
69
+ try {
70
+ resolveInside(root, file);
71
+ await assertParentInsideRoot(root, file);
72
+ return undefined;
73
+ }
74
+ catch (error) {
75
+ return {
76
+ code,
77
+ severity: 'error',
78
+ message: `${label} escapes the adoption root: ${errorMessage(error)}`,
79
+ file,
80
+ };
81
+ }
82
+ }
83
+ async function linkResolvesTo(linkPath, expectedPath) {
84
+ try {
85
+ const raw = await readlink(linkPath);
86
+ return resolve(dirname(linkPath), raw) === resolve(expectedPath);
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ }
92
+ function unmanagedSymlink(source, target) {
93
+ return {
94
+ code: AdoptionCodes.unmanagedSymlink,
95
+ severity: 'error',
96
+ message: `existing symlink is not managed by DAB and has no authored source: ${source}`,
97
+ file: source,
98
+ hint: `Point it at ${target} after adding that authored source, or remove the symlink; DAB never imports or deletes an unmanaged link.`,
99
+ };
100
+ }
101
+ /**
102
+ * Root-relative `.claude` paths recorded as generated projections. The
103
+ * projection plan owns these targets: managed symlink drift is repaired, and a
104
+ * stale record is removed, without the adoption import planner reporting the
105
+ * path as an unmanaged conflict.
106
+ */
107
+ function managedProjectionTargets(manifest) {
108
+ const generated = manifest === undefined
109
+ ? undefined
110
+ : getGeneratedTarget(manifest, 'claude-code');
111
+ return new Set((generated?.projections ?? []).map((projection) => projection.target));
112
+ }
113
+ /**
114
+ * An entry symlink that does not resolve to its expected `.agents` source is
115
+ * not an import candidate. When the projection plan owns the target (recorded
116
+ * or backed by an authored source), it repairs the link, or reports and
117
+ * `--fix`-backs it up; adoption only reports links DAB cannot map.
118
+ */
119
+ function symlinkDiagnostic(source, target, hasAuthoredSource, managed) {
120
+ // Recorded projection targets are root-relative `.claude` paths, which is
121
+ // exactly the `source` path here; `target` is the `.agents` destination.
122
+ if (managed.has(source) || hasAuthoredSource) {
123
+ return undefined;
124
+ }
125
+ return unmanagedSymlink(source, target);
126
+ }
127
+ function nameMismatch(kind, source, declared, basename) {
128
+ return {
129
+ code: AdoptionCodes.nameMismatch,
130
+ severity: 'warning',
131
+ message: `${kind} ${source} declares name ${declared} but is imported as ${basename}`,
132
+ file: source,
133
+ hint: 'The frontmatter name is the fact id; the .claude basename is preserved, so rename both to align.',
134
+ };
135
+ }
136
+ function contentDiffers(kind, source, target) {
137
+ return {
138
+ code: AdoptionCodes.contentDiffers,
139
+ severity: 'warning',
140
+ message: `${kind} ${source} differs from the existing .agents source ${target}; keeping .agents and backing up .claude`,
141
+ file: target,
142
+ hint: 'The .agents copy is the source of truth; update it if the .claude version should win.',
143
+ };
144
+ }
145
+ function duplicateName(kind, name, file, existing) {
146
+ return {
147
+ code: kind === 'agent'
148
+ ? DiagnosticCodes.agentDuplicateName
149
+ : DiagnosticCodes.skillDuplicateName,
150
+ severity: 'error',
151
+ message: `duplicate ${kind} name ${name}`,
152
+ file,
153
+ hint: `The name is already used by ${existing}.`,
154
+ };
155
+ }
156
+ function targetConflict(kind, target) {
157
+ const expected = kind === 'agent' ? 'a regular file' : 'a directory';
158
+ return {
159
+ code: AdoptionCodes.targetConflict,
160
+ severity: 'error',
161
+ message: `${kind} target is not ${expected}: ${target}`,
162
+ file: target,
163
+ hint: 'Move the existing entry or remove it before importing.',
164
+ };
165
+ }
166
+ function unreadable(code, file, error) {
167
+ return {
168
+ code,
169
+ severity: 'error',
170
+ message: `cannot read ${file}: ${errorMessage(error)}`,
171
+ file,
172
+ };
173
+ }
174
+ function skillSymlinkEscape(file) {
175
+ return {
176
+ code: AdoptionCodes.sourceSymlinkEscape,
177
+ severity: 'error',
178
+ message: `skill source contains a symlink that escapes the adoption root: ${file}`,
179
+ file,
180
+ hint: 'Remove the symlink or point it inside the adoption root before rerunning normalize.',
181
+ };
182
+ }
183
+ async function listFiles(dir, prefix = '') {
184
+ const result = [];
185
+ for (const entry of await readDirOrEmpty(dir)) {
186
+ const path = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
187
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
188
+ result.push(...await listFiles(join(dir, entry.name), path));
189
+ }
190
+ else {
191
+ result.push(path);
192
+ }
193
+ }
194
+ return result;
195
+ }
196
+ async function planAgents(input, authored, managed) {
197
+ const sourceDir = join(input.claudeRoot, 'agents');
198
+ const entries = [];
199
+ const diagnostics = [];
200
+ const names = new Map();
201
+ const rootDiagnostic = await sourceRootDiagnostic(input.root, sourceDir, '.claude/agents');
202
+ if (rootDiagnostic !== undefined) {
203
+ return { entries, diagnostics: [rootDiagnostic] };
204
+ }
205
+ for (const entry of await readDirOrEmpty(sourceDir)) {
206
+ if (!entry.name.endsWith('.md')) {
207
+ continue;
208
+ }
209
+ const sourceAbs = join(sourceDir, entry.name);
210
+ const source = relativePath(input.root, sourceAbs);
211
+ const target = relativePath(input.root, join(input.agentsRoot, 'agents', entry.name));
212
+ const sourceEscape = await pathDiagnostic(input.root, source, AdoptionCodes.sourceEscape, 'agent source');
213
+ const targetEscape = await pathDiagnostic(input.root, target, AdoptionCodes.targetEscape, 'agent target');
214
+ if (sourceEscape !== undefined || targetEscape !== undefined) {
215
+ if (sourceEscape !== undefined) {
216
+ diagnostics.push(sourceEscape);
217
+ }
218
+ if (targetEscape !== undefined) {
219
+ diagnostics.push(targetEscape);
220
+ }
221
+ continue;
222
+ }
223
+ if (entry.isSymbolicLink()) {
224
+ const expected = resolveInside(input.agentsRoot, join('agents', entry.name));
225
+ if (await linkResolvesTo(sourceAbs, expected)) {
226
+ continue;
227
+ }
228
+ const expectedInfo = await lstatOrNull(expected);
229
+ const problem = symlinkDiagnostic(source, target, expectedInfo?.isFile() === true, managed);
230
+ if (problem !== undefined) {
231
+ diagnostics.push(problem);
232
+ }
233
+ continue;
234
+ }
235
+ if (!entry.isFile()) {
236
+ continue;
237
+ }
238
+ const validated = await validateAgentSource(input.root, sourceAbs);
239
+ if (validated.item === undefined) {
240
+ diagnostics.push(...validated.diagnostics);
241
+ continue;
242
+ }
243
+ const entryDiagnostics = [...validated.diagnostics];
244
+ const sourceBasename = entry.name.slice(0, -'.md'.length);
245
+ if (validated.item.name !== sourceBasename) {
246
+ entryDiagnostics.push(nameMismatch('agent', source, validated.item.name, entry.name));
247
+ }
248
+ const existing = names.get(validated.item.name);
249
+ if (existing !== undefined) {
250
+ diagnostics.push(...entryDiagnostics, duplicateName('agent', validated.item.name, source, existing));
251
+ continue;
252
+ }
253
+ names.set(validated.item.name, source);
254
+ // Copying a different `.claude` file into `.agents` must not introduce a
255
+ // name already used by an authored agent. The same file/target pair is the
256
+ // existing-entry case and stays importable.
257
+ const authoredFile = authored.get(validated.item.name);
258
+ if (authoredFile !== undefined && authoredFile !== target) {
259
+ diagnostics.push(...entryDiagnostics, duplicateName('agent', validated.item.name, source, authoredFile));
260
+ continue;
261
+ }
262
+ const targetAbs = resolveInside(input.root, target);
263
+ const targetInfo = await lstatOrNull(targetAbs);
264
+ let writeSource = true;
265
+ if (targetInfo !== null) {
266
+ if (targetInfo.isSymbolicLink() || !targetInfo.isFile()) {
267
+ diagnostics.push(...entryDiagnostics, targetConflict('agent', target));
268
+ continue;
269
+ }
270
+ writeSource = false;
271
+ let sourceContent;
272
+ let targetContent;
273
+ try {
274
+ sourceContent = await readTextFile(sourceAbs);
275
+ }
276
+ catch (error) {
277
+ diagnostics.push(...entryDiagnostics, unreadable(AdoptionCodes.sourceUnreadable, source, error));
278
+ continue;
279
+ }
280
+ try {
281
+ targetContent = await readTextFile(targetAbs);
282
+ }
283
+ catch (error) {
284
+ diagnostics.push(...entryDiagnostics, unreadable(AdoptionCodes.targetUnreadable, target, error));
285
+ continue;
286
+ }
287
+ if (sourceContent !== targetContent) {
288
+ entryDiagnostics.push(contentDiffers('agent', source, target));
289
+ }
290
+ }
291
+ entries.push({
292
+ kind: 'agent',
293
+ name: validated.item.name,
294
+ source,
295
+ target,
296
+ writeSource,
297
+ replaceTarget: true,
298
+ diagnostics: entryDiagnostics,
299
+ });
300
+ }
301
+ return { entries, diagnostics };
302
+ }
303
+ async function planSkills(input, authored, managed) {
304
+ const sourceDir = join(input.claudeRoot, 'skills');
305
+ const entries = [];
306
+ const diagnostics = [];
307
+ const names = new Map();
308
+ const rootDiagnostic = await sourceRootDiagnostic(input.root, sourceDir, '.claude/skills');
309
+ if (rootDiagnostic !== undefined) {
310
+ return { entries, diagnostics: [rootDiagnostic] };
311
+ }
312
+ for (const entry of await readDirOrEmpty(sourceDir)) {
313
+ const sourceAbs = join(sourceDir, entry.name);
314
+ const source = relativePath(input.root, sourceAbs);
315
+ const target = relativePath(input.root, join(input.agentsRoot, 'skills', entry.name));
316
+ const sourceEscape = await pathDiagnostic(input.root, source, AdoptionCodes.sourceEscape, 'skill source');
317
+ const targetEscape = await pathDiagnostic(input.root, target, AdoptionCodes.targetEscape, 'skill target');
318
+ if (sourceEscape !== undefined || targetEscape !== undefined) {
319
+ if (sourceEscape !== undefined) {
320
+ diagnostics.push(sourceEscape);
321
+ }
322
+ if (targetEscape !== undefined) {
323
+ diagnostics.push(targetEscape);
324
+ }
325
+ continue;
326
+ }
327
+ if (entry.isSymbolicLink()) {
328
+ const expected = resolveInside(input.agentsRoot, join('skills', entry.name));
329
+ if (await linkResolvesTo(sourceAbs, expected)) {
330
+ continue;
331
+ }
332
+ const expectedInfo = await lstatOrNull(expected);
333
+ const problem = symlinkDiagnostic(source, target, expectedInfo?.isDirectory() === true, managed);
334
+ if (problem !== undefined) {
335
+ diagnostics.push(problem);
336
+ }
337
+ continue;
338
+ }
339
+ if (!entry.isDirectory()) {
340
+ continue;
341
+ }
342
+ const validated = await validateSkillSource(input.root, sourceAbs);
343
+ if (validated.item === undefined) {
344
+ diagnostics.push(...validated.diagnostics);
345
+ continue;
346
+ }
347
+ const entryDiagnostics = [...validated.diagnostics];
348
+ if (validated.item.name !== entry.name) {
349
+ entryDiagnostics.push(nameMismatch('skill', source, validated.item.name, entry.name));
350
+ }
351
+ const existing = names.get(validated.item.name);
352
+ if (existing !== undefined) {
353
+ diagnostics.push(...entryDiagnostics, duplicateName('skill', validated.item.name, source, existing));
354
+ continue;
355
+ }
356
+ names.set(validated.item.name, source);
357
+ const authoredDir = authored.get(validated.item.name);
358
+ if (authoredDir !== undefined && authoredDir !== target) {
359
+ diagnostics.push(...entryDiagnostics, duplicateName('skill', validated.item.name, source, authoredDir));
360
+ continue;
361
+ }
362
+ const targetAbs = resolveInside(input.root, target);
363
+ const targetInfo = await lstatOrNull(targetAbs);
364
+ let writeSource = true;
365
+ if (targetInfo !== null) {
366
+ if (targetInfo.isSymbolicLink() || !targetInfo.isDirectory()) {
367
+ diagnostics.push(...entryDiagnostics, targetConflict('skill', target));
368
+ continue;
369
+ }
370
+ writeSource = false;
371
+ const sourceSkillFile = join(sourceAbs, 'SKILL.md');
372
+ const targetSkillFile = join(targetAbs, 'SKILL.md');
373
+ let sourceContent;
374
+ let targetContent;
375
+ try {
376
+ sourceContent = await readTextFile(sourceSkillFile);
377
+ }
378
+ catch (error) {
379
+ diagnostics.push(...entryDiagnostics, unreadable(AdoptionCodes.sourceUnreadable, `${source}/SKILL.md`, error));
380
+ continue;
381
+ }
382
+ try {
383
+ const targetSkillInfo = await lstatOrNull(targetSkillFile);
384
+ targetContent = targetSkillInfo === null ? undefined : await readTextFile(targetSkillFile);
385
+ }
386
+ catch (error) {
387
+ diagnostics.push(...entryDiagnostics, unreadable(AdoptionCodes.targetUnreadable, `${target}/SKILL.md`, error));
388
+ continue;
389
+ }
390
+ if (sourceContent !== targetContent) {
391
+ entryDiagnostics.push(contentDiffers('skill', source, target));
392
+ }
393
+ try {
394
+ const sourceFiles = await listFiles(sourceAbs);
395
+ const targetFiles = new Set(await listFiles(targetAbs));
396
+ const extraFiles = sourceFiles.filter((file) => file !== 'SKILL.md' && !targetFiles.has(file));
397
+ if (extraFiles.length > 0) {
398
+ entryDiagnostics.push({
399
+ code: AdoptionCodes.skillExtraFiles,
400
+ severity: 'warning',
401
+ message: `skill ${source} has extra files that are not merged into ${target}: ${extraFiles.join(', ')}`,
402
+ file: source,
403
+ hint: 'The .agents copy is the source of truth; extra files stay in the backup after replacement.',
404
+ });
405
+ }
406
+ }
407
+ catch (error) {
408
+ diagnostics.push(...entryDiagnostics, unreadable(AdoptionCodes.sourceUnreadable, source, error));
409
+ continue;
410
+ }
411
+ }
412
+ // A fresh skill directory is copied wholesale, so an escaping symlink is a
413
+ // plan error: the zero-write gate must see it before copying anything.
414
+ if (writeSource) {
415
+ try {
416
+ const escaping = await findEscapingSymlink(input.root, sourceAbs);
417
+ if (escaping !== undefined) {
418
+ diagnostics.push(...entryDiagnostics, skillSymlinkEscape(relativePath(input.root, escaping)));
419
+ continue;
420
+ }
421
+ }
422
+ catch (error) {
423
+ diagnostics.push(...entryDiagnostics, unreadable(AdoptionCodes.sourceUnreadable, source, error));
424
+ continue;
425
+ }
426
+ }
427
+ entries.push({
428
+ kind: 'skill',
429
+ name: validated.item.name,
430
+ source,
431
+ target,
432
+ writeSource,
433
+ replaceTarget: true,
434
+ diagnostics: entryDiagnostics,
435
+ });
436
+ }
437
+ return { entries, diagnostics };
438
+ }
439
+ /**
440
+ * Only the exact `.agents/rules` and `.agents/skills` parents are
441
+ * practice-owned: a failure there is reported by the practice checks, so
442
+ * imports treat the affected tree as empty. A nested unreadable skill directory
443
+ * is reported per entry by `discoverSkills` and keeps its sibling facts.
444
+ */
445
+ async function discoverAuthored(root, run) {
446
+ try {
447
+ return await run();
448
+ }
449
+ catch (error) {
450
+ if (isAuthoredPathProblem(error, root)) {
451
+ return { items: [], diagnostics: [] };
452
+ }
453
+ throw error;
454
+ }
455
+ }
456
+ /**
457
+ * Authored names already used under `.agents`. Only valid discovered items are
458
+ * indexed; discovery diagnostics surface through the import plan so preflight
459
+ * and initialized runs report the same governed skill errors.
460
+ */
461
+ async function authoredFacts(input) {
462
+ const [agents, skills] = await Promise.all([
463
+ discoverAuthored(input.root, () => discoverAgents(input.root, input.agentsRoot)),
464
+ discoverAuthored(input.root, () => discoverSkills(input.root, input.agentsRoot)),
465
+ ]);
466
+ const agentNames = new Map();
467
+ for (const item of agents.items) {
468
+ if (!agentNames.has(item.name)) {
469
+ agentNames.set(item.name, item.file);
470
+ }
471
+ }
472
+ const skillNames = new Map();
473
+ for (const item of skills.items) {
474
+ if (!skillNames.has(item.name)) {
475
+ skillNames.set(item.name, item.dir);
476
+ }
477
+ }
478
+ // Only skill discovery is fault-isolated per entry. Agent diagnostics keep
479
+ // their existing pipeline ownership, while an unreadable nested skill must
480
+ // surface here so preflight cannot plan an import around a hidden skill.
481
+ return {
482
+ agents: agentNames,
483
+ skills: skillNames,
484
+ diagnostics: [...skills.diagnostics],
485
+ };
486
+ }
487
+ /**
488
+ * Plan the import of physical `.claude/agents/*.md` files and
489
+ * `.claude/skills/<dir>/SKILL.md` directories into the authored `.agents`
490
+ * tree. The plan is read-only; applying it is a separate step.
491
+ */
492
+ export async function planClaudeAdoption(input) {
493
+ const authored = await authoredFacts(input);
494
+ const managed = managedProjectionTargets(input.manifest);
495
+ const agents = await planAgents(input, authored.agents, managed);
496
+ const skills = await planSkills(input, authored.skills, managed);
497
+ const entries = [...agents.entries, ...skills.entries];
498
+ return {
499
+ entries,
500
+ diagnostics: [
501
+ ...authored.diagnostics,
502
+ ...agents.diagnostics,
503
+ ...skills.diagnostics,
504
+ ...entries.flatMap((entry) => entry.diagnostics),
505
+ ],
506
+ };
507
+ }
508
+ function applyDiagnostic(code, file, message, hint) {
509
+ return {
510
+ code,
511
+ severity: 'error',
512
+ message,
513
+ file,
514
+ ...(hint === undefined ? {} : { hint }),
515
+ };
516
+ }
517
+ function applyFailure(entry, error) {
518
+ return applyDiagnostic(AdoptionCodes.applyFailed, entry.source, `cannot import ${entry.kind} ${entry.source}: ${errorMessage(error)}`, 'Fix the filesystem error and rerun normalize; the reported copies, backups and links are kept.');
519
+ }
520
+ async function safeResolve(root, relativePath) {
521
+ try {
522
+ const absolute = resolveInside(root, relativePath);
523
+ await assertParentInsideRoot(root, relativePath);
524
+ return { ok: true, absolute };
525
+ }
526
+ catch (error) {
527
+ return { ok: false, error };
528
+ }
529
+ }
530
+ function targetComponents(raw) {
531
+ const normalized = sep === '\\' ? raw.replaceAll('/', '\\') : raw;
532
+ return normalized.split(sep).filter((part) => part.length > 0 && part !== '.');
533
+ }
534
+ /**
535
+ * Resolve a dangling link target the way the filesystem would: existing
536
+ * symlink components are expanded before later `..` components are applied.
537
+ * Only after the first missing component is the remainder collapsed lexically,
538
+ * because nothing below a missing path can be traversed.
539
+ */
540
+ async function resolveLinkTarget(linkPath, raw) {
541
+ let resolved = isAbsolute(raw) ? parse(raw).root : await realpath(dirname(linkPath));
542
+ const pending = targetComponents(raw);
543
+ let depth = 0;
544
+ while (pending.length > 0) {
545
+ const component = pending.shift();
546
+ if (component === '..') {
547
+ resolved = dirname(resolved);
548
+ continue;
549
+ }
550
+ const candidate = join(resolved, component);
551
+ const info = await lstatOrNull(candidate);
552
+ if (info === null) {
553
+ return resolve(resolved, component, ...pending);
554
+ }
555
+ if (info.isSymbolicLink()) {
556
+ depth += 1;
557
+ if (depth > 40) {
558
+ throw new Error(`too many levels of symbolic links: ${linkPath}`);
559
+ }
560
+ const nested = await readlink(candidate);
561
+ if (isAbsolute(nested)) {
562
+ resolved = parse(nested).root;
563
+ }
564
+ pending.unshift(...targetComponents(nested));
565
+ continue;
566
+ }
567
+ resolved = candidate;
568
+ if (pending.length > 0 && !info.isDirectory()) {
569
+ return resolve(candidate, ...pending);
570
+ }
571
+ }
572
+ return resolved;
573
+ }
574
+ /**
575
+ * Copying a skill directory must not smuggle a link to a path outside the
576
+ * adoption root into the authored tree. Links are copied verbatim, so they are
577
+ * never followed while copying; this check decides whether they may be copied.
578
+ * The check must be filesystem-aware: `symlink/..` is resolved through the
579
+ * symlink, not collapsed lexically before it.
580
+ */
581
+ async function symlinkEscapesRoot(root, linkPath) {
582
+ const realRoot = await realpath(root);
583
+ let target;
584
+ try {
585
+ target = await realpath(linkPath);
586
+ }
587
+ catch (error) {
588
+ const code = error.code;
589
+ if (code !== 'ENOENT' && code !== 'ENOTDIR') {
590
+ throw error;
591
+ }
592
+ target = await resolveLinkTarget(linkPath, await readlink(linkPath));
593
+ }
594
+ return !isPathInside(realRoot, target);
595
+ }
596
+ async function findEscapingSymlink(root, dir) {
597
+ for (const entry of await readDirOrEmpty(dir)) {
598
+ const entryPath = join(dir, entry.name);
599
+ if (entry.isSymbolicLink()) {
600
+ if (await symlinkEscapesRoot(root, entryPath)) {
601
+ return entryPath;
602
+ }
603
+ }
604
+ else if (entry.isDirectory()) {
605
+ const nested = await findEscapingSymlink(root, entryPath);
606
+ if (nested !== undefined) {
607
+ return nested;
608
+ }
609
+ }
610
+ }
611
+ return undefined;
612
+ }
613
+ /**
614
+ * Copy into a staging directory and rename, so a failed copy never leaves a
615
+ * half-written skill that a later run would treat as the authored source.
616
+ */
617
+ async function copySkillDirectory(sourceAbs, targetAbs) {
618
+ await ensureDir(dirname(targetAbs));
619
+ const staging = join(dirname(targetAbs), `.${basename(targetAbs)}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
620
+ try {
621
+ await cp(sourceAbs, staging, {
622
+ recursive: true,
623
+ force: false,
624
+ errorOnExist: true,
625
+ dereference: false,
626
+ verbatimSymlinks: true,
627
+ });
628
+ await rename(staging, targetAbs);
629
+ }
630
+ catch (error) {
631
+ await rm(staging, { recursive: true, force: true }).catch(() => undefined);
632
+ throw error;
633
+ }
634
+ }
635
+ async function applyAdoptionEntry(context, entry) {
636
+ if (!entry.writeSource && !entry.replaceTarget) {
637
+ return undefined;
638
+ }
639
+ const source = await safeResolve(context.root, entry.source);
640
+ if (!source.ok) {
641
+ return applyDiagnostic(AdoptionCodes.sourceEscape, entry.source, `${entry.kind} source is not a safe import path: ${errorMessage(source.error)}`, 'Rerun normalize to rebuild the import plan.');
642
+ }
643
+ const target = await safeResolve(context.root, entry.target);
644
+ if (!target.ok) {
645
+ return applyDiagnostic(AdoptionCodes.targetEscape, entry.target, `${entry.kind} target is not a safe import path: ${errorMessage(target.error)}`, 'Rerun normalize to rebuild the import plan.');
646
+ }
647
+ const sourceInfo = await lstatOrNull(source.absolute);
648
+ const expectedSource = entry.kind === 'agent'
649
+ ? sourceInfo?.isFile() === true
650
+ : sourceInfo?.isDirectory() === true;
651
+ if (sourceInfo === null || sourceInfo.isSymbolicLink() || !expectedSource) {
652
+ return applyDiagnostic(AdoptionCodes.sourceMissing, entry.source, `${entry.kind} source is no longer a physical ${entry.kind === 'agent' ? 'file' : 'directory'}: ${entry.source}`, 'Rerun normalize to rebuild the import plan.');
653
+ }
654
+ const targetInfo = await lstatOrNull(target.absolute);
655
+ if (entry.writeSource) {
656
+ if (targetInfo !== null) {
657
+ return applyDiagnostic(AdoptionCodes.targetExists, entry.target, `refusing to overwrite the existing .agents source: ${entry.target}`, 'Rerun normalize so the plan keeps the existing source and only migrates the .claude entry.');
658
+ }
659
+ }
660
+ else {
661
+ if (targetInfo === null) {
662
+ return applyDiagnostic(AdoptionCodes.targetMissing, entry.target, `the existing .agents source disappeared before the import: ${entry.target}`, 'Rerun normalize to rebuild the import plan.');
663
+ }
664
+ const expectedTarget = entry.kind === 'agent'
665
+ ? targetInfo.isFile()
666
+ : targetInfo.isDirectory();
667
+ if (targetInfo.isSymbolicLink() || !expectedTarget) {
668
+ return applyDiagnostic(AdoptionCodes.targetConflict, entry.target, `${entry.kind} target is not ${entry.kind === 'agent' ? 'a regular file' : 'a directory'}: ${entry.target}`, 'Move the existing entry or remove it before importing.');
669
+ }
670
+ }
671
+ if (entry.writeSource) {
672
+ if (entry.kind === 'skill') {
673
+ const escaping = await findEscapingSymlink(context.root, source.absolute);
674
+ if (escaping !== undefined) {
675
+ return skillSymlinkEscape(relativePath(context.root, escaping));
676
+ }
677
+ await copySkillDirectory(source.absolute, target.absolute);
678
+ }
679
+ else {
680
+ await ensureDir(dirname(target.absolute));
681
+ await copyFile(source.absolute, target.absolute, constants.COPYFILE_EXCL);
682
+ }
683
+ context.actions.push(`import ${entry.source} -> ${entry.target}`);
684
+ }
685
+ if (entry.replaceTarget) {
686
+ const backup = await backupPath(context.root, entry.source, context.backupRoot);
687
+ context.backups.push(backup);
688
+ context.actions.push(`backup ${entry.source} -> ${relativePath(context.root, backup)}`);
689
+ await rm(source.absolute, { recursive: true, force: true });
690
+ const linkTarget = relativeLink(source.absolute, target.absolute);
691
+ await replaceSymlink(source.absolute, linkTarget);
692
+ context.actions.push(`symlink ${entry.source} -> ${linkTarget}`);
693
+ }
694
+ return undefined;
695
+ }
696
+ /**
697
+ * Apply a Claude import plan: copy importable agents/skills into the authored
698
+ * `.agents` tree, then back up and replace each `.claude` entry with a
699
+ * per-entry symlink. Existing `.agents` sources are never overwritten.
700
+ * A backup failure aborts before replacement; there is no automatic rollback,
701
+ * so `actions` and `backups` report writes that already happened and a rerun
702
+ * rebuilds the plan from the resulting tree.
703
+ */
704
+ export async function applyClaudeAdoption(input) {
705
+ const actions = [];
706
+ const backups = [];
707
+ const diagnostics = [];
708
+ const context = {
709
+ root: input.root,
710
+ backupRoot: input.backupRoot,
711
+ actions,
712
+ backups,
713
+ };
714
+ for (const entry of input.plan.entries) {
715
+ try {
716
+ const problem = await applyAdoptionEntry(context, entry);
717
+ if (problem !== undefined) {
718
+ diagnostics.push(problem);
719
+ }
720
+ }
721
+ catch (error) {
722
+ diagnostics.push(applyFailure(entry, error));
723
+ break;
724
+ }
725
+ }
726
+ return { actions, backups, diagnostics };
727
+ }
728
+ /**
729
+ * Describe what `applyClaudeAdoption` would do without touching the
730
+ * filesystem. Backup paths are relative to `root`, matching the applied
731
+ * result. Used by `dab normalize --dry-run`.
732
+ */
733
+ export function previewClaudeAdoption(root, plan, backupRoot) {
734
+ const actions = [];
735
+ const backups = [];
736
+ for (const entry of plan.entries) {
737
+ if (entry.writeSource) {
738
+ actions.push(`import ${entry.source} -> ${entry.target}`);
739
+ }
740
+ if (entry.replaceTarget) {
741
+ const backup = toPosix(relative(root, join(backupRoot, entry.source)));
742
+ backups.push(backup);
743
+ actions.push(`backup ${entry.source} -> ${backup}`);
744
+ actions.push(`symlink ${entry.source} -> ${relativeLink(resolve(root, entry.source), resolve(root, entry.target))}`);
745
+ }
746
+ }
747
+ return { actions, backups };
748
+ }
749
+ //# sourceMappingURL=adoption.js.map