@saydone/dab 0.0.0-stage → 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 (242) hide show
  1. package/AGENTS.md +62 -0
  2. package/CHANGELOG.md +52 -0
  3. package/CHANGELOG.zh.md +52 -0
  4. package/LICENSE +21 -0
  5. package/README.i18n.yaml +55 -0
  6. package/README.md +157 -2
  7. package/README.zh.md +158 -0
  8. package/dist/adapter/claude-code/adapter.d.ts +10 -0
  9. package/dist/adapter/claude-code/adapter.js +226 -0
  10. package/dist/adapter/claude-code/adapter.js.map +1 -0
  11. package/dist/adapter/claude-code/adoption.d.ts +58 -0
  12. package/dist/adapter/claude-code/adoption.js +749 -0
  13. package/dist/adapter/claude-code/adoption.js.map +1 -0
  14. package/dist/adapter/claude-code/hooks.d.ts +10 -0
  15. package/dist/adapter/claude-code/hooks.js +58 -0
  16. package/dist/adapter/claude-code/hooks.js.map +1 -0
  17. package/dist/adapter/claude-code/instructions.d.ts +26 -0
  18. package/dist/adapter/claude-code/instructions.js +235 -0
  19. package/dist/adapter/claude-code/instructions.js.map +1 -0
  20. package/dist/adapter/claude-code/options.d.ts +12 -0
  21. package/dist/adapter/claude-code/options.js +27 -0
  22. package/dist/adapter/claude-code/options.js.map +1 -0
  23. package/dist/adapter/claude-code/policy-compile.d.ts +30 -0
  24. package/dist/adapter/claude-code/policy-compile.js +293 -0
  25. package/dist/adapter/claude-code/policy-compile.js.map +1 -0
  26. package/dist/adapter/claude-code/projection.d.ts +36 -0
  27. package/dist/adapter/claude-code/projection.js +272 -0
  28. package/dist/adapter/claude-code/projection.js.map +1 -0
  29. package/dist/adapter/claude-code/settings-plan.d.ts +12 -0
  30. package/dist/adapter/claude-code/settings-plan.js +64 -0
  31. package/dist/adapter/claude-code/settings-plan.js.map +1 -0
  32. package/dist/adapter/claude-code/settings.d.ts +21 -0
  33. package/dist/adapter/claude-code/settings.js +58 -0
  34. package/dist/adapter/claude-code/settings.js.map +1 -0
  35. package/dist/adapter/claude-code/version.d.ts +8 -0
  36. package/dist/adapter/claude-code/version.js +32 -0
  37. package/dist/adapter/claude-code/version.js.map +1 -0
  38. package/dist/adapter/registry.d.ts +3 -0
  39. package/dist/adapter/registry.js +8 -0
  40. package/dist/adapter/registry.js.map +1 -0
  41. package/dist/adapter/types.d.ts +70 -0
  42. package/dist/adapter/types.js +2 -0
  43. package/dist/adapter/types.js.map +1 -0
  44. package/dist/cli.d.ts +12 -0
  45. package/dist/cli.js +260 -0
  46. package/dist/cli.js.map +1 -0
  47. package/dist/commands/detect.d.ts +44 -0
  48. package/dist/commands/detect.js +543 -0
  49. package/dist/commands/detect.js.map +1 -0
  50. package/dist/commands/init.d.ts +48 -0
  51. package/dist/commands/init.js +727 -0
  52. package/dist/commands/init.js.map +1 -0
  53. package/dist/commands/normalize.d.ts +106 -0
  54. package/dist/commands/normalize.js +715 -0
  55. package/dist/commands/normalize.js.map +1 -0
  56. package/dist/commands/policy-explain.d.ts +47 -0
  57. package/dist/commands/policy-explain.js +283 -0
  58. package/dist/commands/policy-explain.js.map +1 -0
  59. package/dist/core/command.d.ts +13 -0
  60. package/dist/core/command.js +68 -0
  61. package/dist/core/command.js.map +1 -0
  62. package/dist/core/compare.d.ts +7 -0
  63. package/dist/core/compare.js +16 -0
  64. package/dist/core/compare.js.map +1 -0
  65. package/dist/core/diagnostics.d.ts +15 -0
  66. package/dist/core/diagnostics.js +65 -0
  67. package/dist/core/diagnostics.js.map +1 -0
  68. package/dist/core/errors.d.ts +25 -0
  69. package/dist/core/errors.js +45 -0
  70. package/dist/core/errors.js.map +1 -0
  71. package/dist/core/exit-codes.d.ts +8 -0
  72. package/dist/core/exit-codes.js +8 -0
  73. package/dist/core/exit-codes.js.map +1 -0
  74. package/dist/core/fs-atomic.d.ts +13 -0
  75. package/dist/core/fs-atomic.js +113 -0
  76. package/dist/core/fs-atomic.js.map +1 -0
  77. package/dist/core/gitignore.d.ts +6 -0
  78. package/dist/core/gitignore.js +54 -0
  79. package/dist/core/gitignore.js.map +1 -0
  80. package/dist/core/hash.d.ts +1 -0
  81. package/dist/core/hash.js +5 -0
  82. package/dist/core/hash.js.map +1 -0
  83. package/dist/core/json.d.ts +3 -0
  84. package/dist/core/json.js +21 -0
  85. package/dist/core/json.js.map +1 -0
  86. package/dist/core/markdown-links.d.ts +5 -0
  87. package/dist/core/markdown-links.js +37 -0
  88. package/dist/core/markdown-links.js.map +1 -0
  89. package/dist/core/paths.d.ts +12 -0
  90. package/dist/core/paths.js +152 -0
  91. package/dist/core/paths.js.map +1 -0
  92. package/dist/core/platform.d.ts +1 -0
  93. package/dist/core/platform.js +7 -0
  94. package/dist/core/platform.js.map +1 -0
  95. package/dist/core/practice-paths.d.ts +73 -0
  96. package/dist/core/practice-paths.js +310 -0
  97. package/dist/core/practice-paths.js.map +1 -0
  98. package/dist/core/security.d.ts +2 -0
  99. package/dist/core/security.js +101 -0
  100. package/dist/core/security.js.map +1 -0
  101. package/dist/core/semver.d.ts +9 -0
  102. package/dist/core/semver.js +32 -0
  103. package/dist/core/semver.js.map +1 -0
  104. package/dist/core/skill-marker.d.ts +28 -0
  105. package/dist/core/skill-marker.js +57 -0
  106. package/dist/core/skill-marker.js.map +1 -0
  107. package/dist/core/version-check.d.ts +10 -0
  108. package/dist/core/version-check.js +28 -0
  109. package/dist/core/version-check.js.map +1 -0
  110. package/dist/core/version-compare.d.ts +8 -0
  111. package/dist/core/version-compare.js +23 -0
  112. package/dist/core/version-compare.js.map +1 -0
  113. package/dist/core/version.d.ts +2 -0
  114. package/dist/core/version.js +13 -0
  115. package/dist/core/version.js.map +1 -0
  116. package/dist/core/yaml.d.ts +4 -0
  117. package/dist/core/yaml.js +24 -0
  118. package/dist/core/yaml.js.map +1 -0
  119. package/dist/detect/ancestor-claude-md.d.ts +1 -0
  120. package/dist/detect/ancestor-claude-md.js +33 -0
  121. package/dist/detect/ancestor-claude-md.js.map +1 -0
  122. package/dist/detect/checklist.d.ts +42 -0
  123. package/dist/detect/checklist.js +137 -0
  124. package/dist/detect/checklist.js.map +1 -0
  125. package/dist/detect/checks.d.ts +13 -0
  126. package/dist/detect/checks.js +537 -0
  127. package/dist/detect/checks.js.map +1 -0
  128. package/dist/detect/practice.d.ts +43 -0
  129. package/dist/detect/practice.js +782 -0
  130. package/dist/detect/practice.js.map +1 -0
  131. package/dist/detect/preflight.d.ts +21 -0
  132. package/dist/detect/preflight.js +408 -0
  133. package/dist/detect/preflight.js.map +1 -0
  134. package/dist/docs/budgets.d.ts +2 -0
  135. package/dist/docs/budgets.js +57 -0
  136. package/dist/docs/budgets.js.map +1 -0
  137. package/dist/docs/cli.d.ts +7 -0
  138. package/dist/docs/cli.js +102 -0
  139. package/dist/docs/cli.js.map +1 -0
  140. package/dist/docs/config.d.ts +8 -0
  141. package/dist/docs/config.js +82 -0
  142. package/dist/docs/config.js.map +1 -0
  143. package/dist/docs/doc-sync.d.ts +10 -0
  144. package/dist/docs/doc-sync.js +33 -0
  145. package/dist/docs/doc-sync.js.map +1 -0
  146. package/dist/docs/files.d.ts +1 -0
  147. package/dist/docs/files.js +42 -0
  148. package/dist/docs/files.js.map +1 -0
  149. package/dist/docs/links.d.ts +3 -0
  150. package/dist/docs/links.js +90 -0
  151. package/dist/docs/links.js.map +1 -0
  152. package/dist/docs/markdown.d.ts +55 -0
  153. package/dist/docs/markdown.js +227 -0
  154. package/dist/docs/markdown.js.map +1 -0
  155. package/dist/docs/notes.d.ts +2 -0
  156. package/dist/docs/notes.js +175 -0
  157. package/dist/docs/notes.js.map +1 -0
  158. package/dist/docs/pairing.d.ts +45 -0
  159. package/dist/docs/pairing.js +472 -0
  160. package/dist/docs/pairing.js.map +1 -0
  161. package/dist/docs/wrap.d.ts +2 -0
  162. package/dist/docs/wrap.js +98 -0
  163. package/dist/docs/wrap.js.map +1 -0
  164. package/dist/init/adoption.d.ts +138 -0
  165. package/dist/init/adoption.js +747 -0
  166. package/dist/init/adoption.js.map +1 -0
  167. package/dist/init/ai-proposal.d.ts +15 -0
  168. package/dist/init/ai-proposal.js +164 -0
  169. package/dist/init/ai-proposal.js.map +1 -0
  170. package/dist/init/docs-language.d.ts +12 -0
  171. package/dist/init/docs-language.js +110 -0
  172. package/dist/init/docs-language.js.map +1 -0
  173. package/dist/init/managed-skills.d.ts +81 -0
  174. package/dist/init/managed-skills.js +407 -0
  175. package/dist/init/managed-skills.js.map +1 -0
  176. package/dist/init/minimal-source.d.ts +14 -0
  177. package/dist/init/minimal-source.js +42 -0
  178. package/dist/init/minimal-source.js.map +1 -0
  179. package/dist/init/practice-authoring.d.ts +5 -0
  180. package/dist/init/practice-authoring.js +36 -0
  181. package/dist/init/practice-authoring.js.map +1 -0
  182. package/dist/init/practice-docs.d.ts +13 -0
  183. package/dist/init/practice-docs.js +278 -0
  184. package/dist/init/practice-docs.js.map +1 -0
  185. package/dist/init/practice.d.ts +78 -0
  186. package/dist/init/practice.js +528 -0
  187. package/dist/init/practice.js.map +1 -0
  188. package/dist/init/scanner.d.ts +22 -0
  189. package/dist/init/scanner.js +190 -0
  190. package/dist/init/scanner.js.map +1 -0
  191. package/dist/init/skill-templates.d.ts +7 -0
  192. package/dist/init/skill-templates.js +25 -0
  193. package/dist/init/skill-templates.js.map +1 -0
  194. package/dist/init/templates.d.ts +53 -0
  195. package/dist/init/templates.js +254 -0
  196. package/dist/init/templates.js.map +1 -0
  197. package/dist/model/agents-md.d.ts +6 -0
  198. package/dist/model/agents-md.js +41 -0
  199. package/dist/model/agents-md.js.map +1 -0
  200. package/dist/model/agents.d.ts +12 -0
  201. package/dist/model/agents.js +346 -0
  202. package/dist/model/agents.js.map +1 -0
  203. package/dist/model/diagnostics-codes.d.ts +34 -0
  204. package/dist/model/diagnostics-codes.js +35 -0
  205. package/dist/model/diagnostics-codes.js.map +1 -0
  206. package/dist/model/facts.d.ts +10 -0
  207. package/dist/model/facts.js +36 -0
  208. package/dist/model/facts.js.map +1 -0
  209. package/dist/model/frontmatter.d.ts +17 -0
  210. package/dist/model/frontmatter.js +97 -0
  211. package/dist/model/frontmatter.js.map +1 -0
  212. package/dist/model/hooks.d.ts +2 -0
  213. package/dist/model/hooks.js +175 -0
  214. package/dist/model/hooks.js.map +1 -0
  215. package/dist/model/memory.d.ts +3 -0
  216. package/dist/model/memory.js +165 -0
  217. package/dist/model/memory.js.map +1 -0
  218. package/dist/model/policy.d.ts +8 -0
  219. package/dist/model/policy.js +46 -0
  220. package/dist/model/policy.js.map +1 -0
  221. package/dist/model/project-manifest.d.ts +26 -0
  222. package/dist/model/project-manifest.js +210 -0
  223. package/dist/model/project-manifest.js.map +1 -0
  224. package/dist/model/rules.d.ts +2 -0
  225. package/dist/model/rules.js +98 -0
  226. package/dist/model/rules.js.map +1 -0
  227. package/dist/model/schemas.d.ts +379 -0
  228. package/dist/model/schemas.js +310 -0
  229. package/dist/model/schemas.js.map +1 -0
  230. package/dist/model/scope.d.ts +29 -0
  231. package/dist/model/scope.js +204 -0
  232. package/dist/model/scope.js.map +1 -0
  233. package/dist/model/skills.d.ts +12 -0
  234. package/dist/model/skills.js +181 -0
  235. package/dist/model/skills.js.map +1 -0
  236. package/dist/model/types.d.ts +87 -0
  237. package/dist/model/types.js +2 -0
  238. package/dist/model/types.js.map +1 -0
  239. package/package.json +60 -4
  240. package/skills/dab-architecture-writing/SKILL.md +58 -0
  241. package/skills/dab-decision-notes/SKILL.md +57 -0
  242. package/skills/dab-doc-writing/SKILL.md +58 -0
@@ -0,0 +1,715 @@
1
+ import { homedir } from 'node:os';
2
+ import { join, relative, resolve } from 'node:path';
3
+ import { runCommand } from '../core/command.js';
4
+ import { dedupeDiagnostics, formatDiagnostics, hasErrors, sortDiagnostics, } from '../core/diagnostics.js';
5
+ import { DabError } from '../core/errors.js';
6
+ import { ExitCode } from '../core/exit-codes.js';
7
+ import { lstatOrNull } from '../core/fs-atomic.js';
8
+ import { DAB_GITIGNORE_ENTRIES, ensureGitignoreBlock } from '../core/gitignore.js';
9
+ import { contractJson, stableJson } from '../core/json.js';
10
+ import { assertRealPathInsideRoot, assertRealPathsDisjoint, isPathInside, realPathNearest, toPosix, } from '../core/paths.js';
11
+ import { assertSupportedPlatform } from '../core/platform.js';
12
+ import { getTargetAdapter } from '../adapter/registry.js';
13
+ import { previewClaudeAdoption } from '../adapter/claude-code/adoption.js';
14
+ import { parseClaudeTargetOptions } from '../adapter/claude-code/options.js';
15
+ import { discoverProjections } from '../adapter/claude-code/projection.js';
16
+ import { checkClaudeCode } from '../adapter/claude-code/version.js';
17
+ import { checkAgentHooks, checkHookSafety, checkSecrets } from '../detect/checks.js';
18
+ import { applyNormalizeAdoption, planManagedSkillWrites, planSourceWrites, prepareNormalizeAdoption, summarizeManagedSkills, writeSourceFiles, } from '../init/adoption.js';
19
+ import { applyManagedSkillWrites } from '../init/managed-skills.js';
20
+ import { checkAgentsMd } from '../model/agents-md.js';
21
+ import { discoverSourceFacts } from '../model/facts.js';
22
+ import { getEnabledTargets, getGeneratedTarget, loadProjectManifest, resolveProjectPaths, updateGeneratedManifest, } from '../model/project-manifest.js';
23
+ const PRACTICE_SKILL_PREFIX = '.agents/skills/';
24
+ function isDocsPracticePath(path) {
25
+ return path === 'docs' || path.startsWith('docs/');
26
+ }
27
+ function isAuthoringSkillPath(path) {
28
+ return path.startsWith(PRACTICE_SKILL_PREFIX)
29
+ && path.slice(PRACTICE_SKILL_PREFIX.length).startsWith('dab-');
30
+ }
31
+ function isPracticeDirectory(path) {
32
+ return isDocsPracticePath(path) || isAuthoringSkillPath(path);
33
+ }
34
+ function policySkipDiagnostic(path) {
35
+ return {
36
+ code: 'practice.docs-bilingual-policy',
37
+ severity: 'warning',
38
+ message: `project bilingual rule skips single-language documentation: ${path}`,
39
+ file: path,
40
+ hint: 'Remove .agents/rules/docs-bilingual.md to let DAB scaffold single-language docs.',
41
+ };
42
+ }
43
+ function policySkipWarnings(plan) {
44
+ return (plan?.policySkipped ?? []).filter(isDocsPracticePath).map(policySkipDiagnostic);
45
+ }
46
+ function uniquePaths(...lists) {
47
+ const seen = new Set();
48
+ const result = [];
49
+ for (const list of lists) {
50
+ for (const path of list) {
51
+ if (!seen.has(path)) {
52
+ seen.add(path);
53
+ result.push(path);
54
+ }
55
+ }
56
+ }
57
+ return result;
58
+ }
59
+ function buildPractices(plan, created, skipped, diagnostics, managed = summarizeManagedSkills(undefined)) {
60
+ const practiceCreated = created.filter((path) => isDocsPracticePath(path) || isAuthoringSkillPath(path));
61
+ // `plan.skipped` is the planner's existing-path report; write-time skips add
62
+ // only the files the planner planned but another writer created first.
63
+ const practiceSkipped = [...new Set([
64
+ ...plan.skipped.filter((path) => isDocsPracticePath(path) || isAuthoringSkillPath(path)),
65
+ ...skipped.filter((path) => isDocsPracticePath(path) || isAuthoringSkillPath(path)),
66
+ ])];
67
+ return {
68
+ profile: plan.profile,
69
+ mode: plan.mode === 'converge' ? 'converge' : 'adoption',
70
+ language: plan.docsLanguage,
71
+ created: practiceCreated.filter((path) => !isAuthoringSkillPath(path)),
72
+ skipped: practiceSkipped.filter((path) => !isAuthoringSkillPath(path)),
73
+ policySkipped: plan.policySkipped.filter(isDocsPracticePath),
74
+ directories: plan.directories.filter(isPracticeDirectory),
75
+ skills: {
76
+ // The authoring pack writes missing files; the managed writer only
77
+ // creates a missing SKILL.md when the pack skipped an existing directory.
78
+ created: uniquePaths(practiceCreated.filter(isAuthoringSkillPath), managed.created),
79
+ skipped: uniquePaths(practiceSkipped.filter(isAuthoringSkillPath), managed.skipped),
80
+ updated: managed.updated,
81
+ migrated: managed.migrated,
82
+ modified: managed.modified,
83
+ newer: managed.newer,
84
+ legacy: managed.legacy,
85
+ unversioned: managed.unversioned,
86
+ markerMismatch: managed.markerMismatch,
87
+ concurrent: managed.concurrent,
88
+ },
89
+ diagnostics: [...diagnostics],
90
+ };
91
+ }
92
+ function practiceExtras(scope, practices) {
93
+ return scope === 'project' && practices !== undefined ? { practices } : {};
94
+ }
95
+ function errorDiagnostic(error, file = 'dab.yaml') {
96
+ return {
97
+ code: error.code,
98
+ severity: 'error',
99
+ message: error.message,
100
+ file,
101
+ ...(error.hint === undefined ? {} : { hint: error.hint }),
102
+ };
103
+ }
104
+ function emptySettings() {
105
+ return {
106
+ path: '.claude/settings.json',
107
+ sha256: '',
108
+ changed: false,
109
+ };
110
+ }
111
+ function targetResult(plan, backups = [], root) {
112
+ return {
113
+ provider: plan.provider,
114
+ actions: plan.actions,
115
+ ...(plan.settings === undefined ? {} : { settings: plan.settings }),
116
+ ...(plan.instructions === undefined ? {} : { instructions: plan.instructions }),
117
+ backups: root === undefined
118
+ ? [...backups]
119
+ : backups.map((backup) => toPosix(relative(root, resolve(root, backup)))),
120
+ };
121
+ }
122
+ function claudeTargetResult(targets) {
123
+ return targets.find((item) => item.provider === 'claude-code');
124
+ }
125
+ function topLevelSettings(targets, changed) {
126
+ const settings = claudeTargetResult(targets)?.settings;
127
+ if (settings === undefined) {
128
+ return emptySettings();
129
+ }
130
+ return changed === undefined ? { ...settings } : { ...settings, changed };
131
+ }
132
+ function compatShimAction(targets) {
133
+ return claudeTargetResult(targets)?.instructions?.action ?? 'none';
134
+ }
135
+ function blockedResult(root, scope, options, diagnostics, extras = {}) {
136
+ const targets = extras.targets ?? [];
137
+ const compat = extras.compatTargets ?? targets;
138
+ const adoptionActions = extras.adoption === undefined
139
+ ? []
140
+ : [...extras.adoption.sourceActions, ...extras.adoption.importActions];
141
+ return {
142
+ ok: false,
143
+ root,
144
+ scope,
145
+ dryRun: options.dryRun === true,
146
+ exitCode: extras.exitCode ?? ExitCode.Validation,
147
+ actions: [...adoptionActions, ...targets.flatMap((item) => item.actions)],
148
+ targets,
149
+ diagnostics: sortDiagnostics(dedupeDiagnostics(diagnostics)),
150
+ settings: topLevelSettings(compat, false),
151
+ shimAction: compatShimAction(compat),
152
+ backups: [],
153
+ gitignore: { changed: false, path: '' },
154
+ manifestUpdated: false,
155
+ ...(extras.adoption === undefined ? {} : { adoption: extras.adoption }),
156
+ ...(extras.practices === undefined ? {} : { practices: extras.practices }),
157
+ };
158
+ }
159
+ function adoptionExtras(adoption) {
160
+ return adoption === undefined ? {} : { adoption };
161
+ }
162
+ function backupRootFor(root, now) {
163
+ const stamp = now.toISOString().replaceAll(':', '-').replaceAll('.', '-');
164
+ return join(root, '.dab', 'backups', stamp);
165
+ }
166
+ /**
167
+ * The command layer checks the runtime before source validation and the target
168
+ * adapter checks again for direct callers. Cache the version command so both
169
+ * checks observe one `claude --version` invocation.
170
+ */
171
+ function memoizeClaudeVersion(runner = runCommand) {
172
+ let cached;
173
+ return (cmd, args, opts) => {
174
+ if (cmd === 'claude' && args.length === 1 && args[0] === '--version') {
175
+ // Resolve inside a promise so a synchronous throw is cached too.
176
+ cached ??= Promise.resolve().then(() => runner(cmd, args, opts));
177
+ return cached;
178
+ }
179
+ return runner(cmd, args, opts);
180
+ };
181
+ }
182
+ async function assertSourceTreesSafe(root) {
183
+ await assertRealPathInsideRoot(root, '.claude');
184
+ await assertRealPathInsideRoot(root, '.agents');
185
+ await assertRealPathsDisjoint(root, '.agents', '.claude');
186
+ for (const directory of [
187
+ '.agents/agents',
188
+ '.agents/skills',
189
+ '.agents/rules',
190
+ '.agents/policies',
191
+ '.agents/adapters',
192
+ '.agents/hooks',
193
+ '.agents/memory',
194
+ '.agents/notes',
195
+ '.claude/agents',
196
+ '.claude/skills',
197
+ '.claude/rules',
198
+ ]) {
199
+ await assertRealPathInsideRoot(root, directory);
200
+ }
201
+ }
202
+ async function projectionOverlapDiagnostics(root, projections, generated) {
203
+ const diagnostics = [];
204
+ const agentsExists = (await lstatOrNull(join(root, '.agents'))) !== null;
205
+ const realAgents = agentsExists ? await realPathNearest(root, '.agents') : undefined;
206
+ const sourceReals = new Set();
207
+ for (const projection of projections) {
208
+ sourceReals.add(await realPathNearest(root, projection.source));
209
+ }
210
+ const all = [...projections, ...(generated?.projections ?? [])];
211
+ const seen = new Set();
212
+ for (const projection of all) {
213
+ if (seen.has(projection.target)) {
214
+ continue;
215
+ }
216
+ seen.add(projection.target);
217
+ const targetInfo = await lstatOrNull(join(root, projection.target));
218
+ if (targetInfo?.isSymbolicLink() === true) {
219
+ // A projection symlink is safe to replace: replaceSymlink never
220
+ // follows or deletes the target it points at.
221
+ continue;
222
+ }
223
+ const realTarget = await realPathNearest(root, projection.target);
224
+ if (sourceReals.has(realTarget)
225
+ || (realAgents !== undefined && isPathInside(realAgents, realTarget))) {
226
+ diagnostics.push({
227
+ code: 'path.overlap',
228
+ severity: 'error',
229
+ message: `generated target overlaps an authored source: ${projection.target}`,
230
+ file: projection.target,
231
+ hint: 'Use the default disjoint .agents and .claude trees.',
232
+ });
233
+ }
234
+ }
235
+ return diagnostics;
236
+ }
237
+ export async function normalizeProject(options) {
238
+ assertSupportedPlatform(options.platform);
239
+ const runner = memoizeClaudeVersion(options.runner);
240
+ const home = resolve(options.home ?? homedir());
241
+ const cwd = resolve(options.cwd);
242
+ // Adoption runs before source-root resolution: an uninitialized scope has no
243
+ // manifest for resolveSourceRoot to anchor on.
244
+ const preparation = await prepareNormalizeAdoption({
245
+ cwd,
246
+ home,
247
+ ...(options.now === undefined ? {} : { now: options.now }),
248
+ ...(options.suppressImports === true ? { suppressImports: true } : {}),
249
+ ...(options.suppressManagedSkills === true ? { suppressManagedSkills: true } : {}),
250
+ });
251
+ const root = preparation.sourceRoot.root;
252
+ const scope = preparation.sourceRoot.scope;
253
+ const backupRoot = backupRootFor(root, options.now ?? new Date());
254
+ const practicePlan = preparation.practicePlan;
255
+ const sourceProblems = preparation.sourceProblems ?? [];
256
+ const managedDiagnostics = preparation.managedSkills?.diagnostics ?? [];
257
+ // The authoring pack creates missing skills it planned; the managed writer
258
+ // owns existing stale/legacy files and missing SKILL.md under a user-owned
259
+ // directory. Exactly one writer therefore plans each skill file.
260
+ const managedWritePlan = preparation.managedSkills === undefined
261
+ ? undefined
262
+ : planManagedSkillWrites(preparation.managedSkills, new Set(Object.keys(practicePlan?.files ?? {})));
263
+ let managed = summarizeManagedSkills(managedWritePlan);
264
+ const practiceWarnings = scope === 'project' ? policySkipWarnings(practicePlan) : [];
265
+ const practiceDiagnostics = [
266
+ ...(practicePlan?.diagnostics ?? []),
267
+ ...managedDiagnostics,
268
+ ...practiceWarnings,
269
+ ...sourceProblems,
270
+ ];
271
+ const imports = preparation.claudePlan?.entries ?? [];
272
+ const importDiagnostics = preparation.claudePlan?.diagnostics ?? [];
273
+ const preparationDiagnostics = [
274
+ ...preparation.diagnostics,
275
+ ...importDiagnostics,
276
+ ...practiceWarnings,
277
+ ];
278
+ const importPreview = preparation.claudePlan === undefined
279
+ ? { actions: [], backups: [] }
280
+ : previewClaudeAdoption(root, preparation.claudePlan, backupRoot);
281
+ let practices;
282
+ let adoption = {
283
+ phase: preparation.phase,
284
+ ...(preparation.sourcePlan === undefined ? {} : { sourcePlan: preparation.sourcePlan }),
285
+ sourceActions: [],
286
+ importActions: [],
287
+ imports: [],
288
+ backups: [],
289
+ diagnostics: [...preparationDiagnostics],
290
+ };
291
+ if (preparation.phase !== 'initialized' && preparation.sourcePlan !== undefined) {
292
+ const sourcePlan = preparation.sourcePlan;
293
+ const practicesFor = (created, skipped, managedSummary = managed) => practicePlan === undefined
294
+ ? undefined
295
+ : buildPractices(practicePlan, created, skipped, practiceDiagnostics, managedSummary);
296
+ // Any invalid import candidate gates the minimal source copy as well, so a
297
+ // rejected plan writes neither `.agents` nor `.claude`. Planned practice
298
+ // paths stay in the result even though nothing is written.
299
+ if (hasErrors(preparationDiagnostics)) {
300
+ const planned = await planSourceWrites(root, sourcePlan);
301
+ practices = practicesFor(planned.create, planned.skip);
302
+ return blockedResult(root, scope, options, preparationDiagnostics, {
303
+ adoption,
304
+ ...practiceExtras(scope, practices),
305
+ });
306
+ }
307
+ const applied = await applyNormalizeAdoption({ ...preparation, claudePlan: undefined, managedSkills: managedWritePlan }, { dryRun: options.dryRun === true, backupRoot });
308
+ // Apply-time managed warnings (a concurrent change) belong to the run and
309
+ // the practice report, not only to the adoption step.
310
+ preparationDiagnostics.push(...applied.diagnostics);
311
+ practiceDiagnostics.push(...applied.diagnostics);
312
+ adoption = {
313
+ ...adoption,
314
+ sourceActions: applied.actions,
315
+ diagnostics: [...adoption.diagnostics, ...applied.diagnostics],
316
+ };
317
+ practices = practicesFor(applied.created, applied.skipped, applied.managed);
318
+ if (hasErrors(applied.diagnostics)) {
319
+ const planned = await planSourceWrites(root, sourcePlan);
320
+ practices = practicesFor(planned.create, planned.skip);
321
+ return blockedResult(root, scope, options, [...preparationDiagnostics, ...applied.diagnostics], { adoption, ...practiceExtras(scope, practices) });
322
+ }
323
+ if (options.dryRun === true) {
324
+ // The target plan needs the written source tree, so an adoption dry run
325
+ // previews the source and import plan and leaves the target plan out.
326
+ return {
327
+ ok: true,
328
+ root,
329
+ scope,
330
+ dryRun: true,
331
+ exitCode: ExitCode.Ok,
332
+ actions: [...applied.actions, ...importPreview.actions],
333
+ targets: [],
334
+ diagnostics: sortDiagnostics(dedupeDiagnostics(preparationDiagnostics)),
335
+ settings: emptySettings(),
336
+ shimAction: 'none',
337
+ backups: importPreview.backups,
338
+ gitignore: { changed: false, path: '' },
339
+ manifestUpdated: false,
340
+ adoption: {
341
+ ...adoption,
342
+ importActions: importPreview.actions,
343
+ backups: importPreview.backups,
344
+ imports,
345
+ },
346
+ ...practiceExtras(scope, practices),
347
+ };
348
+ }
349
+ }
350
+ // Converge plans practice writes before target planning so newly scaffolded
351
+ // docs and skills are discovered and projected in the same run. A blocking
352
+ // practice error returns before anything is written.
353
+ let practiceSourcePlan;
354
+ if (preparation.phase === 'initialized' && practicePlan !== undefined) {
355
+ if (hasErrors(practicePlan.diagnostics) || hasErrors(managedDiagnostics)) {
356
+ practices = buildPractices(practicePlan, [], [], practiceDiagnostics, managed);
357
+ return blockedResult(root, scope, options, preparationDiagnostics, {
358
+ ...adoptionExtras(adoption),
359
+ ...practiceExtras(scope, practices),
360
+ });
361
+ }
362
+ practiceSourcePlan = {
363
+ files: practicePlan.files,
364
+ directories: practicePlan.directories,
365
+ manifest: practicePlan.manifest ?? preparation.manifest,
366
+ };
367
+ const planned = await planSourceWrites(root, practiceSourcePlan);
368
+ practices = buildPractices(practicePlan, planned.create, planned.skip, practiceDiagnostics, managed);
369
+ }
370
+ // A broken non-practice source parent ( `.agents/agents`, `.agents/hooks`,
371
+ // `.agents/memory`, `.agents/policies` or `.agents/adapters`) already made
372
+ // preparation skip imports. Discovery would fail with an internal error, so
373
+ // report the governed conflict and keep the planned practice fields unread.
374
+ if (sourceProblems.length > 0) {
375
+ practices = practicePlan === undefined
376
+ ? undefined
377
+ : buildPractices(practicePlan, [], [], practiceDiagnostics, managed);
378
+ return blockedResult(root, scope, options, preparationDiagnostics, {
379
+ ...adoptionExtras(adoption),
380
+ ...practiceExtras(scope, practices),
381
+ });
382
+ }
383
+ const loaded = await loadProjectManifest(root, { scope });
384
+ const paths = resolveProjectPaths(root, loaded.manifest);
385
+ const enabledTargets = getEnabledTargets(loaded.manifest);
386
+ const claudeTarget = enabledTargets.find((target) => target.provider === 'claude-code');
387
+ // Parse before source safety so malformed Claude options still fail loudly for
388
+ // direct callers, matching the pre-adapter behavior.
389
+ const claudeOptions = claudeTarget === undefined
390
+ ? undefined
391
+ : parseClaudeTargetOptions(claudeTarget);
392
+ const diagnostics = [...preparationDiagnostics];
393
+ try {
394
+ await assertSourceTreesSafe(root);
395
+ }
396
+ catch (error) {
397
+ if (error instanceof DabError) {
398
+ return blockedResult(root, scope, options, [errorDiagnostic(error)], {
399
+ ...adoptionExtras(adoption),
400
+ ...practiceExtras(scope, practices),
401
+ });
402
+ }
403
+ throw error;
404
+ }
405
+ // Runtime incompatibility takes precedence over authored-source validation, as
406
+ // it did before the adapter seam. The adapter still checks for direct callers.
407
+ if (claudeOptions !== undefined) {
408
+ const runtime = await checkClaudeCode(claudeOptions.minVersion, runner);
409
+ if (runtime.diagnostics.some((item) => item.code === 'backend.version' && item.severity === 'error')) {
410
+ return blockedResult(root, scope, options, runtime.diagnostics, {
411
+ exitCode: ExitCode.Backend,
412
+ ...adoptionExtras(adoption),
413
+ ...practiceExtras(scope, practices),
414
+ });
415
+ }
416
+ }
417
+ // Errors already known before target planning (invalid imports, scan or
418
+ // planner errors) and a manifest without an enabled target must not scaffold
419
+ // practice files. Skip the writes now; the blocked result is returned after
420
+ // the read-only source/projection diagnostics below so those still surface.
421
+ const blockedBeforePlanning = hasErrors(preparationDiagnostics)
422
+ || enabledTargets.length === 0;
423
+ // Practice writes run after the source-tree safety gate but before target
424
+ // planning, so the new files become projections of this same normalization.
425
+ // Managed skill writes share this phase; a dry run reports the same plan
426
+ // without touching bytes.
427
+ if (practiceSourcePlan !== undefined && practicePlan !== undefined
428
+ && !blockedBeforePlanning) {
429
+ if (options.dryRun !== true) {
430
+ const written = await writeSourceFiles(root, practiceSourcePlan);
431
+ if (managedWritePlan !== undefined) {
432
+ const appliedManaged = await applyManagedSkillWrites(root, managedWritePlan, { dryRun: false });
433
+ // Revalidation can turn a planned write into a preserved file, so the
434
+ // report is rebuilt from the apply outcome rather than the plan.
435
+ managed = summarizeManagedSkills(managedWritePlan, appliedManaged);
436
+ practiceDiagnostics.push(...appliedManaged.diagnostics);
437
+ diagnostics.push(...appliedManaged.diagnostics);
438
+ }
439
+ practices = buildPractices(practicePlan, written.created, written.skipped, practiceDiagnostics, managed);
440
+ }
441
+ if (managed.actions.length > 0) {
442
+ adoption = {
443
+ ...adoption,
444
+ sourceActions: [...adoption.sourceActions, ...managed.actions],
445
+ };
446
+ }
447
+ }
448
+ const facts = await discoverSourceFacts(root, paths);
449
+ diagnostics.push(...facts.agents.diagnostics, ...facts.skills.diagnostics, ...facts.rules.diagnostics, ...facts.hooks.diagnostics);
450
+ diagnostics.push(...checkAgentHooks(facts.agents.items, facts.hooks.items));
451
+ diagnostics.push(...await checkHookSafety(facts.hooks.items));
452
+ diagnostics.push(...await checkSecrets(root, paths));
453
+ if (claudeTarget !== undefined) {
454
+ const discovered = await discoverProjections(root, paths, {
455
+ agents: facts.agents.items,
456
+ skills: facts.skills.items,
457
+ rules: facts.rules.items,
458
+ });
459
+ diagnostics.push(...discovered.diagnostics);
460
+ diagnostics.push(...await projectionOverlapDiagnostics(root, discovered.projections, getGeneratedTarget(loaded.manifest, 'claude-code')));
461
+ }
462
+ const agentsMd = await checkAgentsMd(root, paths.instructions);
463
+ diagnostics.push(...agentsMd.diagnostics);
464
+ if (enabledTargets.length === 0) {
465
+ diagnostics.push({
466
+ code: 'target.none',
467
+ severity: 'error',
468
+ file: 'dab.yaml',
469
+ message: 'manifest has no enabled targets',
470
+ hint: 'Enable at least one target or omit it from the manifest.',
471
+ });
472
+ return blockedResult(root, scope, options, diagnostics, {
473
+ ...adoptionExtras(adoption),
474
+ ...practiceExtras(scope, practices),
475
+ });
476
+ }
477
+ // Known preparation errors block before target planning and before any
478
+ // import/target apply; practice writes were already skipped above.
479
+ if (hasErrors(preparationDiagnostics)) {
480
+ return blockedResult(root, scope, options, diagnostics, {
481
+ ...adoptionExtras(adoption),
482
+ ...practiceExtras(scope, practices),
483
+ });
484
+ }
485
+ const plans = [];
486
+ for (const target of enabledTargets) {
487
+ const adapter = getTargetAdapter(target.provider);
488
+ if (adapter === undefined) {
489
+ diagnostics.push({
490
+ code: 'target.unsupported',
491
+ severity: 'error',
492
+ file: 'dab.yaml',
493
+ message: `no adapter is available for target ${target.provider}`,
494
+ hint: 'Remove or disable the target until its adapter is implemented.',
495
+ });
496
+ continue;
497
+ }
498
+ const plan = await adapter.normalize({
499
+ paths,
500
+ manifest: loaded.manifest,
501
+ target,
502
+ facts,
503
+ fix: options.fix === true,
504
+ dryRun: options.dryRun === true,
505
+ runner,
506
+ // The import step owns these targets and replaces them after the
507
+ // preflight, so the adapter must not plan competing backup actions.
508
+ importedTargets: imports.map((entry) => entry.source),
509
+ ...(options.now === undefined ? {} : { now: options.now }),
510
+ });
511
+ diagnostics.push(...plan.diagnostics);
512
+ plans.push(plan);
513
+ }
514
+ if (hasErrors(diagnostics)) {
515
+ const backendError = diagnostics.some((item) => item.code === 'backend.version' && item.severity === 'error');
516
+ return blockedResult(root, scope, options, diagnostics, {
517
+ compatTargets: plans.map((plan) => targetResult(plan)),
518
+ ...(backendError ? { exitCode: ExitCode.Backend } : {}),
519
+ ...adoptionExtras(adoption),
520
+ ...practiceExtras(scope, practices),
521
+ });
522
+ }
523
+ if (options.dryRun === true) {
524
+ const targets = plans.map((plan) => targetResult(plan));
525
+ return {
526
+ ok: true,
527
+ root,
528
+ scope,
529
+ dryRun: true,
530
+ exitCode: ExitCode.Ok,
531
+ actions: [
532
+ ...adoption.sourceActions,
533
+ ...importPreview.actions,
534
+ ...targets.flatMap((item) => item.actions),
535
+ ],
536
+ targets,
537
+ diagnostics: sortDiagnostics(diagnostics),
538
+ settings: topLevelSettings(targets),
539
+ shimAction: compatShimAction(targets),
540
+ backups: importPreview.backups,
541
+ gitignore: {
542
+ changed: false,
543
+ path: paths.scope === 'global' ? '' : '.gitignore',
544
+ },
545
+ manifestUpdated: false,
546
+ ...adoptionExtras({
547
+ ...adoption,
548
+ importActions: importPreview.actions,
549
+ backups: importPreview.backups,
550
+ imports,
551
+ }),
552
+ ...practiceExtras(scope, practices),
553
+ };
554
+ }
555
+ // Imports replace physical `.claude` entries with per-entry symlinks only
556
+ // after every plan is clean; `.claude` stays untouched on earlier failures.
557
+ if (preparation.claudePlan !== undefined) {
558
+ const imported = await applyNormalizeAdoption({ ...preparation, sourcePlan: undefined, managedSkills: undefined }, { dryRun: false, backupRoot });
559
+ // Apply returns absolute paths; NormalizeResult paths are root-relative.
560
+ const importedBackups = imported.backups.map((backup) => toPosix(relative(root, resolve(root, backup))));
561
+ if (hasErrors(imported.diagnostics)) {
562
+ // Apply does not report per-entry success, so a failed run claims no
563
+ // imports; actions, backups and diagnostics still describe what happened.
564
+ adoption = {
565
+ ...adoption,
566
+ imports: [],
567
+ importActions: imported.actions,
568
+ backups: [...adoption.backups, ...importedBackups],
569
+ diagnostics: [...adoption.diagnostics, ...imported.diagnostics],
570
+ };
571
+ return blockedResult(root, scope, options, [...diagnostics, ...imported.diagnostics], { adoption, ...practiceExtras(scope, practices) });
572
+ }
573
+ adoption = {
574
+ ...adoption,
575
+ imports,
576
+ importActions: imported.actions,
577
+ backups: [...adoption.backups, ...importedBackups],
578
+ diagnostics: [...adoption.diagnostics, ...imported.diagnostics],
579
+ };
580
+ }
581
+ const targets = [];
582
+ for (const plan of plans) {
583
+ const applied = await plan.apply({ backupRoot });
584
+ targets.push(targetResult(plan, applied.backups, root));
585
+ }
586
+ const generated = {
587
+ targets: plans.map((plan) => plan.generated),
588
+ };
589
+ const manifestUpdated = loaded.legacy
590
+ || stableJson(loaded.manifest.generated ?? null) !== stableJson(generated);
591
+ if (manifestUpdated) {
592
+ await updateGeneratedManifest(root, generated, { scope });
593
+ }
594
+ // $HOME/.gitignore is user-owned; global scope never manages it.
595
+ const gitignore = paths.scope === 'global'
596
+ ? { changed: false, path: '' }
597
+ : await ensureGitignoreBlock(root, DAB_GITIGNORE_ENTRIES);
598
+ return {
599
+ ok: true,
600
+ root,
601
+ scope,
602
+ dryRun: false,
603
+ exitCode: ExitCode.Ok,
604
+ actions: [
605
+ ...adoption.sourceActions,
606
+ ...adoption.importActions,
607
+ ...targets.flatMap((item) => item.actions),
608
+ ],
609
+ targets,
610
+ diagnostics: sortDiagnostics(dedupeDiagnostics(diagnostics)),
611
+ settings: topLevelSettings(targets),
612
+ shimAction: compatShimAction(targets),
613
+ backups: claudeTargetResult(targets)?.backups ?? [],
614
+ gitignore: {
615
+ changed: gitignore.changed,
616
+ path: gitignore.path === '' ? '' : toPosix(relative(root, gitignore.path)),
617
+ },
618
+ manifestUpdated,
619
+ ...adoptionExtras(adoption),
620
+ ...practiceExtras(scope, practices),
621
+ };
622
+ }
623
+ function formatHuman(result) {
624
+ const lines = [];
625
+ lines.push(`dab normalize${result.dryRun ? ' (dry run)' : ''}`);
626
+ if (result.practices !== undefined) {
627
+ lines.push(`Language: ${result.practices.language.value} (source: ${result.practices.language.source})`);
628
+ }
629
+ for (const action of result.actions) {
630
+ lines.push(` ${action}`);
631
+ }
632
+ if (result.practices?.mode === 'converge') {
633
+ // Adoption already reports these paths through its source actions. A skill
634
+ // the managed writer created (an existing directory without SKILL.md) is
635
+ // already in the action list as `create skill`, so do not print it twice.
636
+ const skills = result.practices.skills;
637
+ const actions = new Set(result.actions);
638
+ for (const file of result.practices.created) {
639
+ lines.push(` create ${file}`);
640
+ }
641
+ for (const file of skills.created) {
642
+ if (!actions.has(`create skill ${file}`)) {
643
+ lines.push(` create ${file}`);
644
+ }
645
+ }
646
+ for (const file of result.practices.skipped) {
647
+ lines.push(` skip ${file}`);
648
+ }
649
+ // A managed skill file is current (the directory skip already reports it)
650
+ // or has its own `skip skill ... (...)` action, so a plain file skip is
651
+ // always redundant. A directory skip is misleading when the managed writer
652
+ // created, updated or migrated its child.
653
+ const writtenDirectories = new Set([...skills.created, ...skills.updated, ...skills.migrated].flatMap((file) => {
654
+ const index = file.lastIndexOf('/');
655
+ return index === -1 ? [] : [file.slice(0, index)];
656
+ }));
657
+ for (const file of skills.skipped) {
658
+ if (file.endsWith('/SKILL.md') || writtenDirectories.has(file)) {
659
+ continue;
660
+ }
661
+ lines.push(` skip ${file}`);
662
+ }
663
+ }
664
+ lines.push(` settings ${result.settings.changed ? 'changed' : 'unchanged'}: ${result.settings.path}`);
665
+ lines.push(` shim ${result.shimAction}`);
666
+ lines.push(` manifest ${result.manifestUpdated ? 'updated' : 'unchanged'}`);
667
+ lines.push(` .gitignore ${result.gitignore.changed ? 'updated' : 'unchanged'}`);
668
+ const backups = [...new Set([
669
+ ...(result.adoption?.backups ?? []),
670
+ ...result.backups,
671
+ ])];
672
+ if (backups.length > 0) {
673
+ lines.push(` ${result.dryRun ? 'planned ' : ''}backups: ${backups.length}`);
674
+ for (const backup of backups) {
675
+ lines.push(` ${toPosix(relative(process.cwd(), resolve(result.root, backup)))}`);
676
+ }
677
+ }
678
+ const diagnostics = formatDiagnostics(result.diagnostics);
679
+ if (diagnostics.length > 0) {
680
+ lines.push(diagnostics.trimEnd());
681
+ }
682
+ lines.push(result.ok ? 'OK' : 'FAILED');
683
+ return `${lines.join('\n')}\n`;
684
+ }
685
+ export async function runNormalize(options, io) {
686
+ try {
687
+ const result = await normalizeProject(options);
688
+ if (options.json === true) {
689
+ io.stdout(contractJson(result));
690
+ }
691
+ else if (result.ok) {
692
+ io.stdout(formatHuman(result));
693
+ }
694
+ else {
695
+ io.stderr(formatHuman(result));
696
+ }
697
+ return result.exitCode;
698
+ }
699
+ catch (error) {
700
+ if (error instanceof DabError) {
701
+ if (options.json === true) {
702
+ io.stdout(contractJson({ ok: false, error: error.toJSON() }));
703
+ }
704
+ else {
705
+ io.stderr(`dab: ${error.message}\n`);
706
+ if (error.hint !== undefined) {
707
+ io.stderr(`${error.hint}\n`);
708
+ }
709
+ }
710
+ return error.exitCode;
711
+ }
712
+ throw error;
713
+ }
714
+ }
715
+ //# sourceMappingURL=normalize.js.map