@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,747 @@
1
+ import { readlink, realpath } from 'node:fs/promises';
2
+ import { dirname, join, relative, resolve } from 'node:path';
3
+ import { ConfigError, DabError } from '../core/errors.js';
4
+ import { ensureDir, lstatOrNull, writeFileIfAbsent } from '../core/fs-atomic.js';
5
+ import { assertParentInsideRoot, assertRealPathInsideRoot, assertRealPathsDisjoint, isPathInside, toPosix, } from '../core/paths.js';
6
+ import { DAB_VERSION } from '../core/version.js';
7
+ import { applyClaudeAdoption, planClaudeAdoption, } from '../adapter/claude-code/adoption.js';
8
+ import { resolveDocsLanguage } from './docs-language.js';
9
+ import { applyManagedSkillWrites, MANAGED_SKILL_DIAGNOSTIC_CODES, planManagedSkills, } from './managed-skills.js';
10
+ import { AUTHORING_SKILL_NAMES, } from './skill-templates.js';
11
+ import { loadProjectManifest, resolveProjectPaths } from '../model/project-manifest.js';
12
+ import { resolveScopeMarker } from '../model/scope.js';
13
+ import { minimalSourcePlan } from './minimal-source.js';
14
+ import { PRACTICE_PACKS, planAuthoredScaffold, } from './practice.js';
15
+ import { practiceParentDiagnostics, practiceParentProblems, probeLstat, sourceParentDiagnostic, sourceParentProblems, } from '../core/practice-paths.js';
16
+ import { scanProject } from './scanner.js';
17
+ export { minimalSourcePlan } from './minimal-source.js';
18
+ async function isManifestValid(marker) {
19
+ if (!marker.hasManifest) {
20
+ return false;
21
+ }
22
+ try {
23
+ await loadProjectManifest(marker.root, { scope: marker.scope });
24
+ return true;
25
+ }
26
+ catch (error) {
27
+ // An authored manifest that cannot be parsed stays in place; callers see
28
+ // manifestValid=false and must not overwrite it.
29
+ if (error instanceof ConfigError) {
30
+ return false;
31
+ }
32
+ throw error;
33
+ }
34
+ }
35
+ function classifyPhase(input) {
36
+ if (input.manifestValid && input.hasAgents) {
37
+ return 'initialized';
38
+ }
39
+ if (input.hasManifest || input.hasAgents) {
40
+ return 'partial';
41
+ }
42
+ return 'uninitialized';
43
+ }
44
+ export async function resolveAdoptionRoot(input) {
45
+ const marker = await resolveScopeMarker(input);
46
+ const manifestValid = await isManifestValid(marker);
47
+ return {
48
+ scope: marker.scope,
49
+ root: marker.root,
50
+ sourceRoot: marker.sourceRoot,
51
+ manifestPath: marker.manifestPath,
52
+ instructionsPath: marker.instructionsPath,
53
+ phase: classifyPhase({
54
+ manifestValid,
55
+ hasManifest: marker.hasManifest,
56
+ hasAgents: marker.hasAgents,
57
+ }),
58
+ manifestValid,
59
+ };
60
+ }
61
+ export async function planSourceWrites(root, plan) {
62
+ const create = [];
63
+ const skip = [];
64
+ for (const relativePath of Object.keys(plan.files)) {
65
+ // This is a reporting-only plan for blocked and dry runs. A path-state
66
+ // error on the parent is already governed by the caller, so the path is
67
+ // reported as skipped instead of failing with an internal error.
68
+ const state = await probeLstat(join(root, relativePath));
69
+ if (state.info === null && state.problem === undefined) {
70
+ create.push(relativePath);
71
+ }
72
+ else {
73
+ skip.push(relativePath);
74
+ }
75
+ }
76
+ return { create, skip };
77
+ }
78
+ export async function writeSourceFiles(root, plan) {
79
+ for (const directory of plan.directories) {
80
+ await ensureDir(join(root, directory));
81
+ }
82
+ const created = [];
83
+ const skipped = [];
84
+ for (const [relativePath, content] of Object.entries(plan.files)) {
85
+ if (await writeFileIfAbsent(join(root, relativePath), content)) {
86
+ created.push(relativePath);
87
+ }
88
+ else {
89
+ skipped.push(relativePath);
90
+ }
91
+ }
92
+ return { created, skipped };
93
+ }
94
+ async function canonicalPath(path) {
95
+ try {
96
+ return await realpath(path);
97
+ }
98
+ catch (error) {
99
+ if (error.code === 'ENOENT') {
100
+ return resolve(path);
101
+ }
102
+ throw error;
103
+ }
104
+ }
105
+ /**
106
+ * A project fallback can resolve to `$HOME` (for example a dotfiles git repo).
107
+ * `$HOME/.agents` is the global source root in that case, so writing a project
108
+ * skeleton there would silently convert the global source into a project.
109
+ */
110
+ async function assertProjectHomeNotGlobal(adoption, home) {
111
+ if (adoption.scope !== 'project' || adoption.phase === 'initialized') {
112
+ return;
113
+ }
114
+ if ((await lstatOrNull(join(home, '.agents'))) === null) {
115
+ return;
116
+ }
117
+ if (await canonicalPath(adoption.root) !== await canonicalPath(home)) {
118
+ return;
119
+ }
120
+ throw new ConfigError('refusing to adopt project source at $HOME while ~/.agents is the global source root', 'config.source-root-nested', { hint: 'Run dab normalize from inside ~/.agents to adopt global scope.' });
121
+ }
122
+ function sourceRootOf(adoption) {
123
+ return {
124
+ scope: adoption.scope,
125
+ root: adoption.root,
126
+ sourceRoot: adoption.sourceRoot,
127
+ manifest: adoption.manifestPath,
128
+ instructions: adoption.instructionsPath,
129
+ };
130
+ }
131
+ /**
132
+ * Plan the import of physical `.claude/agents` and `.claude/skills` entries.
133
+ * The plan is read-only, runs for every phase (including initialized scopes),
134
+ * and is gated by the caller before any source or `.claude` write.
135
+ */
136
+ async function planImports(adoption, manifest, paths) {
137
+ return planClaudeAdoption({
138
+ root: adoption.root,
139
+ scope: adoption.scope,
140
+ agentsRoot: paths.agents,
141
+ claudeRoot: paths.claude,
142
+ manifest,
143
+ });
144
+ }
145
+ function emptyManagedSkillSummary() {
146
+ return {
147
+ actions: [],
148
+ created: [],
149
+ updated: [],
150
+ migrated: [],
151
+ skipped: [],
152
+ modified: [],
153
+ newer: [],
154
+ legacy: [],
155
+ unversioned: [],
156
+ markerMismatch: [],
157
+ concurrent: [],
158
+ };
159
+ }
160
+ /**
161
+ * The authoring pack owns missing skill files it planned itself, so the managed
162
+ * writer must not also create them. Legacy, stale and skipped states are
163
+ * untouched by the pack because an existing skill directory is user-owned.
164
+ */
165
+ export function planManagedSkillWrites(plan, practiceFiles) {
166
+ const states = plan.states.filter((state) => state.status !== 'missing' || !practiceFiles.has(state.file));
167
+ const retained = new Set(states.map((state) => state.file));
168
+ return {
169
+ states,
170
+ writes: plan.writes.filter((write) => retained.has(write.file)),
171
+ diagnostics: [...plan.diagnostics],
172
+ };
173
+ }
174
+ /**
175
+ * Derive the normalize report from the writes plan. When the plan was applied,
176
+ * `applied` carries the revalidation outcome: a target that changed after
177
+ * planning moves from created/updated/migrated to the preserved `concurrent`
178
+ * list instead of claiming a write that did not happen. A dry run passes the
179
+ * same apply result (with no bytes written) so both modes agree.
180
+ */
181
+ export function summarizeManagedSkills(plan, applied) {
182
+ const summary = emptyManagedSkillSummary();
183
+ if (plan === undefined) {
184
+ return summary;
185
+ }
186
+ const writes = new Set(plan.writes.map((write) => write.file));
187
+ const mismatched = new Set(plan.diagnostics
188
+ .filter((item) => item.code === MANAGED_SKILL_DIAGNOSTIC_CODES.mismatch)
189
+ .flatMap((item) => (item.file === undefined ? [] : [item.file])));
190
+ const created = new Set(applied?.created ?? []);
191
+ const updated = new Set(applied?.updated ?? []);
192
+ const migrated = new Set(applied?.migrated ?? []);
193
+ const concurrent = new Set(applied?.concurrent ?? []);
194
+ const markApplied = (state, written, kind) => {
195
+ if (applied === undefined || written.has(state.file)) {
196
+ if (kind === 'create') {
197
+ summary.created.push(state.file);
198
+ }
199
+ else if (kind === 'update') {
200
+ summary.updated.push(state.file);
201
+ }
202
+ else {
203
+ summary.migrated.push(state.file);
204
+ }
205
+ summary.actions.push(`${kind} skill ${state.file}`);
206
+ return;
207
+ }
208
+ if (concurrent.has(state.file)) {
209
+ summary.skipped.push(state.file);
210
+ summary.concurrent.push(state.file);
211
+ summary.actions.push(`skip skill ${state.file} (concurrent-change)`);
212
+ return;
213
+ }
214
+ throw new Error(`managed skill apply result has no ${kind} outcome for ${state.name}`);
215
+ };
216
+ for (const state of plan.states) {
217
+ switch (state.status) {
218
+ case 'missing': {
219
+ markApplied(state, created, 'create');
220
+ break;
221
+ }
222
+ case 'stale': {
223
+ markApplied(state, updated, 'update');
224
+ break;
225
+ }
226
+ case 'legacy': {
227
+ if (writes.has(state.file)) {
228
+ markApplied(state, migrated, 'migrate');
229
+ }
230
+ else {
231
+ summary.skipped.push(state.file);
232
+ summary.legacy.push(state.file);
233
+ summary.actions.push(`skip skill ${state.file} (legacy)`);
234
+ }
235
+ break;
236
+ }
237
+ case 'current': {
238
+ summary.skipped.push(state.file);
239
+ break;
240
+ }
241
+ case 'modified': {
242
+ summary.skipped.push(state.file);
243
+ summary.modified.push(state.file);
244
+ summary.actions.push(`skip skill ${state.file} (modified)`);
245
+ break;
246
+ }
247
+ case 'newer': {
248
+ summary.skipped.push(state.file);
249
+ summary.newer.push(state.file);
250
+ summary.actions.push(`skip skill ${state.file} (newer)`);
251
+ break;
252
+ }
253
+ case 'unversioned': {
254
+ summary.skipped.push(state.file);
255
+ if (mismatched.has(state.file)) {
256
+ summary.markerMismatch.push(state.file);
257
+ summary.actions.push(`skip skill ${state.file} (marker-mismatch)`);
258
+ }
259
+ else {
260
+ summary.unversioned.push(state.file);
261
+ summary.actions.push(`skip skill ${state.file} (unversioned)`);
262
+ }
263
+ break;
264
+ }
265
+ }
266
+ }
267
+ return summary;
268
+ }
269
+ /**
270
+ * Plan authored practice artifacts through the shared planner. Normalize uses
271
+ * adoption mode before a manifest exists and converge mode afterwards; the
272
+ * production pack registry is always explicit.
273
+ *
274
+ * A regular file at `.agents/rules` or `.agents/skills` breaks discovery and
275
+ * child writes with ENOTDIR. The planner reports child conflicts for adoption,
276
+ * but converge has no core targets, so probe both parents first and return a
277
+ * governed practice diagnostic with an empty plan.
278
+ */
279
+ async function planPractices(input) {
280
+ const docsLanguage = await resolveDocsLanguage({
281
+ root: input.root,
282
+ configured: input.manifest?.docs.language ?? 'auto',
283
+ env: process.env,
284
+ });
285
+ if (input.scope === 'project') {
286
+ const problems = await practiceParentProblems(input.root);
287
+ const diagnostics = [];
288
+ for (const [code, problem] of [
289
+ ['practice.docs-path', problems.docs],
290
+ ['practice.skill-path', problems.skills],
291
+ ]) {
292
+ if (problem === undefined) {
293
+ continue;
294
+ }
295
+ diagnostics.push({
296
+ code,
297
+ severity: 'error',
298
+ message: problem.message,
299
+ file: problem.path,
300
+ hint: 'Resolve the path conflict manually; DAB never writes through it.',
301
+ });
302
+ }
303
+ if (diagnostics.length > 0) {
304
+ return {
305
+ profile: input.profile,
306
+ mode: input.mode,
307
+ files: {},
308
+ directories: [],
309
+ skipped: [],
310
+ policySkipped: [],
311
+ diagnostics,
312
+ ...(input.manifest === undefined ? {} : { manifest: input.manifest }),
313
+ docsLanguage,
314
+ };
315
+ }
316
+ }
317
+ return planAuthoredScaffold({
318
+ root: input.root,
319
+ scope: input.scope,
320
+ scan: input.scan,
321
+ profile: input.profile,
322
+ mode: input.mode,
323
+ version: DAB_VERSION,
324
+ env: process.env,
325
+ ...(input.manifest === undefined ? {} : { manifest: input.manifest }),
326
+ }, PRACTICE_PACKS);
327
+ }
328
+ /**
329
+ * The practice planner resolves real parent paths, which cannot resolve a
330
+ * dangling `.agents` symlink. Normalize still needs to reach its source-write
331
+ * safety gate to report the alias/escape, so detect this layout before planning
332
+ * and use the minimal plan instead of throwing a raw filesystem error.
333
+ */
334
+ async function danglingSourceDiagnostic(root) {
335
+ const agents = join(root, '.agents');
336
+ const info = await lstatOrNull(agents);
337
+ if (info?.isSymbolicLink() !== true) {
338
+ return undefined;
339
+ }
340
+ try {
341
+ await realpath(agents);
342
+ return undefined;
343
+ }
344
+ catch (error) {
345
+ if (error.code !== 'ENOENT') {
346
+ throw error;
347
+ }
348
+ }
349
+ if (await lexicalAlias(root, '.agents', '.claude')) {
350
+ return {
351
+ code: 'path.overlap',
352
+ severity: 'error',
353
+ message: 'authored and generated trees overlap: .agents and .claude',
354
+ file: '.agents',
355
+ };
356
+ }
357
+ return {
358
+ code: 'path.symlink-escape',
359
+ severity: 'error',
360
+ message: 'authored source parent is a dangling symlink: .agents',
361
+ file: '.agents',
362
+ };
363
+ }
364
+ /**
365
+ * Names of authoring skills whose `.agents` source is written by a Claude
366
+ * import. A physical `.claude/skills/dab-*` entry is an import fact; the import
367
+ * owns that skill, so the authoring pack and the managed writer must both stay
368
+ * away from it.
369
+ */
370
+ function importedAuthoringSkillNames(claudePlan) {
371
+ const imported = new Set();
372
+ for (const entry of claudePlan?.entries ?? []) {
373
+ if (entry.kind !== 'skill' || !entry.writeSource) {
374
+ continue;
375
+ }
376
+ for (const name of AUTHORING_SKILL_NAMES) {
377
+ if (entry.target === `.agents/skills/${name}`) {
378
+ imported.add(name);
379
+ }
380
+ }
381
+ }
382
+ return imported;
383
+ }
384
+ function suppressImportedAuthoringSkillTemplates(plan, imported) {
385
+ if (imported.size === 0) {
386
+ return plan;
387
+ }
388
+ const targets = new Set([...imported].map((name) => `.agents/skills/${name}`));
389
+ const suppressed = (path) => {
390
+ for (const target of targets) {
391
+ if (path === target || path.startsWith(`${target}/`)) {
392
+ return true;
393
+ }
394
+ }
395
+ return false;
396
+ };
397
+ return {
398
+ ...plan,
399
+ files: Object.fromEntries(Object.entries(plan.files).filter(([path]) => !suppressed(path))),
400
+ directories: plan.directories.filter((path) => !suppressed(path)),
401
+ };
402
+ }
403
+ /**
404
+ * Plan managed `dab-*` skills for project scope only. Imports that will write
405
+ * a missing `.agents` source are excluded: the import owns that skill and
406
+ * `applyClaudeAdoption` refuses to overwrite a source that appeared first.
407
+ */
408
+ async function planManagedSkillsFor(root, scope, options) {
409
+ if (scope !== 'project' || options.suppress === true) {
410
+ return undefined;
411
+ }
412
+ const names = AUTHORING_SKILL_NAMES.filter((name) => !options.imported.has(name));
413
+ return planManagedSkills({ root, version: DAB_VERSION, names });
414
+ }
415
+ export async function prepareNormalizeAdoption(input) {
416
+ const adoption = await resolveAdoptionRoot({ cwd: input.cwd, home: input.home });
417
+ const sourceRoot = sourceRootOf(adoption);
418
+ const manifestKey = toPosix(relative(adoption.root, adoption.manifestPath));
419
+ const hasManifest = (await lstatOrNull(adoption.manifestPath)) !== null;
420
+ // Project practice parents are probed by the practice planner, which owns
421
+ // their `practice.docs-path`/`practice.skill-path` codes. Global scope has no
422
+ // practice packs, so their access and type conflicts are governed here.
423
+ const sourceProblems = [
424
+ ...(await sourceParentProblems(adoption.root)).map(sourceParentDiagnostic),
425
+ ...(adoption.scope === 'global'
426
+ ? practiceParentDiagnostics(await practiceParentProblems(adoption.root))
427
+ : []),
428
+ ];
429
+ const sourceExtras = sourceProblems.length === 0
430
+ ? {}
431
+ : { sourceProblems };
432
+ // Import planning reads the authored agents and skills trees. A broken core
433
+ // source parent already blocks the run, so the plan is skipped instead of
434
+ // failing discovery with an internal error.
435
+ const importPlan = (manifest, paths) => input.suppressImports === true || sourceProblems.length > 0
436
+ ? Promise.resolve(undefined)
437
+ : planImports(adoption, manifest, paths);
438
+ if (hasManifest && !adoption.manifestValid) {
439
+ // Re-run the loader so callers receive the exact ConfigError (invalid
440
+ // manifest, scope mismatch, unsupported paths) and nothing is overwritten.
441
+ await loadProjectManifest(adoption.root, { scope: adoption.scope });
442
+ throw new ConfigError(`invalid ${manifestKey}`, 'config.invalid');
443
+ }
444
+ const sourceProblem = await danglingSourceDiagnostic(adoption.root);
445
+ if (hasManifest) {
446
+ const loaded = await loadProjectManifest(adoption.root, { scope: adoption.scope });
447
+ const paths = resolveProjectPaths(adoption.root, loaded.manifest);
448
+ if (adoption.phase === 'initialized') {
449
+ if (sourceProblem !== undefined) {
450
+ return {
451
+ sourceRoot,
452
+ phase: adoption.phase,
453
+ manifest: loaded.manifest,
454
+ paths,
455
+ claudePlan: await importPlan(loaded.manifest, paths),
456
+ ...sourceExtras,
457
+ diagnostics: [sourceProblem, ...sourceProblems],
458
+ };
459
+ }
460
+ const scan = await scanProject(adoption.root);
461
+ const claudePlan = await importPlan(loaded.manifest, paths);
462
+ const imported = importedAuthoringSkillNames(claudePlan);
463
+ const practicePlan = suppressImportedAuthoringSkillTemplates(await planPractices({
464
+ root: adoption.root,
465
+ scope: adoption.scope,
466
+ scan,
467
+ profile: loaded.manifest.profile,
468
+ mode: 'converge',
469
+ manifest: loaded.manifest,
470
+ }), imported);
471
+ const managedSkills = await planManagedSkillsFor(adoption.root, adoption.scope, {
472
+ suppress: input.suppressManagedSkills,
473
+ imported,
474
+ });
475
+ return {
476
+ sourceRoot,
477
+ phase: adoption.phase,
478
+ manifest: loaded.manifest,
479
+ paths,
480
+ practicePlan,
481
+ claudePlan,
482
+ ...(managedSkills === undefined ? {} : { managedSkills }),
483
+ ...sourceExtras,
484
+ diagnostics: [
485
+ ...scan.diagnostics,
486
+ ...practicePlan.diagnostics,
487
+ ...(managedSkills?.diagnostics ?? []),
488
+ ...sourceProblems,
489
+ ],
490
+ };
491
+ }
492
+ await assertProjectHomeNotGlobal(adoption, input.home);
493
+ const scan = await scanProject(adoption.root);
494
+ if (sourceProblem !== undefined) {
495
+ const plan = minimalSourcePlan(scan, adoption.scope);
496
+ const { [manifestKey]: _authored, ...files } = plan.files;
497
+ return {
498
+ sourceRoot,
499
+ phase: adoption.phase,
500
+ manifest: loaded.manifest,
501
+ paths,
502
+ sourcePlan: { ...plan, files, manifest: loaded.manifest },
503
+ claudePlan: await importPlan(loaded.manifest, paths),
504
+ ...sourceExtras,
505
+ diagnostics: [sourceProblem, ...scan.diagnostics, ...sourceProblems],
506
+ };
507
+ }
508
+ const claudePlan = await importPlan(loaded.manifest, paths);
509
+ const imported = importedAuthoringSkillNames(claudePlan);
510
+ const practicePlan = suppressImportedAuthoringSkillTemplates(await planPractices({
511
+ root: adoption.root,
512
+ scope: adoption.scope,
513
+ scan,
514
+ profile: loaded.manifest.profile,
515
+ mode: 'adoption',
516
+ manifest: loaded.manifest,
517
+ }), imported);
518
+ const managedSkills = await planManagedSkillsFor(adoption.root, adoption.scope, {
519
+ suppress: input.suppressManagedSkills,
520
+ imported,
521
+ });
522
+ // The authored manifest is authoritative: it is never part of the write
523
+ // plan and `practicePlan.manifest` stays equal to what normalize loads.
524
+ const { [manifestKey]: _authored, ...files } = practicePlan.files;
525
+ return {
526
+ sourceRoot,
527
+ phase: adoption.phase,
528
+ manifest: loaded.manifest,
529
+ paths,
530
+ sourcePlan: {
531
+ files,
532
+ directories: practicePlan.directories,
533
+ manifest: loaded.manifest,
534
+ },
535
+ practicePlan,
536
+ claudePlan,
537
+ ...(managedSkills === undefined ? {} : { managedSkills }),
538
+ ...sourceExtras,
539
+ diagnostics: [
540
+ ...scan.diagnostics,
541
+ ...practicePlan.diagnostics,
542
+ ...(managedSkills?.diagnostics ?? []),
543
+ ...sourceProblems,
544
+ ],
545
+ };
546
+ }
547
+ await assertProjectHomeNotGlobal(adoption, input.home);
548
+ const scan = await scanProject(adoption.root);
549
+ if (sourceProblem !== undefined) {
550
+ const plan = minimalSourcePlan(scan, adoption.scope);
551
+ const paths = resolveProjectPaths(adoption.root, plan.manifest);
552
+ return {
553
+ sourceRoot,
554
+ phase: adoption.phase,
555
+ manifest: plan.manifest,
556
+ paths,
557
+ sourcePlan: plan,
558
+ claudePlan: await importPlan(plan.manifest, paths),
559
+ ...sourceExtras,
560
+ diagnostics: [sourceProblem, ...scan.diagnostics, ...sourceProblems],
561
+ };
562
+ }
563
+ const rawPracticePlan = await planPractices({
564
+ root: adoption.root,
565
+ scope: adoption.scope,
566
+ scan,
567
+ profile: 'generic',
568
+ mode: 'adoption',
569
+ });
570
+ const manifest = rawPracticePlan.manifest ?? minimalSourcePlan(scan, adoption.scope).manifest;
571
+ const paths = resolveProjectPaths(adoption.root, manifest);
572
+ const claudePlan = await importPlan(manifest, paths);
573
+ const imported = importedAuthoringSkillNames(claudePlan);
574
+ const practicePlan = suppressImportedAuthoringSkillTemplates(rawPracticePlan, imported);
575
+ const managedSkills = await planManagedSkillsFor(adoption.root, adoption.scope, {
576
+ suppress: input.suppressManagedSkills,
577
+ imported,
578
+ });
579
+ return {
580
+ sourceRoot,
581
+ phase: adoption.phase,
582
+ manifest,
583
+ paths,
584
+ sourcePlan: {
585
+ files: practicePlan.files,
586
+ directories: practicePlan.directories,
587
+ manifest,
588
+ },
589
+ practicePlan,
590
+ claudePlan,
591
+ ...(managedSkills === undefined ? {} : { managedSkills }),
592
+ ...sourceExtras,
593
+ diagnostics: [
594
+ ...scan.diagnostics,
595
+ ...practicePlan.diagnostics,
596
+ ...(managedSkills?.diagnostics ?? []),
597
+ ...sourceProblems,
598
+ ],
599
+ };
600
+ }
601
+ function adoptionDiagnostic(error, file) {
602
+ return {
603
+ code: error.code,
604
+ severity: 'error',
605
+ message: error.message,
606
+ file,
607
+ ...(error.hint === undefined ? {} : { hint: error.hint }),
608
+ };
609
+ }
610
+ /**
611
+ * Real-path disjointness cannot compare a dangling symlink with its intended
612
+ * target (`realpath` fails). Compare the direct link text as well so
613
+ * `.agents -> .claude` or `.claude -> .agents` is rejected before the source
614
+ * write creates the missing target.
615
+ */
616
+ async function lexicalAlias(root, first, second) {
617
+ const firstPath = join(root, first);
618
+ const secondPath = join(root, second);
619
+ for (const [linkPath, otherPath] of [
620
+ [firstPath, secondPath],
621
+ [secondPath, firstPath],
622
+ ]) {
623
+ const info = await lstatOrNull(linkPath);
624
+ if (info?.isSymbolicLink() !== true) {
625
+ continue;
626
+ }
627
+ const resolved = resolve(dirname(linkPath), await readlink(linkPath));
628
+ if (resolved === otherPath
629
+ || isPathInside(resolved, otherPath)
630
+ || isPathInside(otherPath, resolved)) {
631
+ return true;
632
+ }
633
+ }
634
+ return false;
635
+ }
636
+ /**
637
+ * Init-style containment checks run before the first write. `plan.directories`
638
+ * omits implicitly created parents (policies, adapters), so every planned file
639
+ * is checked as well as the source tree itself.
640
+ */
641
+ async function sourceWriteDiagnostics(root, plan, agents) {
642
+ // An aliased `.agents`/`.claude` pair would route the minimal source writes
643
+ // through the generated tree before the target preflight notices. Check the
644
+ // tree identity first so a rejected layout writes nothing at all.
645
+ try {
646
+ await assertRealPathInsideRoot(root, '.claude');
647
+ await assertRealPathsDisjoint(root, '.agents', '.claude');
648
+ if (await lexicalAlias(root, '.agents', '.claude')) {
649
+ throw new ConfigError('authored and generated trees overlap: .agents and .claude', 'path.overlap');
650
+ }
651
+ }
652
+ catch (error) {
653
+ if (error instanceof DabError) {
654
+ return [adoptionDiagnostic(error, '.agents')];
655
+ }
656
+ throw error;
657
+ }
658
+ for (const relativePath of [
659
+ agents,
660
+ ...plan.directories,
661
+ ...Object.keys(plan.files),
662
+ ]) {
663
+ try {
664
+ await assertRealPathInsideRoot(root, relativePath);
665
+ await assertParentInsideRoot(root, relativePath);
666
+ }
667
+ catch (error) {
668
+ if (error instanceof DabError) {
669
+ return [adoptionDiagnostic(error, relativePath)];
670
+ }
671
+ throw error;
672
+ }
673
+ }
674
+ return [];
675
+ }
676
+ /**
677
+ * Applies the prepared adoption: minimal source writes first, then the Claude
678
+ * imports/backups/symlinks under the same backup root. Callers may pass a
679
+ * preparation with only one of the two plans to stage the writes around a
680
+ * read-only target preflight; a source containment failure skips the imports
681
+ * entirely so neither tree is touched.
682
+ */
683
+ export async function applyNormalizeAdoption(prep, options) {
684
+ const root = prep.sourceRoot.root;
685
+ const actions = [];
686
+ const backups = [];
687
+ const diagnostics = [];
688
+ const created = [];
689
+ const skipped = [];
690
+ if (prep.sourcePlan !== undefined) {
691
+ const agents = toPosix(relative(root, prep.paths.agents));
692
+ const sourceDiagnostics = await sourceWriteDiagnostics(root, prep.sourcePlan, agents);
693
+ if (sourceDiagnostics.length > 0) {
694
+ return {
695
+ actions: [],
696
+ backups: [],
697
+ diagnostics: sourceDiagnostics,
698
+ created: [],
699
+ skipped: [],
700
+ };
701
+ }
702
+ if (options.dryRun) {
703
+ const planned = await planSourceWrites(root, prep.sourcePlan);
704
+ created.push(...planned.create);
705
+ skipped.push(...planned.skip);
706
+ }
707
+ else {
708
+ const written = await writeSourceFiles(root, prep.sourcePlan);
709
+ created.push(...written.created);
710
+ skipped.push(...written.skipped);
711
+ }
712
+ actions.push(...created.map((file) => `create ${file}`), ...skipped.map((file) => `skip ${file}`));
713
+ }
714
+ // Managed skill writes share the practice source phase: every blocking
715
+ // preflight has already run, and the new skill content is visible to target
716
+ // planning in this same normalization.
717
+ let managed;
718
+ if (prep.managedSkills !== undefined) {
719
+ // Apply (or revalidate on a dry run) first so the report never claims a
720
+ // write that a concurrent change turned into a preserved file.
721
+ const appliedManaged = await applyManagedSkillWrites(root, prep.managedSkills, { dryRun: options.dryRun });
722
+ managed = summarizeManagedSkills(prep.managedSkills, appliedManaged);
723
+ actions.push(...managed.actions);
724
+ diagnostics.push(...appliedManaged.diagnostics);
725
+ }
726
+ // A dry run never replaces .claude entries; the import plan itself is
727
+ // reported through NormalizeResult.adoption.imports.
728
+ if (prep.claudePlan !== undefined && !options.dryRun) {
729
+ const applied = await applyClaudeAdoption({
730
+ root,
731
+ plan: prep.claudePlan,
732
+ backupRoot: options.backupRoot,
733
+ });
734
+ actions.push(...applied.actions);
735
+ backups.push(...applied.backups);
736
+ diagnostics.push(...applied.diagnostics);
737
+ }
738
+ return {
739
+ actions,
740
+ backups,
741
+ diagnostics,
742
+ created,
743
+ skipped,
744
+ ...(managed === undefined ? {} : { managed }),
745
+ };
746
+ }
747
+ //# sourceMappingURL=adoption.js.map