@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,727 @@
1
+ import { readlink, realpath, stat } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { runCommand } from '../core/command.js';
5
+ import { dedupeDiagnostics, formatDiagnostics, hasErrors, } from '../core/diagnostics.js';
6
+ import { ConfigError, DabError, UsageError, ValidationError } from '../core/errors.js';
7
+ import { ExitCode } from '../core/exit-codes.js';
8
+ import { ensureDir, lstatOrNull, writeFileAtomic } from '../core/fs-atomic.js';
9
+ import { contractJson } from '../core/json.js';
10
+ import { DAB_VERSION } from '../core/version.js';
11
+ import { assertParentInsideRoot, assertRealPathInsideRoot, assertRealPathsDisjoint, } from '../core/paths.js';
12
+ import { assertSupportedPlatform } from '../core/platform.js';
13
+ import { loadYamlDocument } from '../core/yaml.js';
14
+ import { inspectInstructionTarget, } from '../adapter/claude-code/instructions.js';
15
+ import { parseClaudeTargetOptions } from '../adapter/claude-code/options.js';
16
+ import { discoverProjections } from '../adapter/claude-code/projection.js';
17
+ import { checkAgentHooks, checkHookSafety, checkSecrets } from '../detect/checks.js';
18
+ import { discoverAgents } from '../model/agents.js';
19
+ import { parseFrontmatter } from '../model/frontmatter.js';
20
+ import { discoverHooks } from '../model/hooks.js';
21
+ import { discoverMemory } from '../model/memory.js';
22
+ import { getGeneratedTarget, getTarget, loadProjectManifest, resolveProjectPaths, } from '../model/project-manifest.js';
23
+ import { assertInitRoot } from '../model/scope.js';
24
+ import { AgentFrontmatterSchema, ClaudeCodePolicySchema, PolicySpecSchema, } from '../model/schemas.js';
25
+ import { formatProposal, requestAiProposal, } from '../init/ai-proposal.js';
26
+ import { resolveDocsLanguage, } from '../init/docs-language.js';
27
+ import { PRACTICE_PACKS, planAuthoredScaffold, } from '../init/practice.js';
28
+ import { AUTHORING_SKILL_NAMES } from '../init/practice-authoring.js';
29
+ import { authoredDirectoryState, practiceParentDiagnostics, practiceParentProblems, probeStat, sourceParentDiagnostic, sourceParentProblems, } from '../core/practice-paths.js';
30
+ import { scanProject } from '../init/scanner.js';
31
+ import { renderAgentFromProposal, TEMPLATE_PROJECTIONS, } from '../init/templates.js';
32
+ import { normalizeProject } from './normalize.js';
33
+ function blocked(scope, root, scopeRoot, language, diagnostics, conflicts, dryRun = false) {
34
+ return {
35
+ ok: false,
36
+ exitCode: ExitCode.Validation,
37
+ scope,
38
+ root,
39
+ scopeRoot,
40
+ dryRun,
41
+ created: [],
42
+ skipped: [],
43
+ conflicts,
44
+ pending: [],
45
+ diagnostics,
46
+ language,
47
+ normalize: null,
48
+ };
49
+ }
50
+ function policySkipDiagnostic(path) {
51
+ return {
52
+ code: 'practice.docs-bilingual-policy',
53
+ severity: 'warning',
54
+ message: `project bilingual rule skips single-language documentation: ${path}`,
55
+ file: path,
56
+ hint: 'Remove .agents/rules/docs-bilingual.md to let DAB scaffold single-language docs.',
57
+ };
58
+ }
59
+ function pendingDiagnostic(item) {
60
+ return {
61
+ ...item,
62
+ severity: 'warning',
63
+ hint: [item.hint, 'Run dab normalize --dry-run, then dab normalize --fix.']
64
+ .filter((value) => value !== undefined && value.length > 0)
65
+ .join(' '),
66
+ };
67
+ }
68
+ /**
69
+ * Init never imports Claude entries and authoring skills are project-only. An
70
+ * importable `.claude/skills/dab-<name>` directory is pending for normalize, so
71
+ * init drops that template. A non-directory entry cannot be imported: drop the
72
+ * template too and report a governed conflict without an import hint.
73
+ */
74
+ async function pendingSkillImports(root, scope, plan) {
75
+ const files = { ...plan.files };
76
+ const directories = [...plan.directories];
77
+ const diagnostics = [];
78
+ if (scope !== 'project') {
79
+ return { files, directories, diagnostics };
80
+ }
81
+ for (const name of AUTHORING_SKILL_NAMES) {
82
+ const source = `.agents/skills/${name}`;
83
+ if ((await lstatOrNull(join(root, source))) !== null) {
84
+ continue;
85
+ }
86
+ const target = `.claude/skills/${name}`;
87
+ const state = await authoredDirectoryState(root, target);
88
+ if (state.kind === 'missing') {
89
+ continue;
90
+ }
91
+ delete files[`${source}/SKILL.md`];
92
+ const index = directories.indexOf(source);
93
+ if (index !== -1) {
94
+ directories.splice(index, 1);
95
+ }
96
+ if (state.kind === 'conflict') {
97
+ // Pending conflicts are warnings in init: init leaves the physical entry
98
+ // untouched, skips the template and still completes the remaining safe
99
+ // writes. A user resolves it by hand; there is no import action.
100
+ diagnostics.push({
101
+ code: 'practice.skill-import-conflict',
102
+ severity: 'warning',
103
+ message: `existing Claude skill path is not an importable directory: ${state.message}`,
104
+ file: target,
105
+ hint: `Remove ${target} or replace it with a directory, then rerun dab init.`,
106
+ });
107
+ continue;
108
+ }
109
+ diagnostics.push({
110
+ code: 'practice.skill-import-pending',
111
+ severity: 'warning',
112
+ message: 'existing Claude skill is not imported by init',
113
+ file: target,
114
+ hint: 'Run dab normalize to import the existing skill into .agents.',
115
+ });
116
+ }
117
+ return { files, directories, diagnostics };
118
+ }
119
+ function manifestConflict() {
120
+ return {
121
+ code: 'claude-md.unmanaged',
122
+ severity: 'error',
123
+ message: 'root CLAUDE.md is user-owned and blocks DAB instructions',
124
+ file: 'CLAUDE.md',
125
+ hint: 'Merge its content into AGENTS.md and remove the file before running dab init.',
126
+ };
127
+ }
128
+ async function findAuthoredConflicts(root) {
129
+ const conflicts = [];
130
+ if ((await lstatOrNull(join(root, 'CLAUDE.md'))) !== null) {
131
+ conflicts.push(manifestConflict());
132
+ }
133
+ return conflicts;
134
+ }
135
+ async function findGeneratedConflicts(root, paths, manifest, targets) {
136
+ const pending = [];
137
+ const fatal = [];
138
+ const generated = manifest === undefined
139
+ ? undefined
140
+ : getGeneratedTarget(manifest, 'claude-code');
141
+ const claudeTarget = manifest === undefined ? undefined : getTarget(manifest, 'claude-code');
142
+ if (manifest !== undefined && claudeTarget === undefined) {
143
+ throw new ConfigError('manifest has no claude-code target', 'target.claude-missing');
144
+ }
145
+ const mode = claudeTarget === undefined
146
+ ? 'symlink'
147
+ : parseClaudeTargetOptions(claudeTarget).instructions;
148
+ // User-level settings under $HOME/.claude are never managed in global scope.
149
+ if (paths.scope !== 'global') {
150
+ const settingsPath = join(paths.claude, 'settings.json');
151
+ const settingsManaged = generated?.settings !== undefined && generated.settings !== null;
152
+ if ((await lstatOrNull(settingsPath)) !== null && !settingsManaged) {
153
+ pending.push({
154
+ code: 'claude-settings.unmanaged',
155
+ severity: 'error',
156
+ message: 'existing .claude/settings.json is not DAB-managed',
157
+ file: '.claude/settings.json',
158
+ hint: 'Normalize can back it up and replace it after review.',
159
+ });
160
+ }
161
+ }
162
+ const instructionConflict = await inspectInstructionTarget(root, paths, mode, generated);
163
+ if (instructionConflict !== undefined) {
164
+ pending.push(instructionConflict);
165
+ }
166
+ for (const [target, source] of targets) {
167
+ try {
168
+ await assertRealPathInsideRoot(root, target);
169
+ await assertParentInsideRoot(root, target);
170
+ }
171
+ catch (error) {
172
+ if (error instanceof DabError) {
173
+ const diagnostic = {
174
+ code: error.code,
175
+ severity: 'error',
176
+ message: error.message,
177
+ file: target,
178
+ ...(error.hint === undefined ? {} : { hint: error.hint }),
179
+ };
180
+ if (error.code === 'path.symlink-escape' || error.code === 'path.escape') {
181
+ fatal.push(diagnostic);
182
+ }
183
+ else {
184
+ pending.push(diagnostic);
185
+ }
186
+ continue;
187
+ }
188
+ throw error;
189
+ }
190
+ const absolute = join(root, target);
191
+ const info = await lstatOrNull(absolute);
192
+ if (info === null) {
193
+ continue;
194
+ }
195
+ const managed = generated?.projections.some((projection) => projection.target === target) ?? false;
196
+ if (info.isSymbolicLink()) {
197
+ const raw = await readlink(absolute);
198
+ const resolved = resolve(dirname(absolute), raw);
199
+ if (resolved === resolve(root, source) || managed) {
200
+ continue;
201
+ }
202
+ pending.push({
203
+ code: 'projection.unmanaged',
204
+ severity: 'error',
205
+ message: 'existing projection is not DAB-managed',
206
+ file: target,
207
+ });
208
+ }
209
+ else {
210
+ pending.push({
211
+ code: 'projection.physical-copy',
212
+ severity: 'error',
213
+ message: 'existing projection target is a physical file or directory',
214
+ file: target,
215
+ });
216
+ }
217
+ }
218
+ return { pending, fatal };
219
+ }
220
+ async function validateExistingAuthored(root, paths) {
221
+ const diagnostics = [];
222
+ const policyFiles = [
223
+ {
224
+ absolute: join(paths.agents, 'policies/project.yaml'),
225
+ relative: '.agents/policies/project.yaml',
226
+ schema: PolicySpecSchema,
227
+ },
228
+ {
229
+ absolute: join(paths.agents, 'adapters/claude-code.yaml'),
230
+ relative: '.agents/adapters/claude-code.yaml',
231
+ schema: ClaudeCodePolicySchema,
232
+ },
233
+ ];
234
+ for (const file of policyFiles) {
235
+ if ((await lstatOrNull(file.absolute)) === null) {
236
+ continue;
237
+ }
238
+ try {
239
+ await assertRealPathInsideRoot(root, file.relative);
240
+ }
241
+ catch (error) {
242
+ diagnostics.push({
243
+ code: error instanceof DabError ? error.code : 'policy.invalid',
244
+ severity: 'error',
245
+ message: error instanceof Error ? error.message : String(error),
246
+ file: file.relative,
247
+ });
248
+ continue;
249
+ }
250
+ try {
251
+ const document = await loadYamlDocument(file.absolute);
252
+ const parsed = file.schema.safeParse(document.toJS());
253
+ if (!parsed.success) {
254
+ diagnostics.push({
255
+ code: 'policy.invalid',
256
+ severity: 'error',
257
+ message: `invalid ${file.relative}`,
258
+ file: file.relative,
259
+ });
260
+ }
261
+ }
262
+ catch (error) {
263
+ diagnostics.push({
264
+ code: 'policy.invalid',
265
+ severity: 'error',
266
+ message: `invalid ${file.relative}: ${error instanceof Error ? error.message : String(error)}`,
267
+ file: file.relative,
268
+ });
269
+ }
270
+ }
271
+ const agents = await discoverAgents(root, paths.agents);
272
+ const hooks = await discoverHooks(root, paths.agents);
273
+ diagnostics.push(...agents.diagnostics);
274
+ diagnostics.push(...hooks.diagnostics);
275
+ diagnostics.push(...checkAgentHooks(agents.items, hooks.items));
276
+ diagnostics.push(...await checkHookSafety(hooks.items));
277
+ const memory = await discoverMemory(root, paths.agents);
278
+ diagnostics.push(...memory.diagnostics);
279
+ diagnostics.push(...await checkSecrets(root, paths));
280
+ return diagnostics;
281
+ }
282
+ async function writeIfMissing(root, relativePath, content, created, skipped) {
283
+ const absolute = join(root, relativePath);
284
+ if ((await lstatOrNull(absolute)) !== null) {
285
+ skipped.push(relativePath);
286
+ return;
287
+ }
288
+ await assertParentInsideRoot(root, relativePath);
289
+ await writeFileAtomic(absolute, content);
290
+ created.push(relativePath);
291
+ }
292
+ function targetMap(existing) {
293
+ const targets = new Map();
294
+ for (const projection of existing) {
295
+ targets.set(projection.target, projection.source);
296
+ }
297
+ for (const projection of TEMPLATE_PROJECTIONS) {
298
+ if (!targets.has(projection.target)) {
299
+ targets.set(projection.target, projection.source);
300
+ }
301
+ }
302
+ return targets;
303
+ }
304
+ async function statOrNull(path) {
305
+ try {
306
+ return await stat(path);
307
+ }
308
+ catch (error) {
309
+ if (error.code === 'ENOENT') {
310
+ return null;
311
+ }
312
+ throw error;
313
+ }
314
+ }
315
+ async function resolveInitRoot(options) {
316
+ const root = resolve(options.cwd, options.path ?? '.');
317
+ const info = await lstatOrNull(root);
318
+ if (info === null) {
319
+ return { root, scopePath: root };
320
+ }
321
+ if (!info.isSymbolicLink()) {
322
+ if (!info.isDirectory()) {
323
+ throw new ConfigError(`init target is not a directory: ${root}`, 'config.not-directory');
324
+ }
325
+ return { root, scopePath: root };
326
+ }
327
+ // A symlinked source root is supported; it must resolve to a directory. Scope
328
+ // must be validated on the canonical target, never on the lexical link path.
329
+ const target = await statOrNull(root);
330
+ if (target === null || !target.isDirectory()) {
331
+ throw new ConfigError(`init target is not a directory: ${root}`, 'config.not-directory');
332
+ }
333
+ return { root, scopePath: await realpath(root) };
334
+ }
335
+ async function resolveInitScope(initRoot, home) {
336
+ try {
337
+ return await assertInitRoot({ root: initRoot, home });
338
+ }
339
+ catch (error) {
340
+ if (error instanceof DabError && error.code === 'config.source-root-nested') {
341
+ // `dab init` reports a refused nested target as a validation failure while
342
+ // preserving the source-root diagnostic code.
343
+ throw new ValidationError(error.message, error.code, {
344
+ ...(error.hint === undefined ? {} : { hint: error.hint }),
345
+ });
346
+ }
347
+ throw error;
348
+ }
349
+ }
350
+ function resolveInitLayout(initRoot, scope, home) {
351
+ if (scope === 'global') {
352
+ // Global init targets the canonical $HOME/.agents source root; its generated
353
+ // projections live under $HOME, never next to an alias path.
354
+ return {
355
+ scopeRoot: home,
356
+ manifestPath: join(initRoot, 'dab.yaml'),
357
+ };
358
+ }
359
+ return {
360
+ scopeRoot: initRoot,
361
+ manifestPath: join(initRoot, 'dab.yaml'),
362
+ };
363
+ }
364
+ function formatInit(result) {
365
+ const lines = [
366
+ `dab init ${result.root} scope=${result.scope}${result.dryRun ? ' (dry run)' : ''}`,
367
+ `Language: ${result.language.value} (source: ${result.language.source})`,
368
+ ];
369
+ if (result.created.length > 0) {
370
+ lines.push(result.dryRun ? 'would create:' : 'created:');
371
+ for (const file of result.created) {
372
+ lines.push(` ${file}`);
373
+ }
374
+ }
375
+ if (result.skipped.length > 0) {
376
+ lines.push('skipped (already present):');
377
+ for (const file of result.skipped) {
378
+ lines.push(` ${file}`);
379
+ }
380
+ }
381
+ if (result.ai !== undefined) {
382
+ lines.push(`AI proposal: ${result.ai.applied ? 'applied' : 'declined'}`);
383
+ }
384
+ if (result.normalize !== null) {
385
+ lines.push(`normalize: ${result.normalize.ok ? 'ok' : 'failed'}`);
386
+ }
387
+ if (result.pending.length > 0) {
388
+ lines.push('pending conflicts:');
389
+ for (const item of result.pending) {
390
+ lines.push(` ${item.file ?? '-'} ${item.code} ${item.message}`);
391
+ }
392
+ // A non-importable `.claude` entry and an import pending are resolved by
393
+ // hand or by plain normalize, never by the destructive `--fix` path.
394
+ const targetConflicts = result.pending.some((item) => item.code !== 'practice.skill-import-pending'
395
+ && item.code !== 'practice.skill-import-conflict');
396
+ if (targetConflicts) {
397
+ lines.push('next: dab normalize --dry-run');
398
+ lines.push('next: dab normalize --fix');
399
+ }
400
+ if (result.pending.some((item) => item.code === 'practice.skill-import-pending')) {
401
+ lines.push('next: dab normalize');
402
+ }
403
+ }
404
+ const pendingKeys = new Set(result.pending.map((item) => `${item.code}|${item.file ?? ''}|${item.line ?? ''}`));
405
+ const diagnostics = formatDiagnostics(result.diagnostics.filter((item) => !pendingKeys.has(`${item.code}|${item.file ?? ''}|${item.line ?? ''}`)));
406
+ if (diagnostics.length > 0) {
407
+ lines.push(diagnostics.trimEnd());
408
+ }
409
+ lines.push(result.ok ? 'OK' : 'FAILED');
410
+ return `${lines.join('\n')}\n`;
411
+ }
412
+ export async function initializeProject(options) {
413
+ assertSupportedPlatform(options.platform);
414
+ if (options.profile !== undefined
415
+ && options.profile !== 'generic'
416
+ && options.profile !== 'feature') {
417
+ throw new UsageError(`unsupported profile: ${String(options.profile)}; supported profiles: generic, feature`, 'usage.invalid-profile');
418
+ }
419
+ if (options.ai === true && options.dryRun === true) {
420
+ throw new UsageError('--ai cannot be combined with --dry-run', 'usage.ai-dry-run', { hint: 'Run dab init --dry-run for a preview, then dab init --ai interactively.' });
421
+ }
422
+ const home = resolve(options.home ?? homedir());
423
+ const dryRun = options.dryRun === true;
424
+ const initTarget = await resolveInitRoot(options);
425
+ const root = initTarget.root;
426
+ const scope = await resolveInitScope(initTarget.scopePath, home);
427
+ const layout = resolveInitLayout(root, scope, home);
428
+ if (!dryRun) {
429
+ await ensureDir(root);
430
+ }
431
+ const scan = await scanProject(root);
432
+ const existingManifest = (await lstatOrNull(layout.manifestPath)) === null
433
+ ? undefined
434
+ : await loadProjectManifest(layout.scopeRoot, { scope });
435
+ // An authored manifest wins over --profile; init never rewrites it.
436
+ const resolvedProfile = existingManifest?.manifest.profile
437
+ ?? options.profile
438
+ ?? 'generic';
439
+ const manifest = existingManifest?.manifest ?? {
440
+ version: 2,
441
+ scope,
442
+ project: { id: scan.projectId, name: scan.projectName },
443
+ profile: resolvedProfile,
444
+ docs: { language: 'auto' },
445
+ targets: [{
446
+ provider: 'claude-code',
447
+ enabled: true,
448
+ options: { minVersion: '2.1.277', instructions: 'symlink' },
449
+ }],
450
+ paths: { agents: '.agents', claude: '.claude' },
451
+ };
452
+ const paths = resolveProjectPaths(layout.scopeRoot, manifest);
453
+ const language = await resolveDocsLanguage({
454
+ root: layout.scopeRoot,
455
+ configured: existingManifest?.manifest.docs.language ?? 'auto',
456
+ env: process.env,
457
+ });
458
+ const safety = [];
459
+ try {
460
+ await assertRealPathInsideRoot(layout.scopeRoot, '.claude');
461
+ await assertRealPathInsideRoot(layout.scopeRoot, '.agents');
462
+ await assertRealPathsDisjoint(layout.scopeRoot, '.agents', '.claude');
463
+ for (const directory of [
464
+ '.agents/agents',
465
+ '.agents/skills',
466
+ '.agents/rules',
467
+ '.agents/policies',
468
+ '.agents/adapters',
469
+ '.agents/hooks',
470
+ '.agents/memory',
471
+ '.agents/notes',
472
+ '.claude/agents',
473
+ '.claude/skills',
474
+ '.claude/rules',
475
+ ]) {
476
+ await assertRealPathInsideRoot(layout.scopeRoot, directory);
477
+ }
478
+ }
479
+ catch (error) {
480
+ if (error instanceof DabError) {
481
+ safety.push({
482
+ code: error.code,
483
+ severity: 'error',
484
+ message: error.message,
485
+ file: scope === 'global' ? '.agents/dab.yaml' : 'dab.yaml',
486
+ });
487
+ return blocked(scope, root, layout.scopeRoot, language, [...scan.diagnostics, ...safety], safety, dryRun);
488
+ }
489
+ throw error;
490
+ }
491
+ // Discovery reads every `.agents` source parent directly. A regular file,
492
+ // dangling link or denied access at any of them would fail as an internal
493
+ // error, so report a governed conflict and block before any write or
494
+ // discovery. Practice parents share the same probe and diagnostic shape.
495
+ const sourceDiagnostics = [
496
+ ...(await sourceParentProblems(layout.scopeRoot)).map(sourceParentDiagnostic),
497
+ ...practiceParentDiagnostics(await practiceParentProblems(layout.scopeRoot)),
498
+ ];
499
+ if (sourceDiagnostics.length > 0) {
500
+ return blocked(scope, root, layout.scopeRoot, language, [...scan.diagnostics, ...sourceDiagnostics], sourceDiagnostics, dryRun);
501
+ }
502
+ const authoredConflicts = await findAuthoredConflicts(layout.scopeRoot);
503
+ const authored = await validateExistingAuthored(layout.scopeRoot, paths);
504
+ const authoredErrors = [
505
+ ...authoredConflicts,
506
+ ...authored.filter((item) => item.severity === 'error'),
507
+ ];
508
+ if (authoredErrors.length > 0) {
509
+ return blocked(scope, root, layout.scopeRoot, language, [...scan.diagnostics, ...authored, ...authoredConflicts], authoredErrors, dryRun);
510
+ }
511
+ const preflightDiagnostics = [
512
+ ...scan.diagnostics,
513
+ ...authored.filter((item) => item.severity !== 'error'),
514
+ ];
515
+ let existingProjections = [];
516
+ // Discovery reads `.agents/skills` and `.agents/rules`; a regular file at
517
+ // either parent raises ENOTDIR. The planner reports those conflicts and
518
+ // blocks every write, so enumeration is skipped instead of failing here.
519
+ const agentsProbe = await probeStat(paths.agents);
520
+ const parentProblems = await practiceParentProblems(layout.scopeRoot);
521
+ if (agentsProbe.info?.isDirectory() === true
522
+ && parentProblems.docs === undefined
523
+ && parentProblems.skills === undefined) {
524
+ const existing = await discoverProjections(layout.scopeRoot, paths);
525
+ const errors = existing.diagnostics.filter((item) => item.severity === 'error');
526
+ if (errors.length > 0) {
527
+ return blocked(scope, root, layout.scopeRoot, language, [...scan.diagnostics, ...existing.diagnostics], errors, dryRun);
528
+ }
529
+ existingProjections = existing.projections;
530
+ }
531
+ let proposal;
532
+ let aiApplied = false;
533
+ if (options.ai === true) {
534
+ if (options.confirm === undefined) {
535
+ throw new UsageError('AI init requires interactive confirmation', 'init.ai-confirmation-required', { hint: 'Run dab init --ai in a terminal, or run dab init without --ai.' });
536
+ }
537
+ proposal = await requestAiProposal(scan, options.runner ?? runCommand, root);
538
+ for (const agent of proposal.agents) {
539
+ const rendered = renderAgentFromProposal(agent);
540
+ try {
541
+ const parsed = parseFrontmatter(rendered, `.agents/agents/${agent.name}.md`);
542
+ const validated = AgentFrontmatterSchema.safeParse(parsed.data);
543
+ if (!validated.success) {
544
+ throw new Error('frontmatter does not match the agent schema');
545
+ }
546
+ }
547
+ catch (error) {
548
+ throw new ConfigError(`AI proposal agent ${agent.name} is not a valid agent definition: ${error instanceof Error ? error.message : String(error)}`, 'ai.invalid-proposal', { hint: 'Retry dab init --ai; the proposal must serialize to valid agent frontmatter.' });
549
+ }
550
+ }
551
+ options.onProposal?.(formatProposal(scan, proposal));
552
+ const approved = await options.confirm('Apply this AI proposal? [y/N] ');
553
+ if (!approved) {
554
+ return {
555
+ ok: true,
556
+ exitCode: ExitCode.Ok,
557
+ scope,
558
+ root,
559
+ scopeRoot: layout.scopeRoot,
560
+ dryRun: false,
561
+ created: [],
562
+ skipped: [],
563
+ conflicts: [],
564
+ pending: [],
565
+ diagnostics: preflightDiagnostics,
566
+ language,
567
+ normalize: null,
568
+ ai: { applied: false, proposal },
569
+ };
570
+ }
571
+ aiApplied = true;
572
+ }
573
+ const proposals = proposal === undefined
574
+ ? undefined
575
+ : { agentsMdAddition: proposal.agentsMdAddition, agents: proposal.agents };
576
+ const plan = await planAuthoredScaffold({
577
+ root: layout.scopeRoot,
578
+ scope,
579
+ scan,
580
+ profile: resolvedProfile,
581
+ mode: 'full',
582
+ version: DAB_VERSION,
583
+ env: process.env,
584
+ ...(existingManifest === undefined ? {} : { manifest: existingManifest.manifest }),
585
+ ...(proposals === undefined ? {} : { proposals }),
586
+ }, PRACTICE_PACKS);
587
+ const planDiagnostics = [
588
+ ...plan.diagnostics,
589
+ ...plan.policySkipped.map(policySkipDiagnostic),
590
+ ];
591
+ if (hasErrors(plan.diagnostics)) {
592
+ return blocked(scope, root, layout.scopeRoot, plan.docsLanguage, [...preflightDiagnostics, ...planDiagnostics], plan.diagnostics.filter((item) => item.severity === 'error'), dryRun);
593
+ }
594
+ const skillImports = await pendingSkillImports(layout.scopeRoot, scope, plan);
595
+ const files = skillImports.files;
596
+ const targets = targetMap(existingProjections);
597
+ for (const agent of proposal?.agents ?? []) {
598
+ targets.set(`.claude/agents/${agent.name}.md`, `.agents/agents/${agent.name}.md`);
599
+ }
600
+ const generated = await findGeneratedConflicts(layout.scopeRoot, paths, existingManifest?.manifest, targets);
601
+ if (generated.fatal.length > 0) {
602
+ return blocked(scope, root, layout.scopeRoot, plan.docsLanguage, [...preflightDiagnostics, ...planDiagnostics, ...generated.fatal], generated.fatal, dryRun);
603
+ }
604
+ const pending = [
605
+ ...generated.pending.map(pendingDiagnostic),
606
+ ...skillImports.diagnostics,
607
+ ];
608
+ if (dryRun) {
609
+ return {
610
+ ok: true,
611
+ exitCode: ExitCode.Ok,
612
+ scope,
613
+ root,
614
+ scopeRoot: layout.scopeRoot,
615
+ dryRun: true,
616
+ created: Object.keys(files).sort(),
617
+ skipped: [...plan.skipped].sort(),
618
+ conflicts: [],
619
+ pending,
620
+ diagnostics: [...preflightDiagnostics, ...planDiagnostics, ...pending],
621
+ language: plan.docsLanguage,
622
+ normalize: null,
623
+ ...(proposal === undefined ? {} : { ai: { applied: false, proposal } }),
624
+ };
625
+ }
626
+ for (const directory of skillImports.directories) {
627
+ await ensureDir(join(layout.scopeRoot, directory));
628
+ }
629
+ const created = [];
630
+ const writeSkipped = [];
631
+ for (const file of Object.keys(files).sort()) {
632
+ await writeIfMissing(layout.scopeRoot, file, files[file] ?? '', created, writeSkipped);
633
+ }
634
+ const skipped = [...plan.skipped];
635
+ for (const path of writeSkipped) {
636
+ if (!skipped.includes(path)) {
637
+ skipped.push(path);
638
+ }
639
+ }
640
+ if (pending.length > 0) {
641
+ return {
642
+ ok: true,
643
+ exitCode: ExitCode.Ok,
644
+ scope,
645
+ root,
646
+ scopeRoot: layout.scopeRoot,
647
+ dryRun: false,
648
+ created,
649
+ skipped,
650
+ conflicts: [],
651
+ pending,
652
+ diagnostics: [...preflightDiagnostics, ...planDiagnostics, ...pending],
653
+ language: plan.docsLanguage,
654
+ normalize: null,
655
+ ...(proposal === undefined ? {} : { ai: { applied: aiApplied, proposal } }),
656
+ };
657
+ }
658
+ const normalize = await normalizeProject({
659
+ cwd: root,
660
+ home,
661
+ platform: options.platform,
662
+ // Init keeps its existing behavior on an existing `.claude` tree: imports
663
+ // are normalize's job, so init never migrates or backs up entries.
664
+ suppressImports: true,
665
+ // Init installs missing skills only; managed updates belong to normalize.
666
+ suppressManagedSkills: true,
667
+ ...(options.runner === undefined ? {} : { runner: options.runner }),
668
+ });
669
+ // The nested normalize re-plans the same practice policy skips, so merge with
670
+ // exact-duplicate removal: one warning per skipped docs path.
671
+ const diagnostics = dedupeDiagnostics([
672
+ ...scan.diagnostics,
673
+ ...planDiagnostics,
674
+ ...normalize.diagnostics,
675
+ ]);
676
+ return {
677
+ ok: normalize.ok,
678
+ exitCode: normalize.exitCode,
679
+ scope,
680
+ root,
681
+ scopeRoot: layout.scopeRoot,
682
+ dryRun: false,
683
+ created,
684
+ skipped,
685
+ conflicts: [],
686
+ pending: [],
687
+ diagnostics,
688
+ language: plan.docsLanguage,
689
+ normalize,
690
+ ...(proposal === undefined ? {} : { ai: { applied: aiApplied, proposal } }),
691
+ };
692
+ }
693
+ export async function runInit(options, io) {
694
+ try {
695
+ const result = await initializeProject({
696
+ ...options,
697
+ onProposal: options.onProposal
698
+ ?? (options.json === true ? (text) => io.stderr(text) : io.stdout),
699
+ });
700
+ if (options.json === true) {
701
+ io.stdout(contractJson(result));
702
+ }
703
+ else if (result.ok) {
704
+ io.stdout(formatInit(result));
705
+ }
706
+ else {
707
+ io.stderr(formatInit(result));
708
+ }
709
+ return result.exitCode;
710
+ }
711
+ catch (error) {
712
+ if (error instanceof DabError) {
713
+ if (options.json === true) {
714
+ io.stdout(contractJson({ ok: false, error: error.toJSON() }));
715
+ }
716
+ else {
717
+ io.stderr(`dab: ${error.message}\n`);
718
+ if (error.hint !== undefined) {
719
+ io.stderr(`${error.hint}\n`);
720
+ }
721
+ }
722
+ return error.exitCode;
723
+ }
724
+ throw error;
725
+ }
726
+ }
727
+ //# sourceMappingURL=init.js.map