@hexagen-monaco/sync 0.5.2 → 0.7.0

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 (148) hide show
  1. package/dist/cli.js +1610 -620
  2. package/dist/cli.js.map +1 -1
  3. package/dist/config.d.ts +24 -0
  4. package/dist/config.d.ts.map +1 -1
  5. package/dist/domain/types.d.ts +8 -1
  6. package/dist/domain/types.d.ts.map +1 -1
  7. package/dist/fs-utils.d.ts +17 -4
  8. package/dist/fs-utils.d.ts.map +1 -1
  9. package/dist/generators/apps-framework-templates.d.ts +2 -1
  10. package/dist/generators/apps-framework-templates.d.ts.map +1 -1
  11. package/dist/generators/apps.d.ts.map +1 -1
  12. package/dist/generators/architecture-files.d.ts.map +1 -1
  13. package/dist/generators/barrels/recursive.d.ts +2 -3
  14. package/dist/generators/barrels/recursive.d.ts.map +1 -1
  15. package/dist/generators/barrels.d.ts +2 -3
  16. package/dist/generators/barrels.d.ts.map +1 -1
  17. package/dist/generators/cross-context.d.ts +5 -0
  18. package/dist/generators/cross-context.d.ts.map +1 -0
  19. package/dist/generators/eslint.d.ts +3 -1
  20. package/dist/generators/eslint.d.ts.map +1 -1
  21. package/dist/generators/layer-folders.d.ts +18 -6
  22. package/dist/generators/layer-folders.d.ts.map +1 -1
  23. package/dist/generators/package-json.d.ts +2 -3
  24. package/dist/generators/package-json.d.ts.map +1 -1
  25. package/dist/generators/port-analyzer.d.ts +38 -4
  26. package/dist/generators/port-analyzer.d.ts.map +1 -1
  27. package/dist/generators/reap.d.ts +7 -3
  28. package/dist/generators/reap.d.ts.map +1 -1
  29. package/dist/generators/root-file-templates.d.ts +4 -4
  30. package/dist/generators/root-file-templates.d.ts.map +1 -1
  31. package/dist/generators/root-files.d.ts.map +1 -1
  32. package/dist/generators/shared-kernel.d.ts +23 -0
  33. package/dist/generators/shared-kernel.d.ts.map +1 -0
  34. package/dist/generators/stubs.d.ts +13 -0
  35. package/dist/generators/stubs.d.ts.map +1 -1
  36. package/dist/generators/tsconfig.d.ts.map +1 -1
  37. package/dist/index.js +1441 -470
  38. package/dist/index.js.map +1 -1
  39. package/dist/journal.d.ts +64 -0
  40. package/dist/journal.d.ts.map +1 -0
  41. package/dist/migration-report.d.ts +13 -2
  42. package/dist/migration-report.d.ts.map +1 -1
  43. package/dist/results.d.ts +66 -0
  44. package/dist/results.d.ts.map +1 -1
  45. package/dist/scope-filter.d.ts +35 -0
  46. package/dist/scope-filter.d.ts.map +1 -0
  47. package/dist/sync-engine-helpers.d.ts.map +1 -1
  48. package/dist/sync-engine.d.ts +13 -1
  49. package/dist/sync-engine.d.ts.map +1 -1
  50. package/dist/templates/adobe-creative-production/manifest.json +2 -0
  51. package/dist/templates/adobe-express/manifest.json +2 -0
  52. package/dist/templates/adobe-firefly-composite/manifest.json +2 -0
  53. package/dist/templates/adobe-firefly-content-tagging/manifest.json +2 -0
  54. package/dist/templates/adobe-firefly-core/manifest.json +2 -0
  55. package/dist/templates/adobe-firefly-custom-models/manifest.json +2 -0
  56. package/dist/templates/adobe-firefly-generate/manifest.json +2 -0
  57. package/dist/templates/adobe-firefly-media/manifest.json +2 -0
  58. package/dist/templates/adobe-firefly-storage-azure/manifest.json +2 -0
  59. package/dist/templates/adobe-firefly-storage-gcs/manifest.json +2 -0
  60. package/dist/templates/adobe-firefly-storage-s3/manifest.json +2 -0
  61. package/dist/templates/adobe-firefly-upscale/manifest.json +2 -0
  62. package/dist/templates/adobe-illustrator/manifest.json +2 -0
  63. package/dist/templates/adobe-ims-spa/manifest.json +2 -0
  64. package/dist/templates/adobe-indesign/manifest.json +2 -0
  65. package/dist/templates/adobe-lightroom/manifest.json +2 -0
  66. package/dist/templates/adobe-photoshop/manifest.json +2 -0
  67. package/dist/templates/adobe-substance-3d/manifest.json +2 -0
  68. package/dist/templates/auth-mock/manifest.json +2 -0
  69. package/dist/templates/bedrock-agentcore-runtime/manifest.json +10 -2
  70. package/dist/templates/bedrock-agentcore-services/manifest.json +38 -9
  71. package/dist/templates/better-auth/manifest.json +2 -0
  72. package/dist/templates/bullmq/manifest.json +2 -0
  73. package/dist/templates/ci-github-actions/README.md +7 -0
  74. package/dist/templates/ci-github-actions/files/.github/dependabot.yml +16 -4
  75. package/dist/templates/ci-github-actions/files/.github/workflows/ci.yml +7 -3
  76. package/dist/templates/ci-github-actions/files/.github/workflows/preview.yml +20 -2
  77. package/dist/templates/ci-github-actions/manifest.json +26 -6
  78. package/dist/templates/clerk/manifest.json +2 -0
  79. package/dist/templates/design-system/manifest.json +14 -3
  80. package/dist/templates/docker/manifest.json +2 -0
  81. package/dist/templates/error-handling/manifest.json +2 -0
  82. package/dist/templates/eslint-no-console/manifest.json +2 -0
  83. package/dist/templates/github-oauth/manifest.json +2 -0
  84. package/dist/templates/google-oauth/manifest.json +2 -0
  85. package/dist/templates/langgraph/manifest.json +62 -15
  86. package/dist/templates/llm-adapter/manifest.json +2 -0
  87. package/dist/templates/magic-link/manifest.json +2 -0
  88. package/dist/templates/mcp-server/README.md +49 -0
  89. package/dist/templates/mcp-server/files/.env.mcp.example +6 -0
  90. package/dist/templates/mcp-server/files/.mcp.json.example +8 -0
  91. package/dist/templates/mcp-server/files/bin/cli.ts +15 -0
  92. package/dist/templates/mcp-server/files/src/infrastructure/mcp/prompts/example.prompt.ts +32 -0
  93. package/dist/templates/mcp-server/files/src/infrastructure/mcp/registry/register-all.ts +11 -0
  94. package/dist/templates/mcp-server/files/src/infrastructure/mcp/registry/tool-registry.test.ts +67 -0
  95. package/dist/templates/mcp-server/files/src/infrastructure/mcp/registry/tool-registry.ts +45 -0
  96. package/dist/templates/mcp-server/files/src/infrastructure/mcp/resources/example.resource.ts +28 -0
  97. package/dist/templates/mcp-server/files/src/infrastructure/mcp/sdk.ts +41 -0
  98. package/dist/templates/mcp-server/files/src/infrastructure/mcp/server.ts +52 -0
  99. package/dist/templates/mcp-server/files/src/infrastructure/mcp/tools/example.tool.test.ts +31 -0
  100. package/dist/templates/mcp-server/files/src/infrastructure/mcp/tools/example.tool.ts +74 -0
  101. package/dist/templates/mcp-server/files/src/infrastructure/mcp/transport/register-transports.ts +15 -0
  102. package/dist/templates/mcp-server/files/src/infrastructure/mcp/transport/stdio.ts +14 -0
  103. package/dist/templates/mcp-server/manifest.json +68 -0
  104. package/dist/templates/mcp-server-http/README.md +98 -0
  105. package/dist/templates/mcp-server-http/files/.env.mcp-http.example +22 -0
  106. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/bearer.test.ts +54 -0
  107. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/bearer.ts +49 -0
  108. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/oauth.test.ts +50 -0
  109. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/auth/oauth.ts +53 -0
  110. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/guard.test.ts +75 -0
  111. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/guard.ts +26 -0
  112. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/transport/http.ts +94 -0
  113. package/dist/templates/mcp-server-http/files/src/infrastructure/mcp/transport/register-transports.ts +15 -0
  114. package/dist/templates/mcp-server-http/manifest.json +56 -0
  115. package/dist/templates/microsoft-entra/manifest.json +2 -0
  116. package/dist/templates/nextauth/manifest.json +2 -0
  117. package/dist/templates/observability/manifest.json +10 -2
  118. package/dist/templates/rate-limiting/manifest.json +2 -0
  119. package/dist/templates/shared-types/manifest.json +2 -0
  120. package/dist/templates/supabase/manifest.json +2 -0
  121. package/dist/templates/supabase-auth/manifest.json +2 -0
  122. package/dist/toolchain-version.d.ts +14 -0
  123. package/dist/toolchain-version.d.ts.map +1 -0
  124. package/dist/types/manifest/apps.d.ts +12 -1
  125. package/dist/types/manifest/apps.d.ts.map +1 -1
  126. package/package.json +1 -1
  127. package/dist/application/use-cases/stub-generation.use-case.d.ts +0 -23
  128. package/dist/application/use-cases/stub-generation.use-case.d.ts.map +0 -1
  129. package/dist/generators/migration-assistant.d.ts +0 -7
  130. package/dist/generators/migration-assistant.d.ts.map +0 -1
  131. package/dist/generators/migration-audit.d.ts +0 -28
  132. package/dist/generators/migration-audit.d.ts.map +0 -1
  133. package/dist/generators/migration-stubs.d.ts +0 -7
  134. package/dist/generators/migration-stubs.d.ts.map +0 -1
  135. package/dist/generators/test-generator.d.ts +0 -7
  136. package/dist/generators/test-generator.d.ts.map +0 -1
  137. package/dist/generators/test-templates/data-builder.d.ts +0 -2
  138. package/dist/generators/test-templates/data-builder.d.ts.map +0 -1
  139. package/dist/generators/test-templates/enhanced-test-double.d.ts +0 -2
  140. package/dist/generators/test-templates/enhanced-test-double.d.ts.map +0 -1
  141. package/dist/generators/test-templates/index.d.ts +0 -5
  142. package/dist/generators/test-templates/index.d.ts.map +0 -1
  143. package/dist/generators/test-templates/integration-test.d.ts +0 -2
  144. package/dist/generators/test-templates/integration-test.d.ts.map +0 -1
  145. package/dist/generators/test-templates/unit-test.d.ts +0 -2
  146. package/dist/generators/test-templates/unit-test.d.ts.map +0 -1
  147. package/dist/generators/wiring.d.ts +0 -20
  148. package/dist/generators/wiring.d.ts.map +0 -1
package/dist/cli.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import * as fs19 from 'fs';
3
- import fs19__default, { mkdirSync, writeFileSync, renameSync, unlinkSync, existsSync, readFileSync, realpathSync, lstatSync, createWriteStream } from 'fs';
4
- import { fileURLToPath } from 'url';
5
- import * as path28 from 'path';
6
- import path28__default, { dirname, join } from 'path';
7
2
  import { Command } from 'commander';
8
- import fs22, { readFile } from 'fs/promises';
3
+ import * as path34 from 'path';
4
+ import path34__default, { dirname, join } from 'path';
5
+ import * as fs24 from 'fs';
6
+ import fs24__default, { mkdirSync, writeFileSync, renameSync, unlinkSync, existsSync, readFileSync, realpathSync, lstatSync, createWriteStream } from 'fs';
7
+ import fs27, { readFile } from 'fs/promises';
9
8
  import { promisify } from 'util';
10
9
  import { exec, execSync, spawn } from 'child_process';
11
10
  import yaml9 from 'js-yaml';
12
11
  import crypto from 'crypto';
12
+ import { fileURLToPath } from 'url';
13
13
  import { Project, SyntaxKind, MethodSignature } from 'ts-morph';
14
14
  import * as readline from 'readline';
15
15
  import { tmpdir } from 'os';
@@ -25,26 +25,132 @@ var MigrationReport = class {
25
25
  this.entries.push({ type, target, message });
26
26
  }
27
27
  async writeReport(config) {
28
- const reportPath = path28__default.join(
29
- config.workspaceRoot,
30
- "SYNC-MIGRATION-REPORT.md"
31
- );
28
+ if (config.dryRun && !config.report) {
29
+ const counts = /* @__PURE__ */ new Map();
30
+ for (const e of this.entries) {
31
+ counts.set(e.type, (counts.get(e.type) ?? 0) + 1);
32
+ }
33
+ const breakdown = [...counts.entries()].map(([type, n]) => `${n} ${type}`).join(", ");
34
+ config.logger.info(
35
+ `[DRY-RUN] skipping migration report file (${this.entries.length} entries${breakdown ? `: ${breakdown}` : ""}) — pass --report <path> to write it anyway`
36
+ );
37
+ return;
38
+ }
39
+ const reportPath = config.report ? path34__default.resolve(config.workspaceRoot, config.report) : path34__default.join(config.workspaceRoot, "SYNC-MIGRATION-REPORT.md");
40
+ await fs27.mkdir(path34__default.dirname(reportPath), { recursive: true });
41
+ let preContent = null;
42
+ try {
43
+ preContent = await fs27.readFile(reportPath, "utf8");
44
+ } catch (e) {
45
+ if (!(e instanceof Error && "code" in e && e.code === "ENOENT"))
46
+ throw e;
47
+ }
48
+ config.journal?.recordWrite(reportPath, preContent);
32
49
  const stream = createWriteStream(reportPath, { flags: "w" });
33
- stream.write("# Sync Migration Report\n\n");
34
- for (const e of this.entries) {
35
- stream.write(
36
- `- ${e.type.toUpperCase()}: ${e.target}${e.message ? ` – ${e.message}` : ""}
50
+ await new Promise((resolve, reject) => {
51
+ stream.on("error", reject);
52
+ stream.write("# Sync Migration Report\n\n");
53
+ for (const e of this.entries) {
54
+ stream.write(
55
+ `- ${e.type.toUpperCase()}: ${e.target}${e.message ? ` – ${e.message}` : ""}
37
56
  `
38
- );
57
+ );
58
+ }
59
+ stream.end(resolve);
60
+ });
61
+ }
62
+ };
63
+ var SyncJournal = class {
64
+ entries = [];
65
+ /**
66
+ * Record a write BEFORE it is attempted. `preContent: null` means the file
67
+ * did not exist (a create); a string is the full pre-image of an overwrite.
68
+ * Over-recording is safe: rolling back a write that never happened either
69
+ * restores identical content or unlinks a file that is not there (ENOENT
70
+ * tolerated below). Under-recording loses user data — so mutation sites
71
+ * record first, mutate second.
72
+ */
73
+ recordWrite(filePath, preContent) {
74
+ this.entries.push({
75
+ path: filePath,
76
+ kind: preContent === null ? "created" : "overwritten",
77
+ preContent
78
+ });
79
+ }
80
+ /** Record a deletion BEFORE the unlink, with the full pre-image. */
81
+ recordDelete(filePath, preContent) {
82
+ this.entries.push({ path: filePath, kind: "deleted", preContent });
83
+ }
84
+ get size() {
85
+ return this.entries.length;
86
+ }
87
+ /**
88
+ * Human-readable journal lines (workspace-relative), oldest first — printed
89
+ * verbatim when a failed run must NOT roll back (--allow-dirty).
90
+ */
91
+ describeEntries(workspaceRoot) {
92
+ return this.entries.map(
93
+ (e) => `${e.kind} ${path34__default.relative(workspaceRoot, e.path)}`
94
+ );
95
+ }
96
+ /**
97
+ * Replay the journal in REVERSE order: restore pre-images, unlink created
98
+ * files. Reverse order makes repeated writes to the same path converge on
99
+ * the OLDEST pre-image (pass-1 barrel pre-image is restored last), i.e. the
100
+ * true pre-sync state.
101
+ *
102
+ * Per-entry best-effort: a failing inverse op is collected and replay
103
+ * CONTINUES — restoring nine of ten files beats aborting at the first
104
+ * error. The caller prints the failures; nothing here (or anywhere) falls
105
+ * back to a git-wide reset/clean.
106
+ *
107
+ * Restores use a plain writeFile, not the atomic tmp+rename protocol: the
108
+ * rollback may be running on the same broken substrate that failed the
109
+ * sync, and the simplest possible write maximizes the odds of getting the
110
+ * user's bytes back on disk.
111
+ */
112
+ async rollback(logger2, workspaceRoot) {
113
+ const outcome = {
114
+ attempted: this.entries.length,
115
+ restored: 0,
116
+ failures: []
117
+ };
118
+ for (const entry of [...this.entries].reverse()) {
119
+ const relative = path34__default.relative(workspaceRoot, entry.path);
120
+ try {
121
+ if (entry.preContent === null) {
122
+ try {
123
+ await fs27.unlink(entry.path);
124
+ } catch (err3) {
125
+ if (!(err3 instanceof Error && "code" in err3 && err3.code === "ENOENT")) {
126
+ throw err3;
127
+ }
128
+ }
129
+ logger2.info(`rolled back (removed) ${relative}`);
130
+ } else {
131
+ await fs27.mkdir(path34__default.dirname(entry.path), { recursive: true });
132
+ await fs27.writeFile(entry.path, entry.preContent, {
133
+ encoding: "utf8"
134
+ });
135
+ logger2.info(`rolled back (restored) ${relative}`);
136
+ }
137
+ outcome.restored += 1;
138
+ } catch (err3) {
139
+ outcome.failures.push({
140
+ path: entry.path,
141
+ intended: entry.preContent === null ? "remove created file" : "restore pre-image",
142
+ error: err3 instanceof Error ? err3.message : String(err3)
143
+ });
144
+ }
39
145
  }
40
- stream.end();
146
+ return outcome;
41
147
  }
42
148
  };
43
149
  var LOCK_FILE = ".architecture/.sync.lock";
44
150
  var LockFile = class {
45
- constructor(workspaceRoot, fsImpl = fs22, logger2 = console) {
151
+ constructor(workspaceRoot, fsImpl = fs27, logger2 = console) {
46
152
  this.workspaceRoot = workspaceRoot;
47
- this.lockPath = path28__default.join(workspaceRoot, LOCK_FILE);
153
+ this.lockPath = path34__default.join(workspaceRoot, LOCK_FILE);
48
154
  this.fsImpl = fsImpl;
49
155
  this.logger = logger2;
50
156
  }
@@ -111,11 +217,11 @@ var LockFile = class {
111
217
  };
112
218
  var BIN_NAME = process.platform === "win32" ? "hexagen-lint.cmd" : "hexagen-lint";
113
219
  function resolveArchLinterBin(startDir) {
114
- let dir = path28__default.resolve(startDir);
220
+ let dir = path34__default.resolve(startDir);
115
221
  for (; ; ) {
116
- const candidate = path28__default.join(dir, "node_modules", ".bin", BIN_NAME);
117
- if (fs19__default.existsSync(candidate)) return candidate;
118
- const parent = path28__default.dirname(dir);
222
+ const candidate = path34__default.join(dir, "node_modules", ".bin", BIN_NAME);
223
+ if (fs24__default.existsSync(candidate)) return candidate;
224
+ const parent = path34__default.dirname(dir);
119
225
  if (parent === dir) return null;
120
226
  dir = parent;
121
227
  }
@@ -161,9 +267,64 @@ function createEmptyResult() {
161
267
  created: [],
162
268
  skipped: [],
163
269
  updated: [],
270
+ deleted: [],
271
+ unchanged: [],
164
272
  totalOps: 0
165
273
  };
166
274
  }
275
+ function recordWriteStatus(result, filePath, status) {
276
+ if (status === "created") {
277
+ result.created.push(filePath);
278
+ result.totalOps += 1;
279
+ } else if (status === "updated") {
280
+ result.updated.push(filePath);
281
+ result.totalOps += 1;
282
+ } else if (status === "unchanged") {
283
+ result.unchanged.push(filePath);
284
+ } else {
285
+ result.skipped.push(filePath);
286
+ }
287
+ }
288
+
289
+ // src/scope-filter.ts
290
+ var GLOB_META = /[*?]/;
291
+ function normalize(p) {
292
+ return p.replace(/\\/g, "/").replace(/^\.?\//, "").replace(/\/+$/, "");
293
+ }
294
+ function globToRegExp(glob) {
295
+ let re = "";
296
+ for (let i = 0; i < glob.length; i++) {
297
+ const c = glob[i];
298
+ if (c === "*") {
299
+ if (glob[i + 1] === "*") {
300
+ re += ".*";
301
+ i++;
302
+ } else {
303
+ re += "[^/]*";
304
+ }
305
+ } else if (c === "?") {
306
+ re += "[^/]";
307
+ } else if ("\\^$.|+()[]{}".includes(c)) {
308
+ re += `\\${c}`;
309
+ } else {
310
+ re += c;
311
+ }
312
+ }
313
+ return new RegExp(`^${re}$`);
314
+ }
315
+ function matchesScope(relativePath, patterns) {
316
+ const rel = normalize(relativePath);
317
+ return patterns.some((raw) => {
318
+ const pat = normalize(raw);
319
+ if (pat === "") return false;
320
+ if (!GLOB_META.test(pat)) {
321
+ return rel === pat || rel.startsWith(`${pat}/`);
322
+ }
323
+ return globToRegExp(pat).test(rel);
324
+ });
325
+ }
326
+
327
+ // src/fs-utils.ts
167
328
  var GENERATED_MARKER = "// @generated by @hexagen/sync";
168
329
  var protectedFiles = /* @__PURE__ */ new Set([
169
330
  ".gitignore",
@@ -190,20 +351,29 @@ function isGeneratedFile(content) {
190
351
  return content.includes(GENERATED_MARKER);
191
352
  }
192
353
  function isProtectedRoot(filePath, config) {
193
- const relative = path28__default.relative(config.workspaceRoot, filePath);
354
+ const relative = path34__default.relative(config.workspaceRoot, filePath);
194
355
  const isRootLevel = !relative.startsWith("packages/") && !relative.startsWith("tools/") && !relative.startsWith("apps/");
195
356
  return isRootLevel && Array.from(protectedFiles).some(
196
357
  (f) => relative.endsWith(f) || relative.includes(f)
197
358
  );
198
359
  }
360
+ function isInScope(filePath, config) {
361
+ if (!config.only || config.only.length === 0) return true;
362
+ const relativePath = path34__default.relative(config.workspaceRoot, filePath);
363
+ return matchesScope(relativePath, config.only);
364
+ }
199
365
  async function safeWriteFileAtomic(filePath, content, config, report, skipGeneratedCheck = false) {
200
366
  const { dryRun, forceRoot, logger: logger2, workspaceRoot } = config;
201
- const relativePath = path28__default.relative(workspaceRoot, filePath);
367
+ const relativePath = path34__default.relative(workspaceRoot, filePath);
368
+ if (!isInScope(filePath, config)) {
369
+ logger2.debug(`skipped (outside --only) ${relativePath}`);
370
+ return "skipped";
371
+ }
202
372
  let exists = false;
203
373
  let currentContent = "";
204
374
  let currentHash = "";
205
375
  try {
206
- currentContent = await fs22.readFile(filePath, "utf8");
376
+ currentContent = await fs27.readFile(filePath, "utf8");
207
377
  currentHash = contentHash(currentContent);
208
378
  exists = true;
209
379
  } catch (e) {
@@ -215,36 +385,39 @@ async function safeWriteFileAtomic(filePath, content, config, report, skipGenera
215
385
  logger2.debug(`unchanged ${relativePath}`);
216
386
  return "unchanged";
217
387
  }
218
- if (dryRun) {
219
- const action = exists ? "update" : "create";
220
- logger2.info(`[DRY-RUN] would ${action} ${relativePath}`);
221
- return exists ? "updated" : "created";
222
- }
223
388
  if (isProtectedRoot(filePath, config) && !forceRoot) {
224
- logger2.warn(`skipped (root protected, use --force-root) ${relativePath}`);
389
+ const verb = dryRun ? "[DRY-RUN] would skip" : "skipped";
390
+ logger2.warn(`${verb} (root protected, use --force-root) ${relativePath}`);
225
391
  if (report) report.record("blocked", filePath, "Root file protected");
226
392
  return "protected";
227
393
  }
228
394
  if (exists && !forceRoot && !skipGeneratedCheck && !isGeneratedFile(currentContent)) {
395
+ const verb = dryRun ? "[DRY-RUN] would skip" : "skipped";
229
396
  logger2.warn(
230
- `skipped (hand-written, use --force-root to overwrite) ${relativePath}`
397
+ `${verb} (hand-written, use --force-root to overwrite) ${relativePath}`
231
398
  );
232
399
  return "skipped";
233
400
  }
234
- await fs22.mkdir(path28__default.dirname(filePath), { recursive: true });
235
- const tmpName = `.${path28__default.basename(filePath)}.${crypto.randomUUID()}.tmp`;
236
- const tmpPath = path28__default.join(path28__default.dirname(filePath), tmpName);
237
- await fs22.writeFile(tmpPath, content, { encoding: "utf8" });
401
+ if (dryRun) {
402
+ const action = exists ? "update" : "create";
403
+ logger2.info(`[DRY-RUN] would ${action} ${relativePath}`);
404
+ return exists ? "updated" : "created";
405
+ }
406
+ config.journal?.recordWrite(filePath, exists ? currentContent : null);
407
+ await fs27.mkdir(path34__default.dirname(filePath), { recursive: true });
408
+ const tmpName = `.${path34__default.basename(filePath)}.${crypto.randomUUID()}.tmp`;
409
+ const tmpPath = path34__default.join(path34__default.dirname(filePath), tmpName);
410
+ await fs27.writeFile(tmpPath, content, { encoding: "utf8" });
238
411
  try {
239
- await fs22.rename(tmpPath, filePath);
412
+ await fs27.rename(tmpPath, filePath);
240
413
  const status = exists ? "updated" : "created";
241
414
  logger2.info(`${status} ${relativePath}`);
242
415
  return status;
243
416
  } catch (err3) {
244
417
  if (err3 instanceof Error && "code" in err3 && err3.code === "EXDEV") {
245
418
  try {
246
- await fs22.copyFile(tmpPath, filePath);
247
- await fs22.unlink(tmpPath);
419
+ await fs27.copyFile(tmpPath, filePath);
420
+ await fs27.unlink(tmpPath);
248
421
  const status = exists ? "updated" : "created";
249
422
  logger2.info(`${status} ${relativePath}`);
250
423
  return status;
@@ -252,55 +425,52 @@ async function safeWriteFileAtomic(filePath, content, config, report, skipGenera
252
425
  logger2.warn(`EXDEV fallback failed for ${relativePath}: ${copyErr}`);
253
426
  }
254
427
  }
255
- await fs22.unlink(tmpPath).catch(() => {
428
+ await fs27.unlink(tmpPath).catch(() => {
256
429
  });
257
430
  throw err3;
258
431
  }
259
432
  }
260
433
 
261
434
  // src/generators/layer-folders.ts
262
- var GENERATED_MARKER2 = "// @generated by @hexagen/sync";
263
- async function loadYamlSafe(filePath) {
435
+ async function directoryExists(dirPath) {
264
436
  try {
265
- const content = await fs22.readFile(filePath, "utf8");
266
- return yaml9.load(content);
437
+ const stats = await fs27.stat(dirPath);
438
+ return stats.isDirectory();
267
439
  } catch (e) {
268
440
  if (e instanceof Error && "code" in e && e.code === "ENOENT") {
269
- return null;
441
+ return false;
270
442
  }
271
443
  throw e;
272
444
  }
273
445
  }
274
- async function generateBarrelContent(dirPath) {
275
- const exportLines = [];
446
+ async function ensureDirectoryCounted(dirPath, config, result) {
447
+ const existed = await directoryExists(dirPath);
448
+ if (existed) return;
449
+ const relativePath = path34__default.relative(config.workspaceRoot, dirPath);
450
+ if (config.dryRun) {
451
+ config.logger.info(`[DRY-RUN] would create directory ${relativePath}`);
452
+ } else {
453
+ await fs27.mkdir(dirPath, { recursive: true });
454
+ config.logger.info(`created directory ${relativePath}`);
455
+ }
456
+ result.created.push(dirPath);
457
+ result.totalOps += 1;
458
+ }
459
+ async function loadYamlSafe(filePath) {
276
460
  try {
277
- const entries = await fs22.readdir(dirPath, { withFileTypes: true });
278
- for (const entry of entries) {
279
- if (entry.name === "index.ts" || entry.name.startsWith(".")) continue;
280
- if (entry.isFile() && entry.name.endsWith(".ts")) {
281
- const base = entry.name.replace(/\.ts$/, "");
282
- exportLines.push(`export * from './${base}.js';`);
283
- } else if (entry.isDirectory()) {
284
- exportLines.push(`export * from './${entry.name}/index.js';`);
285
- }
286
- }
461
+ const content = await fs27.readFile(filePath, "utf8");
462
+ return yaml9.load(content);
287
463
  } catch (e) {
288
- if (e instanceof Error && "code" in e && e.code === "ENOENT") ; else {
289
- throw e;
464
+ if (e instanceof Error && "code" in e && e.code === "ENOENT") {
465
+ return null;
290
466
  }
467
+ throw e;
291
468
  }
292
- return exportLines.length > 0 ? `${GENERATED_MARKER2}
293
-
294
- ${exportLines.join("\n")}
295
- ` : `${GENERATED_MARKER2}
296
-
297
- // No exports yet
298
- `;
299
469
  }
300
- async function ensureLayerFolders(moduleDir, layers, config, report) {
470
+ async function ensureLayerFolders(moduleDir, layers, config) {
301
471
  const result = createEmptyResult();
302
472
  const { logger: logger2 } = config;
303
- const layerRulesPath = path28__default.join(
473
+ const layerRulesPath = path34__default.join(
304
474
  config.workspaceRoot,
305
475
  ".architecture",
306
476
  "invariants",
@@ -311,58 +481,18 @@ async function ensureLayerFolders(moduleDir, layers, config, report) {
311
481
  logger2.warn("layer-rules.yaml not found — skipping layer rule enforcement");
312
482
  }
313
483
  for (const [, layerConfig] of Object.entries(layers)) {
314
- const layerPath = path28__default.join(moduleDir, layerConfig.folder);
315
- try {
316
- await fs22.mkdir(layerPath, { recursive: true });
317
- result.created.push(layerPath);
318
- result.totalOps += 1;
319
- } catch (e) {
320
- if (e instanceof Error && "code" in e && e.code === "EEXIST") {
321
- result.skipped.push(layerPath);
322
- } else {
323
- throw e;
324
- }
484
+ const layerPath = path34__default.join(moduleDir, layerConfig.folder);
485
+ if (!isInScope(layerPath, config) && !isInScope(path34__default.join(layerPath, "index.ts"), config)) {
486
+ continue;
325
487
  }
326
- const barrelPath = path28__default.join(layerPath, "index.ts");
327
- const barrelContent = await generateBarrelContent(layerPath);
328
- const barrelStatus = await safeWriteFileAtomic(
329
- barrelPath,
330
- barrelContent,
331
- config,
332
- report
333
- );
334
- if (barrelStatus === "created") result.created.push(barrelPath);
335
- if (barrelStatus === "updated") result.updated.push(barrelPath);
336
- if (barrelStatus === "skipped" || barrelStatus === "protected")
337
- result.skipped.push(barrelPath);
338
- result.totalOps += barrelStatus === "created" || barrelStatus === "updated" ? 1 : 0;
488
+ await ensureDirectoryCounted(layerPath, config, result);
339
489
  const subfolders = layerConfig.subfolders ?? [];
340
490
  for (const sub of subfolders) {
341
- const subPath = path28__default.join(layerPath, sub);
342
- try {
343
- await fs22.mkdir(subPath, { recursive: true });
344
- result.created.push(subPath);
345
- result.totalOps += 1;
346
- } catch (e) {
347
- if (e instanceof Error && "code" in e && e.code === "EEXIST") {
348
- result.skipped.push(subPath);
349
- } else {
350
- throw e;
351
- }
491
+ const subPath = path34__default.join(layerPath, sub);
492
+ if (!isInScope(subPath, config) && !isInScope(path34__default.join(subPath, "index.ts"), config)) {
493
+ continue;
352
494
  }
353
- const subBarrelPath = path28__default.join(subPath, "index.ts");
354
- const subBarrelContent = await generateBarrelContent(subPath);
355
- const subBarrelStatus = await safeWriteFileAtomic(
356
- subBarrelPath,
357
- subBarrelContent,
358
- config,
359
- report
360
- );
361
- if (subBarrelStatus === "created") result.created.push(subBarrelPath);
362
- if (subBarrelStatus === "updated") result.updated.push(subBarrelPath);
363
- if (subBarrelStatus === "skipped" || subBarrelStatus === "protected")
364
- result.skipped.push(subBarrelPath);
365
- result.totalOps += subBarrelStatus === "created" || subBarrelStatus === "updated" ? 1 : 0;
495
+ await ensureDirectoryCounted(subPath, config, result);
366
496
  }
367
497
  }
368
498
  return result;
@@ -383,10 +513,10 @@ var BARREL_EXCLUSIONS = /* @__PURE__ */ new Set([
383
513
  function isExcludedDirectory(name) {
384
514
  return BARREL_EXCLUSIONS.has(name) || name.startsWith(".");
385
515
  }
386
- var GENERATED_MARKER3 = "// @generated by @hexagen/sync";
516
+ var GENERATED_MARKER2 = "// @generated by @hexagen/sync";
387
517
  var LEGACY_GENERATED_MARKER = "— generated by sync.ts";
388
518
  function isGeneratedFile2(content) {
389
- return content.includes(GENERATED_MARKER3) || content.includes(LEGACY_GENERATED_MARKER);
519
+ return content.includes(GENERATED_MARKER2) || content.includes(LEGACY_GENERATED_MARKER);
390
520
  }
391
521
  function contentHash2(content) {
392
522
  return crypto.createHash("sha256").update(content).digest("hex");
@@ -394,18 +524,18 @@ function contentHash2(content) {
394
524
  function detectCircularExports(exportGraph) {
395
525
  const visited = /* @__PURE__ */ new Set();
396
526
  const recursionStack = /* @__PURE__ */ new Set();
397
- const path32 = [];
527
+ const path38 = [];
398
528
  function dfs(node) {
399
529
  if (recursionStack.has(node)) {
400
- const cycleStart = path32.indexOf(node);
401
- return [...path32.slice(cycleStart), node];
530
+ const cycleStart = path38.indexOf(node);
531
+ return [...path38.slice(cycleStart), node];
402
532
  }
403
533
  if (visited.has(node)) {
404
534
  return null;
405
535
  }
406
536
  visited.add(node);
407
537
  recursionStack.add(node);
408
- path32.push(node);
538
+ path38.push(node);
409
539
  const exports$1 = exportGraph.get(node) ?? [];
410
540
  for (const exportPath of exports$1) {
411
541
  const cycle = dfs(exportPath);
@@ -413,7 +543,7 @@ function detectCircularExports(exportGraph) {
413
543
  return cycle;
414
544
  }
415
545
  }
416
- path32.pop();
546
+ path38.pop();
417
547
  recursionStack.delete(node);
418
548
  return null;
419
549
  }
@@ -425,15 +555,15 @@ function detectCircularExports(exportGraph) {
425
555
  }
426
556
  return { hasCircular: false, cycle: null };
427
557
  }
428
- function generateBarrelContent2(entries) {
558
+ function generateBarrelContent(entries) {
429
559
  if (entries.length === 0) {
430
560
  return null;
431
561
  }
432
562
  const exportLines = entries.sort((a, b) => a.name.localeCompare(b.name)).map((entry) => {
433
- const path32 = entry.isDirectory ? `./${entry.name}/index.js` : `./${entry.name}.js`;
434
- return `export * from "${path32}";`;
563
+ const path38 = entry.isDirectory ? `./${entry.name}/index.js` : `./${entry.name}.js`;
564
+ return `export * from "${path38}";`;
435
565
  });
436
- return `${GENERATED_MARKER3}
566
+ return `${GENERATED_MARKER2}
437
567
 
438
568
  ${exportLines.join("\n")}
439
569
  `;
@@ -453,25 +583,47 @@ var CircularExportError = class extends Error {
453
583
  };
454
584
  async function generateRecursiveBarrels(moduleDir, config, report) {
455
585
  const result = createEmptyResult();
456
- const srcDir = path28__default.join(moduleDir, "src");
586
+ const srcDir = path34__default.join(moduleDir, "src");
457
587
  const layers = ["domain", "application", "infrastructure"];
458
588
  const pendingWrites = [];
459
589
  const preserved = [];
460
590
  const exportGraph = /* @__PURE__ */ new Map();
591
+ const layersWithContent = [];
461
592
  for (const layer of layers) {
462
- const layerDir = path28__default.join(srcDir, layer);
593
+ const layerDir = path34__default.join(srcDir, layer);
463
594
  try {
464
- await fs22.access(layerDir);
595
+ await fs27.access(layerDir);
465
596
  } catch {
466
597
  continue;
467
598
  }
468
- await walkDirectory(
599
+ const layerExports = await walkDirectory(
469
600
  layerDir,
470
601
  pendingWrites,
471
602
  preserved,
472
603
  exportGraph,
473
604
  config
474
605
  );
606
+ if (layerExports.length > 0) layersWithContent.push(layer);
607
+ }
608
+ if (config.mode === "external" && layersWithContent.length > 0) {
609
+ const rootBarrelPath = path34__default.join(srcDir, "index.ts");
610
+ if (await shouldGenerateBarrel(rootBarrelPath, preserved, config.logger)) {
611
+ const content = generateBarrelContent(
612
+ layersWithContent.map((name) => ({ name, isDirectory: true }))
613
+ );
614
+ const existing = await readFileIfExists(rootBarrelPath);
615
+ if (content !== null && !(existing && contentHash2(existing) === contentHash2(content))) {
616
+ pendingWrites.push({
617
+ filePath: rootBarrelPath,
618
+ content,
619
+ isNew: !existing
620
+ });
621
+ exportGraph.set(
622
+ rootBarrelPath,
623
+ layersWithContent.map((name) => path34__default.join(srcDir, name, "index.ts"))
624
+ );
625
+ }
626
+ }
475
627
  }
476
628
  const circularCheck = detectCircularExports(exportGraph);
477
629
  if (circularCheck.hasCircular && circularCheck.cycle) {
@@ -479,9 +631,19 @@ async function generateRecursiveBarrels(moduleDir, config, report) {
479
631
  }
480
632
  for (const pending of pendingWrites) {
481
633
  if (pending.content === "") {
634
+ if (config.dryRun) {
635
+ config.logger.info(
636
+ `[DRY-RUN] would delete empty barrel ${pending.filePath}`
637
+ );
638
+ result.deleted.push(pending.filePath);
639
+ result.totalOps++;
640
+ continue;
641
+ }
482
642
  try {
483
- await fs22.unlink(pending.filePath);
484
- result.created.push(pending.filePath);
643
+ const preContent = await fs27.readFile(pending.filePath, "utf8");
644
+ config.journal?.recordDelete(pending.filePath, preContent);
645
+ await fs27.unlink(pending.filePath);
646
+ result.deleted.push(pending.filePath);
485
647
  result.totalOps++;
486
648
  continue;
487
649
  } catch (err3) {
@@ -497,15 +659,7 @@ async function generateRecursiveBarrels(moduleDir, config, report) {
497
659
  config,
498
660
  report
499
661
  );
500
- if (status === "created") {
501
- result.created.push(pending.filePath);
502
- result.totalOps++;
503
- } else if (status === "updated") {
504
- result.updated.push(pending.filePath);
505
- result.totalOps++;
506
- } else if (status === "skipped" || status === "protected") {
507
- result.skipped.push(pending.filePath);
508
- }
662
+ recordWriteStatus(result, pending.filePath, status);
509
663
  }
510
664
  result.skipped.push(...preserved);
511
665
  return result;
@@ -515,7 +669,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
515
669
  const exportEntries = [];
516
670
  let entries;
517
671
  try {
518
- entries = await fs22.readdir(dirPath, { withFileTypes: true });
672
+ entries = await fs27.readdir(dirPath, { withFileTypes: true });
519
673
  } catch {
520
674
  return exportEntries;
521
675
  }
@@ -532,7 +686,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
532
686
  }
533
687
  }
534
688
  for (const dir of directories) {
535
- const subDirPath = path28__default.join(dirPath, dir);
689
+ const subDirPath = path34__default.join(dirPath, dir);
536
690
  const subExports = await walkDirectory(
537
691
  subDirPath,
538
692
  pendingWrites,
@@ -540,7 +694,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
540
694
  exportGraph,
541
695
  config
542
696
  );
543
- const subBarrelPath = path28__default.join(subDirPath, "index.ts");
697
+ const subBarrelPath = path34__default.join(subDirPath, "index.ts");
544
698
  const isQueuedForDeletion = pendingWrites.some(
545
699
  (p) => p.filePath === subBarrelPath && p.content === ""
546
700
  );
@@ -552,9 +706,9 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
552
706
  exportEntries.push({ name: file, isDirectory: false });
553
707
  }
554
708
  if (exportEntries.length === 0) {
555
- const barrelPath2 = path28__default.join(dirPath, "index.ts");
709
+ const barrelPath2 = path34__default.join(dirPath, "index.ts");
556
710
  const existingBarrel = await readFileIfExists(barrelPath2);
557
- const dirName = path28__default.basename(dirPath);
711
+ const dirName = path34__default.basename(dirPath);
558
712
  const isLayerDir = ["domain", "application", "infrastructure"].includes(
559
713
  dirName
560
714
  );
@@ -569,7 +723,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
569
723
  isNew: false
570
724
  });
571
725
  } else if (isEmptyStub && isLayerDir) {
572
- const newContent = `${GENERATED_MARKER3}
726
+ const newContent = `${GENERATED_MARKER2}
573
727
 
574
728
  export {};
575
729
  `;
@@ -581,7 +735,7 @@ export {};
581
735
  });
582
736
  }
583
737
  } else if (!existingBarrel.includes("export {}") && isLayerDir) {
584
- const newContent = `${GENERATED_MARKER3}
738
+ const newContent = `${GENERATED_MARKER2}
585
739
 
586
740
  export {};
587
741
  `;
@@ -592,7 +746,7 @@ export {};
592
746
  });
593
747
  }
594
748
  } else if (isLayerDir) {
595
- const newContent = `${GENERATED_MARKER3}
749
+ const newContent = `${GENERATED_MARKER2}
596
750
 
597
751
  export {};
598
752
  `;
@@ -604,14 +758,14 @@ export {};
604
758
  }
605
759
  return [];
606
760
  }
607
- const barrelPath = path28__default.join(dirPath, "index.ts");
761
+ const barrelPath = path34__default.join(dirPath, "index.ts");
608
762
  const shouldCreateBarrel = await shouldGenerateBarrel(
609
763
  barrelPath,
610
764
  preserved,
611
765
  logger2
612
766
  );
613
767
  if (shouldCreateBarrel) {
614
- const content = generateBarrelContent2(exportEntries);
768
+ const content = generateBarrelContent(exportEntries);
615
769
  if (content === null) {
616
770
  return [];
617
771
  }
@@ -624,14 +778,14 @@ export {};
624
778
  content,
625
779
  isNew: !existingContent
626
780
  });
627
- const exportPaths = exportEntries.filter((e) => e.isDirectory).map((e) => path28__default.join(dirPath, e.name, "index.ts"));
781
+ const exportPaths = exportEntries.filter((e) => e.isDirectory).map((e) => path34__default.join(dirPath, e.name, "index.ts"));
628
782
  exportGraph.set(barrelPath, exportPaths);
629
783
  }
630
784
  return exportEntries;
631
785
  }
632
786
  async function hasBarrel(dirPath) {
633
787
  try {
634
- await fs22.access(path28__default.join(dirPath, "index.ts"));
788
+ await fs27.access(path34__default.join(dirPath, "index.ts"));
635
789
  return true;
636
790
  } catch {
637
791
  return false;
@@ -651,7 +805,7 @@ async function shouldGenerateBarrel(barrelPath, preserved, logger2) {
651
805
  }
652
806
  async function readFileIfExists(filePath) {
653
807
  try {
654
- return await fs22.readFile(filePath, "utf8");
808
+ return await fs27.readFile(filePath, "utf8");
655
809
  } catch (err3) {
656
810
  if (err3 && typeof err3 === "object" && "code" in err3 && err3.code === "ENOENT") {
657
811
  return null;
@@ -696,7 +850,12 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
696
850
  const moduleOverrides = context?.packageJson ?? {};
697
851
  const scope = config.manifest ? resolveScope(config.manifest) : "generated-project";
698
852
  const dependsOnDeps = context ? expandDependsOn(context, scope) : {};
699
- const pkgPath = path28__default.join(modulePath, "package.json");
853
+ const pkgPath = path34__default.join(modulePath, "package.json");
854
+ const dependencies = {
855
+ ...dependsOnDeps,
856
+ ...defaults.dependencies ?? {},
857
+ ...moduleOverrides.dependencies ?? {}
858
+ };
700
859
  const desiredPkg = {
701
860
  name: `@${scope}/${moduleName}`,
702
861
  version: "0.1.0",
@@ -717,11 +876,17 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
717
876
  ...defaults.scripts ?? {},
718
877
  ...moduleOverrides.scripts ?? {}
719
878
  },
720
- dependencies: {
721
- ...dependsOnDeps,
722
- ...defaults.dependencies ?? {},
723
- ...moduleOverrides.dependencies ?? {}
724
- },
879
+ // Emitted only when non-empty (PR-B2, capstone 6f): Yarn 4 deletes an
880
+ // empty `"dependencies": {}` from workspace manifests during install, so
881
+ // emitting one creates a permanent install↔sync churn loop — install
882
+ // strips the key, the next sync re-injects it (`dependencies` is
883
+ // protected, but a protected key MISSING from the current file is
884
+ // re-added), and the tree never converges across the consumer's
885
+ // sync → install → sync workflow. A dependency-less package carries no
886
+ // block at all, matching yarn's normalized form. Existing trees that
887
+ // still carry `{}` on disk stay untouched via the protected-key merge.
888
+ // devDependencies/scripts can't go empty (both have built-in entries).
889
+ ...Object.keys(dependencies).length > 0 ? { dependencies } : {},
725
890
  devDependencies: {
726
891
  typescript: "^5.0.0",
727
892
  ...defaults.devDependencies ?? {},
@@ -730,7 +895,7 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
730
895
  };
731
896
  let currentPkg = {};
732
897
  try {
733
- const currentContent = await fs22.readFile(pkgPath, "utf8");
898
+ const currentContent = await fs27.readFile(pkgPath, "utf8");
734
899
  currentPkg = JSON.parse(currentContent);
735
900
  } catch (e) {
736
901
  if (!(e instanceof Error && "code" in e && e.code === "ENOENT")) {
@@ -770,11 +935,7 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
770
935
  report,
771
936
  true
772
937
  );
773
- if (status === "created") result.created.push(pkgPath);
774
- if (status === "updated") result.updated.push(pkgPath);
775
- if (status === "skipped" || status === "protected")
776
- result.skipped.push(pkgPath);
777
- result.totalOps += status === "created" || status === "updated" ? 1 : 0;
938
+ recordWriteStatus(result, pkgPath, status);
778
939
  return result;
779
940
  }
780
941
  var BUILTIN_FALLBACK_TEMPLATE = {
@@ -844,7 +1005,7 @@ function buildTemplate(base, context, scope) {
844
1005
  }
845
1006
  async function generateTsconfig(moduleDir, moduleName, config, report) {
846
1007
  const result = createEmptyResult();
847
- const filePath = path28__default.join(moduleDir, "tsconfig.json");
1008
+ const filePath = path34__default.join(moduleDir, "tsconfig.json");
848
1009
  try {
849
1010
  const base = resolveWorkspaceTemplate(config.manifest);
850
1011
  const context = config.manifest.bounded_contexts?.find(
@@ -859,16 +1020,14 @@ async function generateTsconfig(moduleDir, moduleName, config, report) {
859
1020
  config,
860
1021
  report
861
1022
  );
862
- if (status === "created") result.created.push(filePath);
863
- if (status === "updated") result.updated.push(filePath);
864
- if (status === "skipped" || status === "protected")
865
- result.skipped.push(filePath);
866
- result.totalOps += status === "created" || status === "updated" ? 1 : 0;
1023
+ recordWriteStatus(result, filePath, status);
867
1024
  return result;
868
1025
  } catch (err3) {
869
1026
  const message = err3 instanceof Error ? err3.message : String(err3);
870
1027
  result.error = err3 instanceof Error ? err3 : new Error(`tsconfig generation failed for ${moduleName}: ${message}`);
871
1028
  result.summary = `tsconfig generation failed for ${moduleName}: ${message}`;
1029
+ config.logger.error(result.summary);
1030
+ if (report) report.record("error", filePath, result.summary);
872
1031
  return result;
873
1032
  }
874
1033
  }
@@ -876,15 +1035,15 @@ async function reapLegacyFolders(moduleDir, config, report) {
876
1035
  const { dryRun, logger: logger2 } = config;
877
1036
  const legacyLayers = ["domain", "application", "infrastructure"];
878
1037
  for (const layer of legacyLayers) {
879
- const layerPath = path28__default.join(moduleDir, layer);
880
- const relativePath = path28__default.relative(config.workspaceRoot, layerPath);
1038
+ const layerPath = path34__default.join(moduleDir, layer);
1039
+ const relativePath = path34__default.relative(config.workspaceRoot, layerPath);
881
1040
  try {
882
- const entries = await fs22.readdir(layerPath);
1041
+ const entries = await fs27.readdir(layerPath);
883
1042
  if (entries.length === 0) {
884
1043
  if (dryRun) {
885
1044
  logger2.info(`[DRY-RUN] would delete empty folder ${relativePath}`);
886
1045
  } else {
887
- await fs22.rm(layerPath, { recursive: true, force: true });
1046
+ await fs27.rmdir(layerPath);
888
1047
  logger2.info(`deleted empty folder ${relativePath}`);
889
1048
  if (report) report.record("deleted", layerPath);
890
1049
  }
@@ -1374,8 +1533,8 @@ function getErrorMap() {
1374
1533
 
1375
1534
  // ../../node_modules/zod/v3/helpers/parseUtil.js
1376
1535
  var makeIssue = (params) => {
1377
- const { data, path: path32, errorMaps, issueData } = params;
1378
- const fullPath = [...path32, ...issueData.path || []];
1536
+ const { data, path: path38, errorMaps, issueData } = params;
1537
+ const fullPath = [...path38, ...issueData.path || []];
1379
1538
  const fullIssue = {
1380
1539
  ...issueData,
1381
1540
  path: fullPath
@@ -1491,11 +1650,11 @@ var errorUtil;
1491
1650
 
1492
1651
  // ../../node_modules/zod/v3/types.js
1493
1652
  var ParseInputLazyPath = class {
1494
- constructor(parent, value, path32, key) {
1653
+ constructor(parent, value, path38, key) {
1495
1654
  this._cachedPath = [];
1496
1655
  this.parent = parent;
1497
1656
  this.data = value;
1498
- this._path = path32;
1657
+ this._path = path38;
1499
1658
  this._key = key;
1500
1659
  }
1501
1660
  get path() {
@@ -5006,6 +5165,7 @@ var BUILTIN_PACKAGE_JSON_TEMPLATE = `{
5006
5165
  "sync": "hexagen sync",
5007
5166
  "sync:dry": "hexagen sync --dry-run",
5008
5167
  "sync:force": "hexagen sync --force",
5168
+ "sync:check": "hexagen sync --check",
5009
5169
  "lint:arch": "hexagen arch validate",
5010
5170
  "templates:add": "hexagen add",
5011
5171
  "templates:validate": "hexagen validate-templates",
@@ -5016,8 +5176,8 @@ var BUILTIN_PACKAGE_JSON_TEMPLATE = `{
5016
5176
  "typescript": "^5.5.4",
5017
5177
  "eslint": "^9.0.0",
5018
5178
  "prettier": "^3.0.0",
5019
- "@hexagen-monaco/sync": "^0.4.0",
5020
- "@hexagen-monaco/arch-linter": "^0.4.0"
5179
+ "@hexagen-monaco/sync": "^{toolchainVersion}",
5180
+ "@hexagen-monaco/arch-linter": "^{toolchainVersion}"
5021
5181
  }
5022
5182
  }`;
5023
5183
  var BUILTIN_TSCONFIG_BASE_TEMPLATE = `{
@@ -5026,6 +5186,7 @@ var BUILTIN_TSCONFIG_BASE_TEMPLATE = `{
5026
5186
  "module": "ESNext",
5027
5187
  "moduleResolution": "bundler",
5028
5188
  "strict": true,
5189
+ "skipLibCheck": true,
5029
5190
  "composite": true,
5030
5191
  "declaration": true,
5031
5192
  "emitDeclarationOnly": true,
@@ -5057,6 +5218,9 @@ var BUILTIN_TURBO_TEMPLATE = `{
5057
5218
  ]
5058
5219
  },
5059
5220
  "typecheck": {
5221
+ "dependsOn": [
5222
+ "^build"
5223
+ ],
5060
5224
  "outputs": [],
5061
5225
  "cache": true
5062
5226
  },
@@ -5077,7 +5241,13 @@ node_modules/
5077
5241
  dist/
5078
5242
  .turbo/
5079
5243
  .next/
5080
- out/
5244
+ .nitro/
5245
+ .output/
5246
+
5247
+ # Next.js static export — anchored to apps so a bare \`out/\` can't shadow a
5248
+ # bounded context's hexagonal \`src/application/ports/out/\` source (which a
5249
+ # pattern without a leading path matches at any depth).
5250
+ apps/*/out/
5081
5251
 
5082
5252
  # Test / coverage
5083
5253
  coverage/
@@ -5119,15 +5289,33 @@ adding \`--immutable\` to the \`yarn install\` step in
5119
5289
  Its pre-lockfile guidance goes stale once \`yarn.lock\` is committed. (Run
5120
5290
  \`hexagen sync\` won't bring it back — it's a protected root file.)
5121
5291
  `;
5292
+ var SEMVER_2_0_0 = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
5293
+ function assertValidToolchainVersion(version, source) {
5294
+ const invalid = !SEMVER_2_0_0.test(version) || /^0\.0\.0(?:$|[-+])/.test(version);
5295
+ if (invalid) {
5296
+ throw new Error(
5297
+ `Toolchain version unavailable, malformed, or degenerate (${source} → ${JSON.stringify(version)}). Refusing to continue: the scaffold would pin @hexagen-monaco/* devDependencies to a version that does not exist (RCA #1 — never emit a degenerate pin).`
5298
+ );
5299
+ }
5300
+ return version;
5301
+ }
5302
+ function resolveToolchainVersion() {
5303
+ {
5304
+ return assertValidToolchainVersion(
5305
+ "0.7.0",
5306
+ "build-injected __HEXAGEN_TOOLCHAIN_VERSION__"
5307
+ );
5308
+ }
5309
+ }
5122
5310
 
5123
5311
  // src/generators/root-files.ts
5124
- function buildVars(manifest) {
5312
+ function buildVars(manifest, toolchainVersion) {
5125
5313
  const system = typeof manifest.system === "string" && manifest.system.length > 0 ? manifest.system : "generated-project";
5126
5314
  const scope = resolveScope(manifest);
5127
5315
  const packageManager = typeof manifest.monorepo?.packageManager === "string" && manifest.monorepo.packageManager.length > 0 ? manifest.monorepo.packageManager : "yarn@4.12.0";
5128
5316
  const workspacesArray = Array.isArray(manifest.monorepo?.workspaces) && manifest.monorepo.workspaces.length > 0 ? manifest.monorepo.workspaces : ["apps/*", "packages/*"];
5129
5317
  const workspaces = "[\n" + workspacesArray.map((w) => ` ${JSON.stringify(w)}`).join(",\n") + "\n ]";
5130
- return { system, scope, packageManager, workspaces };
5318
+ return { system, scope, packageManager, workspaces, toolchainVersion };
5131
5319
  }
5132
5320
  function resolveTemplate(manifestTemplate, builtin) {
5133
5321
  if (typeof manifestTemplate === "string" && manifestTemplate.length > 0) {
@@ -5153,17 +5341,14 @@ async function writeRootFile(filePath, content, config, report, result) {
5153
5341
  report,
5154
5342
  true
5155
5343
  );
5156
- if (status === "created") result.created.push(filePath);
5157
- if (status === "updated") result.updated.push(filePath);
5158
- if (status === "skipped" || status === "protected")
5159
- result.skipped.push(filePath);
5160
- if (status === "created" || status === "updated") result.totalOps += 1;
5344
+ recordWriteStatus(result, filePath, status);
5161
5345
  }
5162
5346
  async function generateRootFiles(config, report) {
5163
5347
  const result = createEmptyResult();
5348
+ const toolchainVersion = resolveToolchainVersion();
5164
5349
  try {
5165
5350
  const rootFiles = config.manifest.monorepo?.rootFiles;
5166
- const vars = buildVars(config.manifest);
5351
+ const vars = buildVars(config.manifest, toolchainVersion);
5167
5352
  const packageJsonTemplate = resolveTemplate(
5168
5353
  rootFiles?.packageJson?.template,
5169
5354
  BUILTIN_PACKAGE_JSON_TEMPLATE
@@ -5175,7 +5360,7 @@ async function generateRootFiles(config, report) {
5175
5360
  "package.json"
5176
5361
  );
5177
5362
  await writeRootFile(
5178
- path28__default.join(config.workspaceRoot, "package.json"),
5363
+ path34__default.join(config.workspaceRoot, "package.json"),
5179
5364
  packageJsonContent,
5180
5365
  config,
5181
5366
  report,
@@ -5192,7 +5377,7 @@ async function generateRootFiles(config, report) {
5192
5377
  "tsconfig.base.json"
5193
5378
  );
5194
5379
  await writeRootFile(
5195
- path28__default.join(config.workspaceRoot, "tsconfig.base.json"),
5380
+ path34__default.join(config.workspaceRoot, "tsconfig.base.json"),
5196
5381
  tsconfigContent,
5197
5382
  config,
5198
5383
  report,
@@ -5209,7 +5394,7 @@ async function generateRootFiles(config, report) {
5209
5394
  "turbo.json"
5210
5395
  );
5211
5396
  await writeRootFile(
5212
- path28__default.join(config.workspaceRoot, "turbo.json"),
5397
+ path34__default.join(config.workspaceRoot, "turbo.json"),
5213
5398
  turboContent,
5214
5399
  config,
5215
5400
  report,
@@ -5220,7 +5405,7 @@ async function generateRootFiles(config, report) {
5220
5405
  BUILTIN_GITIGNORE_TEMPLATE
5221
5406
  );
5222
5407
  await writeRootFile(
5223
- path28__default.join(config.workspaceRoot, ".gitignore"),
5408
+ path34__default.join(config.workspaceRoot, ".gitignore"),
5224
5409
  interpolateAndWarn(gitignoreTemplate, vars, config, ".gitignore"),
5225
5410
  config,
5226
5411
  report,
@@ -5231,7 +5416,7 @@ async function generateRootFiles(config, report) {
5231
5416
  BUILTIN_YARNRC_TEMPLATE
5232
5417
  );
5233
5418
  await writeRootFile(
5234
- path28__default.join(config.workspaceRoot, ".yarnrc.yml"),
5419
+ path34__default.join(config.workspaceRoot, ".yarnrc.yml"),
5235
5420
  interpolateAndWarn(yarnrcTemplate, vars, config, ".yarnrc.yml"),
5236
5421
  config,
5237
5422
  report,
@@ -5242,7 +5427,7 @@ async function generateRootFiles(config, report) {
5242
5427
  BUILTIN_SETUP_MD_TEMPLATE
5243
5428
  );
5244
5429
  await writeRootFile(
5245
- path28__default.join(config.workspaceRoot, "SETUP.md"),
5430
+ path34__default.join(config.workspaceRoot, "SETUP.md"),
5246
5431
  interpolateAndWarn(setupTemplate, vars, config, "SETUP.md"),
5247
5432
  config,
5248
5433
  report,
@@ -5253,6 +5438,8 @@ async function generateRootFiles(config, report) {
5253
5438
  const message = err3 instanceof Error ? err3.message : String(err3);
5254
5439
  result.error = err3 instanceof Error ? err3 : new Error(`root-files generation failed: ${message}`);
5255
5440
  result.summary = `root-files generation failed: ${message}`;
5441
+ config.logger.error(result.summary);
5442
+ if (report) report.record("error", "root-files", result.summary);
5256
5443
  return result;
5257
5444
  }
5258
5445
  }
@@ -5468,23 +5655,21 @@ function interpolateWithLogging(label, template, vars, config) {
5468
5655
  }
5469
5656
  return output;
5470
5657
  }
5471
- function recordStatus(result, filePath, status) {
5472
- if (status === "created") result.created.push(filePath);
5473
- else if (status === "updated") result.updated.push(filePath);
5474
- else if (status === "skipped" || status === "protected")
5475
- result.skipped.push(filePath);
5476
- if (status === "created" || status === "updated") result.totalOps += 1;
5477
- }
5478
5658
  async function writeManifestIfFreshExternal(config, result, report) {
5479
5659
  if (config.mode !== "external") {
5480
5660
  return;
5481
5661
  }
5482
- const archDir = path28__default.join(config.workspaceRoot, ".architecture");
5483
- const manifestPath = path28__default.join(archDir, "manifest.yaml");
5484
- const relative = path28__default.relative(config.workspaceRoot, manifestPath);
5662
+ const archDir = path34__default.join(config.workspaceRoot, ".architecture");
5663
+ const manifestPath = path34__default.join(archDir, "manifest.yaml");
5664
+ const relative = path34__default.relative(config.workspaceRoot, manifestPath);
5665
+ if (!isInScope(manifestPath, config)) {
5666
+ config.logger.debug(`skipped (outside --only) ${relative}`);
5667
+ result.skipped.push(manifestPath);
5668
+ return;
5669
+ }
5485
5670
  let exists = false;
5486
5671
  try {
5487
- await fs22.access(manifestPath);
5672
+ await fs27.access(manifestPath);
5488
5673
  exists = true;
5489
5674
  } catch {
5490
5675
  exists = false;
@@ -5503,8 +5688,9 @@ async function writeManifestIfFreshExternal(config, result, report) {
5503
5688
  return;
5504
5689
  }
5505
5690
  const content = yaml9.dump(config.manifest);
5506
- await fs22.mkdir(archDir, { recursive: true });
5507
- await fs22.writeFile(manifestPath, content, { encoding: "utf8" });
5691
+ config.journal?.recordWrite(manifestPath, null);
5692
+ await fs27.mkdir(archDir, { recursive: true });
5693
+ await fs27.writeFile(manifestPath, content, { encoding: "utf8" });
5508
5694
  config.logger.info(`created ${relative}`);
5509
5695
  if (report)
5510
5696
  report.record(
@@ -5518,12 +5704,12 @@ async function writeManifestIfFreshExternal(config, result, report) {
5518
5704
  async function generateArchitectureFiles(config, report) {
5519
5705
  const result = createEmptyResult();
5520
5706
  const manifest = config.manifest;
5521
- const archRoot = path28__default.join(config.workspaceRoot, ".architecture");
5707
+ const archRoot = path34__default.join(config.workspaceRoot, ".architecture");
5522
5708
  const archInvariants = manifest.monorepo?.archInvariants;
5523
5709
  const vars = buildInterpolationVars(manifest);
5524
5710
  const workspaceTemplate = vars.workspaceTemplate ?? "modular-monolith";
5525
5711
  await writeManifestIfFreshExternal(config, result, report);
5526
- const layerRulesPath = path28__default.join(archRoot, "invariants", "layer-rules.yaml");
5712
+ const layerRulesPath = path34__default.join(archRoot, "invariants", "layer-rules.yaml");
5527
5713
  const layerRulesTemplate = resolveTemplate2(
5528
5714
  archInvariants?.layerRules,
5529
5715
  builtInLayerRules(workspaceTemplate)
@@ -5541,8 +5727,8 @@ async function generateArchitectureFiles(config, report) {
5541
5727
  report,
5542
5728
  true
5543
5729
  );
5544
- recordStatus(result, layerRulesPath, layerRulesStatus);
5545
- const linterConfigPath = path28__default.join(
5730
+ recordWriteStatus(result, layerRulesPath, layerRulesStatus);
5731
+ const linterConfigPath = path34__default.join(
5546
5732
  archRoot,
5547
5733
  "invariants",
5548
5734
  "linter-config.yaml"
@@ -5564,8 +5750,8 @@ async function generateArchitectureFiles(config, report) {
5564
5750
  report,
5565
5751
  true
5566
5752
  );
5567
- recordStatus(result, linterConfigPath, linterConfigStatus);
5568
- const generatorConfigPath = path28__default.join(archRoot, "generator.config.yaml");
5753
+ recordWriteStatus(result, linterConfigPath, linterConfigStatus);
5754
+ const generatorConfigPath = path34__default.join(archRoot, "generator.config.yaml");
5569
5755
  const generatorConfigTemplate = resolveTemplate2(
5570
5756
  archInvariants?.generatorConfig,
5571
5757
  GENERATOR_CONFIG_TEMPLATE
@@ -5583,7 +5769,7 @@ async function generateArchitectureFiles(config, report) {
5583
5769
  report,
5584
5770
  true
5585
5771
  );
5586
- recordStatus(result, generatorConfigPath, generatorConfigStatus);
5772
+ recordWriteStatus(result, generatorConfigPath, generatorConfigStatus);
5587
5773
  return result;
5588
5774
  }
5589
5775
 
@@ -5687,7 +5873,6 @@ var PLAIN_TS_PACKAGE_JSON_TEMPLATE = `{
5687
5873
  "lint": "eslint src --ext .ts,.tsx",
5688
5874
  "typecheck": "tsc --noEmit"
5689
5875
  },
5690
- "dependencies": {},
5691
5876
  "devDependencies": {
5692
5877
  "typescript": "^5.5.4",
5693
5878
  "eslint": "^9.0.0",
@@ -5713,6 +5898,50 @@ export function main(): void {
5713
5898
  // Application bootstrap for {appName}
5714
5899
  }
5715
5900
  `;
5901
+ var NITRO_PACKAGE_JSON_TEMPLATE = `{
5902
+ "name": "@{scope}/{appName}",
5903
+ "version": "0.0.0",
5904
+ "private": true,
5905
+ "type": "module",
5906
+ "scripts": {
5907
+ "build": "nitro build",
5908
+ "dev": "nitro dev",
5909
+ "preview": "node .output/server/index.mjs",
5910
+ "prepare": "nitro prepare",
5911
+ "lint": "eslint server --ext .ts",
5912
+ "typecheck": "nitro prepare && tsc --noEmit"
5913
+ },
5914
+ "dependencies": {
5915
+ "nitropack": "^2.13.0"
5916
+ },
5917
+ "devDependencies": {
5918
+ "typescript": "^5.5.4",
5919
+ "eslint": "^9.0.0",
5920
+ "@typescript-eslint/parser": "^8.0.0",
5921
+ "@typescript-eslint/eslint-plugin": "^8.0.0"
5922
+ }
5923
+ }
5924
+ `;
5925
+ var NITRO_TSCONFIG = {
5926
+ extends: "./.nitro/types/tsconfig.json",
5927
+ compilerOptions: {
5928
+ moduleResolution: "bundler",
5929
+ strict: true,
5930
+ skipLibCheck: true
5931
+ }
5932
+ };
5933
+ var NITRO_CONFIG_TEMPLATE = `import { defineNitroConfig } from "nitropack/config";
5934
+
5935
+ // https://nitro.build/config
5936
+ export default defineNitroConfig({
5937
+ srcDir: "server",
5938
+ compatibilityDate: "2025-01-01",
5939
+ });
5940
+ `;
5941
+ var NITRO_ROUTE_TEMPLATE = `// Auto-generated Nitro route — GET /
5942
+ // \`defineEventHandler\` is auto-imported by Nitro (see ./.nitro/types).
5943
+ export default defineEventHandler(() => ({ status: "ok", app: "{appName}" }));
5944
+ `;
5716
5945
  var BUILTIN_FRAMEWORK_TEMPLATES = {
5717
5946
  "next.js": {
5718
5947
  packageJson: { template: NEXTJS_PACKAGE_JSON_TEMPLATE },
@@ -5737,8 +5966,103 @@ var BUILTIN_FRAMEWORK_TEMPLATES = {
5737
5966
  path: "src/index.ts",
5738
5967
  template: PLAIN_TS_ENTRY_TEMPLATE
5739
5968
  }
5969
+ },
5970
+ nitro: {
5971
+ packageJson: { template: NITRO_PACKAGE_JSON_TEMPLATE },
5972
+ tsConfig: NITRO_TSCONFIG,
5973
+ entryPoint: {
5974
+ path: "server/routes/index.ts",
5975
+ template: NITRO_ROUTE_TEMPLATE
5976
+ },
5977
+ extraFiles: [{ path: "nitro.config.ts", template: NITRO_CONFIG_TEMPLATE }]
5740
5978
  }
5741
5979
  };
5980
+ var GENERATED_MARKER_LINE = "// @generated by @hexagen/sync";
5981
+ var BUILTIN_FALLBACK_TEMPLATE2 = `import eslint from '@eslint/js';
5982
+ import tseslint from 'typescript-eslint';
5983
+
5984
+ export default tseslint.config(
5985
+ eslint.configs.recommended,
5986
+ ...tseslint.configs.recommended,
5987
+ {
5988
+ rules: {
5989
+ '@typescript-eslint/no-explicit-any': 'warn',
5990
+ '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
5991
+ },
5992
+ },
5993
+ {
5994
+ ignores: ['dist/**', 'node_modules/**'],
5995
+ },
5996
+ );
5997
+ `;
5998
+ function resolveTemplate3(manifest, moduleName, usePerContextOverride) {
5999
+ const contextOverride = usePerContextOverride ? manifest.bounded_contexts?.find((c) => c.name === moduleName)?.generator?.eslint : void 0;
6000
+ if (contextOverride?.template !== void 0) {
6001
+ return { template: contextOverride.template, source: "per-context" };
6002
+ }
6003
+ const rootLevel = manifest.workspaceDefaults?.eslint;
6004
+ if (rootLevel?.template !== void 0) {
6005
+ return { template: rootLevel.template, source: "workspace" };
6006
+ }
6007
+ const monorepoLevel = manifest.monorepo?.workspaceDefaults?.eslint;
6008
+ if (monorepoLevel?.template !== void 0) {
6009
+ return { template: monorepoLevel.template, source: "workspace" };
6010
+ }
6011
+ return { template: BUILTIN_FALLBACK_TEMPLATE2, source: "fallback" };
6012
+ }
6013
+ function withGeneratedMarker(content) {
6014
+ if (content.startsWith(GENERATED_MARKER_LINE)) {
6015
+ return content;
6016
+ }
6017
+ return `${GENERATED_MARKER_LINE}
6018
+ ${content}`;
6019
+ }
6020
+ async function generateEslintConfig(moduleDir, moduleName, config, report, options = {}) {
6021
+ const result = createEmptyResult();
6022
+ const filePath = path34__default.join(moduleDir, "eslint.config.js");
6023
+ try {
6024
+ const { template, source } = resolveTemplate3(
6025
+ config.manifest,
6026
+ moduleName,
6027
+ options.usePerContextOverride ?? true
6028
+ );
6029
+ if (typeof template !== "string" || template.length === 0) {
6030
+ const message = `No eslint template resolved for ${moduleName} (source: ${source}); skipping`;
6031
+ config.logger.error(message);
6032
+ if (report) report.record("error", filePath, message);
6033
+ result.skipped.push(filePath);
6034
+ result.summary = message;
6035
+ return result;
6036
+ }
6037
+ const scope = resolveScope(config.manifest);
6038
+ const { output: interpolated, warnings } = interpolate(template, {
6039
+ packageName: moduleName,
6040
+ scope
6041
+ });
6042
+ for (const missingVar of warnings) {
6043
+ const message = `Missing interpolation variable "${missingVar}" in eslint template for ${moduleName} (source: ${source}); placeholder left verbatim`;
6044
+ config.logger.warn(message);
6045
+ if (report) report.record("warning", filePath, message);
6046
+ }
6047
+ const content = withGeneratedMarker(interpolated);
6048
+ const status = await safeWriteFileAtomic(
6049
+ filePath,
6050
+ content,
6051
+ config,
6052
+ report,
6053
+ false
6054
+ );
6055
+ recordWriteStatus(result, filePath, status);
6056
+ return result;
6057
+ } catch (err3) {
6058
+ const message = err3 instanceof Error ? err3.message : String(err3);
6059
+ result.error = err3 instanceof Error ? err3 : new Error(`eslint generation failed for ${moduleName}: ${message}`);
6060
+ result.summary = `eslint generation failed for ${moduleName}: ${message}`;
6061
+ config.logger.error(result.summary);
6062
+ if (report) report.record("error", filePath, result.summary);
6063
+ return result;
6064
+ }
6065
+ }
5742
6066
 
5743
6067
  // src/generators/apps.ts
5744
6068
  function resolveFrameworkConfig(framework, manifestConfig) {
@@ -5749,7 +6073,8 @@ function resolveFrameworkConfig(framework, manifestConfig) {
5749
6073
  return {
5750
6074
  packageJson: manifestConfig.packageJson ?? builtin.packageJson,
5751
6075
  tsConfig: manifestConfig.tsConfig ?? builtin.tsConfig,
5752
- entryPoint: manifestConfig.entryPoint ?? builtin.entryPoint
6076
+ entryPoint: manifestConfig.entryPoint ?? builtin.entryPoint,
6077
+ extraFiles: manifestConfig.extraFiles ?? builtin.extraFiles
5753
6078
  };
5754
6079
  }
5755
6080
  function interpolateWithLogging2(template, vars, context, config) {
@@ -5762,16 +6087,58 @@ function interpolateWithLogging2(template, vars, context, config) {
5762
6087
  }
5763
6088
  return output;
5764
6089
  }
5765
- function recordStatus2(result, filePath, status) {
5766
- if (status === "created") {
5767
- result.created.push(filePath);
5768
- result.totalOps += 1;
5769
- } else if (status === "updated") {
5770
- result.updated.push(filePath);
5771
- result.totalOps += 1;
5772
- } else {
5773
- result.skipped.push(filePath);
6090
+ function mergeResult(result, sub) {
6091
+ result.created.push(...sub.created);
6092
+ result.updated.push(...sub.updated);
6093
+ result.skipped.push(...sub.skipped);
6094
+ result.deleted.push(...sub.deleted);
6095
+ result.unchanged.push(...sub.unchanged);
6096
+ result.totalOps += sub.totalOps;
6097
+ if (sub.error && !result.error) {
6098
+ result.error = sub.error;
6099
+ result.summary = sub.summary;
6100
+ }
6101
+ }
6102
+ async function emitAppFile(appDir, relPath, template, vars, config, report, result, appName) {
6103
+ const content = interpolateWithLogging2(
6104
+ template,
6105
+ vars,
6106
+ `apps/${appName}/${relPath}`,
6107
+ config
6108
+ );
6109
+ const target = path34__default.resolve(appDir, relPath);
6110
+ const relative = path34__default.relative(appDir, target);
6111
+ if (relative === "" || relative.startsWith("..") || path34__default.isAbsolute(relative)) {
6112
+ config.logger.warn(
6113
+ `[apps] skipping file with unsafe path (escapes apps/${appName}): ${relPath}`
6114
+ );
6115
+ if (report) {
6116
+ report.record(
6117
+ "blocked",
6118
+ appName,
6119
+ `Unsafe file path (potential path traversal): ${relPath}`
6120
+ );
6121
+ }
6122
+ return "unsafe";
5774
6123
  }
6124
+ if (!config.dryRun && isInScope(target, config)) {
6125
+ try {
6126
+ await fs27.mkdir(path34__default.dirname(target), { recursive: true });
6127
+ } catch (err3) {
6128
+ const message = err3 instanceof Error ? err3.message : String(err3);
6129
+ config.logger.error(
6130
+ `[apps] failed to create dir for "${appName}" file ${relPath}: ${message}`
6131
+ );
6132
+ if (report) report.record("blocked", appName, message);
6133
+ return "error";
6134
+ }
6135
+ }
6136
+ recordWriteStatus(
6137
+ result,
6138
+ target,
6139
+ await safeWriteFileAtomic(target, content, config, report)
6140
+ );
6141
+ return "ok";
5775
6142
  }
5776
6143
  async function generateApps(config, report) {
5777
6144
  const result = createEmptyResult();
@@ -5792,6 +6159,19 @@ async function generateApps(config, report) {
5792
6159
  config.logger.warn(`[apps] skipping entry with missing or empty name`);
5793
6160
  continue;
5794
6161
  }
6162
+ if (app.name.includes("..") || app.name.includes("/") || app.name.includes("\\") || app.name.startsWith(".")) {
6163
+ config.logger.warn(
6164
+ `[apps] skipping app with unsafe name (potential path traversal): ${app.name}`
6165
+ );
6166
+ if (report) {
6167
+ report.record(
6168
+ "blocked",
6169
+ app.name,
6170
+ "Unsafe app name (potential path traversal)"
6171
+ );
6172
+ }
6173
+ continue;
6174
+ }
5795
6175
  if (seen.has(app.name)) {
5796
6176
  config.logger.warn(
5797
6177
  `[apps] duplicate app name "${app.name}" — keeping first occurrence, skipping this duplicate`
@@ -5834,18 +6214,20 @@ async function generateApps(config, report) {
5834
6214
  version: app.version ?? "",
5835
6215
  depends_on: (app.depends_on ?? []).join(", ")
5836
6216
  };
5837
- const appDir = path28__default.join(config.workspaceRoot, "apps", app.name);
5838
- const srcDir = path28__default.join(appDir, "src");
5839
- try {
5840
- await fs22.mkdir(appDir, { recursive: true });
5841
- await fs22.mkdir(srcDir, { recursive: true });
5842
- } catch (err3) {
5843
- const message = err3 instanceof Error ? err3.message : String(err3);
5844
- config.logger.error(
5845
- `[apps] failed to create directory for "${app.name}": ${message}`
5846
- );
5847
- if (report) report.record("blocked", app.name, message);
5848
- continue;
6217
+ const appDir = path34__default.join(config.workspaceRoot, "apps", app.name);
6218
+ const srcDir = path34__default.join(appDir, "src");
6219
+ if (!config.dryRun && isInScope(appDir, config)) {
6220
+ try {
6221
+ await fs27.mkdir(appDir, { recursive: true });
6222
+ await fs27.mkdir(srcDir, { recursive: true });
6223
+ } catch (err3) {
6224
+ const message = err3 instanceof Error ? err3.message : String(err3);
6225
+ config.logger.error(
6226
+ `[apps] failed to create directory for "${app.name}": ${message}`
6227
+ );
6228
+ if (report) report.record("blocked", app.name, message);
6229
+ continue;
6230
+ }
5849
6231
  }
5850
6232
  const pkgTemplate = frameworkConfig.packageJson?.template;
5851
6233
  if (pkgTemplate) {
@@ -5855,14 +6237,14 @@ async function generateApps(config, report) {
5855
6237
  `apps/${app.name}/package.json`,
5856
6238
  config
5857
6239
  );
5858
- const pkgPath = path28__default.join(appDir, "package.json");
6240
+ const pkgPath = path34__default.join(appDir, "package.json");
5859
6241
  const status = await safeWriteFileAtomic(
5860
6242
  pkgPath,
5861
6243
  pkgContent,
5862
6244
  config,
5863
6245
  report
5864
6246
  );
5865
- recordStatus2(result, pkgPath, status);
6247
+ recordWriteStatus(result, pkgPath, status);
5866
6248
  } else {
5867
6249
  config.logger.warn(
5868
6250
  `[apps] framework "${framework}" has no package.json template — skipping package.json for "${app.name}"`
@@ -5871,146 +6253,136 @@ async function generateApps(config, report) {
5871
6253
  const tsConfig = frameworkConfig.tsConfig;
5872
6254
  if (tsConfig) {
5873
6255
  const tsContent = JSON.stringify(tsConfig, null, 2) + "\n";
5874
- const tsPath = path28__default.join(appDir, "tsconfig.json");
6256
+ const tsPath = path34__default.join(appDir, "tsconfig.json");
5875
6257
  const status = await safeWriteFileAtomic(
5876
6258
  tsPath,
5877
6259
  tsContent,
5878
6260
  config,
5879
6261
  report
5880
6262
  );
5881
- recordStatus2(result, tsPath, status);
6263
+ recordWriteStatus(result, tsPath, status);
5882
6264
  } else {
5883
6265
  config.logger.warn(
5884
6266
  `[apps] framework "${framework}" has no tsConfig — skipping tsconfig.json for "${app.name}"`
5885
6267
  );
5886
6268
  }
5887
- const entry = frameworkConfig.entryPoint;
5888
- if (entry?.path && entry.template !== void 0) {
5889
- const entryContent = interpolateWithLogging2(
5890
- entry.template,
5891
- vars,
5892
- `apps/${app.name}/${entry.path}`,
5893
- config
5894
- );
5895
- const entryPath = path28__default.join(appDir, entry.path);
5896
- try {
5897
- await fs22.mkdir(path28__default.dirname(entryPath), { recursive: true });
5898
- } catch (err3) {
5899
- const message = err3 instanceof Error ? err3.message : String(err3);
5900
- config.logger.error(
5901
- `[apps] failed to create entry-point dir for "${app.name}": ${message}`
5902
- );
5903
- if (report) report.record("blocked", app.name, message);
5904
- continue;
5905
- }
5906
- const status = await safeWriteFileAtomic(
5907
- entryPath,
5908
- entryContent,
5909
- config,
5910
- report
5911
- );
5912
- recordStatus2(result, entryPath, status);
5913
- } else {
5914
- config.logger.warn(
5915
- `[apps] framework "${framework}" has no entryPoint template — skipping entry file for "${app.name}"`
5916
- );
5917
- }
5918
- }
5919
- result.summary = `apps: ${result.created.length} created, ${result.updated.length} updated, ${result.skipped.length} skipped`;
5920
- return result;
5921
- } catch (err3) {
5922
- const message = err3 instanceof Error ? err3.message : String(err3);
5923
- result.error = err3 instanceof Error ? err3 : new Error(`apps generation failed: ${message}`);
5924
- result.summary = `apps generation failed: ${message}`;
5925
- return result;
5926
- }
5927
- }
5928
- var GENERATED_MARKER_LINE = "// @generated by @hexagen/sync";
5929
- var BUILTIN_FALLBACK_TEMPLATE2 = `import eslint from '@eslint/js';
5930
- import tseslint from 'typescript-eslint';
5931
-
5932
- export default tseslint.config(
5933
- eslint.configs.recommended,
5934
- ...tseslint.configs.recommended,
5935
- {
5936
- rules: {
5937
- '@typescript-eslint/no-explicit-any': 'warn',
5938
- '@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
5939
- },
5940
- },
5941
- {
5942
- ignores: ['dist/**', 'node_modules/**'],
5943
- },
5944
- );
5945
- `;
5946
- function resolveTemplate3(manifest, moduleName) {
5947
- const contextOverride = manifest.bounded_contexts?.find((c) => c.name === moduleName)?.generator?.eslint;
5948
- if (contextOverride?.template !== void 0) {
5949
- return { template: contextOverride.template, source: "per-context" };
5950
- }
5951
- const rootLevel = manifest.workspaceDefaults?.eslint;
5952
- if (rootLevel?.template !== void 0) {
5953
- return { template: rootLevel.template, source: "workspace" };
5954
- }
5955
- const monorepoLevel = manifest.monorepo?.workspaceDefaults?.eslint;
5956
- if (monorepoLevel?.template !== void 0) {
5957
- return { template: monorepoLevel.template, source: "workspace" };
5958
- }
5959
- return { template: BUILTIN_FALLBACK_TEMPLATE2, source: "fallback" };
5960
- }
5961
- function withGeneratedMarker(content) {
5962
- if (content.startsWith(GENERATED_MARKER_LINE)) {
5963
- return content;
5964
- }
5965
- return `${GENERATED_MARKER_LINE}
5966
- ${content}`;
5967
- }
5968
- async function generateEslintConfig(moduleDir, moduleName, config, report) {
5969
- const result = createEmptyResult();
5970
- const filePath = path28__default.join(moduleDir, "eslint.config.js");
5971
- try {
5972
- const { template, source } = resolveTemplate3(config.manifest, moduleName);
5973
- if (typeof template !== "string" || template.length === 0) {
5974
- const message = `No eslint template resolved for ${moduleName} (source: ${source}); skipping`;
5975
- config.logger.error(message);
5976
- if (report) report.record("error", filePath, message);
5977
- result.skipped.push(filePath);
5978
- result.summary = message;
5979
- return result;
6269
+ const entry = frameworkConfig.entryPoint;
6270
+ if (entry?.path && entry.template !== void 0) {
6271
+ const status = await emitAppFile(
6272
+ appDir,
6273
+ entry.path,
6274
+ entry.template,
6275
+ vars,
6276
+ config,
6277
+ report,
6278
+ result,
6279
+ app.name
6280
+ );
6281
+ if (status !== "ok") continue;
6282
+ } else {
6283
+ config.logger.warn(
6284
+ `[apps] framework "${framework}" has no entryPoint template — skipping entry file for "${app.name}"`
6285
+ );
6286
+ }
6287
+ for (const extra of frameworkConfig.extraFiles ?? []) {
6288
+ if (!extra?.path || extra.template === void 0) continue;
6289
+ await emitAppFile(
6290
+ appDir,
6291
+ extra.path,
6292
+ extra.template,
6293
+ vars,
6294
+ config,
6295
+ report,
6296
+ result,
6297
+ app.name
6298
+ );
6299
+ }
6300
+ const eslintResult = await generateEslintConfig(
6301
+ appDir,
6302
+ app.name,
6303
+ config,
6304
+ report,
6305
+ { usePerContextOverride: false }
6306
+ );
6307
+ mergeResult(result, eslintResult);
5980
6308
  }
5981
- const scope = resolveScope(config.manifest);
5982
- const { output: interpolated, warnings } = interpolate(template, {
5983
- packageName: moduleName,
5984
- scope
5985
- });
5986
- for (const missingVar of warnings) {
5987
- const message = `Missing interpolation variable "${missingVar}" in eslint template for ${moduleName} (source: ${source}); placeholder left verbatim`;
5988
- config.logger.warn(message);
5989
- if (report) report.record("warning", filePath, message);
6309
+ if (!result.error) {
6310
+ result.summary = `apps: ${result.created.length} created, ${result.updated.length} updated, ${result.skipped.length} skipped`;
5990
6311
  }
5991
- const content = withGeneratedMarker(interpolated);
5992
- const status = await safeWriteFileAtomic(
5993
- filePath,
5994
- content,
5995
- config,
5996
- report,
5997
- false
5998
- );
5999
- if (status === "created") result.created.push(filePath);
6000
- if (status === "updated") result.updated.push(filePath);
6001
- if (status === "skipped" || status === "protected")
6002
- result.skipped.push(filePath);
6003
- result.totalOps += status === "created" || status === "updated" ? 1 : 0;
6004
6312
  return result;
6005
6313
  } catch (err3) {
6006
6314
  const message = err3 instanceof Error ? err3.message : String(err3);
6007
- result.error = err3 instanceof Error ? err3 : new Error(`eslint generation failed for ${moduleName}: ${message}`);
6008
- result.summary = `eslint generation failed for ${moduleName}: ${message}`;
6315
+ result.error = err3 instanceof Error ? err3 : new Error(`apps generation failed: ${message}`);
6316
+ result.summary = `apps generation failed: ${message}`;
6009
6317
  config.logger.error(result.summary);
6010
- if (report) report.record("error", filePath, result.summary);
6318
+ if (report) report.record("error", "apps", result.summary);
6011
6319
  return result;
6012
6320
  }
6013
6321
  }
6322
+ function relativeImportSpecifier(fromFile, toFile) {
6323
+ let rel = path34__default.relative(path34__default.dirname(fromFile), toFile).split(path34__default.sep).join("/").replace(/\.tsx?$/, ".js");
6324
+ if (!rel.startsWith(".")) rel = `./${rel}`;
6325
+ return rel;
6326
+ }
6327
+ function rewriteRelativeSpecifier(specifier, fromFile, toFile) {
6328
+ if (!specifier.startsWith(".")) return specifier;
6329
+ const absolute = path34__default.resolve(path34__default.dirname(fromFile), specifier);
6330
+ let rel = path34__default.relative(path34__default.dirname(toFile), absolute).split(path34__default.sep).join("/");
6331
+ if (!rel.startsWith(".")) rel = `./${rel}`;
6332
+ return rel;
6333
+ }
6334
+ var RESERVED_IDENTIFIERS = /* @__PURE__ */ new Set([
6335
+ "break",
6336
+ "case",
6337
+ "catch",
6338
+ "class",
6339
+ "const",
6340
+ "continue",
6341
+ "debugger",
6342
+ "default",
6343
+ "delete",
6344
+ "do",
6345
+ "else",
6346
+ "enum",
6347
+ "export",
6348
+ "extends",
6349
+ "false",
6350
+ "finally",
6351
+ "for",
6352
+ "function",
6353
+ "if",
6354
+ "import",
6355
+ "in",
6356
+ "instanceof",
6357
+ "new",
6358
+ "null",
6359
+ "return",
6360
+ "super",
6361
+ "switch",
6362
+ "this",
6363
+ "throw",
6364
+ "true",
6365
+ "try",
6366
+ "typeof",
6367
+ "var",
6368
+ "void",
6369
+ "while",
6370
+ "with",
6371
+ "yield",
6372
+ "let",
6373
+ "static",
6374
+ "implements",
6375
+ "interface",
6376
+ "package",
6377
+ "private",
6378
+ "protected",
6379
+ "public",
6380
+ "await"
6381
+ ]);
6382
+ function safeParamName(name) {
6383
+ const candidate = name.length === 0 ? "dep" : name;
6384
+ return RESERVED_IDENTIFIERS.has(candidate) ? `${candidate}_` : candidate;
6385
+ }
6014
6386
  function analyzePortFile(portFilePath) {
6015
6387
  try {
6016
6388
  const project = new Project({
@@ -6086,13 +6458,22 @@ function extractImports(importDecls) {
6086
6458
  }
6087
6459
  return imports;
6088
6460
  }
6089
- function generateAdapterFromPort(analysis, adapterName) {
6461
+ function generateAdapterFromPort(analysis, adapterName, portImportSpecifier, outputFilePath) {
6090
6462
  const { interfaceName, methods, imports } = analysis;
6091
- const importStatements = imports.map((imp) => {
6092
- const typeOnly = imp.isTypeOnly ? "type " : "";
6093
- const names = imp.namedImports.join(", ");
6094
- return `import ${typeOnly}{ ${names} } from '${imp.moduleSpecifier}';`;
6095
- }).join("\n");
6463
+ const portImport = portImportSpecifier ? `import type { ${interfaceName} } from '${portImportSpecifier}';` : "";
6464
+ const importStatements = [
6465
+ portImport,
6466
+ ...imports.map((imp) => {
6467
+ const specifier = outputFilePath ? rewriteRelativeSpecifier(
6468
+ imp.moduleSpecifier,
6469
+ analysis.filePath,
6470
+ outputFilePath
6471
+ ) : imp.moduleSpecifier;
6472
+ const typeOnly = imp.isTypeOnly ? "type " : "";
6473
+ const names = imp.namedImports.join(", ");
6474
+ return `import ${typeOnly}{ ${names} } from '${specifier}';`;
6475
+ })
6476
+ ].filter(Boolean).join("\n");
6096
6477
  const methodImpls = methods.map((method) => {
6097
6478
  const params = method.parameters.map((p) => `${p.name}${p.isOptional ? "?" : ""}: ${p.type}`).join(", ");
6098
6479
  const asyncKeyword = method.isAsync ? "async " : "";
@@ -6120,16 +6501,48 @@ ${methodImpls}
6120
6501
  }
6121
6502
  `;
6122
6503
  }
6123
- function generateUseCaseFromPort(analysis, useCaseName, outPorts) {
6504
+ function generateUseCaseFromPort(analysis, useCaseName, outPorts, portImportSpecifier, outputFilePath) {
6124
6505
  const { interfaceName, methods, imports } = analysis;
6125
- const importStatements = imports.map((imp) => {
6506
+ const importLines = [];
6507
+ const taken = /* @__PURE__ */ new Set();
6508
+ const importType = (name, specifier) => {
6509
+ let local = name;
6510
+ let n = 2;
6511
+ while (taken.has(local)) local = `${name}_${n++}`;
6512
+ taken.add(local);
6513
+ importLines.push(
6514
+ local === name ? `import type { ${name} } from '${specifier}';` : `import type { ${name} as ${local} } from '${specifier}';`
6515
+ );
6516
+ return local;
6517
+ };
6518
+ const implementsName = portImportSpecifier ? importType(interfaceName, portImportSpecifier) : interfaceName;
6519
+ const seenDeps = /* @__PURE__ */ new Map();
6520
+ const usedParams = /* @__PURE__ */ new Set();
6521
+ const constructorEntries = [];
6522
+ for (const p of outPorts) {
6523
+ const depKey = `${p.interfaceName}|${p.importSpecifier}`;
6524
+ if (seenDeps.has(depKey)) continue;
6525
+ const localType = importType(p.interfaceName, p.importSpecifier);
6526
+ seenDeps.set(depKey, localType);
6527
+ let param = safeParamName(p.paramName);
6528
+ const paramBase = param;
6529
+ let n = 2;
6530
+ while (usedParams.has(param)) param = `${paramBase}${n++}`;
6531
+ usedParams.add(param);
6532
+ constructorEntries.push(`private readonly ${param}: ${localType}`);
6533
+ }
6534
+ for (const imp of imports) {
6535
+ const specifier = outputFilePath ? rewriteRelativeSpecifier(
6536
+ imp.moduleSpecifier,
6537
+ analysis.filePath,
6538
+ outputFilePath
6539
+ ) : imp.moduleSpecifier;
6126
6540
  const typeOnly = imp.isTypeOnly ? "type " : "";
6127
- const names = imp.namedImports.join(", ");
6128
- return `import ${typeOnly}{ ${names} } from '${imp.moduleSpecifier}';`;
6129
- }).join("\n");
6130
- const constructorParams = outPorts.map(
6131
- (port) => `private readonly ${port.charAt(0).toLowerCase() + port.slice(1)}: ${port}`
6132
- ).join(",\n ");
6541
+ const line = `import ${typeOnly}{ ${imp.namedImports.join(", ")} } from '${specifier}';`;
6542
+ if (!importLines.includes(line)) importLines.push(line);
6543
+ }
6544
+ const importStatements = importLines.join("\n");
6545
+ const constructorParams = constructorEntries.join(",\n ");
6133
6546
  const methodImpls = methods.map((method) => {
6134
6547
  const params = method.parameters.map((p) => `${p.name}${p.isOptional ? "?" : ""}: ${p.type}`).join(", ");
6135
6548
  const asyncKeyword = method.isAsync ? "async " : "";
@@ -6142,12 +6555,12 @@ function generateUseCaseFromPort(analysis, useCaseName, outPorts) {
6142
6555
  throw new Error('Not implemented: ${method.name}');
6143
6556
  }`;
6144
6557
  }).join("\n\n");
6145
- const constructorBlock = outPorts.length > 0 ? ` constructor(
6558
+ const constructorBlock = constructorEntries.length > 0 ? ` constructor(
6146
6559
  ${constructorParams}
6147
6560
  ) {}` : "";
6148
6561
  return `// @generated use-case stub — edit freely
6149
6562
  /**
6150
- * ${useCaseName} implements ${interfaceName}
6563
+ * ${useCaseName} implements ${implementsName}
6151
6564
  *
6152
6565
  * This use case was generated from the port interface.
6153
6566
  * Replace TODO implementations with actual business logic.
@@ -6155,7 +6568,7 @@ function generateUseCaseFromPort(analysis, useCaseName, outPorts) {
6155
6568
 
6156
6569
  ${importStatements}
6157
6570
 
6158
- export class ${useCaseName} implements ${interfaceName} {
6571
+ export class ${useCaseName} implements ${implementsName} {
6159
6572
  ${constructorBlock}
6160
6573
 
6161
6574
  ${methodImpls}
@@ -6548,9 +6961,15 @@ function resolveNaming(kind, contextNaming, manifestNaming) {
6548
6961
  return contextNaming?.[kind] ?? manifestNaming?.[kind] ?? DEFAULT_NAMING[kind];
6549
6962
  }
6550
6963
  async function writeStubFile(filePath, content, config, report) {
6964
+ if (!isInScope(filePath, config)) {
6965
+ config.logger.debug(
6966
+ `skipped (outside --only) ${path34__default.relative(config.workspaceRoot, filePath)}`
6967
+ );
6968
+ return "skipped";
6969
+ }
6551
6970
  try {
6552
- await fs22.stat(filePath);
6553
- const relative = path28__default.relative(config.workspaceRoot, filePath);
6971
+ await fs27.stat(filePath);
6972
+ const relative = path34__default.relative(config.workspaceRoot, filePath);
6554
6973
  config.logger.debug(`stub preserved ${relative}`);
6555
6974
  if (report) {
6556
6975
  report.record(
@@ -6565,15 +6984,19 @@ async function writeStubFile(filePath, content, config, report) {
6565
6984
  throw err3;
6566
6985
  }
6567
6986
  }
6568
- await fs22.mkdir(path28__default.dirname(filePath), { recursive: true });
6987
+ if (!config.dryRun) {
6988
+ await fs27.mkdir(path34__default.dirname(filePath), { recursive: true });
6989
+ }
6569
6990
  return safeWriteFileAtomic(filePath, content, config, report, false);
6570
6991
  }
6571
- async function tryAnalyzeRelatedPort(moduleDir, name, kind, context) {
6992
+ async function tryAnalyzeRelatedPort(moduleDir, name, kind, context, relatedPortNamingTemplate) {
6572
6993
  const portType = kind === "adapter" ? "out" : "in";
6573
6994
  const portSubdir = `application/ports/${portType}`;
6574
6995
  const derivedPortName = name.replace(/Adapter$|UseCase$/, "Port");
6575
6996
  const declaredPorts = portType === "in" ? context.layers?.application?.ports?.in || [] : context.layers?.application?.ports?.out || [];
6576
- if (!declaredPorts.some((p) => portName(p) === derivedPortName)) {
6997
+ if (!declaredPorts.some(
6998
+ (p) => normalizeStubName(portName(p), relatedPortNamingTemplate) === derivedPortName
6999
+ )) {
6577
7000
  return null;
6578
7001
  }
6579
7002
  const possibleFilenames = [
@@ -6582,7 +7005,7 @@ async function tryAnalyzeRelatedPort(moduleDir, name, kind, context) {
6582
7005
  `${derivedPortName}.ts`
6583
7006
  ];
6584
7007
  for (const filename of possibleFilenames) {
6585
- const portFilePath = path28__default.join(moduleDir, "src", portSubdir, filename);
7008
+ const portFilePath = path34__default.join(moduleDir, "src", portSubdir, filename);
6586
7009
  const analysis = analyzePortFile(portFilePath);
6587
7010
  if (analysis) {
6588
7011
  return analysis;
@@ -6590,6 +7013,15 @@ async function tryAnalyzeRelatedPort(moduleDir, name, kind, context) {
6590
7013
  }
6591
7014
  return null;
6592
7015
  }
7016
+ function normalizeStubName(rawName, namingTemplate) {
7017
+ const placeholder = "{name}";
7018
+ const idx = namingTemplate.lastIndexOf(placeholder);
7019
+ const ext = idx >= 0 ? namingTemplate.slice(idx + placeholder.length) : "";
7020
+ const base = ext && rawName.endsWith(ext) ? rawName.slice(0, -ext.length) : rawName;
7021
+ const pascal = base.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
7022
+ if (pascal.length === 0) return "Stub";
7023
+ return /^[0-9]/.test(pascal) ? `Stub${pascal}` : pascal;
7024
+ }
6593
7025
  async function generateStubs(moduleDir, moduleName, config, report) {
6594
7026
  const result = createEmptyResult();
6595
7027
  const stubs = config.manifest.generator?.sync?.stubs;
@@ -6618,27 +7050,73 @@ async function generateStubs(moduleDir, moduleName, config, report) {
6618
7050
  for (const { kind, subdir, names } of plan) {
6619
7051
  const contentTemplate = resolveTemplate4(kind, manifestTemplates);
6620
7052
  const namingTemplate = resolveNaming(kind, contextNaming, manifestNaming);
6621
- for (const name of names) {
7053
+ for (const rawName of names) {
7054
+ const name = normalizeStubName(rawName, namingTemplate);
6622
7055
  const filename = interpolateWithLog(
6623
7056
  namingTemplate,
6624
7057
  name,
6625
7058
  `stubs.naming.${kind}`,
6626
7059
  config
6627
7060
  );
7061
+ const filePath = path34__default.join(moduleDir, "src", subdir, filename);
6628
7062
  let content;
6629
7063
  if (kind === "adapter" || kind === "useCase") {
7064
+ const relatedPortNaming = resolveNaming(
7065
+ kind === "adapter" ? "outPort" : "inPort",
7066
+ contextNaming,
7067
+ manifestNaming
7068
+ );
6630
7069
  const portAnalysis = await tryAnalyzeRelatedPort(
6631
7070
  moduleDir,
6632
7071
  name,
6633
7072
  kind,
6634
- context
7073
+ context,
7074
+ relatedPortNaming
6635
7075
  );
6636
7076
  if (portAnalysis) {
6637
7077
  if (kind === "adapter") {
6638
- content = generateAdapterFromPort(portAnalysis, name);
7078
+ content = generateAdapterFromPort(
7079
+ portAnalysis,
7080
+ name,
7081
+ relativeImportSpecifier(filePath, portAnalysis.filePath),
7082
+ filePath
7083
+ );
6639
7084
  } else {
6640
- const outPorts = context.layers?.application?.ports?.out?.map(portName) || [];
6641
- content = generateUseCaseFromPort(portAnalysis, name, outPorts);
7085
+ const outPortNaming = resolveNaming(
7086
+ "outPort",
7087
+ contextNaming,
7088
+ manifestNaming
7089
+ );
7090
+ const outPortDir = path34__default.join(
7091
+ moduleDir,
7092
+ "src",
7093
+ "application",
7094
+ "ports",
7095
+ "out"
7096
+ );
7097
+ const outPorts = (context.layers?.application?.ports?.out ?? []).map((p) => {
7098
+ const base = normalizeStubName(portName(p), outPortNaming);
7099
+ const outFile = interpolateWithLog(
7100
+ outPortNaming,
7101
+ base,
7102
+ "stubs.naming.outPort",
7103
+ config
7104
+ );
7105
+ const outPortPath = path34__default.join(outPortDir, outFile);
7106
+ const analyzed = analyzePortFile(outPortPath);
7107
+ return {
7108
+ interfaceName: analyzed?.interfaceName ?? `${base}Port`,
7109
+ paramName: base.charAt(0).toLowerCase() + base.slice(1),
7110
+ importSpecifier: relativeImportSpecifier(filePath, outPortPath)
7111
+ };
7112
+ });
7113
+ content = generateUseCaseFromPort(
7114
+ portAnalysis,
7115
+ name,
7116
+ outPorts,
7117
+ relativeImportSpecifier(filePath, portAnalysis.filePath),
7118
+ filePath
7119
+ );
6642
7120
  }
6643
7121
  config.logger.debug(`Generated ${kind} '${name}' from port analysis`);
6644
7122
  } else {
@@ -6657,15 +7135,347 @@ async function generateStubs(moduleDir, moduleName, config, report) {
6657
7135
  config
6658
7136
  );
6659
7137
  }
6660
- const filePath = path28__default.join(moduleDir, "src", subdir, filename);
6661
7138
  const status = await writeStubFile(filePath, content, config, report);
6662
- if (status === "created") result.created.push(filePath);
6663
- if (status === "updated") result.updated.push(filePath);
6664
- if (status === "skipped" || status === "protected")
6665
- result.skipped.push(filePath);
6666
- if (status === "created" || status === "updated") result.totalOps += 1;
7139
+ recordWriteStatus(result, filePath, status);
7140
+ }
7141
+ }
7142
+ return result;
7143
+ }
7144
+ var OHS_NOTE = "\n *\n * Open Host Service (open-host): this is this context's published language for consuming contexts — keep it stable.";
7145
+ var ACL_NOTE = "\n *\n * Anti-Corruption Layer (acl): translate the upstream contract into this context's own domain model; do not leak provider types inward.";
7146
+ function addAll(map, key, values) {
7147
+ const set = map.get(key) ?? /* @__PURE__ */ new Set();
7148
+ values.forEach((v) => set.add(v));
7149
+ map.set(key, set);
7150
+ }
7151
+ function toPascalCase2(stem) {
7152
+ return stem.split(/[-.]/).filter((part) => part.length > 0).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
7153
+ }
7154
+ function toCamelCase(pascal) {
7155
+ return pascal.length > 0 ? pascal.charAt(0).toLowerCase() + pascal.slice(1) : pascal;
7156
+ }
7157
+ function isSafePathSegment(name) {
7158
+ return name.length > 0 && !name.includes("..") && !name.includes("/") && !name.includes("\\") && !name.startsWith(".");
7159
+ }
7160
+ function isValidTsIdentifier(name) {
7161
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
7162
+ }
7163
+ function eventContractContent(name) {
7164
+ return `// @generated cross-context event contract — edit freely
7165
+ /**
7166
+ * ${name} is a domain event published across an event-bus boundary.
7167
+ * Both the publishing and subscribing contexts depend on this shared contract.
7168
+ */
7169
+ export interface ${name} {
7170
+ // TODO: define the event payload
7171
+ readonly occurredAt: string;
7172
+ }
7173
+ `;
7174
+ }
7175
+ function dtoContent(op) {
7176
+ return `// @generated cross-context DTO — edit freely
7177
+ /**
7178
+ * Request/response payloads for the ${op} operation, exchanged across the
7179
+ * network boundary. Both the calling (client) and serving (controller) contexts
7180
+ * depend on these shared contracts.
7181
+ */
7182
+ export interface ${op}Request {
7183
+ // TODO: define the request fields
7184
+ readonly _placeholder?: never;
7185
+ }
7186
+
7187
+ export interface ${op}Response {
7188
+ // TODO: define the response fields
7189
+ readonly _placeholder?: never;
7190
+ }
7191
+ `;
7192
+ }
7193
+ function portContent(scope, interfaceName, methods, importedTypes, doc) {
7194
+ const uniqueImports = [...new Set(importedTypes)].sort();
7195
+ const importLine = uniqueImports.length > 0 ? `import type { ${uniqueImports.join(", ")} } from "@${scope}/shared";
7196
+
7197
+ ` : "";
7198
+ const methodLines = methods.map(
7199
+ (m) => ` ${m.name}(${m.paramName}: ${m.paramType}): Promise<${m.returnType}>;`
7200
+ ).join("\n");
7201
+ return `// @generated cross-context port — edit freely
7202
+ ${importLine}/**
7203
+ * ${doc}
7204
+ */
7205
+ export interface ${interfaceName} {
7206
+ ${methodLines}
7207
+ }
7208
+ `;
7209
+ }
7210
+ async function emitPortAndAdapter(result, config, report, scope, spec) {
7211
+ const moduleRoot = path34__default.join(
7212
+ config.workspaceRoot,
7213
+ "packages",
7214
+ spec.contextName
7215
+ );
7216
+ const portDir = path34__default.join(
7217
+ moduleRoot,
7218
+ "src",
7219
+ "application",
7220
+ "ports",
7221
+ spec.portKind
7222
+ );
7223
+ const portPath = path34__default.join(
7224
+ portDir,
7225
+ `${spec.portBase}.${spec.portKind}-port.ts`
7226
+ );
7227
+ if (!isInScope(portPath, config)) {
7228
+ return;
7229
+ }
7230
+ if (!config.dryRun) {
7231
+ await fs27.mkdir(portDir, { recursive: true });
7232
+ }
7233
+ recordWriteStatus(
7234
+ result,
7235
+ portPath,
7236
+ await safeWriteFileAtomic(
7237
+ portPath,
7238
+ portContent(
7239
+ scope,
7240
+ spec.interfaceName,
7241
+ spec.methods,
7242
+ spec.importedTypes,
7243
+ spec.doc
7244
+ ),
7245
+ config,
7246
+ report
7247
+ )
7248
+ );
7249
+ const analysis = analyzePortFile(portPath);
7250
+ if (!analysis) {
7251
+ config.logger.warn(
7252
+ `[cross-context] could not analyze ${portPath}; skipping adapter`
7253
+ );
7254
+ return;
7255
+ }
7256
+ const adapterDir = path34__default.join(moduleRoot, "src", "infrastructure", "adapters");
7257
+ const adapterPath = path34__default.join(adapterDir, `${spec.portBase}.adapter.ts`);
7258
+ if (!isInScope(adapterPath, config)) {
7259
+ return;
7260
+ }
7261
+ if (!config.dryRun) {
7262
+ await fs27.mkdir(adapterDir, { recursive: true });
7263
+ }
7264
+ const adapterClassName = `${toPascalCase2(spec.portBase)}Adapter`;
7265
+ const portSpecifier = relativeImportSpecifier(adapterPath, portPath);
7266
+ recordWriteStatus(
7267
+ result,
7268
+ adapterPath,
7269
+ await safeWriteFileAtomic(
7270
+ adapterPath,
7271
+ generateAdapterFromPort(analysis, adapterClassName, portSpecifier),
7272
+ config,
7273
+ report
7274
+ )
7275
+ );
7276
+ }
7277
+ function operationMethods(ops) {
7278
+ return ops.map((op) => ({
7279
+ name: toCamelCase(op),
7280
+ paramName: "request",
7281
+ paramType: `${op}Request`,
7282
+ returnType: `${op}Response`
7283
+ }));
7284
+ }
7285
+ function operationImports(ops) {
7286
+ return ops.flatMap((op) => [`${op}Request`, `${op}Response`]);
7287
+ }
7288
+ async function writeSharedContract(result, config, report, relSegments, content) {
7289
+ const contractPath = path34__default.join(
7290
+ config.workspaceRoot,
7291
+ "packages",
7292
+ "shared",
7293
+ "src",
7294
+ ...relSegments
7295
+ );
7296
+ if (!config.dryRun) {
7297
+ await fs27.mkdir(path34__default.dirname(contractPath), { recursive: true });
7298
+ }
7299
+ recordWriteStatus(
7300
+ result,
7301
+ contractPath,
7302
+ await safeWriteFileAtomic(contractPath, content, config, report)
7303
+ );
7304
+ }
7305
+ async function generateCrossContext(config, report) {
7306
+ const result = createEmptyResult();
7307
+ const edges = config.manifest.cross_context;
7308
+ if (!Array.isArray(edges) || edges.length === 0) return result;
7309
+ const scope = resolveScope(config.manifest);
7310
+ const allEvents = /* @__PURE__ */ new Set();
7311
+ const publisherEvents = /* @__PURE__ */ new Map();
7312
+ const subscriberEvents = /* @__PURE__ */ new Map();
7313
+ const allOperations = /* @__PURE__ */ new Set();
7314
+ const controllerOps = /* @__PURE__ */ new Map();
7315
+ const clientOps = /* @__PURE__ */ new Map();
7316
+ const ohsProviders = /* @__PURE__ */ new Set();
7317
+ const aclConsumers = /* @__PURE__ */ new Set();
7318
+ for (const edge of edges) {
7319
+ if (edge.provider && !isSafePathSegment(edge.provider) || edge.consumer && !isSafePathSegment(edge.consumer)) {
7320
+ config.logger.warn(
7321
+ `[cross-context] skipping edge with unsafe context name: ${edge.consumer} -> ${edge.provider}`
7322
+ );
7323
+ continue;
7324
+ }
7325
+ if (edge.integrationPattern === "open-host" && edge.provider)
7326
+ ohsProviders.add(edge.provider);
7327
+ if (edge.integrationPattern === "acl" && edge.consumer)
7328
+ aclConsumers.add(edge.consumer);
7329
+ if (edge.transport === "network") {
7330
+ const operations = (edge.operations ?? []).filter(
7331
+ (o) => typeof o === "string" && isValidTsIdentifier(o)
7332
+ );
7333
+ operations.forEach((o) => allOperations.add(o));
7334
+ if (edge.provider) addAll(controllerOps, edge.provider, operations);
7335
+ if (edge.consumer) addAll(clientOps, edge.consumer, operations);
7336
+ } else {
7337
+ const events = (edge.events ?? []).filter(
7338
+ (e) => typeof e === "string" && isValidTsIdentifier(e)
7339
+ );
7340
+ events.forEach((e) => allEvents.add(e));
7341
+ if (edge.provider) addAll(publisherEvents, edge.provider, events);
7342
+ if (edge.consumer) addAll(subscriberEvents, edge.consumer, events);
6667
7343
  }
6668
7344
  }
7345
+ for (const event of [...allEvents].sort()) {
7346
+ await writeSharedContract(
7347
+ result,
7348
+ config,
7349
+ report,
7350
+ ["domain", "events", `${event}.event.ts`],
7351
+ eventContractContent(event)
7352
+ );
7353
+ }
7354
+ for (const provider of [...publisherEvents.keys()].sort()) {
7355
+ const events = [...publisherEvents.get(provider) ?? []].sort();
7356
+ await emitPortAndAdapter(result, config, report, scope, {
7357
+ contextName: provider,
7358
+ portKind: "out",
7359
+ portBase: "message-publisher",
7360
+ interfaceName: "MessagePublisherPort",
7361
+ methods: [
7362
+ {
7363
+ name: "publish",
7364
+ paramName: "event",
7365
+ paramType: events.join(" | ") || "unknown",
7366
+ returnType: "void"
7367
+ }
7368
+ ],
7369
+ importedTypes: events,
7370
+ doc: "Publishes this context's domain events across the event-bus boundary." + (ohsProviders.has(provider) ? OHS_NOTE : "")
7371
+ });
7372
+ }
7373
+ for (const consumer of [...subscriberEvents.keys()].sort()) {
7374
+ const events = [...subscriberEvents.get(consumer) ?? []].sort();
7375
+ await emitPortAndAdapter(result, config, report, scope, {
7376
+ contextName: consumer,
7377
+ portKind: "in",
7378
+ portBase: "event-listener",
7379
+ interfaceName: "EventListenerPort",
7380
+ methods: [
7381
+ {
7382
+ name: "handle",
7383
+ paramName: "event",
7384
+ paramType: events.join(" | ") || "unknown",
7385
+ returnType: "void"
7386
+ }
7387
+ ],
7388
+ importedTypes: events,
7389
+ doc: "Handles cross-context events this context subscribes to." + (aclConsumers.has(consumer) ? ACL_NOTE : "")
7390
+ });
7391
+ }
7392
+ for (const op of [...allOperations].sort()) {
7393
+ await writeSharedContract(
7394
+ result,
7395
+ config,
7396
+ report,
7397
+ ["domain", "dtos", `${op}.dto.ts`],
7398
+ dtoContent(op)
7399
+ );
7400
+ }
7401
+ for (const provider of [...controllerOps.keys()].sort()) {
7402
+ const ops = [...controllerOps.get(provider) ?? []].sort();
7403
+ await emitPortAndAdapter(result, config, report, scope, {
7404
+ contextName: provider,
7405
+ portKind: "in",
7406
+ portBase: "rest-controller",
7407
+ interfaceName: "RestControllerPort",
7408
+ methods: operationMethods(ops),
7409
+ importedTypes: operationImports(ops),
7410
+ doc: "Serves this context's operations over the network boundary." + (ohsProviders.has(provider) ? OHS_NOTE : "")
7411
+ });
7412
+ }
7413
+ for (const consumer of [...clientOps.keys()].sort()) {
7414
+ const ops = [...clientOps.get(consumer) ?? []].sort();
7415
+ await emitPortAndAdapter(result, config, report, scope, {
7416
+ contextName: consumer,
7417
+ portKind: "out",
7418
+ portBase: "external-service-client",
7419
+ interfaceName: "ExternalServiceClientPort",
7420
+ methods: operationMethods(ops),
7421
+ importedTypes: operationImports(ops),
7422
+ doc: "Calls operations on the contexts this context depends on over the network." + (aclConsumers.has(consumer) ? ACL_NOTE : "")
7423
+ });
7424
+ }
7425
+ return result;
7426
+ }
7427
+ var RESULT_KERNEL = `// @generated by @hexagen/sync — shared Result kernel (edit freely)
7428
+ /**
7429
+ * Result is the explicit success/failure type generated use-cases return.
7430
+ * Mirrors @hexagen/shared's Result. Created once, then preserved on re-sync.
7431
+ */
7432
+ export type Result<T, E = unknown> =
7433
+ | { success: true; value: T }
7434
+ | { success: false; error: E };
7435
+
7436
+ export const ok = <T>(value: T): Result<T, never> => ({ success: true, value });
7437
+ export const err = <E>(error: E): Result<never, E> => ({
7438
+ success: false,
7439
+ error,
7440
+ });
7441
+ `;
7442
+ async function generateSharedKernel(config, report) {
7443
+ const result = createEmptyResult();
7444
+ if (config.mode !== "external") return result;
7445
+ const hasShared = (config.manifest.bounded_contexts ?? []).some(
7446
+ (bc) => bc.name?.toLowerCase() === "shared"
7447
+ );
7448
+ if (!hasShared) return result;
7449
+ const kernelPath = path34__default.join(
7450
+ config.workspaceRoot,
7451
+ "packages",
7452
+ "shared",
7453
+ "src",
7454
+ "domain",
7455
+ "result.ts"
7456
+ );
7457
+ if (!isInScope(kernelPath, config)) {
7458
+ result.skipped.push(kernelPath);
7459
+ return result;
7460
+ }
7461
+ try {
7462
+ await fs27.stat(kernelPath);
7463
+ result.skipped.push(kernelPath);
7464
+ return result;
7465
+ } catch (err3) {
7466
+ if (err3.code !== "ENOENT") throw err3;
7467
+ }
7468
+ if (!config.dryRun) {
7469
+ await fs27.mkdir(path34__default.dirname(kernelPath), { recursive: true });
7470
+ }
7471
+ const status = await safeWriteFileAtomic(
7472
+ kernelPath,
7473
+ RESULT_KERNEL,
7474
+ config,
7475
+ report,
7476
+ false
7477
+ );
7478
+ recordWriteStatus(result, kernelPath, status);
6669
7479
  return result;
6670
7480
  }
6671
7481
  var execAsync = promisify(exec);
@@ -6695,18 +7505,31 @@ async function ensureDependenciesBuilt(config) {
6695
7505
  }
6696
7506
 
6697
7507
  // src/sync-engine-helpers.ts
6698
- function mergeResult(dest, src) {
7508
+ function mergeResult2(dest, src) {
6699
7509
  dest.created.push(...src.created);
6700
7510
  dest.updated.push(...src.updated);
6701
7511
  dest.skipped.push(...src.skipped);
7512
+ dest.deleted.push(...src.deleted);
7513
+ dest.unchanged.push(...src.unchanged);
6702
7514
  dest.totalOps += src.totalOps;
7515
+ if (src.error && !dest.error) {
7516
+ dest.error = src.error;
7517
+ dest.summary = src.summary;
7518
+ }
6703
7519
  }
6704
7520
  function mergeBarrelPasses(firstPass, secondPass) {
6705
7521
  const combined = createEmptyResult();
6706
7522
  const secondPaths = /* @__PURE__ */ new Set([
6707
7523
  ...secondPass.created,
6708
7524
  ...secondPass.updated,
6709
- ...secondPass.skipped
7525
+ ...secondPass.skipped,
7526
+ ...secondPass.deleted
7527
+ ]);
7528
+ const secondAll = /* @__PURE__ */ new Set([...secondPaths, ...secondPass.unchanged]);
7529
+ const firstMutations = /* @__PURE__ */ new Set([
7530
+ ...firstPass.created,
7531
+ ...firstPass.updated,
7532
+ ...firstPass.deleted
6710
7533
  ]);
6711
7534
  for (const p of firstPass.created) {
6712
7535
  if (!secondPaths.has(p)) combined.created.push(p);
@@ -6715,12 +7538,29 @@ function mergeBarrelPasses(firstPass, secondPass) {
6715
7538
  if (!secondPaths.has(p)) combined.updated.push(p);
6716
7539
  }
6717
7540
  for (const p of firstPass.skipped) {
6718
- if (!secondPaths.has(p)) combined.skipped.push(p);
7541
+ if (!secondAll.has(p)) combined.skipped.push(p);
7542
+ }
7543
+ for (const p of firstPass.deleted) {
7544
+ if (!secondPaths.has(p)) combined.deleted.push(p);
7545
+ }
7546
+ for (const p of firstPass.unchanged) {
7547
+ if (!secondAll.has(p)) combined.unchanged.push(p);
6719
7548
  }
6720
7549
  combined.created.push(...secondPass.created);
6721
7550
  combined.updated.push(...secondPass.updated);
6722
7551
  combined.skipped.push(...secondPass.skipped);
6723
- combined.totalOps = firstPass.totalOps + secondPass.totalOps;
7552
+ combined.deleted.push(...secondPass.deleted);
7553
+ for (const p of secondPass.unchanged) {
7554
+ if (!firstMutations.has(p)) combined.unchanged.push(p);
7555
+ }
7556
+ combined.totalOps = combined.created.length + combined.updated.length + combined.deleted.length;
7557
+ if (firstPass.error) {
7558
+ combined.error = firstPass.error;
7559
+ combined.summary = firstPass.summary;
7560
+ } else if (secondPass.error) {
7561
+ combined.error = secondPass.error;
7562
+ combined.summary = secondPass.summary;
7563
+ }
6724
7564
  return combined;
6725
7565
  }
6726
7566
 
@@ -6729,14 +7569,15 @@ function caseInsensitiveEnum(schema, dir = "lower") {
6729
7569
  return external_exports.preprocess((value) => typeof value === "string" ? dir === "lower" ? value.trim().toLowerCase() : value.trim().toUpperCase() : value, schema);
6730
7570
  }
6731
7571
  var BoundedContextTypeSchema = boundedContextTypeSchema;
6732
- var PlaneTypeSchema = caseInsensitiveEnum(external_exports.enum([
7572
+ var PLANE_NAMES = [
6733
7573
  "projection",
6734
7574
  "probabilistic",
6735
7575
  "infrastructure",
6736
7576
  "shared-kernel",
6737
7577
  "core",
6738
7578
  "supporting"
6739
- ]));
7579
+ ];
7580
+ var PlaneTypeSchema = caseInsensitiveEnum(external_exports.enum(PLANE_NAMES));
6740
7581
  var StatusTypeSchema = caseInsensitiveEnum(external_exports.enum(["active", "frozen", "deprecated", "experimental"]));
6741
7582
  var RelationshipPatternSchema = caseInsensitiveEnum(external_exports.enum(["U/D", "ACL", "SK", "P", "OHS"]), "upper");
6742
7583
  var RelationshipRoleSchema = caseInsensitiveEnum(external_exports.enum(["upstream", "downstream", "peer"]));
@@ -6847,12 +7688,23 @@ var IndexManifestSchema = external_exports.object({
6847
7688
  message: "Context plane does not match file path subdirectory",
6848
7689
  path: ["bounded_contexts"]
6849
7690
  });
7691
+ var CrossContextEdgeSchema = external_exports.object({
7692
+ consumer: external_exports.string(),
7693
+ provider: external_exports.string(),
7694
+ transport: external_exports.enum(["event-bus", "network"]),
7695
+ events: external_exports.array(external_exports.string()).optional(),
7696
+ operations: external_exports.array(external_exports.string()).optional(),
7697
+ integrationPattern: external_exports.enum(["open-host", "acl"]).optional()
7698
+ });
6850
7699
  var ManifestSchema = external_exports.object({
6851
7700
  version: external_exports.string().optional(),
6852
7701
  description: external_exports.string().optional(),
6853
7702
  system: external_exports.string().optional(),
6854
7703
  scope: external_exports.string().optional(),
6855
7704
  architecture: external_exports.string().optional(),
7705
+ // The wizard records the chosen workspace template (e.g. "strict-enterprise")
7706
+ // alongside `architecture`; persisted into .architecture/manifest.yaml.
7707
+ workspaceTemplate: external_exports.string().optional(),
6856
7708
  planes: external_exports.record(external_exports.array(external_exports.string())).optional(),
6857
7709
  monorepo: external_exports.record(external_exports.unknown()).optional(),
6858
7710
  generator: external_exports.record(external_exports.unknown()).optional(),
@@ -6867,6 +7719,7 @@ var ManifestSchema = external_exports.object({
6867
7719
  })).optional(),
6868
7720
  bounded_contexts: external_exports.array(BoundedContextSchema),
6869
7721
  apps: external_exports.array(AppSchema).optional(),
7722
+ cross_context: external_exports.array(CrossContextEdgeSchema).optional(),
6870
7723
  context_mappings: external_exports.array(external_exports.object({
6871
7724
  upstream: external_exports.string(),
6872
7725
  downstream: external_exports.string(),
@@ -6935,7 +7788,15 @@ var BoundedContextSchema2 = external_exports.object({
6935
7788
  id: external_exports.string(),
6936
7789
  name: external_exports.string().min(1, "Please enter a name for this bounded context (e.g., 'UserService', 'OrderProcessing')"),
6937
7790
  description: external_exports.string().optional(),
6938
- infrastructureTarget: external_exports.enum(["nestjs", "express", "serverless", "plain-ts"]).optional(),
7791
+ // ADR-0041: `infrastructureTarget` (API backend) and `uiFramework` (below)
7792
+ // are PROJECT-LEVEL choices managed by the wizard's Applications step, which
7793
+ // fans a single selection out to every context. They persist per-context (the
7794
+ // source of truth `deriveApps` reads), but are NOT direct per-context input —
7795
+ // do not re-add per-context UI/API editing without revisiting ADR-0041.
7796
+ // `"none"` = the project opts out of a separate API backend (UI-only, e.g. a
7797
+ // Next.js app with built-in routes); `deriveApps` then emits no `api` app.
7798
+ // Distinct from `undefined` (legacy/unset → defaults to the preset).
7799
+ infrastructureTarget: external_exports.enum(["nestjs", "express", "serverless", "plain-ts", "nitro", "none"]).optional(),
6939
7800
  coreDomainEntities: external_exports.array(external_exports.string()).default([]),
6940
7801
  valueObjects: external_exports.array(external_exports.string()).default([]),
6941
7802
  domainEvents: external_exports.array(external_exports.string()).default([]),
@@ -7020,21 +7881,21 @@ external_exports.object({
7020
7881
  turboConfig: external_exports.record(external_exports.unknown()).optional()
7021
7882
  });
7022
7883
  function assertPathWithinArchitecture(workspaceRoot, relativePath) {
7023
- const resolved = path28__default.resolve(workspaceRoot, ".architecture", relativePath);
7024
- const archRoot = path28__default.resolve(workspaceRoot, ".architecture");
7884
+ const resolved = path34__default.resolve(workspaceRoot, ".architecture", relativePath);
7885
+ const archRoot = path34__default.resolve(workspaceRoot, ".architecture");
7025
7886
  try {
7026
7887
  const realResolved = realpathSync(resolved);
7027
7888
  const realArchRoot = realpathSync(archRoot);
7028
- const archRootWithSep = realArchRoot + path28__default.sep;
7889
+ const archRootWithSep = realArchRoot + path34__default.sep;
7029
7890
  if (realResolved !== realArchRoot && !realResolved.startsWith(archRootWithSep)) {
7030
7891
  throw new Error(`Path traversal detected: "${relativePath}" resolves outside .architecture/`);
7031
7892
  }
7032
7893
  } catch (err3) {
7033
7894
  if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
7034
7895
  let checkPath = archRoot;
7035
- const pathSegments = path28__default.relative(archRoot, resolved).split(path28__default.sep);
7896
+ const pathSegments = path34__default.relative(archRoot, resolved).split(path34__default.sep);
7036
7897
  for (const segment of pathSegments) {
7037
- checkPath = path28__default.join(checkPath, segment);
7898
+ checkPath = path34__default.join(checkPath, segment);
7038
7899
  try {
7039
7900
  const stat = lstatSync(checkPath);
7040
7901
  if (stat.isSymbolicLink()) {
@@ -7050,7 +7911,7 @@ function assertPathWithinArchitecture(workspaceRoot, relativePath) {
7050
7911
  throw statErr;
7051
7912
  }
7052
7913
  }
7053
- const archRootWithSep = archRoot + path28__default.sep;
7914
+ const archRootWithSep = archRoot + path34__default.sep;
7054
7915
  if (resolved !== archRoot && !resolved.startsWith(archRootWithSep)) {
7055
7916
  throw new Error(`Path traversal detected: "${relativePath}" resolves outside .architecture/`);
7056
7917
  }
@@ -7060,7 +7921,7 @@ function assertPathWithinArchitecture(workspaceRoot, relativePath) {
7060
7921
  }
7061
7922
  }
7062
7923
  async function mergeSplitManifest(workspaceRoot, manifestPath) {
7063
- const content = await fs22.readFile(manifestPath, "utf-8");
7924
+ const content = await fs27.readFile(manifestPath, "utf-8");
7064
7925
  const parsed = yaml9.load(content);
7065
7926
  if (parsed == null) {
7066
7927
  throw new Error("Manifest file is empty");
@@ -7093,10 +7954,10 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7093
7954
  continue;
7094
7955
  }
7095
7956
  assertPathWithinArchitecture(workspaceRoot, indexEntry.file);
7096
- const contextFilePath = path28__default.join(workspaceRoot, ".architecture", indexEntry.file);
7957
+ const contextFilePath = path34__default.join(workspaceRoot, ".architecture", indexEntry.file);
7097
7958
  let contextContent;
7098
7959
  try {
7099
- contextContent = await fs22.readFile(contextFilePath, "utf-8");
7960
+ contextContent = await fs27.readFile(contextFilePath, "utf-8");
7100
7961
  } catch (err3) {
7101
7962
  if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
7102
7963
  throw new Error(`Context file not found: ${contextFilePath}`);
@@ -7128,10 +7989,10 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7128
7989
  continue;
7129
7990
  }
7130
7991
  assertPathWithinArchitecture(workspaceRoot, appEntry.file);
7131
- const appFilePath = path28__default.join(workspaceRoot, ".architecture", appEntry.file);
7992
+ const appFilePath = path34__default.join(workspaceRoot, ".architecture", appEntry.file);
7132
7993
  let appContent;
7133
7994
  try {
7134
- appContent = await fs22.readFile(appFilePath, "utf-8");
7995
+ appContent = await fs27.readFile(appFilePath, "utf-8");
7135
7996
  } catch (err3) {
7136
7997
  if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
7137
7998
  throw new Error(`App file not found: ${appFilePath}`);
@@ -7150,23 +8011,23 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7150
8011
 
7151
8012
  // src/sync-engine-init.ts
7152
8013
  var __filename$1 = fileURLToPath(import.meta.url);
7153
- var __dirname$1 = path28__default.dirname(__filename$1);
8014
+ var __dirname$1 = path34__default.dirname(__filename$1);
7154
8015
  async function findWorkspaceRoot(options) {
7155
8016
  if (options.targetRoot) {
7156
8017
  return options.targetRoot;
7157
8018
  }
7158
8019
  let currentDir = __dirname$1;
7159
- while (currentDir !== path28__default.parse(currentDir).root) {
8020
+ while (currentDir !== path34__default.parse(currentDir).root) {
7160
8021
  try {
7161
- const pkgPath = path28__default.join(currentDir, "package.json");
7162
- const pkgContent = await fs22.readFile(pkgPath, "utf-8");
8022
+ const pkgPath = path34__default.join(currentDir, "package.json");
8023
+ const pkgContent = await fs27.readFile(pkgPath, "utf-8");
7163
8024
  const pkg = JSON.parse(pkgContent);
7164
8025
  if (pkg.workspaces && Array.isArray(pkg.workspaces)) {
7165
8026
  return currentDir;
7166
8027
  }
7167
8028
  } catch {
7168
8029
  }
7169
- currentDir = path28__default.dirname(currentDir);
8030
+ currentDir = path34__default.dirname(currentDir);
7170
8031
  }
7171
8032
  throw new Error(
7172
8033
  'Could not locate monorepo root. No package.json with "workspaces" field found.'
@@ -7177,7 +8038,7 @@ async function loadManifest(workspaceRoot, flags, options) {
7177
8038
  return options.manifest;
7178
8039
  }
7179
8040
  const { logger: logger2, dryRun } = flags;
7180
- const manifestPath = path28__default.join(workspaceRoot, ".architecture/manifest.yaml");
8041
+ const manifestPath = path34__default.join(workspaceRoot, ".architecture/manifest.yaml");
7181
8042
  logger2.debug(`[debug] __dirname (ESM): ${__dirname$1}`);
7182
8043
  logger2.debug(`[debug] resolved workspaceRoot: ${workspaceRoot}`);
7183
8044
  logger2.debug(`[debug] resolved manifestPath: ${manifestPath}`);
@@ -7231,6 +8092,23 @@ function validateManifest(manifest, flags) {
7231
8092
  var execAsync2 = promisify(exec);
7232
8093
  var SyncEngine = class {
7233
8094
  report = new MigrationReport();
8095
+ // PR-B1 (RCA #4): per-run mutation journal — pre-images of every file sync
8096
+ // touches, replayed in reverse on failure (see journal.ts). The lifetime is
8097
+ // one RUN, not one instance: run() re-news it on entry, so a reused engine
8098
+ // can never replay a previous run's pre-images into a later rollback.
8099
+ journal = new SyncJournal();
8100
+ // B-1 (PR-B2 review): generators that failed-soft this run. Four generators
8101
+ // catch their own exceptions into `result.error` by contract (Wave-2e: skip
8102
+ // the package, do not abort the run) — but a swallowed failure plans zero
8103
+ // ops, so a run that could not even read a target still summarized as
8104
+ // `Total ops : 0` and the CLI exited 0: errors masqueraded as convergence,
8105
+ // silently breaking `--check`'s "exit 0 ⇒ converged" promise. Failures are
8106
+ // recorded at each production site (NOT off the merged rows — mergeResult
8107
+ // keeps only the first error, so row-level counting would under-report
8108
+ // multi-module failures), printed as FAILED rows under the summary, and
8109
+ // surfaced as `SyncRunSummary.errors` for cli.ts to turn into exit ≠ 0.
8110
+ // Per-run lifetime, same reset discipline as the journal.
8111
+ failures = [];
7234
8112
  partialConfig;
7235
8113
  fullConfig = null;
7236
8114
  manifest = {};
@@ -7252,6 +8130,19 @@ var SyncEngine = class {
7252
8130
  }
7253
8131
  return this.fullConfig;
7254
8132
  }
8133
+ /**
8134
+ * Record a failed-soft generator result (B-1). Called at every site that
8135
+ * receives a GeneratorResult, including the ones that never set `error`
8136
+ * today — the check is one truthy test, and a future generator adopting the
8137
+ * catch-into-result contract is then surfaced without anyone remembering
8138
+ * this seam. `row` matches the summary-table label so the FAILED line and
8139
+ * the table read as one report.
8140
+ */
8141
+ noteFailure(row, result) {
8142
+ if (result.error) {
8143
+ this.failures.push({ row, message: result.error.message });
8144
+ }
8145
+ }
7255
8146
  async ensureDirectories() {
7256
8147
  const config = this.getConfig();
7257
8148
  const result = createEmptyResult();
@@ -7266,20 +8157,12 @@ var SyncEngine = class {
7266
8157
  );
7267
8158
  continue;
7268
8159
  }
7269
- const moduleDir = path28__default.join(this.workspaceRoot, "packages", mod.name);
8160
+ const moduleDir = path34__default.join(this.workspaceRoot, "packages", mod.name);
7270
8161
  logger2.info(
7271
8162
  `Ensuring directories for module: ${mod.name} at ${moduleDir}`
7272
8163
  );
7273
- const layerResult = await ensureLayerFolders(
7274
- moduleDir,
7275
- layers,
7276
- config,
7277
- this.report
7278
- );
7279
- result.created.push(...layerResult.created);
7280
- result.skipped.push(...layerResult.skipped);
7281
- result.updated.push(...layerResult.updated);
7282
- result.totalOps += layerResult.totalOps;
8164
+ const layerResult = await ensureLayerFolders(moduleDir, layers, config);
8165
+ mergeResult2(result, layerResult);
7283
8166
  }
7284
8167
  return result;
7285
8168
  }
@@ -7294,7 +8177,7 @@ var SyncEngine = class {
7294
8177
  const stubs = createEmptyResult();
7295
8178
  for (const module of modules) {
7296
8179
  const moduleName = module.name;
7297
- const moduleDir = path28__default.join(this.workspaceRoot, "packages", moduleName);
8180
+ const moduleDir = path34__default.join(this.workspaceRoot, "packages", moduleName);
7298
8181
  if (moduleName.includes("..") || moduleName.includes("/") || moduleName.startsWith(".")) {
7299
8182
  logger2.warn(
7300
8183
  `Skipping invalid module name (potential path traversal): ${moduleName}`
@@ -7331,14 +8214,19 @@ var SyncEngine = class {
7331
8214
  config,
7332
8215
  this.report
7333
8216
  );
8217
+ this.noteFailure("Barrels", barrelResult);
8218
+ this.noteFailure("package.json", pkgResult);
8219
+ this.noteFailure("tsconfig.json", tsResult);
8220
+ this.noteFailure("ESLint", eslintResult);
8221
+ this.noteFailure("Stubs", stubResult);
7334
8222
  if (this.partialConfig.mode === "self-regen") {
7335
8223
  await reapLegacyFolders(moduleDir, config, this.report);
7336
8224
  }
7337
- mergeResult(barrels, barrelResult);
7338
- mergeResult(pkgs, pkgResult);
7339
- mergeResult(tsconfigs, tsResult);
7340
- mergeResult(eslint, eslintResult);
7341
- mergeResult(stubs, stubResult);
8225
+ mergeResult2(barrels, barrelResult);
8226
+ mergeResult2(pkgs, pkgResult);
8227
+ mergeResult2(tsconfigs, tsResult);
8228
+ mergeResult2(eslint, eslintResult);
8229
+ mergeResult2(stubs, stubResult);
7342
8230
  }
7343
8231
  return {
7344
8232
  rootFiles: createEmptyResult(),
@@ -7356,6 +8244,8 @@ var SyncEngine = class {
7356
8244
  const { logger: logger2, dryRun, allowDirty, mode } = this.partialConfig;
7357
8245
  const start = Date.now();
7358
8246
  let lockFile = null;
8247
+ this.journal = new SyncJournal();
8248
+ this.failures = [];
7359
8249
  logger2.info(
7360
8250
  dryRun ? "[DRY-RUN MODE] Starting sync..." : "Starting sync..."
7361
8251
  );
@@ -7404,7 +8294,8 @@ var SyncEngine = class {
7404
8294
  this.fullConfig = {
7405
8295
  ...this.partialConfig,
7406
8296
  workspaceRoot: this.workspaceRoot,
7407
- manifest: this.manifest
8297
+ manifest: this.manifest,
8298
+ journal: this.journal
7408
8299
  };
7409
8300
  if (!dryRun && mode === "self-regen") {
7410
8301
  lockFile = new LockFile(this.workspaceRoot);
@@ -7430,15 +8321,29 @@ var SyncEngine = class {
7430
8321
  this.fullConfig,
7431
8322
  this.report
7432
8323
  );
8324
+ this.noteFailure("RootFiles", rootFilesResult);
7433
8325
  const archFilesResult = await generateArchitectureFiles(
7434
8326
  this.fullConfig,
7435
8327
  this.report
7436
8328
  );
8329
+ this.noteFailure("ArchFiles", archFilesResult);
7437
8330
  const layerResult = await this.ensureDirectories();
8331
+ this.noteFailure("Layers", layerResult);
7438
8332
  const coreResults = await this.generateCoreArtifacts();
7439
8333
  const { pkgs, tsconfigs, eslint, stubs } = coreResults;
7440
8334
  const firstPassBarrels = coreResults.barrels;
7441
8335
  const appsResult = await generateApps(this.fullConfig, this.report);
8336
+ this.noteFailure("Apps", appsResult);
8337
+ const crossContextResult = await generateCrossContext(
8338
+ this.fullConfig,
8339
+ this.report
8340
+ );
8341
+ this.noteFailure("CrossContext", crossContextResult);
8342
+ const sharedKernelResult = await generateSharedKernel(
8343
+ this.fullConfig,
8344
+ this.report
8345
+ );
8346
+ this.noteFailure("SharedKernel", sharedKernelResult);
7442
8347
  const secondPassBarrels = createEmptyResult();
7443
8348
  const modules = this.fullConfig.manifest.bounded_contexts ?? [];
7444
8349
  for (const module of modules) {
@@ -7446,16 +8351,47 @@ var SyncEngine = class {
7446
8351
  if (!moduleName || moduleName.includes("..") || moduleName.includes("/") || moduleName.startsWith(".")) {
7447
8352
  continue;
7448
8353
  }
7449
- const moduleDir = path28__default.join(this.workspaceRoot, "packages", moduleName);
8354
+ const moduleDir = path34__default.join(this.workspaceRoot, "packages", moduleName);
7450
8355
  const pass2 = await generateBarrels(
7451
8356
  moduleDir,
7452
8357
  this.fullConfig,
7453
8358
  this.report
7454
8359
  );
7455
- mergeResult(secondPassBarrels, pass2);
8360
+ this.noteFailure("Barrels", pass2);
8361
+ mergeResult2(secondPassBarrels, pass2);
7456
8362
  }
7457
8363
  const barrels = mergeBarrelPasses(firstPassBarrels, secondPassBarrels);
7458
- const totalOps = rootFilesResult.totalOps + archFilesResult.totalOps + layerResult.totalOps + barrels.totalOps + pkgs.totalOps + tsconfigs.totalOps + eslint.totalOps + stubs.totalOps + appsResult.totalOps;
8364
+ const rows = [
8365
+ ["RootFiles", rootFilesResult],
8366
+ ["ArchFiles", archFilesResult],
8367
+ ["Layers", layerResult],
8368
+ ["Barrels", barrels],
8369
+ ["CrossContext", crossContextResult],
8370
+ ["SharedKernel", sharedKernelResult],
8371
+ ["package.json", pkgs],
8372
+ ["tsconfig.json", tsconfigs],
8373
+ ["ESLint", eslint],
8374
+ ["Stubs", stubs],
8375
+ ["Apps", appsResult]
8376
+ ];
8377
+ const runSummary = {
8378
+ created: 0,
8379
+ updated: 0,
8380
+ deleted: 0,
8381
+ unchanged: 0,
8382
+ skipped: 0,
8383
+ totalOps: 0,
8384
+ errors: this.failures.length,
8385
+ durationMs: 0
8386
+ };
8387
+ for (const [, r] of rows) {
8388
+ runSummary.created += r.created.length;
8389
+ runSummary.updated += r.updated.length;
8390
+ runSummary.deleted += r.deleted.length;
8391
+ runSummary.unchanged += r.unchanged.length;
8392
+ runSummary.skipped += r.skipped.length;
8393
+ runSummary.totalOps += r.totalOps;
8394
+ }
7459
8395
  if (mode === "self-regen") {
7460
8396
  await runArchLinter(this.fullConfig);
7461
8397
  await this.report.writeReport(this.fullConfig);
@@ -7463,56 +8399,70 @@ var SyncEngine = class {
7463
8399
  logger2.info("Skipping arch-linter and report (external mode)");
7464
8400
  }
7465
8401
  const duration = Date.now() - start;
7466
- logger2.info("\nSync completed successfully.");
8402
+ runSummary.durationMs = duration;
8403
+ if (this.failures.length === 0) {
8404
+ logger2.info("\nSync completed successfully.");
8405
+ } else {
8406
+ logger2.error(
8407
+ `
8408
+ Sync completed with ${this.failures.length} generator failure(s) — see the FAILED row(s) below.`
8409
+ );
8410
+ }
7467
8411
  logger2.info(
7468
8412
  `Processed ${this.manifest.bounded_contexts?.length ?? 0} modules in ${duration}ms`
7469
8413
  );
7470
8414
  logger2.info(`
7471
8415
  === Generator Summary ===`);
7472
- logger2.info(
7473
- `• RootFiles : ${rootFilesResult.created.length} created, ${rootFilesResult.updated.length} updated, ${rootFilesResult.skipped.length} skipped`
7474
- );
7475
- logger2.info(
7476
- `• ArchFiles : ${archFilesResult.created.length} created, ${archFilesResult.updated.length} updated, ${archFilesResult.skipped.length} skipped`
7477
- );
7478
- logger2.info(
7479
- `• Layers : ${layerResult.created.length} created, ${layerResult.updated.length} updated, ${layerResult.skipped.length} skipped`
7480
- );
7481
- logger2.info(
7482
- `• Barrels : ${barrels.created.length} created, ${barrels.updated.length} updated, ${barrels.skipped.length} skipped`
7483
- );
7484
- logger2.info(
7485
- `• package.json : ${pkgs.created.length} created, ${pkgs.updated.length} updated, ${pkgs.skipped.length} skipped`
7486
- );
7487
- logger2.info(
7488
- `• tsconfig.json : ${tsconfigs.created.length} created, ${tsconfigs.updated.length} updated, ${tsconfigs.skipped.length} skipped`
7489
- );
7490
- logger2.info(
7491
- `• ESLint : ${eslint.created.length} created, ${eslint.updated.length} updated, ${eslint.skipped.length} skipped`
7492
- );
7493
- logger2.info(
7494
- `• Stubs : ${stubs.created.length} created, ${stubs.updated.length} updated, ${stubs.skipped.length} skipped`
7495
- );
7496
- logger2.info(
7497
- `• Apps : ${appsResult.created.length} created, ${appsResult.updated.length} updated, ${appsResult.skipped.length} skipped`
7498
- );
7499
- logger2.info(`• Total ops : ${totalOps}`);
8416
+ for (const [label, r] of rows) {
8417
+ logger2.info(
8418
+ `• ${label} : ${r.created.length} created, ${r.updated.length} updated, ${r.deleted.length} deleted, ${r.unchanged.length} unchanged, ${r.skipped.length} skipped`
8419
+ );
8420
+ }
8421
+ for (const f of this.failures) {
8422
+ logger2.error(`• ${f.row} : FAILED — ${f.message}`);
8423
+ }
8424
+ logger2.info(`• Total ops : ${runSummary.totalOps}`);
8425
+ return runSummary;
7500
8426
  } catch (err3) {
7501
8427
  const message = err3 instanceof Error ? err3.message : "Unknown sync error";
7502
8428
  logger2.error(`Sync failed: ${message}`);
7503
8429
  if (!dryRun) {
7504
- try {
7505
- await execAsync2("git reset --hard HEAD && git clean -fd", {
7506
- cwd: this.workspaceRoot
7507
- });
7508
- logger2.info("Rollback completed after failure.");
7509
- } catch (rollbackErr) {
8430
+ if (this.journal.size === 0) {
8431
+ logger2.info(
8432
+ "No files were touched before the failure — nothing to roll back."
8433
+ );
8434
+ } else if (allowDirty) {
7510
8435
  logger2.warn(
7511
- `Rollback failed: ${rollbackErr instanceof Error ? rollbackErr.message : rollbackErr}`
8436
+ `Sync failed after touching ${this.journal.size} path(s) — NO rollback under --allow-dirty; the tree is left as-is:`
8437
+ );
8438
+ for (const line of this.journal.describeEntries(this.workspaceRoot)) {
8439
+ logger2.warn(` ${line}`);
8440
+ }
8441
+ } else {
8442
+ logger2.info(
8443
+ `Rolling back ${this.journal.size} journaled path(s) (inverse-ops; never git reset/clean)...`
8444
+ );
8445
+ const outcome = await this.journal.rollback(
8446
+ logger2,
8447
+ this.workspaceRoot
7512
8448
  );
8449
+ if (outcome.failures.length === 0) {
8450
+ logger2.info(
8451
+ `Rollback completed: ${outcome.restored}/${outcome.attempted} path(s) restored.`
8452
+ );
8453
+ } else {
8454
+ for (const f of outcome.failures) {
8455
+ logger2.error(
8456
+ `Rollback failed for ${path34__default.relative(this.workspaceRoot, f.path)}: intended to ${f.intended} — ${f.error}`
8457
+ );
8458
+ }
8459
+ logger2.error(
8460
+ `Rollback incomplete: ${outcome.failures.length} of ${outcome.attempted} path(s) NOT restored — inspect the paths above.`
8461
+ );
8462
+ }
7513
8463
  }
7514
- process.exit(1);
7515
8464
  }
8465
+ throw err3;
7516
8466
  } finally {
7517
8467
  if (lockFile) {
7518
8468
  try {
@@ -7539,7 +8489,7 @@ function err2(error) {
7539
8489
  var execAsync3 = promisify(exec);
7540
8490
  async function loadManifest2(workspaceRoot) {
7541
8491
  try {
7542
- const manifestPath = path28__default.join(
8492
+ const manifestPath = path34__default.join(
7543
8493
  workspaceRoot,
7544
8494
  ".architecture/manifest.yaml"
7545
8495
  );
@@ -7727,27 +8677,27 @@ var YamlSaveError = class extends Error {
7727
8677
  filePath;
7728
8678
  };
7729
8679
  var YamlService = class {
7730
- async loadManifest(path32) {
8680
+ async loadManifest(path38) {
7731
8681
  try {
7732
- const content = await readFile(path32, "utf-8");
8682
+ const content = await readFile(path38, "utf-8");
7733
8683
  const manifest = yaml9.load(content);
7734
8684
  return ok2(manifest);
7735
8685
  } catch (e) {
7736
8686
  const error = e;
7737
8687
  if (error.code === "ENOENT") {
7738
- return err2(new YamlLoadError(`File not found: ${path32}`, path32));
8688
+ return err2(new YamlLoadError(`File not found: ${path38}`, path38));
7739
8689
  }
7740
- return err2(new YamlLoadError(error.message, path32));
8690
+ return err2(new YamlLoadError(error.message, path38));
7741
8691
  }
7742
8692
  }
7743
- saveManifest(manifest, path32) {
7744
- const dir = dirname(path32);
7745
- const tempPath = `${path32}.tmp`;
8693
+ saveManifest(manifest, path38) {
8694
+ const dir = dirname(path38);
8695
+ const tempPath = `${path38}.tmp`;
7746
8696
  try {
7747
8697
  mkdirSync(dir, { recursive: true });
7748
8698
  const content = yaml9.dump(manifest, { indent: 2 });
7749
8699
  writeFileSync(tempPath, content, "utf-8");
7750
- renameSync(tempPath, path32);
8700
+ renameSync(tempPath, path38);
7751
8701
  return ok2(void 0);
7752
8702
  } catch (e) {
7753
8703
  const error = e;
@@ -7755,7 +8705,7 @@ var YamlService = class {
7755
8705
  if (existsSync(tempPath)) unlinkSync(tempPath);
7756
8706
  } catch {
7757
8707
  }
7758
- return err2(new YamlSaveError(error.message, path32));
8708
+ return err2(new YamlSaveError(error.message, path38));
7759
8709
  }
7760
8710
  }
7761
8711
  parse(content) {
@@ -7964,8 +8914,8 @@ function resolveTemplatesDir() {
7964
8914
  if (process.env.HEXAGEN_TEMPLATES_DIR) {
7965
8915
  return process.env.HEXAGEN_TEMPLATES_DIR;
7966
8916
  }
7967
- const cliDir = path28__default.dirname(fileURLToPath(import.meta.url));
7968
- return path28__default.resolve(cliDir, "templates");
8917
+ const cliDir = path34__default.dirname(fileURLToPath(import.meta.url));
8918
+ return path34__default.resolve(cliDir, "templates");
7969
8919
  }
7970
8920
 
7971
8921
  // src/commands/arch/port.ts
@@ -8593,8 +9543,8 @@ var removeCommander = new Command("remove").description("Remove a port or bounde
8593
9543
  function getManifestPath2(cwd) {
8594
9544
  return join(cwd, ".architecture", "manifest.yaml");
8595
9545
  }
8596
- async function loadManifestFromPath(path32) {
8597
- const result = await yamlService.loadManifest(path32);
9546
+ async function loadManifestFromPath(path38) {
9547
+ const result = await yamlService.loadManifest(path38);
8598
9548
  if (!result.success) {
8599
9549
  return err2(result.error);
8600
9550
  }
@@ -8878,7 +9828,26 @@ function validateManifest3(raw) {
8878
9828
  envVars: validatedStringArray(m.envVars, "envVars"),
8879
9829
  outputs: validatedOutputs(m.outputs, questionTypes),
8880
9830
  checklist: validatedStringArray(m.checklist, "checklist"),
8881
- branch: typeof m.branch === "string" ? m.branch : void 0
9831
+ branch: typeof m.branch === "string" ? m.branch : void 0,
9832
+ ...validatedMapping(m)
9833
+ };
9834
+ }
9835
+ function validatedMapping(m) {
9836
+ const { provides, scope } = m;
9837
+ if (provides !== void 0 && (typeof provides !== "string" || !provides.trim())) {
9838
+ throw new Error("Template manifest field 'provides' must be a non-empty string");
9839
+ }
9840
+ const scopes = ["context", "shared", "project"];
9841
+ if (scope !== void 0 && !(typeof scope === "string" && scopes.includes(scope))) {
9842
+ throw new Error("Template manifest field 'scope' must be one of: context, shared, project");
9843
+ }
9844
+ if (provides === void 0 !== (scope === void 0)) {
9845
+ throw new Error("Template manifest fields 'provides' and 'scope' must be set together");
9846
+ }
9847
+ return {
9848
+ // Trimmed so a padded capability key can't silently miss the canvas join.
9849
+ provides: provides === void 0 ? void 0 : provides.trim(),
9850
+ scope
8882
9851
  };
8883
9852
  }
8884
9853
  function validatedStringArray(raw, field) {
@@ -8993,7 +9962,7 @@ function isInstalled(config, templateId) {
8993
9962
  return templateId in config.templates;
8994
9963
  }
8995
9964
  function conflictFilePath(filePath) {
8996
- const ext = path28__default.extname(filePath);
9965
+ const ext = path34__default.extname(filePath);
8997
9966
  return ext ? filePath.slice(0, -ext.length) + ".hexagen-update" + ext : filePath + ".hexagen-update";
8998
9967
  }
8999
9968
 
@@ -9056,19 +10025,19 @@ function resolveDependencies(requested, registry) {
9056
10025
  }
9057
10026
  const sorted = [];
9058
10027
  const state = /* @__PURE__ */ new Map();
9059
- function visit(id, path32) {
10028
+ function visit(id, path38) {
9060
10029
  const s = state.get(id);
9061
10030
  if (s === "done")
9062
10031
  return;
9063
10032
  if (s === "visiting") {
9064
- const cycleStart = path32.indexOf(id);
9065
- throw new CyclicDependencyError([...path32.slice(cycleStart), id]);
10033
+ const cycleStart = path38.indexOf(id);
10034
+ throw new CyclicDependencyError([...path38.slice(cycleStart), id]);
9066
10035
  }
9067
10036
  state.set(id, "visiting");
9068
10037
  const manifest = registry.get(id);
9069
10038
  for (const dep of manifest.requires) {
9070
10039
  if (needed.has(dep))
9071
- visit(dep, [...path32, id]);
10040
+ visit(dep, [...path38, id]);
9072
10041
  }
9073
10042
  state.set(id, "done");
9074
10043
  sorted.push(id);
@@ -9085,11 +10054,13 @@ var AddTemplateUseCase = class {
9085
10054
  questionEngine;
9086
10055
  fileEmitter;
9087
10056
  configStore;
9088
- constructor(registry, questionEngine, fileEmitter, configStore) {
10057
+ quiet;
10058
+ constructor(registry, questionEngine, fileEmitter, configStore, quiet = false) {
9089
10059
  this.registry = registry;
9090
10060
  this.questionEngine = questionEngine;
9091
10061
  this.fileEmitter = fileEmitter;
9092
10062
  this.configStore = configStore;
10063
+ this.quiet = quiet;
9093
10064
  }
9094
10065
  async execute(input) {
9095
10066
  const { templateIds, projectRoot, overrideAnswers = {}, skipInstalled = true } = input;
@@ -9117,7 +10088,8 @@ var AddTemplateUseCase = class {
9117
10088
  };
9118
10089
  config.templates[id] = record;
9119
10090
  applied.push(id);
9120
- this.printChecklist(manifest);
10091
+ if (!this.quiet)
10092
+ this.printChecklist(manifest);
9121
10093
  }
9122
10094
  await this.configStore.save(projectRoot, config);
9123
10095
  return { applied, skipped, warnings: allWarnings };
@@ -9193,9 +10165,9 @@ var ValidateTemplatesUseCase = class {
9193
10165
  if (!isOutputEnabled(output, answers))
9194
10166
  continue;
9195
10167
  const rel = outputPath(output);
9196
- const abs = path28__default.join(projectRoot, rel);
10168
+ const abs = path34__default.join(projectRoot, rel);
9197
10169
  try {
9198
- await fs22.access(abs);
10170
+ await fs27.access(abs);
9199
10171
  } catch {
9200
10172
  missingFiles.push(rel);
9201
10173
  }
@@ -9210,10 +10182,10 @@ var ValidateTemplatesUseCase = class {
9210
10182
  for (const output of manifest.outputs) {
9211
10183
  if (!isOutputEnabled(output, answers))
9212
10184
  continue;
9213
- const absConflict = conflictFilePath(path28__default.join(projectRoot, outputPath(output)));
10185
+ const absConflict = conflictFilePath(path34__default.join(projectRoot, outputPath(output)));
9214
10186
  try {
9215
- await fs22.access(absConflict);
9216
- conflictFiles.push(path28__default.relative(projectRoot, absConflict));
10187
+ await fs27.access(absConflict);
10188
+ conflictFiles.push(path34__default.relative(projectRoot, absConflict));
9217
10189
  } catch {
9218
10190
  }
9219
10191
  }
@@ -9232,25 +10204,25 @@ var ValidateTemplatesUseCase = class {
9232
10204
  return { results, totalWarnings, totalErrors };
9233
10205
  }
9234
10206
  };
9235
- var PACKAGE_ROOT = path28__default.resolve(path28__default.dirname(fileURLToPath(import.meta.url)), "..", "..");
10207
+ var PACKAGE_ROOT = path34__default.resolve(path34__default.dirname(fileURLToPath(import.meta.url)), "..", "..");
9236
10208
  var FileSystemTemplateRegistry = class {
9237
10209
  templatesDir;
9238
10210
  cache = null;
9239
10211
  constructor(templatesDir) {
9240
- this.templatesDir = templatesDir ?? path28__default.join(PACKAGE_ROOT, "templates");
10212
+ this.templatesDir = templatesDir ?? path34__default.join(PACKAGE_ROOT, "templates");
9241
10213
  }
9242
10214
  async loadAll() {
9243
10215
  if (this.cache)
9244
10216
  return this.cache;
9245
10217
  let entries;
9246
10218
  try {
9247
- entries = await fs22.readdir(this.templatesDir);
10219
+ entries = await fs27.readdir(this.templatesDir);
9248
10220
  } catch {
9249
10221
  return [];
9250
10222
  }
9251
10223
  const manifests = [];
9252
10224
  for (const entry of entries) {
9253
- const manifestPath = path28__default.join(this.templatesDir, entry, "manifest.json");
10225
+ const manifestPath = path34__default.join(this.templatesDir, entry, "manifest.json");
9254
10226
  const manifest = await this.readManifest(manifestPath);
9255
10227
  if (manifest)
9256
10228
  manifests.push(manifest);
@@ -9259,16 +10231,22 @@ var FileSystemTemplateRegistry = class {
9259
10231
  return manifests;
9260
10232
  }
9261
10233
  async loadOne(id) {
9262
- const manifestPath = path28__default.join(this.templatesDir, id, "manifest.json");
10234
+ const manifestPath = path34__default.join(this.templatesDir, id, "manifest.json");
9263
10235
  return this.readManifest(manifestPath);
9264
10236
  }
9265
10237
  async readManifest(manifestPath) {
10238
+ let raw;
9266
10239
  try {
9267
- const raw = await fs22.readFile(manifestPath, "utf-8");
9268
- return validateManifest3(JSON.parse(raw));
10240
+ raw = await fs27.readFile(manifestPath, "utf-8");
9269
10241
  } catch {
9270
10242
  return null;
9271
10243
  }
10244
+ try {
10245
+ return validateManifest3(JSON.parse(raw));
10246
+ } catch (err3) {
10247
+ console.warn(`[template-registry] skipping invalid manifest ${manifestPath}: ${err3 instanceof Error ? err3.message : String(err3)}`);
10248
+ return null;
10249
+ }
9272
10250
  }
9273
10251
  };
9274
10252
  var InteractiveQuestionEngine = class {
@@ -9395,31 +10373,31 @@ ${prompt} (comma-separated numbers)`);
9395
10373
  }
9396
10374
  }
9397
10375
  };
9398
- var PACKAGE_ROOT2 = path28__default.resolve(path28__default.dirname(fileURLToPath(import.meta.url)), "..", "..");
10376
+ var PACKAGE_ROOT2 = path34__default.resolve(path34__default.dirname(fileURLToPath(import.meta.url)), "..", "..");
9399
10377
  var FileSystemFileEmitter = class {
9400
10378
  templatesDir;
9401
10379
  constructor(templatesDir) {
9402
- this.templatesDir = templatesDir ?? path28__default.join(PACKAGE_ROOT2, "templates");
10380
+ this.templatesDir = templatesDir ?? path34__default.join(PACKAGE_ROOT2, "templates");
9403
10381
  }
9404
10382
  async emit(manifest, answers, projectRoot, config) {
9405
10383
  const warnings = [];
9406
10384
  const generatedFiles = [];
9407
- const templateFilesDir = path28__default.join(this.templatesDir, manifest.id, "files");
9408
- const resolvedRoot = path28__default.resolve(projectRoot);
10385
+ const templateFilesDir = path34__default.join(this.templatesDir, manifest.id, "files");
10386
+ const resolvedRoot = path34__default.resolve(projectRoot);
9409
10387
  for (const out of manifest.outputs) {
9410
10388
  if (!isOutputEnabled(out, answers))
9411
10389
  continue;
9412
10390
  const outputRelPath = outputPath(out);
9413
- const destFile = path28__default.resolve(projectRoot, outputRelPath);
9414
- if (!destFile.startsWith(resolvedRoot + path28__default.sep) && destFile !== resolvedRoot) {
10391
+ const destFile = path34__default.resolve(projectRoot, outputRelPath);
10392
+ if (!destFile.startsWith(resolvedRoot + path34__default.sep) && destFile !== resolvedRoot) {
9415
10393
  throw new Error(`Output path '${outputRelPath}' escapes the project root`);
9416
10394
  }
9417
- const sourceFile = path28__default.join(templateFilesDir, outputRelPath);
10395
+ const sourceFile = path34__default.join(templateFilesDir, outputRelPath);
9418
10396
  let templateContent;
9419
10397
  let sourceMode = 420;
9420
10398
  try {
9421
- const raw = await fs22.readFile(sourceFile, "utf-8");
9422
- sourceMode = (await fs22.stat(sourceFile)).mode & 511;
10399
+ const raw = await fs27.readFile(sourceFile, "utf-8");
10400
+ sourceMode = (await fs27.stat(sourceFile)).mode & 511;
9423
10401
  const { output, warnings: interpWarnings } = interpolate(raw, answers);
9424
10402
  templateContent = output;
9425
10403
  for (const key of interpWarnings) {
@@ -9434,7 +10412,7 @@ var FileSystemFileEmitter = class {
9434
10412
  const templateHash = sha256(templateContent);
9435
10413
  let existingContent = null;
9436
10414
  try {
9437
- existingContent = await fs22.readFile(destFile, "utf-8");
10415
+ existingContent = await fs27.readFile(destFile, "utf-8");
9438
10416
  } catch {
9439
10417
  }
9440
10418
  if (existingContent !== null) {
@@ -9444,7 +10422,7 @@ var FileSystemFileEmitter = class {
9444
10422
  if (!isAlreadyIdentical && !wasGeneratedByHexagen) {
9445
10423
  const conflictDest = conflictFilePath(destFile);
9446
10424
  await atomicWrite(conflictDest, templateContent, sourceMode);
9447
- const rel = path28__default.relative(projectRoot, conflictDest);
10425
+ const rel = path34__default.relative(projectRoot, conflictDest);
9448
10426
  warnings.push(`⚠️ Conflict: ${outputRelPath} has local changes.
9449
10427
  New version written to ${rel}
9450
10428
  Review and merge manually, then delete the conflict file.`);
@@ -9458,18 +10436,18 @@ var FileSystemFileEmitter = class {
9458
10436
  }
9459
10437
  };
9460
10438
  async function atomicWrite(filePath, content, mode) {
9461
- await fs22.mkdir(path28__default.dirname(filePath), { recursive: true });
10439
+ await fs27.mkdir(path34__default.dirname(filePath), { recursive: true });
9462
10440
  const tmp = `${filePath}.tmp.${Date.now()}`;
9463
10441
  try {
9464
- await fs22.writeFile(tmp, content, "utf-8");
10442
+ await fs27.writeFile(tmp, content, "utf-8");
9465
10443
  if (mode !== void 0 && (mode & 73) !== 0) {
9466
- const created = (await fs22.stat(tmp)).mode & 511;
10444
+ const created = (await fs27.stat(tmp)).mode & 511;
9467
10445
  const execBits = mode & 73 & ~process.umask();
9468
- await fs22.chmod(tmp, created | execBits);
10446
+ await fs27.chmod(tmp, created | execBits);
9469
10447
  }
9470
- await fs22.rename(tmp, filePath);
10448
+ await fs27.rename(tmp, filePath);
9471
10449
  } catch (err3) {
9472
- await fs22.rm(tmp, { force: true }).catch(() => {
10450
+ await fs27.rm(tmp, { force: true }).catch(() => {
9473
10451
  });
9474
10452
  throw err3;
9475
10453
  }
@@ -9479,9 +10457,9 @@ function sha256(content) {
9479
10457
  }
9480
10458
  var FileSystemTemplateConfigStore = class {
9481
10459
  async load(projectRoot) {
9482
- const configPath = path28__default.join(projectRoot, TEMPLATE_CONFIG_FILE);
10460
+ const configPath = path34__default.join(projectRoot, TEMPLATE_CONFIG_FILE);
9483
10461
  try {
9484
- const raw = await fs22.readFile(configPath, "utf-8");
10462
+ const raw = await fs27.readFile(configPath, "utf-8");
9485
10463
  return JSON.parse(raw);
9486
10464
  } catch (err3) {
9487
10465
  if (err3.code === "ENOENT")
@@ -9490,10 +10468,10 @@ var FileSystemTemplateConfigStore = class {
9490
10468
  }
9491
10469
  }
9492
10470
  async save(projectRoot, config) {
9493
- const configPath = path28__default.join(projectRoot, TEMPLATE_CONFIG_FILE);
10471
+ const configPath = path34__default.join(projectRoot, TEMPLATE_CONFIG_FILE);
9494
10472
  const tmp = `${configPath}.tmp.${Date.now()}`;
9495
- await fs22.writeFile(tmp, JSON.stringify(config, null, 2), "utf-8");
9496
- await fs22.rename(tmp, configPath);
10473
+ await fs27.writeFile(tmp, JSON.stringify(config, null, 2), "utf-8");
10474
+ await fs27.rename(tmp, configPath);
9497
10475
  }
9498
10476
  };
9499
10477
 
@@ -9728,8 +10706,8 @@ Installed templates: ${installed}
9728
10706
  function getManifestPath3(cwd) {
9729
10707
  return join(cwd, ".architecture", "manifest.yaml");
9730
10708
  }
9731
- async function loadManifest4(path32) {
9732
- const result = await yamlService.loadManifest(path32);
10709
+ async function loadManifest4(path38) {
10710
+ const result = await yamlService.loadManifest(path38);
9733
10711
  if (!result.success) {
9734
10712
  throw result.error;
9735
10713
  }
@@ -9927,35 +10905,35 @@ var FileSystemWorkspaceAdapter = class {
9927
10905
  }
9928
10906
  workspaceRoot;
9929
10907
  listPackages() {
9930
- const packagesDir = path28.join(this.workspaceRoot, "packages");
9931
- if (!fs19.existsSync(packagesDir)) {
10908
+ const packagesDir = path34.join(this.workspaceRoot, "packages");
10909
+ if (!fs24.existsSync(packagesDir)) {
9932
10910
  return [];
9933
10911
  }
9934
- return fs19.readdirSync(packagesDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
10912
+ return fs24.readdirSync(packagesDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
9935
10913
  }
9936
10914
  listApps() {
9937
- const appsDir = path28.join(this.workspaceRoot, "apps");
9938
- if (!fs19.existsSync(appsDir)) {
10915
+ const appsDir = path34.join(this.workspaceRoot, "apps");
10916
+ if (!fs24.existsSync(appsDir)) {
9939
10917
  return [];
9940
10918
  }
9941
- return fs19.readdirSync(appsDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
10919
+ return fs24.readdirSync(appsDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
9942
10920
  }
9943
10921
  getSourceFiles(dir) {
9944
- if (!fs19.existsSync(dir)) {
10922
+ if (!fs24.existsSync(dir)) {
9945
10923
  return [];
9946
10924
  }
9947
- const entries = fs19.readdirSync(dir, { withFileTypes: true });
10925
+ const entries = fs24.readdirSync(dir, { withFileTypes: true });
9948
10926
  return entries.map((entry) => ({
9949
- path: path28.join(dir, entry.name),
10927
+ path: path34.join(dir, entry.name),
9950
10928
  isDirectory: entry.isDirectory()
9951
10929
  }));
9952
10930
  }
9953
10931
  fileExists(filePath) {
9954
- return fs19.existsSync(filePath);
10932
+ return fs24.existsSync(filePath);
9955
10933
  }
9956
10934
  readFile(filePath) {
9957
10935
  try {
9958
- return fs19.readFileSync(filePath, "utf-8");
10936
+ return fs24.readFileSync(filePath, "utf-8");
9959
10937
  } catch {
9960
10938
  return null;
9961
10939
  }
@@ -10374,15 +11352,15 @@ async function updateBarrelExport(sourceFile, oldName, newName) {
10374
11352
  }
10375
11353
  async function updateManifestEntry(workspaceRoot, updateFn) {
10376
11354
  try {
10377
- const manifestPath = path28__default.join(
11355
+ const manifestPath = path34__default.join(
10378
11356
  workspaceRoot,
10379
11357
  ".architecture/manifest.yaml"
10380
11358
  );
10381
- const content = await fs22.readFile(manifestPath, "utf-8");
11359
+ const content = await fs27.readFile(manifestPath, "utf-8");
10382
11360
  const manifest = yaml9.load(content);
10383
11361
  updateFn(manifest);
10384
11362
  const updatedContent = yaml9.dump(manifest, { indent: 2 });
10385
- await fs22.writeFile(manifestPath, updatedContent, "utf-8");
11363
+ await fs27.writeFile(manifestPath, updatedContent, "utf-8");
10386
11364
  return ok2(void 0);
10387
11365
  } catch (error) {
10388
11366
  return err2(error);
@@ -10446,7 +11424,7 @@ var RenamePortPattern = class {
10446
11424
  (f) => f.reason.includes("Declares")
10447
11425
  );
10448
11426
  for (const file of portFiles) {
10449
- const filePath = path28__default.join(this.workspaceRoot, file.path);
11427
+ const filePath = path34__default.join(this.workspaceRoot, file.path);
10450
11428
  const sourceFile = this.project.addSourceFileAtPath(filePath);
10451
11429
  const existingInterface = sourceFile.getInterface(request.newName);
10452
11430
  if (existingInterface) {
@@ -10468,7 +11446,7 @@ var RenamePortPattern = class {
10468
11446
  const warnings = [];
10469
11447
  try {
10470
11448
  for (const file of impact.filesToModify) {
10471
- const filePath = path28__default.join(this.workspaceRoot, file.path);
11449
+ const filePath = path34__default.join(this.workspaceRoot, file.path);
10472
11450
  if (file.path.endsWith(".ts") || file.path.endsWith(".tsx")) {
10473
11451
  try {
10474
11452
  this.project.addSourceFileAtPath(filePath);
@@ -10571,7 +11549,7 @@ var RenamePortPattern = class {
10571
11549
  */
10572
11550
  async renamePortFile(relativePath, oldName, newName) {
10573
11551
  try {
10574
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11552
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
10575
11553
  const sourceFile = this.project.getSourceFile(filePath);
10576
11554
  if (!sourceFile) {
10577
11555
  return err2(new Error(`Source file not found: ${relativePath}`));
@@ -10584,17 +11562,17 @@ var RenamePortPattern = class {
10584
11562
  if (typeAlias) {
10585
11563
  typeAlias.rename(newName);
10586
11564
  }
10587
- const oldFileName = path28__default.basename(relativePath);
11565
+ const oldFileName = path34__default.basename(relativePath);
10588
11566
  const newFileName = oldFileName.replace(
10589
11567
  toKebabCase(oldName),
10590
11568
  toKebabCase(newName)
10591
11569
  );
10592
11570
  if (oldFileName !== newFileName) {
10593
- const newFilePath = path28__default.join(path28__default.dirname(filePath), newFileName);
11571
+ const newFilePath = path34__default.join(path34__default.dirname(filePath), newFileName);
10594
11572
  await sourceFile.move(newFilePath);
10595
11573
  return ok2([
10596
11574
  relativePath,
10597
- path28__default.relative(this.workspaceRoot, newFilePath)
11575
+ path34__default.relative(this.workspaceRoot, newFilePath)
10598
11576
  ]);
10599
11577
  }
10600
11578
  return ok2([relativePath]);
@@ -10607,7 +11585,7 @@ var RenamePortPattern = class {
10607
11585
  */
10608
11586
  async updateImports(relativePath, oldName, newName) {
10609
11587
  try {
10610
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11588
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
10611
11589
  const sourceFile = this.project.getSourceFile(filePath);
10612
11590
  if (!sourceFile) {
10613
11591
  return ok2([]);
@@ -10623,7 +11601,7 @@ var RenamePortPattern = class {
10623
11601
  */
10624
11602
  async updateBarrelExport(relativePath, oldName, newName) {
10625
11603
  try {
10626
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11604
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
10627
11605
  const sourceFile = this.project.getSourceFile(filePath);
10628
11606
  if (!sourceFile) {
10629
11607
  return ok2([]);
@@ -10666,7 +11644,7 @@ var RenamePortPattern = class {
10666
11644
  */
10667
11645
  async updateTestDouble(relativePath, oldName, newName) {
10668
11646
  try {
10669
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11647
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
10670
11648
  const sourceFile = this.project.getSourceFile(filePath);
10671
11649
  if (!sourceFile) {
10672
11650
  return ok2([]);
@@ -10696,17 +11674,17 @@ var RenamePortPattern = class {
10696
11674
  );
10697
11675
  modified = modified || importsModified;
10698
11676
  if (modified) {
10699
- const oldFileName = path28__default.basename(relativePath);
11677
+ const oldFileName = path34__default.basename(relativePath);
10700
11678
  const newFileName = oldFileName.replace(
10701
11679
  toKebabCase(oldName),
10702
11680
  toKebabCase(newName)
10703
11681
  );
10704
11682
  if (oldFileName !== newFileName) {
10705
- const newFilePath = path28__default.join(path28__default.dirname(filePath), newFileName);
11683
+ const newFilePath = path34__default.join(path34__default.dirname(filePath), newFileName);
10706
11684
  await sourceFile.move(newFilePath);
10707
11685
  return ok2([
10708
11686
  relativePath,
10709
- path28__default.relative(this.workspaceRoot, newFilePath)
11687
+ path34__default.relative(this.workspaceRoot, newFilePath)
10710
11688
  ]);
10711
11689
  }
10712
11690
  }
@@ -10779,7 +11757,7 @@ var RenameUseCasePattern = class {
10779
11757
  const warnings = [];
10780
11758
  try {
10781
11759
  for (const file of impact.filesToModify) {
10782
- const filePath = path28__default.join(this.workspaceRoot, file.path);
11760
+ const filePath = path34__default.join(this.workspaceRoot, file.path);
10783
11761
  if (file.path.endsWith(".ts") || file.path.endsWith(".tsx")) {
10784
11762
  try {
10785
11763
  this.project.addSourceFileAtPath(filePath);
@@ -10890,7 +11868,7 @@ var RenameUseCasePattern = class {
10890
11868
  */
10891
11869
  async renameUseCaseFile(relativePath, oldName, newName) {
10892
11870
  try {
10893
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11871
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
10894
11872
  const sourceFile = this.project.getSourceFile(filePath);
10895
11873
  if (!sourceFile) {
10896
11874
  return err2(new Error(`Source file not found: ${relativePath}`));
@@ -10899,17 +11877,17 @@ var RenameUseCasePattern = class {
10899
11877
  if (classDecl) {
10900
11878
  classDecl.rename(newName);
10901
11879
  }
10902
- const oldFileName = path28__default.basename(relativePath);
11880
+ const oldFileName = path34__default.basename(relativePath);
10903
11881
  const newFileName = oldFileName.replace(
10904
11882
  toKebabCase(oldName),
10905
11883
  toKebabCase(newName)
10906
11884
  );
10907
11885
  if (oldFileName !== newFileName) {
10908
- const newFilePath = path28__default.join(path28__default.dirname(filePath), newFileName);
11886
+ const newFilePath = path34__default.join(path34__default.dirname(filePath), newFileName);
10909
11887
  await sourceFile.move(newFilePath);
10910
11888
  return ok2([
10911
11889
  relativePath,
10912
- path28__default.relative(this.workspaceRoot, newFilePath)
11890
+ path34__default.relative(this.workspaceRoot, newFilePath)
10913
11891
  ]);
10914
11892
  }
10915
11893
  return ok2([relativePath]);
@@ -10919,7 +11897,7 @@ var RenameUseCasePattern = class {
10919
11897
  }
10920
11898
  async updateImports(relativePath, oldName, newName) {
10921
11899
  try {
10922
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11900
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
10923
11901
  const sourceFile = this.project.getSourceFile(filePath);
10924
11902
  if (!sourceFile) {
10925
11903
  return ok2([]);
@@ -10935,7 +11913,7 @@ var RenameUseCasePattern = class {
10935
11913
  */
10936
11914
  async updateBarrelExport(relativePath, oldName, newName) {
10937
11915
  try {
10938
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11916
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
10939
11917
  const sourceFile = this.project.getSourceFile(filePath);
10940
11918
  if (!sourceFile) {
10941
11919
  return ok2([]);
@@ -10972,24 +11950,24 @@ var RenameUseCasePattern = class {
10972
11950
  */
10973
11951
  async updateTestFile(relativePath, oldName, newName) {
10974
11952
  try {
10975
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11953
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
10976
11954
  const sourceFile = this.project.getSourceFile(filePath);
10977
11955
  if (!sourceFile) {
10978
11956
  return ok2([]);
10979
11957
  }
10980
11958
  const modified = await updateImports(sourceFile, oldName, newName);
10981
11959
  if (modified) {
10982
- const oldFileName = path28__default.basename(relativePath);
11960
+ const oldFileName = path34__default.basename(relativePath);
10983
11961
  const newFileName = oldFileName.replace(
10984
11962
  toKebabCase(oldName),
10985
11963
  toKebabCase(newName)
10986
11964
  );
10987
11965
  if (oldFileName !== newFileName) {
10988
- const newFilePath = path28__default.join(path28__default.dirname(filePath), newFileName);
11966
+ const newFilePath = path34__default.join(path34__default.dirname(filePath), newFileName);
10989
11967
  await sourceFile.move(newFilePath);
10990
11968
  return ok2([
10991
11969
  relativePath,
10992
- path28__default.relative(this.workspaceRoot, newFilePath)
11970
+ path34__default.relative(this.workspaceRoot, newFilePath)
10993
11971
  ]);
10994
11972
  }
10995
11973
  }
@@ -11000,7 +11978,7 @@ var RenameUseCasePattern = class {
11000
11978
  }
11001
11979
  async updateCompositionRoot(relativePath, oldName, newName) {
11002
11980
  try {
11003
- const filePath = path28__default.join(this.workspaceRoot, relativePath);
11981
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
11004
11982
  const sourceFile = this.project.getSourceFile(filePath);
11005
11983
  if (!sourceFile) {
11006
11984
  return ok2([]);
@@ -11070,7 +12048,7 @@ var RenameEntityPattern = class {
11070
12048
  if (file.path.endsWith(".ts") || file.path.endsWith(".tsx")) {
11071
12049
  try {
11072
12050
  this.project.addSourceFileAtPath(
11073
- path28__default.join(this.workspaceRoot, file.path)
12051
+ path34__default.join(this.workspaceRoot, file.path)
11074
12052
  );
11075
12053
  } catch {
11076
12054
  }
@@ -11128,7 +12106,7 @@ var RenameEntityPattern = class {
11128
12106
  async renameEntityFile(relativePath, oldName, newName) {
11129
12107
  try {
11130
12108
  const sourceFile = this.project.getSourceFile(
11131
- path28__default.join(this.workspaceRoot, relativePath)
12109
+ path34__default.join(this.workspaceRoot, relativePath)
11132
12110
  );
11133
12111
  if (!sourceFile) return err2(new Error(`File not found: ${relativePath}`));
11134
12112
  const classDecl = sourceFile.getClass(oldName);
@@ -11145,7 +12123,7 @@ var RenameEntityPattern = class {
11145
12123
  async updateReferences(relativePath, oldName, newName) {
11146
12124
  try {
11147
12125
  const sourceFile = this.project.getSourceFile(
11148
- path28__default.join(this.workspaceRoot, relativePath)
12126
+ path34__default.join(this.workspaceRoot, relativePath)
11149
12127
  );
11150
12128
  if (!sourceFile) return ok2([]);
11151
12129
  let modified = false;
@@ -11164,11 +12142,11 @@ var RenameEntityPattern = class {
11164
12142
  }
11165
12143
  async updateManifest(oldName, newName) {
11166
12144
  try {
11167
- const manifestPath = path28__default.join(
12145
+ const manifestPath = path34__default.join(
11168
12146
  this.workspaceRoot,
11169
12147
  ".architecture/manifest.yaml"
11170
12148
  );
11171
- const content = await fs22.readFile(manifestPath, "utf-8");
12149
+ const content = await fs27.readFile(manifestPath, "utf-8");
11172
12150
  const manifest = yaml9.load(content);
11173
12151
  if (manifest.bounded_contexts) {
11174
12152
  for (const context of manifest.bounded_contexts) {
@@ -11180,7 +12158,7 @@ var RenameEntityPattern = class {
11180
12158
  }
11181
12159
  }
11182
12160
  }
11183
- await fs22.writeFile(
12161
+ await fs27.writeFile(
11184
12162
  manifestPath,
11185
12163
  yaml9.dump(manifest, { indent: 2 }),
11186
12164
  "utf-8"
@@ -11864,7 +12842,7 @@ var manifestSplitCommander = new Command("split").description("Split monolithic
11864
12842
  const dryRun = options.dryRun ?? false;
11865
12843
  try {
11866
12844
  const workspaceRoot = await findWorkspaceRoot({});
11867
- const monolithicManifestPath = path28__default.join(
12845
+ const monolithicManifestPath = path34__default.join(
11868
12846
  workspaceRoot,
11869
12847
  ".architecture/manifest.yaml"
11870
12848
  );
@@ -11873,7 +12851,7 @@ var manifestSplitCommander = new Command("split").description("Split monolithic
11873
12851
  );
11874
12852
  let manifestContent;
11875
12853
  try {
11876
- manifestContent = await fs22.readFile(monolithicManifestPath, "utf-8");
12854
+ manifestContent = await fs27.readFile(monolithicManifestPath, "utf-8");
11877
12855
  } catch {
11878
12856
  throw new Error(`Failed to read manifest.yaml. Does it exist?`);
11879
12857
  }
@@ -11901,14 +12879,14 @@ Validation successful. Found ${contexts.length} bounded contexts.`
11901
12879
  const planes = rawYaml.planes ?? {};
11902
12880
  const planeLookup = buildPlaneLookup(planes);
11903
12881
  console.log("Splitting manifest into the new directory structure...");
11904
- const archDir = path28__default.join(workspaceRoot, ".architecture");
11905
- const contextsDir = path28__default.join(archDir, "contexts");
11906
- const appsDir = path28__default.join(archDir, "apps");
11907
- const invariantsDir = path28__default.join(archDir, "invariants");
12882
+ const archDir = path34__default.join(workspaceRoot, ".architecture");
12883
+ const contextsDir = path34__default.join(archDir, "contexts");
12884
+ const appsDir = path34__default.join(archDir, "apps");
12885
+ const invariantsDir = path34__default.join(archDir, "invariants");
11908
12886
  if (!dryRun) {
11909
- await fs22.mkdir(contextsDir, { recursive: true });
11910
- await fs22.mkdir(appsDir, { recursive: true });
11911
- await fs22.mkdir(invariantsDir, { recursive: true });
12887
+ await fs27.mkdir(contextsDir, { recursive: true });
12888
+ await fs27.mkdir(appsDir, { recursive: true });
12889
+ await fs27.mkdir(invariantsDir, { recursive: true });
11912
12890
  }
11913
12891
  const CATEGORY_B_KEYS = /* @__PURE__ */ new Set(["monorepo", "generator"]);
11914
12892
  const workspaceConfig = {};
@@ -11948,12 +12926,12 @@ Validation successful. Found ${contexts.length} bounded contexts.`
11948
12926
  }
11949
12927
  for (const ctx of contexts) {
11950
12928
  const plane = planeLookup.get(ctx.name) ?? ctx.plane ?? "core";
11951
- const ctxDir = path28__default.join(contextsDir, plane, ctx.name);
12929
+ const ctxDir = path34__default.join(contextsDir, plane, ctx.name);
11952
12930
  const contextData = normalizeContextData(
11953
12931
  extractContextData(ctx)
11954
12932
  );
11955
12933
  contextData.plane = plane;
11956
- const ctxFilePath = path28__default.join(ctxDir, "context.yaml");
12934
+ const ctxFilePath = path34__default.join(ctxDir, "context.yaml");
11957
12935
  const ctxYaml = yaml9.dump(contextData, {
11958
12936
  noRefs: true,
11959
12937
  sortKeys: false,
@@ -11962,8 +12940,8 @@ Validation successful. Found ${contexts.length} bounded contexts.`
11962
12940
  if (dryRun) {
11963
12941
  console.log(`[dry-run] Would create: ${ctxFilePath}`);
11964
12942
  } else {
11965
- await fs22.mkdir(ctxDir, { recursive: true });
11966
- await fs22.writeFile(ctxFilePath, ctxYaml, "utf-8");
12943
+ await fs27.mkdir(ctxDir, { recursive: true });
12944
+ await fs27.writeFile(ctxFilePath, ctxYaml, "utf-8");
11967
12945
  }
11968
12946
  indexManifest.bounded_contexts.push({
11969
12947
  name: ctx.name,
@@ -11979,7 +12957,7 @@ Validation successful. Found ${contexts.length} bounded contexts.`
11979
12957
  if (typeof app === "object" && app !== null && "name" in app) {
11980
12958
  const typedApp = app;
11981
12959
  const appName = typedApp.name;
11982
- const appFilePath = path28__default.join(appsDir, `${appName}.app.yaml`);
12960
+ const appFilePath = path34__default.join(appsDir, `${appName}.app.yaml`);
11983
12961
  const appYaml = yaml9.dump(app, {
11984
12962
  noRefs: true,
11985
12963
  sortKeys: false,
@@ -11988,7 +12966,7 @@ Validation successful. Found ${contexts.length} bounded contexts.`
11988
12966
  if (dryRun) {
11989
12967
  console.log(`[dry-run] Would create: ${appFilePath}`);
11990
12968
  } else {
11991
- await fs22.writeFile(appFilePath, appYaml, "utf-8");
12969
+ await fs27.writeFile(appFilePath, appYaml, "utf-8");
11992
12970
  }
11993
12971
  indexManifest.apps.push({
11994
12972
  name: appName,
@@ -11996,7 +12974,7 @@ Validation successful. Found ${contexts.length} bounded contexts.`
11996
12974
  });
11997
12975
  }
11998
12976
  }
11999
- const workspaceConfigPath = path28__default.join(archDir, "workspace.config.yaml");
12977
+ const workspaceConfigPath = path34__default.join(archDir, "workspace.config.yaml");
12000
12978
  const workspaceConfigYaml = yaml9.dump(workspaceConfig, {
12001
12979
  noRefs: true,
12002
12980
  sortKeys: false,
@@ -12007,7 +12985,7 @@ Validation successful. Found ${contexts.length} bounded contexts.`
12007
12985
  console.log("\n--- Preview of workspace.config.yaml ---\n");
12008
12986
  console.log(workspaceConfigYaml);
12009
12987
  } else {
12010
- await fs22.writeFile(workspaceConfigPath, workspaceConfigYaml, "utf-8");
12988
+ await fs27.writeFile(workspaceConfigPath, workspaceConfigYaml, "utf-8");
12011
12989
  }
12012
12990
  const indexYaml = yaml9.dump(indexManifest, {
12013
12991
  noRefs: true,
@@ -12028,9 +13006,9 @@ Validation successful. Found ${contexts.length} bounded contexts.`
12028
13006
  console.log(header + indexYaml);
12029
13007
  } else {
12030
13008
  const backupPath = monolithicManifestPath + ".pre-split-backup";
12031
- await fs22.copyFile(monolithicManifestPath, backupPath);
13009
+ await fs27.copyFile(monolithicManifestPath, backupPath);
12032
13010
  console.log(`Backup created at ${backupPath}`);
12033
- await fs22.writeFile(monolithicManifestPath, header + indexYaml, "utf-8");
13011
+ await fs27.writeFile(monolithicManifestPath, header + indexYaml, "utf-8");
12034
13012
  }
12035
13013
  console.log("\n✅ Manifest split completed successfully!");
12036
13014
  if (dryRun) {
@@ -12077,41 +13055,53 @@ function createLogger() {
12077
13055
  };
12078
13056
  }
12079
13057
  var logger = createLogger();
12080
- function readVersion() {
12081
- try {
12082
- const pkgPath = join(
12083
- dirname(fileURLToPath(import.meta.url)),
12084
- "..",
12085
- "package.json"
12086
- );
12087
- return JSON.parse(readFileSync(pkgPath, "utf8")).version ?? "0.0.0";
12088
- } catch {
12089
- return "0.0.0";
12090
- }
12091
- }
12092
13058
  function buildProgram() {
12093
13059
  const program2 = new Command();
12094
- program2.name("hexagen").description("HexaGen Monaco — Generate and sync modular monorepos").version(readVersion());
12095
- program2.command("sync").description("Run the HexaGen sync engine to generate artifacts").option("--dry-run", "Preview changes without writing files").option("--force", "Overwrite non-generated files in packages").option(
13060
+ program2.name("hexagen").description("HexaGen Monaco — Generate and sync modular monorepos").version(resolveToolchainVersion());
13061
+ program2.command("sync").description("Run the HexaGen sync engine to generate artifacts").option("--dry-run", "Preview changes without writing files").option(
13062
+ "--check",
13063
+ "CI drift gate: implies --dry-run and exits non-zero iff any change would be made (created/updated/deleted). A converged tree exits 0."
13064
+ ).option("--force", "Overwrite non-generated files in packages").option(
12096
13065
  "--force-root",
12097
13066
  "Overwrite protected root files (turbo.json, .gitignore)"
12098
- ).option("--allow-dirty", "Skip git clean check (for development)").option("--strict", "Fail on architecture linter warnings").action(async (options) => {
13067
+ ).option("--allow-dirty", "Skip git clean check (for development)").option("--strict", "Fail on architecture linter warnings").option(
13068
+ "--only <pattern...>",
13069
+ "Limit writes to workspace-relative paths/globs (e.g. packages/shared, 'packages/*/tsconfig.json'). Direct targets only — no dependency fan-out; run a full sync for cross-package changes."
13070
+ ).option(
13071
+ "--report <path>",
13072
+ "Migration-report destination, resolved against the workspace root (absolute paths allowed; parent dirs are created). Real runs default to SYNC-MIGRATION-REPORT.md; --dry-run writes no report unless this is set."
13073
+ ).action(async (options) => {
13074
+ const check = options.check ?? false;
12099
13075
  const flags = {
12100
- dryRun: options.dryRun ?? false,
13076
+ dryRun: (options.dryRun || options.check) ?? false,
12101
13077
  force: options.force ?? false,
12102
13078
  forceRoot: options.forceRoot ?? false,
12103
13079
  allowDirty: options.allowDirty ?? false,
12104
13080
  strict: options.strict ?? false,
13081
+ only: options.only,
13082
+ report: options.report,
12105
13083
  mode: "self-regen",
12106
13084
  logger
12107
13085
  };
12108
13086
  try {
12109
13087
  const engine = new SyncEngine(flags);
12110
- await engine.run();
13088
+ const summary = await engine.run();
13089
+ if (summary.errors > 0) {
13090
+ console.error(
13091
+ `Sync incomplete: ${summary.errors} generator failure(s) — see the FAILED row(s) above.`
13092
+ );
13093
+ process.exitCode = 1;
13094
+ }
13095
+ if (check && summary.totalOps > 0) {
13096
+ console.error(
13097
+ `Drift detected: ${summary.totalOps} pending change(s) (${summary.created} to create, ${summary.updated} to update, ${summary.deleted} to delete). Run \`hexagen sync\` to converge.`
13098
+ );
13099
+ process.exitCode = 1;
13100
+ }
12111
13101
  } catch (err3) {
12112
13102
  const message = err3 instanceof Error ? err3.message : "Unknown fatal error";
12113
13103
  console.error(`Fatal sync error: ${message}`);
12114
- process.exit(1);
13104
+ process.exitCode = 1;
12115
13105
  }
12116
13106
  });
12117
13107
  const archCommand = program2.command("arch").description("Manage architecture manifest.yaml");
@@ -12147,11 +13137,11 @@ function buildProgram() {
12147
13137
  }
12148
13138
  var program = buildProgram();
12149
13139
  try {
12150
- program.parse(process.argv);
13140
+ await program.parseAsync(process.argv);
12151
13141
  } catch (err3) {
12152
13142
  const message = err3 instanceof Error ? err3.message : "Unknown CLI error";
12153
13143
  console.error(`CLI error: ${message}`);
12154
- process.exit(1);
13144
+ process.exitCode = 1;
12155
13145
  }
12156
13146
  //# sourceMappingURL=cli.js.map
12157
13147
  //# sourceMappingURL=cli.js.map