@hexagen-monaco/sync 0.6.0 → 0.7.1

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 (82) hide show
  1. package/dist/application/use-cases/index.d.ts +1 -0
  2. package/dist/application/use-cases/index.d.ts.map +1 -1
  3. package/dist/application/use-cases/migrate-manifest.use-case.d.ts +48 -0
  4. package/dist/application/use-cases/migrate-manifest.use-case.d.ts.map +1 -0
  5. package/dist/cli.js +1009 -538
  6. package/dist/cli.js.map +1 -1
  7. package/dist/commands/arch/validate.d.ts.map +1 -1
  8. package/dist/commands/manifest/index.d.ts.map +1 -1
  9. package/dist/commands/manifest/migrate.d.ts +10 -0
  10. package/dist/commands/manifest/migrate.d.ts.map +1 -0
  11. package/dist/config.d.ts +17 -0
  12. package/dist/config.d.ts.map +1 -1
  13. package/dist/domain/types.d.ts +8 -1
  14. package/dist/domain/types.d.ts.map +1 -1
  15. package/dist/fs-utils.d.ts +4 -4
  16. package/dist/fs-utils.d.ts.map +1 -1
  17. package/dist/generators/apps-framework-templates.d.ts.map +1 -1
  18. package/dist/generators/apps.d.ts.map +1 -1
  19. package/dist/generators/architecture-file-templates.d.ts +1 -1
  20. package/dist/generators/architecture-file-templates.d.ts.map +1 -1
  21. package/dist/generators/architecture-files.d.ts.map +1 -1
  22. package/dist/generators/barrels/recursive.d.ts +2 -3
  23. package/dist/generators/barrels/recursive.d.ts.map +1 -1
  24. package/dist/generators/barrels.d.ts +2 -3
  25. package/dist/generators/barrels.d.ts.map +1 -1
  26. package/dist/generators/cross-context.d.ts.map +1 -1
  27. package/dist/generators/eslint.d.ts.map +1 -1
  28. package/dist/generators/layer-folders.d.ts +23 -6
  29. package/dist/generators/layer-folders.d.ts.map +1 -1
  30. package/dist/generators/package-json.d.ts +2 -3
  31. package/dist/generators/package-json.d.ts.map +1 -1
  32. package/dist/generators/reap.d.ts +7 -3
  33. package/dist/generators/reap.d.ts.map +1 -1
  34. package/dist/generators/root-file-templates.d.ts +1 -1
  35. package/dist/generators/root-file-templates.d.ts.map +1 -1
  36. package/dist/generators/root-files.d.ts.map +1 -1
  37. package/dist/generators/shared-kernel.d.ts.map +1 -1
  38. package/dist/generators/stubs.d.ts.map +1 -1
  39. package/dist/generators/tsconfig.d.ts.map +1 -1
  40. package/dist/index.js +724 -405
  41. package/dist/index.js.map +1 -1
  42. package/dist/journal.d.ts +64 -0
  43. package/dist/journal.d.ts.map +1 -0
  44. package/dist/linter.d.ts.map +1 -1
  45. package/dist/migration-report.d.ts +13 -2
  46. package/dist/migration-report.d.ts.map +1 -1
  47. package/dist/results.d.ts +74 -0
  48. package/dist/results.d.ts.map +1 -1
  49. package/dist/sync-engine-helpers.d.ts.map +1 -1
  50. package/dist/sync-engine-init.d.ts +24 -2
  51. package/dist/sync-engine-init.d.ts.map +1 -1
  52. package/dist/sync-engine.d.ts +14 -1
  53. package/dist/sync-engine.d.ts.map +1 -1
  54. package/dist/templates/agents-md/files/AGENTS.md +7 -5
  55. package/dist/templates/env-setup/files/.gitignore.hexagen +4 -3
  56. package/dist/templates/observability/files/.agents/logging.md +34 -0
  57. package/dist/templates/observability/manifest.json +1 -0
  58. package/dist/toolchain-version.d.ts +14 -0
  59. package/dist/toolchain-version.d.ts.map +1 -0
  60. package/package.json +1 -1
  61. package/dist/application/use-cases/stub-generation.use-case.d.ts +0 -23
  62. package/dist/application/use-cases/stub-generation.use-case.d.ts.map +0 -1
  63. package/dist/generators/migration-assistant.d.ts +0 -7
  64. package/dist/generators/migration-assistant.d.ts.map +0 -1
  65. package/dist/generators/migration-audit.d.ts +0 -28
  66. package/dist/generators/migration-audit.d.ts.map +0 -1
  67. package/dist/generators/migration-stubs.d.ts +0 -7
  68. package/dist/generators/migration-stubs.d.ts.map +0 -1
  69. package/dist/generators/test-generator.d.ts +0 -7
  70. package/dist/generators/test-generator.d.ts.map +0 -1
  71. package/dist/generators/test-templates/data-builder.d.ts +0 -2
  72. package/dist/generators/test-templates/data-builder.d.ts.map +0 -1
  73. package/dist/generators/test-templates/enhanced-test-double.d.ts +0 -2
  74. package/dist/generators/test-templates/enhanced-test-double.d.ts.map +0 -1
  75. package/dist/generators/test-templates/index.d.ts +0 -5
  76. package/dist/generators/test-templates/index.d.ts.map +0 -1
  77. package/dist/generators/test-templates/integration-test.d.ts +0 -2
  78. package/dist/generators/test-templates/integration-test.d.ts.map +0 -1
  79. package/dist/generators/test-templates/unit-test.d.ts +0 -2
  80. package/dist/generators/test-templates/unit-test.d.ts.map +0 -1
  81. package/dist/generators/wiring.d.ts +0 -20
  82. 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 fs22 from 'fs';
3
- import fs22__default, { mkdirSync, writeFileSync, renameSync, unlinkSync, existsSync, readFileSync, realpathSync, lstatSync, createWriteStream } from 'fs';
4
- import { fileURLToPath } from 'url';
5
- import * as path33 from 'path';
6
- import path33__default, { dirname, join } from 'path';
7
2
  import { Command } from 'commander';
8
- import fs25, { readFile } from 'fs/promises';
9
- import { promisify } from 'util';
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';
8
+ import { promisify, isDeepStrictEqual } 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 = path33__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 = fs25, logger2 = console) {
151
+ constructor(workspaceRoot, fsImpl = fs27, logger2 = console) {
46
152
  this.workspaceRoot = workspaceRoot;
47
- this.lockPath = path33__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 = path33__default.resolve(startDir);
220
+ let dir = path34__default.resolve(startDir);
115
221
  for (; ; ) {
116
- const candidate = path33__default.join(dir, "node_modules", ".bin", BIN_NAME);
117
- if (fs22__default.existsSync(candidate)) return candidate;
118
- const parent = path33__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
  }
@@ -144,7 +250,7 @@ async function runArchLinter(config) {
144
250
  });
145
251
  if (stdout) logger2.info(stdout.trim());
146
252
  if (stderr) logger2.error(stderr.trim());
147
- logger2.info("✅ Architecture is compliant with manifest.yaml.");
253
+ logger2.info("✅ Architecture check passed (arch-linter).");
148
254
  } catch (error) {
149
255
  const message = error instanceof Error && "stderr" in error && error.stderr || error instanceof Error && error.message || "Unknown linter error";
150
256
  logger2.error(`Architectural Integrity Check Failed:
@@ -161,9 +267,24 @@ 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
+ }
167
288
 
168
289
  // src/scope-filter.ts
169
290
  var GLOB_META = /[*?]/;
@@ -230,7 +351,7 @@ function isGeneratedFile(content) {
230
351
  return content.includes(GENERATED_MARKER);
231
352
  }
232
353
  function isProtectedRoot(filePath, config) {
233
- const relative = path33__default.relative(config.workspaceRoot, filePath);
354
+ const relative = path34__default.relative(config.workspaceRoot, filePath);
234
355
  const isRootLevel = !relative.startsWith("packages/") && !relative.startsWith("tools/") && !relative.startsWith("apps/");
235
356
  return isRootLevel && Array.from(protectedFiles).some(
236
357
  (f) => relative.endsWith(f) || relative.includes(f)
@@ -238,12 +359,12 @@ function isProtectedRoot(filePath, config) {
238
359
  }
239
360
  function isInScope(filePath, config) {
240
361
  if (!config.only || config.only.length === 0) return true;
241
- const relativePath = path33__default.relative(config.workspaceRoot, filePath);
362
+ const relativePath = path34__default.relative(config.workspaceRoot, filePath);
242
363
  return matchesScope(relativePath, config.only);
243
364
  }
244
365
  async function safeWriteFileAtomic(filePath, content, config, report, skipGeneratedCheck = false) {
245
366
  const { dryRun, forceRoot, logger: logger2, workspaceRoot } = config;
246
- const relativePath = path33__default.relative(workspaceRoot, filePath);
367
+ const relativePath = path34__default.relative(workspaceRoot, filePath);
247
368
  if (!isInScope(filePath, config)) {
248
369
  logger2.debug(`skipped (outside --only) ${relativePath}`);
249
370
  return "skipped";
@@ -252,7 +373,7 @@ async function safeWriteFileAtomic(filePath, content, config, report, skipGenera
252
373
  let currentContent = "";
253
374
  let currentHash = "";
254
375
  try {
255
- currentContent = await fs25.readFile(filePath, "utf8");
376
+ currentContent = await fs27.readFile(filePath, "utf8");
256
377
  currentHash = contentHash(currentContent);
257
378
  exists = true;
258
379
  } catch (e) {
@@ -282,20 +403,21 @@ async function safeWriteFileAtomic(filePath, content, config, report, skipGenera
282
403
  logger2.info(`[DRY-RUN] would ${action} ${relativePath}`);
283
404
  return exists ? "updated" : "created";
284
405
  }
285
- await fs25.mkdir(path33__default.dirname(filePath), { recursive: true });
286
- const tmpName = `.${path33__default.basename(filePath)}.${crypto.randomUUID()}.tmp`;
287
- const tmpPath = path33__default.join(path33__default.dirname(filePath), tmpName);
288
- await fs25.writeFile(tmpPath, content, { encoding: "utf8" });
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" });
289
411
  try {
290
- await fs25.rename(tmpPath, filePath);
412
+ await fs27.rename(tmpPath, filePath);
291
413
  const status = exists ? "updated" : "created";
292
414
  logger2.info(`${status} ${relativePath}`);
293
415
  return status;
294
416
  } catch (err3) {
295
417
  if (err3 instanceof Error && "code" in err3 && err3.code === "EXDEV") {
296
418
  try {
297
- await fs25.copyFile(tmpPath, filePath);
298
- await fs25.unlink(tmpPath);
419
+ await fs27.copyFile(tmpPath, filePath);
420
+ await fs27.unlink(tmpPath);
299
421
  const status = exists ? "updated" : "created";
300
422
  logger2.info(`${status} ${relativePath}`);
301
423
  return status;
@@ -303,55 +425,79 @@ async function safeWriteFileAtomic(filePath, content, config, report, skipGenera
303
425
  logger2.warn(`EXDEV fallback failed for ${relativePath}: ${copyErr}`);
304
426
  }
305
427
  }
306
- await fs25.unlink(tmpPath).catch(() => {
428
+ await fs27.unlink(tmpPath).catch(() => {
307
429
  });
308
430
  throw err3;
309
431
  }
310
432
  }
311
433
 
312
434
  // src/generators/layer-folders.ts
313
- var GENERATED_MARKER2 = "// @generated by @hexagen/sync";
314
- async function loadYamlSafe(filePath) {
435
+ async function directoryExists(dirPath) {
315
436
  try {
316
- const content = await fs25.readFile(filePath, "utf8");
317
- return yaml9.load(content);
437
+ const stats = await fs27.stat(dirPath);
438
+ return stats.isDirectory();
318
439
  } catch (e) {
319
440
  if (e instanceof Error && "code" in e && e.code === "ENOENT") {
320
- return null;
441
+ return false;
321
442
  }
322
443
  throw e;
323
444
  }
324
445
  }
325
- async function generateBarrelContent(dirPath) {
326
- const exportLines = [];
327
- try {
328
- const entries = await fs25.readdir(dirPath, { withFileTypes: true });
329
- for (const entry of entries) {
330
- if (entry.name === "index.ts" || entry.name.startsWith(".")) continue;
331
- if (entry.isFile() && entry.name.endsWith(".ts")) {
332
- const base = entry.name.replace(/\.ts$/, "");
333
- exportLines.push(`export * from './${base}.js';`);
334
- } else if (entry.isDirectory()) {
335
- exportLines.push(`export * from './${entry.name}/index.js';`);
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 ensureGitkeepCounted(dirPath, config, result) {
460
+ const keepPath = path34__default.join(dirPath, ".gitkeep");
461
+ let entries = null;
462
+ if (await directoryExists(dirPath)) {
463
+ entries = await fs27.readdir(dirPath);
464
+ }
465
+ if (entries !== null) {
466
+ const keepIsOnlyEntry = entries.length === 1 && entries[0] === ".gitkeep";
467
+ if (entries.length > 0 && !keepIsOnlyEntry) {
468
+ return;
469
+ }
470
+ if (keepIsOnlyEntry) {
471
+ const existing = await fs27.readFile(keepPath, "utf8").catch(() => null);
472
+ if (existing !== null && existing !== "") {
473
+ return;
336
474
  }
337
475
  }
476
+ }
477
+ const status = await safeWriteFileAtomic(
478
+ keepPath,
479
+ "",
480
+ config,
481
+ void 0,
482
+ true
483
+ );
484
+ recordWriteStatus(result, keepPath, status);
485
+ }
486
+ async function loadYamlSafe(filePath) {
487
+ try {
488
+ const content = await fs27.readFile(filePath, "utf8");
489
+ return yaml9.load(content);
338
490
  } catch (e) {
339
- if (e instanceof Error && "code" in e && e.code === "ENOENT") ; else {
340
- throw e;
491
+ if (e instanceof Error && "code" in e && e.code === "ENOENT") {
492
+ return null;
341
493
  }
494
+ throw e;
342
495
  }
343
- return exportLines.length > 0 ? `${GENERATED_MARKER2}
344
-
345
- ${exportLines.join("\n")}
346
- ` : `${GENERATED_MARKER2}
347
-
348
- // No exports yet
349
- `;
350
496
  }
351
- async function ensureLayerFolders(moduleDir, layers, config, report) {
497
+ async function ensureLayerFolders(moduleDir, layers, config) {
352
498
  const result = createEmptyResult();
353
499
  const { logger: logger2 } = config;
354
- const layerRulesPath = path33__default.join(
500
+ const layerRulesPath = path34__default.join(
355
501
  config.workspaceRoot,
356
502
  ".architecture",
357
503
  "invariants",
@@ -362,64 +508,22 @@ async function ensureLayerFolders(moduleDir, layers, config, report) {
362
508
  logger2.warn("layer-rules.yaml not found — skipping layer rule enforcement");
363
509
  }
364
510
  for (const [, layerConfig] of Object.entries(layers)) {
365
- const layerPath = path33__default.join(moduleDir, layerConfig.folder);
366
- const barrelPath = path33__default.join(layerPath, "index.ts");
367
- if (!isInScope(barrelPath, config)) {
511
+ const layerPath = path34__default.join(moduleDir, layerConfig.folder);
512
+ if (!isInScope(layerPath, config) && !isInScope(path34__default.join(layerPath, "index.ts"), config)) {
368
513
  continue;
369
514
  }
370
- try {
371
- await fs25.mkdir(layerPath, { recursive: true });
372
- result.created.push(layerPath);
373
- result.totalOps += 1;
374
- } catch (e) {
375
- if (e instanceof Error && "code" in e && e.code === "EEXIST") {
376
- result.skipped.push(layerPath);
377
- } else {
378
- throw e;
379
- }
380
- }
381
- const barrelContent = await generateBarrelContent(layerPath);
382
- const barrelStatus = await safeWriteFileAtomic(
383
- barrelPath,
384
- barrelContent,
385
- config,
386
- report
387
- );
388
- if (barrelStatus === "created") result.created.push(barrelPath);
389
- if (barrelStatus === "updated") result.updated.push(barrelPath);
390
- if (barrelStatus === "skipped" || barrelStatus === "protected")
391
- result.skipped.push(barrelPath);
392
- result.totalOps += barrelStatus === "created" || barrelStatus === "updated" ? 1 : 0;
515
+ await ensureDirectoryCounted(layerPath, config, result);
393
516
  const subfolders = layerConfig.subfolders ?? [];
517
+ if (subfolders.length === 0) {
518
+ await ensureGitkeepCounted(layerPath, config, result);
519
+ }
394
520
  for (const sub of subfolders) {
395
- const subPath = path33__default.join(layerPath, sub);
396
- const subBarrelPath = path33__default.join(subPath, "index.ts");
397
- if (!isInScope(subBarrelPath, config)) {
521
+ const subPath = path34__default.join(layerPath, sub);
522
+ if (!isInScope(subPath, config) && !isInScope(path34__default.join(subPath, "index.ts"), config)) {
398
523
  continue;
399
524
  }
400
- try {
401
- await fs25.mkdir(subPath, { recursive: true });
402
- result.created.push(subPath);
403
- result.totalOps += 1;
404
- } catch (e) {
405
- if (e instanceof Error && "code" in e && e.code === "EEXIST") {
406
- result.skipped.push(subPath);
407
- } else {
408
- throw e;
409
- }
410
- }
411
- const subBarrelContent = await generateBarrelContent(subPath);
412
- const subBarrelStatus = await safeWriteFileAtomic(
413
- subBarrelPath,
414
- subBarrelContent,
415
- config,
416
- report
417
- );
418
- if (subBarrelStatus === "created") result.created.push(subBarrelPath);
419
- if (subBarrelStatus === "updated") result.updated.push(subBarrelPath);
420
- if (subBarrelStatus === "skipped" || subBarrelStatus === "protected")
421
- result.skipped.push(subBarrelPath);
422
- result.totalOps += subBarrelStatus === "created" || subBarrelStatus === "updated" ? 1 : 0;
525
+ await ensureDirectoryCounted(subPath, config, result);
526
+ await ensureGitkeepCounted(subPath, config, result);
423
527
  }
424
528
  }
425
529
  return result;
@@ -440,10 +544,10 @@ var BARREL_EXCLUSIONS = /* @__PURE__ */ new Set([
440
544
  function isExcludedDirectory(name) {
441
545
  return BARREL_EXCLUSIONS.has(name) || name.startsWith(".");
442
546
  }
443
- var GENERATED_MARKER3 = "// @generated by @hexagen/sync";
547
+ var GENERATED_MARKER2 = "// @generated by @hexagen/sync";
444
548
  var LEGACY_GENERATED_MARKER = "— generated by sync.ts";
445
549
  function isGeneratedFile2(content) {
446
- return content.includes(GENERATED_MARKER3) || content.includes(LEGACY_GENERATED_MARKER);
550
+ return content.includes(GENERATED_MARKER2) || content.includes(LEGACY_GENERATED_MARKER);
447
551
  }
448
552
  function contentHash2(content) {
449
553
  return crypto.createHash("sha256").update(content).digest("hex");
@@ -451,18 +555,18 @@ function contentHash2(content) {
451
555
  function detectCircularExports(exportGraph) {
452
556
  const visited = /* @__PURE__ */ new Set();
453
557
  const recursionStack = /* @__PURE__ */ new Set();
454
- const path37 = [];
558
+ const path39 = [];
455
559
  function dfs(node) {
456
560
  if (recursionStack.has(node)) {
457
- const cycleStart = path37.indexOf(node);
458
- return [...path37.slice(cycleStart), node];
561
+ const cycleStart = path39.indexOf(node);
562
+ return [...path39.slice(cycleStart), node];
459
563
  }
460
564
  if (visited.has(node)) {
461
565
  return null;
462
566
  }
463
567
  visited.add(node);
464
568
  recursionStack.add(node);
465
- path37.push(node);
569
+ path39.push(node);
466
570
  const exports$1 = exportGraph.get(node) ?? [];
467
571
  for (const exportPath of exports$1) {
468
572
  const cycle = dfs(exportPath);
@@ -470,7 +574,7 @@ function detectCircularExports(exportGraph) {
470
574
  return cycle;
471
575
  }
472
576
  }
473
- path37.pop();
577
+ path39.pop();
474
578
  recursionStack.delete(node);
475
579
  return null;
476
580
  }
@@ -482,15 +586,15 @@ function detectCircularExports(exportGraph) {
482
586
  }
483
587
  return { hasCircular: false, cycle: null };
484
588
  }
485
- function generateBarrelContent2(entries) {
589
+ function generateBarrelContent(entries) {
486
590
  if (entries.length === 0) {
487
591
  return null;
488
592
  }
489
593
  const exportLines = entries.sort((a, b) => a.name.localeCompare(b.name)).map((entry) => {
490
- const path37 = entry.isDirectory ? `./${entry.name}/index.js` : `./${entry.name}.js`;
491
- return `export * from "${path37}";`;
594
+ const path39 = entry.isDirectory ? `./${entry.name}/index.js` : `./${entry.name}.js`;
595
+ return `export * from "${path39}";`;
492
596
  });
493
- return `${GENERATED_MARKER3}
597
+ return `${GENERATED_MARKER2}
494
598
 
495
599
  ${exportLines.join("\n")}
496
600
  `;
@@ -510,16 +614,16 @@ var CircularExportError = class extends Error {
510
614
  };
511
615
  async function generateRecursiveBarrels(moduleDir, config, report) {
512
616
  const result = createEmptyResult();
513
- const srcDir = path33__default.join(moduleDir, "src");
617
+ const srcDir = path34__default.join(moduleDir, "src");
514
618
  const layers = ["domain", "application", "infrastructure"];
515
619
  const pendingWrites = [];
516
620
  const preserved = [];
517
621
  const exportGraph = /* @__PURE__ */ new Map();
518
622
  const layersWithContent = [];
519
623
  for (const layer of layers) {
520
- const layerDir = path33__default.join(srcDir, layer);
624
+ const layerDir = path34__default.join(srcDir, layer);
521
625
  try {
522
- await fs25.access(layerDir);
626
+ await fs27.access(layerDir);
523
627
  } catch {
524
628
  continue;
525
629
  }
@@ -533,9 +637,9 @@ async function generateRecursiveBarrels(moduleDir, config, report) {
533
637
  if (layerExports.length > 0) layersWithContent.push(layer);
534
638
  }
535
639
  if (config.mode === "external" && layersWithContent.length > 0) {
536
- const rootBarrelPath = path33__default.join(srcDir, "index.ts");
640
+ const rootBarrelPath = path34__default.join(srcDir, "index.ts");
537
641
  if (await shouldGenerateBarrel(rootBarrelPath, preserved, config.logger)) {
538
- const content = generateBarrelContent2(
642
+ const content = generateBarrelContent(
539
643
  layersWithContent.map((name) => ({ name, isDirectory: true }))
540
644
  );
541
645
  const existing = await readFileIfExists(rootBarrelPath);
@@ -547,7 +651,7 @@ async function generateRecursiveBarrels(moduleDir, config, report) {
547
651
  });
548
652
  exportGraph.set(
549
653
  rootBarrelPath,
550
- layersWithContent.map((name) => path33__default.join(srcDir, name, "index.ts"))
654
+ layersWithContent.map((name) => path34__default.join(srcDir, name, "index.ts"))
551
655
  );
552
656
  }
553
657
  }
@@ -558,9 +662,19 @@ async function generateRecursiveBarrels(moduleDir, config, report) {
558
662
  }
559
663
  for (const pending of pendingWrites) {
560
664
  if (pending.content === "") {
665
+ if (config.dryRun) {
666
+ config.logger.info(
667
+ `[DRY-RUN] would delete empty barrel ${pending.filePath}`
668
+ );
669
+ result.deleted.push(pending.filePath);
670
+ result.totalOps++;
671
+ continue;
672
+ }
561
673
  try {
562
- await fs25.unlink(pending.filePath);
563
- result.created.push(pending.filePath);
674
+ const preContent = await fs27.readFile(pending.filePath, "utf8");
675
+ config.journal?.recordDelete(pending.filePath, preContent);
676
+ await fs27.unlink(pending.filePath);
677
+ result.deleted.push(pending.filePath);
564
678
  result.totalOps++;
565
679
  continue;
566
680
  } catch (err3) {
@@ -576,15 +690,7 @@ async function generateRecursiveBarrels(moduleDir, config, report) {
576
690
  config,
577
691
  report
578
692
  );
579
- if (status === "created") {
580
- result.created.push(pending.filePath);
581
- result.totalOps++;
582
- } else if (status === "updated") {
583
- result.updated.push(pending.filePath);
584
- result.totalOps++;
585
- } else if (status === "skipped" || status === "protected") {
586
- result.skipped.push(pending.filePath);
587
- }
693
+ recordWriteStatus(result, pending.filePath, status);
588
694
  }
589
695
  result.skipped.push(...preserved);
590
696
  return result;
@@ -594,7 +700,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
594
700
  const exportEntries = [];
595
701
  let entries;
596
702
  try {
597
- entries = await fs25.readdir(dirPath, { withFileTypes: true });
703
+ entries = await fs27.readdir(dirPath, { withFileTypes: true });
598
704
  } catch {
599
705
  return exportEntries;
600
706
  }
@@ -611,7 +717,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
611
717
  }
612
718
  }
613
719
  for (const dir of directories) {
614
- const subDirPath = path33__default.join(dirPath, dir);
720
+ const subDirPath = path34__default.join(dirPath, dir);
615
721
  const subExports = await walkDirectory(
616
722
  subDirPath,
617
723
  pendingWrites,
@@ -619,7 +725,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
619
725
  exportGraph,
620
726
  config
621
727
  );
622
- const subBarrelPath = path33__default.join(subDirPath, "index.ts");
728
+ const subBarrelPath = path34__default.join(subDirPath, "index.ts");
623
729
  const isQueuedForDeletion = pendingWrites.some(
624
730
  (p) => p.filePath === subBarrelPath && p.content === ""
625
731
  );
@@ -631,9 +737,9 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
631
737
  exportEntries.push({ name: file, isDirectory: false });
632
738
  }
633
739
  if (exportEntries.length === 0) {
634
- const barrelPath2 = path33__default.join(dirPath, "index.ts");
740
+ const barrelPath2 = path34__default.join(dirPath, "index.ts");
635
741
  const existingBarrel = await readFileIfExists(barrelPath2);
636
- const dirName = path33__default.basename(dirPath);
742
+ const dirName = path34__default.basename(dirPath);
637
743
  const isLayerDir = ["domain", "application", "infrastructure"].includes(
638
744
  dirName
639
745
  );
@@ -648,7 +754,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
648
754
  isNew: false
649
755
  });
650
756
  } else if (isEmptyStub && isLayerDir) {
651
- const newContent = `${GENERATED_MARKER3}
757
+ const newContent = `${GENERATED_MARKER2}
652
758
 
653
759
  export {};
654
760
  `;
@@ -660,7 +766,7 @@ export {};
660
766
  });
661
767
  }
662
768
  } else if (!existingBarrel.includes("export {}") && isLayerDir) {
663
- const newContent = `${GENERATED_MARKER3}
769
+ const newContent = `${GENERATED_MARKER2}
664
770
 
665
771
  export {};
666
772
  `;
@@ -671,7 +777,7 @@ export {};
671
777
  });
672
778
  }
673
779
  } else if (isLayerDir) {
674
- const newContent = `${GENERATED_MARKER3}
780
+ const newContent = `${GENERATED_MARKER2}
675
781
 
676
782
  export {};
677
783
  `;
@@ -683,14 +789,14 @@ export {};
683
789
  }
684
790
  return [];
685
791
  }
686
- const barrelPath = path33__default.join(dirPath, "index.ts");
792
+ const barrelPath = path34__default.join(dirPath, "index.ts");
687
793
  const shouldCreateBarrel = await shouldGenerateBarrel(
688
794
  barrelPath,
689
795
  preserved,
690
796
  logger2
691
797
  );
692
798
  if (shouldCreateBarrel) {
693
- const content = generateBarrelContent2(exportEntries);
799
+ const content = generateBarrelContent(exportEntries);
694
800
  if (content === null) {
695
801
  return [];
696
802
  }
@@ -703,14 +809,14 @@ export {};
703
809
  content,
704
810
  isNew: !existingContent
705
811
  });
706
- const exportPaths = exportEntries.filter((e) => e.isDirectory).map((e) => path33__default.join(dirPath, e.name, "index.ts"));
812
+ const exportPaths = exportEntries.filter((e) => e.isDirectory).map((e) => path34__default.join(dirPath, e.name, "index.ts"));
707
813
  exportGraph.set(barrelPath, exportPaths);
708
814
  }
709
815
  return exportEntries;
710
816
  }
711
817
  async function hasBarrel(dirPath) {
712
818
  try {
713
- await fs25.access(path33__default.join(dirPath, "index.ts"));
819
+ await fs27.access(path34__default.join(dirPath, "index.ts"));
714
820
  return true;
715
821
  } catch {
716
822
  return false;
@@ -730,7 +836,7 @@ async function shouldGenerateBarrel(barrelPath, preserved, logger2) {
730
836
  }
731
837
  async function readFileIfExists(filePath) {
732
838
  try {
733
- return await fs25.readFile(filePath, "utf8");
839
+ return await fs27.readFile(filePath, "utf8");
734
840
  } catch (err3) {
735
841
  if (err3 && typeof err3 === "object" && "code" in err3 && err3.code === "ENOENT") {
736
842
  return null;
@@ -775,7 +881,12 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
775
881
  const moduleOverrides = context?.packageJson ?? {};
776
882
  const scope = config.manifest ? resolveScope(config.manifest) : "generated-project";
777
883
  const dependsOnDeps = context ? expandDependsOn(context, scope) : {};
778
- const pkgPath = path33__default.join(modulePath, "package.json");
884
+ const pkgPath = path34__default.join(modulePath, "package.json");
885
+ const dependencies = {
886
+ ...dependsOnDeps,
887
+ ...defaults.dependencies ?? {},
888
+ ...moduleOverrides.dependencies ?? {}
889
+ };
779
890
  const desiredPkg = {
780
891
  name: `@${scope}/${moduleName}`,
781
892
  version: "0.1.0",
@@ -796,11 +907,17 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
796
907
  ...defaults.scripts ?? {},
797
908
  ...moduleOverrides.scripts ?? {}
798
909
  },
799
- dependencies: {
800
- ...dependsOnDeps,
801
- ...defaults.dependencies ?? {},
802
- ...moduleOverrides.dependencies ?? {}
803
- },
910
+ // Emitted only when non-empty (PR-B2, capstone 6f): Yarn 4 deletes an
911
+ // empty `"dependencies": {}` from workspace manifests during install, so
912
+ // emitting one creates a permanent install↔sync churn loop — install
913
+ // strips the key, the next sync re-injects it (`dependencies` is
914
+ // protected, but a protected key MISSING from the current file is
915
+ // re-added), and the tree never converges across the consumer's
916
+ // sync → install → sync workflow. A dependency-less package carries no
917
+ // block at all, matching yarn's normalized form. Existing trees that
918
+ // still carry `{}` on disk stay untouched via the protected-key merge.
919
+ // devDependencies/scripts can't go empty (both have built-in entries).
920
+ ...Object.keys(dependencies).length > 0 ? { dependencies } : {},
804
921
  devDependencies: {
805
922
  typescript: "^5.0.0",
806
923
  ...defaults.devDependencies ?? {},
@@ -809,7 +926,7 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
809
926
  };
810
927
  let currentPkg = {};
811
928
  try {
812
- const currentContent = await fs25.readFile(pkgPath, "utf8");
929
+ const currentContent = await fs27.readFile(pkgPath, "utf8");
813
930
  currentPkg = JSON.parse(currentContent);
814
931
  } catch (e) {
815
932
  if (!(e instanceof Error && "code" in e && e.code === "ENOENT")) {
@@ -849,11 +966,7 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
849
966
  report,
850
967
  true
851
968
  );
852
- if (status === "created") result.created.push(pkgPath);
853
- if (status === "updated") result.updated.push(pkgPath);
854
- if (status === "skipped" || status === "protected")
855
- result.skipped.push(pkgPath);
856
- result.totalOps += status === "created" || status === "updated" ? 1 : 0;
969
+ recordWriteStatus(result, pkgPath, status);
857
970
  return result;
858
971
  }
859
972
  var BUILTIN_FALLBACK_TEMPLATE = {
@@ -923,7 +1036,7 @@ function buildTemplate(base, context, scope) {
923
1036
  }
924
1037
  async function generateTsconfig(moduleDir, moduleName, config, report) {
925
1038
  const result = createEmptyResult();
926
- const filePath = path33__default.join(moduleDir, "tsconfig.json");
1039
+ const filePath = path34__default.join(moduleDir, "tsconfig.json");
927
1040
  try {
928
1041
  const base = resolveWorkspaceTemplate(config.manifest);
929
1042
  const context = config.manifest.bounded_contexts?.find(
@@ -938,16 +1051,14 @@ async function generateTsconfig(moduleDir, moduleName, config, report) {
938
1051
  config,
939
1052
  report
940
1053
  );
941
- if (status === "created") result.created.push(filePath);
942
- if (status === "updated") result.updated.push(filePath);
943
- if (status === "skipped" || status === "protected")
944
- result.skipped.push(filePath);
945
- result.totalOps += status === "created" || status === "updated" ? 1 : 0;
1054
+ recordWriteStatus(result, filePath, status);
946
1055
  return result;
947
1056
  } catch (err3) {
948
1057
  const message = err3 instanceof Error ? err3.message : String(err3);
949
1058
  result.error = err3 instanceof Error ? err3 : new Error(`tsconfig generation failed for ${moduleName}: ${message}`);
950
1059
  result.summary = `tsconfig generation failed for ${moduleName}: ${message}`;
1060
+ config.logger.error(result.summary);
1061
+ if (report) report.record("error", filePath, result.summary);
951
1062
  return result;
952
1063
  }
953
1064
  }
@@ -955,15 +1066,15 @@ async function reapLegacyFolders(moduleDir, config, report) {
955
1066
  const { dryRun, logger: logger2 } = config;
956
1067
  const legacyLayers = ["domain", "application", "infrastructure"];
957
1068
  for (const layer of legacyLayers) {
958
- const layerPath = path33__default.join(moduleDir, layer);
959
- const relativePath = path33__default.relative(config.workspaceRoot, layerPath);
1069
+ const layerPath = path34__default.join(moduleDir, layer);
1070
+ const relativePath = path34__default.relative(config.workspaceRoot, layerPath);
960
1071
  try {
961
- const entries = await fs25.readdir(layerPath);
1072
+ const entries = await fs27.readdir(layerPath);
962
1073
  if (entries.length === 0) {
963
1074
  if (dryRun) {
964
1075
  logger2.info(`[DRY-RUN] would delete empty folder ${relativePath}`);
965
1076
  } else {
966
- await fs25.rm(layerPath, { recursive: true, force: true });
1077
+ await fs27.rmdir(layerPath);
967
1078
  logger2.info(`deleted empty folder ${relativePath}`);
968
1079
  if (report) report.record("deleted", layerPath);
969
1080
  }
@@ -1453,8 +1564,8 @@ function getErrorMap() {
1453
1564
 
1454
1565
  // ../../node_modules/zod/v3/helpers/parseUtil.js
1455
1566
  var makeIssue = (params) => {
1456
- const { data, path: path37, errorMaps, issueData } = params;
1457
- const fullPath = [...path37, ...issueData.path || []];
1567
+ const { data, path: path39, errorMaps, issueData } = params;
1568
+ const fullPath = [...path39, ...issueData.path || []];
1458
1569
  const fullIssue = {
1459
1570
  ...issueData,
1460
1571
  path: fullPath
@@ -1570,11 +1681,11 @@ var errorUtil;
1570
1681
 
1571
1682
  // ../../node_modules/zod/v3/types.js
1572
1683
  var ParseInputLazyPath = class {
1573
- constructor(parent, value, path37, key) {
1684
+ constructor(parent, value, path39, key) {
1574
1685
  this._cachedPath = [];
1575
1686
  this.parent = parent;
1576
1687
  this.data = value;
1577
- this._path = path37;
1688
+ this._path = path39;
1578
1689
  this._key = key;
1579
1690
  }
1580
1691
  get path() {
@@ -5085,6 +5196,7 @@ var BUILTIN_PACKAGE_JSON_TEMPLATE = `{
5085
5196
  "sync": "hexagen sync",
5086
5197
  "sync:dry": "hexagen sync --dry-run",
5087
5198
  "sync:force": "hexagen sync --force",
5199
+ "sync:check": "hexagen sync --check",
5088
5200
  "lint:arch": "hexagen arch validate",
5089
5201
  "templates:add": "hexagen add",
5090
5202
  "templates:validate": "hexagen validate-templates",
@@ -5095,8 +5207,8 @@ var BUILTIN_PACKAGE_JSON_TEMPLATE = `{
5095
5207
  "typescript": "^5.5.4",
5096
5208
  "eslint": "^9.0.0",
5097
5209
  "prettier": "^3.0.0",
5098
- "@hexagen-monaco/sync": "^0.4.0",
5099
- "@hexagen-monaco/arch-linter": "^0.4.0"
5210
+ "@hexagen-monaco/sync": "^{toolchainVersion}",
5211
+ "@hexagen-monaco/arch-linter": "^{toolchainVersion}"
5100
5212
  }
5101
5213
  }`;
5102
5214
  var BUILTIN_TSCONFIG_BASE_TEMPLATE = `{
@@ -5208,15 +5320,33 @@ adding \`--immutable\` to the \`yarn install\` step in
5208
5320
  Its pre-lockfile guidance goes stale once \`yarn.lock\` is committed. (Run
5209
5321
  \`hexagen sync\` won't bring it back — it's a protected root file.)
5210
5322
  `;
5323
+ 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-]+)*))?$/;
5324
+ function assertValidToolchainVersion(version, source) {
5325
+ const invalid = !SEMVER_2_0_0.test(version) || /^0\.0\.0(?:$|[-+])/.test(version);
5326
+ if (invalid) {
5327
+ throw new Error(
5328
+ `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).`
5329
+ );
5330
+ }
5331
+ return version;
5332
+ }
5333
+ function resolveToolchainVersion() {
5334
+ {
5335
+ return assertValidToolchainVersion(
5336
+ "0.7.1",
5337
+ "build-injected __HEXAGEN_TOOLCHAIN_VERSION__"
5338
+ );
5339
+ }
5340
+ }
5211
5341
 
5212
5342
  // src/generators/root-files.ts
5213
- function buildVars(manifest) {
5343
+ function buildVars(manifest, toolchainVersion) {
5214
5344
  const system = typeof manifest.system === "string" && manifest.system.length > 0 ? manifest.system : "generated-project";
5215
5345
  const scope = resolveScope(manifest);
5216
5346
  const packageManager = typeof manifest.monorepo?.packageManager === "string" && manifest.monorepo.packageManager.length > 0 ? manifest.monorepo.packageManager : "yarn@4.12.0";
5217
5347
  const workspacesArray = Array.isArray(manifest.monorepo?.workspaces) && manifest.monorepo.workspaces.length > 0 ? manifest.monorepo.workspaces : ["apps/*", "packages/*"];
5218
5348
  const workspaces = "[\n" + workspacesArray.map((w) => ` ${JSON.stringify(w)}`).join(",\n") + "\n ]";
5219
- return { system, scope, packageManager, workspaces };
5349
+ return { system, scope, packageManager, workspaces, toolchainVersion };
5220
5350
  }
5221
5351
  function resolveTemplate(manifestTemplate, builtin) {
5222
5352
  if (typeof manifestTemplate === "string" && manifestTemplate.length > 0) {
@@ -5242,17 +5372,14 @@ async function writeRootFile(filePath, content, config, report, result) {
5242
5372
  report,
5243
5373
  true
5244
5374
  );
5245
- if (status === "created") result.created.push(filePath);
5246
- if (status === "updated") result.updated.push(filePath);
5247
- if (status === "skipped" || status === "protected")
5248
- result.skipped.push(filePath);
5249
- if (status === "created" || status === "updated") result.totalOps += 1;
5375
+ recordWriteStatus(result, filePath, status);
5250
5376
  }
5251
5377
  async function generateRootFiles(config, report) {
5252
5378
  const result = createEmptyResult();
5379
+ const toolchainVersion = resolveToolchainVersion();
5253
5380
  try {
5254
5381
  const rootFiles = config.manifest.monorepo?.rootFiles;
5255
- const vars = buildVars(config.manifest);
5382
+ const vars = buildVars(config.manifest, toolchainVersion);
5256
5383
  const packageJsonTemplate = resolveTemplate(
5257
5384
  rootFiles?.packageJson?.template,
5258
5385
  BUILTIN_PACKAGE_JSON_TEMPLATE
@@ -5264,7 +5391,7 @@ async function generateRootFiles(config, report) {
5264
5391
  "package.json"
5265
5392
  );
5266
5393
  await writeRootFile(
5267
- path33__default.join(config.workspaceRoot, "package.json"),
5394
+ path34__default.join(config.workspaceRoot, "package.json"),
5268
5395
  packageJsonContent,
5269
5396
  config,
5270
5397
  report,
@@ -5281,7 +5408,7 @@ async function generateRootFiles(config, report) {
5281
5408
  "tsconfig.base.json"
5282
5409
  );
5283
5410
  await writeRootFile(
5284
- path33__default.join(config.workspaceRoot, "tsconfig.base.json"),
5411
+ path34__default.join(config.workspaceRoot, "tsconfig.base.json"),
5285
5412
  tsconfigContent,
5286
5413
  config,
5287
5414
  report,
@@ -5298,7 +5425,7 @@ async function generateRootFiles(config, report) {
5298
5425
  "turbo.json"
5299
5426
  );
5300
5427
  await writeRootFile(
5301
- path33__default.join(config.workspaceRoot, "turbo.json"),
5428
+ path34__default.join(config.workspaceRoot, "turbo.json"),
5302
5429
  turboContent,
5303
5430
  config,
5304
5431
  report,
@@ -5309,7 +5436,7 @@ async function generateRootFiles(config, report) {
5309
5436
  BUILTIN_GITIGNORE_TEMPLATE
5310
5437
  );
5311
5438
  await writeRootFile(
5312
- path33__default.join(config.workspaceRoot, ".gitignore"),
5439
+ path34__default.join(config.workspaceRoot, ".gitignore"),
5313
5440
  interpolateAndWarn(gitignoreTemplate, vars, config, ".gitignore"),
5314
5441
  config,
5315
5442
  report,
@@ -5320,7 +5447,7 @@ async function generateRootFiles(config, report) {
5320
5447
  BUILTIN_YARNRC_TEMPLATE
5321
5448
  );
5322
5449
  await writeRootFile(
5323
- path33__default.join(config.workspaceRoot, ".yarnrc.yml"),
5450
+ path34__default.join(config.workspaceRoot, ".yarnrc.yml"),
5324
5451
  interpolateAndWarn(yarnrcTemplate, vars, config, ".yarnrc.yml"),
5325
5452
  config,
5326
5453
  report,
@@ -5331,7 +5458,7 @@ async function generateRootFiles(config, report) {
5331
5458
  BUILTIN_SETUP_MD_TEMPLATE
5332
5459
  );
5333
5460
  await writeRootFile(
5334
- path33__default.join(config.workspaceRoot, "SETUP.md"),
5461
+ path34__default.join(config.workspaceRoot, "SETUP.md"),
5335
5462
  interpolateAndWarn(setupTemplate, vars, config, "SETUP.md"),
5336
5463
  config,
5337
5464
  report,
@@ -5342,6 +5469,8 @@ async function generateRootFiles(config, report) {
5342
5469
  const message = err3 instanceof Error ? err3.message : String(err3);
5343
5470
  result.error = err3 instanceof Error ? err3 : new Error(`root-files generation failed: ${message}`);
5344
5471
  result.summary = `root-files generation failed: ${message}`;
5472
+ config.logger.error(result.summary);
5473
+ if (report) report.record("error", "root-files", result.summary);
5345
5474
  return result;
5346
5475
  }
5347
5476
  }
@@ -5417,7 +5546,7 @@ test_double_rules:
5417
5546
  var GENERATOR_CONFIG_TEMPLATE = `generator:
5418
5547
  version: "1.0"
5419
5548
  description: "Global invariants and safety rules"
5420
- workspace_template: "{workspaceTemplate}"
5549
+ workspaceTemplate: "{workspaceTemplate}"
5421
5550
 
5422
5551
  invariants:
5423
5552
  - name: composite-safety
@@ -5498,37 +5627,65 @@ function resolveWorkspaceTemplate2(manifest) {
5498
5627
  function toPascalCase(stem) {
5499
5628
  return stem.split(/[-.]/).filter((part) => part.length > 0).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
5500
5629
  }
5630
+ function yamlScalar(value) {
5631
+ const plainSafe = /^[A-Za-z][A-Za-z0-9._-]*$/.test(value);
5632
+ const reserved = /^(?:true|false|null|yes|no|on|off)$/i.test(value);
5633
+ return plainSafe && !reserved ? value : JSON.stringify(value);
5634
+ }
5501
5635
  function buildOwnershipBlock(manifest) {
5502
5636
  const contexts = manifest.bounded_contexts ?? [];
5503
5637
  const entries = [];
5638
+ const seen = /* @__PURE__ */ new Set();
5639
+ const owners = /* @__PURE__ */ new Map();
5640
+ const add = (name, context) => {
5641
+ const key = JSON.stringify([name, context]);
5642
+ if (seen.has(key)) return;
5643
+ seen.add(key);
5644
+ entries.push({ name, context });
5645
+ let contextsForName = owners.get(name);
5646
+ if (!contextsForName) {
5647
+ contextsForName = /* @__PURE__ */ new Set();
5648
+ owners.set(name, contextsForName);
5649
+ }
5650
+ contextsForName.add(context);
5651
+ };
5504
5652
  for (const bc of contexts) {
5505
5653
  if (bc.name === "shared") continue;
5506
5654
  const application = bc.layers?.application;
5507
5655
  const infrastructure = bc.layers?.infrastructure;
5508
5656
  for (const p of application?.ports?.in ?? []) {
5509
- const name = toPascalCase(portName(p).replace(/\.in-port\.ts$/, ""));
5510
- entries.push(` ${name}: ${bc.name}`);
5657
+ add(toPascalCase(portName(p).replace(/\.in-port\.ts$/, "")), bc.name);
5511
5658
  }
5512
5659
  for (const p of application?.ports?.out ?? []) {
5513
- const name = toPascalCase(portName(p).replace(/\.out-port\.ts$/, ""));
5514
- entries.push(` ${name}: ${bc.name}`);
5660
+ add(toPascalCase(portName(p).replace(/\.out-port\.ts$/, "")), bc.name);
5515
5661
  }
5516
5662
  for (const a of infrastructure?.adapters ?? []) {
5517
- const name = toPascalCase(a.replace(/\.adapter\.ts$/, ""));
5518
- entries.push(` ${name}: ${bc.name}`);
5663
+ add(toPascalCase(a.replace(/\.adapter\.ts$/, "")), bc.name);
5519
5664
  }
5520
5665
  }
5521
- return entries.length > 0 ? entries.join("\n") : " # No ports declared";
5666
+ const collisions = [...owners.entries()].filter(([, contextsForName]) => contextsForName.size > 1).map(([name]) => name);
5667
+ const contested = new Set(collisions);
5668
+ const lines = entries.map(
5669
+ ({ name, context }) => contested.has(name) ? ` ${JSON.stringify(`${context}.${name}`)}: ${yamlScalar(context)}` : ` ${name}: ${yamlScalar(context)}`
5670
+ );
5671
+ return {
5672
+ block: lines.length > 0 ? lines.join("\n") : " # No ports declared",
5673
+ collisions
5674
+ };
5522
5675
  }
5523
5676
  function buildInterpolationVars(manifest) {
5524
5677
  const scope = resolveScope(manifest);
5525
5678
  const workspaceTemplate = resolveWorkspaceTemplate2(manifest);
5679
+ const { block, collisions } = buildOwnershipBlock(manifest);
5526
5680
  return {
5527
- scope,
5528
- template: workspaceTemplate,
5529
- workspaceTemplate,
5530
- system: typeof manifest.system === "string" ? manifest.system : "",
5531
- ownershipBlock: buildOwnershipBlock(manifest)
5681
+ vars: {
5682
+ scope,
5683
+ template: workspaceTemplate,
5684
+ workspaceTemplate,
5685
+ system: typeof manifest.system === "string" ? manifest.system : "",
5686
+ ownershipBlock: block
5687
+ },
5688
+ ownershipCollisions: collisions
5532
5689
  };
5533
5690
  }
5534
5691
  function builtInLayerRules(workspaceTemplate) {
@@ -5557,20 +5714,13 @@ function interpolateWithLogging(label, template, vars, config) {
5557
5714
  }
5558
5715
  return output;
5559
5716
  }
5560
- function recordStatus(result, filePath, status) {
5561
- if (status === "created") result.created.push(filePath);
5562
- else if (status === "updated") result.updated.push(filePath);
5563
- else if (status === "skipped" || status === "protected")
5564
- result.skipped.push(filePath);
5565
- if (status === "created" || status === "updated") result.totalOps += 1;
5566
- }
5567
5717
  async function writeManifestIfFreshExternal(config, result, report) {
5568
5718
  if (config.mode !== "external") {
5569
5719
  return;
5570
5720
  }
5571
- const archDir = path33__default.join(config.workspaceRoot, ".architecture");
5572
- const manifestPath = path33__default.join(archDir, "manifest.yaml");
5573
- const relative = path33__default.relative(config.workspaceRoot, manifestPath);
5721
+ const archDir = path34__default.join(config.workspaceRoot, ".architecture");
5722
+ const manifestPath = path34__default.join(archDir, "manifest.yaml");
5723
+ const relative = path34__default.relative(config.workspaceRoot, manifestPath);
5574
5724
  if (!isInScope(manifestPath, config)) {
5575
5725
  config.logger.debug(`skipped (outside --only) ${relative}`);
5576
5726
  result.skipped.push(manifestPath);
@@ -5578,7 +5728,7 @@ async function writeManifestIfFreshExternal(config, result, report) {
5578
5728
  }
5579
5729
  let exists = false;
5580
5730
  try {
5581
- await fs25.access(manifestPath);
5731
+ await fs27.access(manifestPath);
5582
5732
  exists = true;
5583
5733
  } catch {
5584
5734
  exists = false;
@@ -5597,8 +5747,9 @@ async function writeManifestIfFreshExternal(config, result, report) {
5597
5747
  return;
5598
5748
  }
5599
5749
  const content = yaml9.dump(config.manifest);
5600
- await fs25.mkdir(archDir, { recursive: true });
5601
- await fs25.writeFile(manifestPath, content, { encoding: "utf8" });
5750
+ config.journal?.recordWrite(manifestPath, null);
5751
+ await fs27.mkdir(archDir, { recursive: true });
5752
+ await fs27.writeFile(manifestPath, content, { encoding: "utf8" });
5602
5753
  config.logger.info(`created ${relative}`);
5603
5754
  if (report)
5604
5755
  report.record(
@@ -5612,12 +5763,17 @@ async function writeManifestIfFreshExternal(config, result, report) {
5612
5763
  async function generateArchitectureFiles(config, report) {
5613
5764
  const result = createEmptyResult();
5614
5765
  const manifest = config.manifest;
5615
- const archRoot = path33__default.join(config.workspaceRoot, ".architecture");
5766
+ const archRoot = path34__default.join(config.workspaceRoot, ".architecture");
5616
5767
  const archInvariants = manifest.monorepo?.archInvariants;
5617
- const vars = buildInterpolationVars(manifest);
5768
+ const { vars, ownershipCollisions } = buildInterpolationVars(manifest);
5618
5769
  const workspaceTemplate = vars.workspaceTemplate ?? "modular-monolith";
5770
+ if (ownershipCollisions.length > 0) {
5771
+ config.logger.warn(
5772
+ `architecture-files: ownership-registry name collision${ownershipCollisions.length === 1 ? "" : "s"} — ${ownershipCollisions.join(", ")} declared by more than one context; emitted with context-qualified keys (the port-single-ownership invariant expects exactly one owner).`
5773
+ );
5774
+ }
5619
5775
  await writeManifestIfFreshExternal(config, result, report);
5620
- const layerRulesPath = path33__default.join(archRoot, "invariants", "layer-rules.yaml");
5776
+ const layerRulesPath = path34__default.join(archRoot, "invariants", "layer-rules.yaml");
5621
5777
  const layerRulesTemplate = resolveTemplate2(
5622
5778
  archInvariants?.layerRules,
5623
5779
  builtInLayerRules(workspaceTemplate)
@@ -5635,8 +5791,8 @@ async function generateArchitectureFiles(config, report) {
5635
5791
  report,
5636
5792
  true
5637
5793
  );
5638
- recordStatus(result, layerRulesPath, layerRulesStatus);
5639
- const linterConfigPath = path33__default.join(
5794
+ recordWriteStatus(result, layerRulesPath, layerRulesStatus);
5795
+ const linterConfigPath = path34__default.join(
5640
5796
  archRoot,
5641
5797
  "invariants",
5642
5798
  "linter-config.yaml"
@@ -5658,8 +5814,8 @@ async function generateArchitectureFiles(config, report) {
5658
5814
  report,
5659
5815
  true
5660
5816
  );
5661
- recordStatus(result, linterConfigPath, linterConfigStatus);
5662
- const generatorConfigPath = path33__default.join(archRoot, "generator.config.yaml");
5817
+ recordWriteStatus(result, linterConfigPath, linterConfigStatus);
5818
+ const generatorConfigPath = path34__default.join(archRoot, "generator.config.yaml");
5663
5819
  const generatorConfigTemplate = resolveTemplate2(
5664
5820
  archInvariants?.generatorConfig,
5665
5821
  GENERATOR_CONFIG_TEMPLATE
@@ -5677,7 +5833,7 @@ async function generateArchitectureFiles(config, report) {
5677
5833
  report,
5678
5834
  true
5679
5835
  );
5680
- recordStatus(result, generatorConfigPath, generatorConfigStatus);
5836
+ recordWriteStatus(result, generatorConfigPath, generatorConfigStatus);
5681
5837
  return result;
5682
5838
  }
5683
5839
 
@@ -5781,7 +5937,6 @@ var PLAIN_TS_PACKAGE_JSON_TEMPLATE = `{
5781
5937
  "lint": "eslint src --ext .ts,.tsx",
5782
5938
  "typecheck": "tsc --noEmit"
5783
5939
  },
5784
- "dependencies": {},
5785
5940
  "devDependencies": {
5786
5941
  "typescript": "^5.5.4",
5787
5942
  "eslint": "^9.0.0",
@@ -5928,7 +6083,7 @@ ${content}`;
5928
6083
  }
5929
6084
  async function generateEslintConfig(moduleDir, moduleName, config, report, options = {}) {
5930
6085
  const result = createEmptyResult();
5931
- const filePath = path33__default.join(moduleDir, "eslint.config.js");
6086
+ const filePath = path34__default.join(moduleDir, "eslint.config.js");
5932
6087
  try {
5933
6088
  const { template, source } = resolveTemplate3(
5934
6089
  config.manifest,
@@ -5961,11 +6116,7 @@ async function generateEslintConfig(moduleDir, moduleName, config, report, optio
5961
6116
  report,
5962
6117
  false
5963
6118
  );
5964
- if (status === "created") result.created.push(filePath);
5965
- if (status === "updated") result.updated.push(filePath);
5966
- if (status === "skipped" || status === "protected")
5967
- result.skipped.push(filePath);
5968
- result.totalOps += status === "created" || status === "updated" ? 1 : 0;
6119
+ recordWriteStatus(result, filePath, status);
5969
6120
  return result;
5970
6121
  } catch (err3) {
5971
6122
  const message = err3 instanceof Error ? err3.message : String(err3);
@@ -6000,21 +6151,12 @@ function interpolateWithLogging2(template, vars, context, config) {
6000
6151
  }
6001
6152
  return output;
6002
6153
  }
6003
- function recordStatus2(result, filePath, status) {
6004
- if (status === "created") {
6005
- result.created.push(filePath);
6006
- result.totalOps += 1;
6007
- } else if (status === "updated") {
6008
- result.updated.push(filePath);
6009
- result.totalOps += 1;
6010
- } else {
6011
- result.skipped.push(filePath);
6012
- }
6013
- }
6014
6154
  function mergeResult(result, sub) {
6015
6155
  result.created.push(...sub.created);
6016
6156
  result.updated.push(...sub.updated);
6017
6157
  result.skipped.push(...sub.skipped);
6158
+ result.deleted.push(...sub.deleted);
6159
+ result.unchanged.push(...sub.unchanged);
6018
6160
  result.totalOps += sub.totalOps;
6019
6161
  if (sub.error && !result.error) {
6020
6162
  result.error = sub.error;
@@ -6028,9 +6170,9 @@ async function emitAppFile(appDir, relPath, template, vars, config, report, resu
6028
6170
  `apps/${appName}/${relPath}`,
6029
6171
  config
6030
6172
  );
6031
- const target = path33__default.resolve(appDir, relPath);
6032
- const relative = path33__default.relative(appDir, target);
6033
- if (relative === "" || relative.startsWith("..") || path33__default.isAbsolute(relative)) {
6173
+ const target = path34__default.resolve(appDir, relPath);
6174
+ const relative = path34__default.relative(appDir, target);
6175
+ if (relative === "" || relative.startsWith("..") || path34__default.isAbsolute(relative)) {
6034
6176
  config.logger.warn(
6035
6177
  `[apps] skipping file with unsafe path (escapes apps/${appName}): ${relPath}`
6036
6178
  );
@@ -6043,9 +6185,9 @@ async function emitAppFile(appDir, relPath, template, vars, config, report, resu
6043
6185
  }
6044
6186
  return "unsafe";
6045
6187
  }
6046
- if (isInScope(target, config)) {
6188
+ if (!config.dryRun && isInScope(target, config)) {
6047
6189
  try {
6048
- await fs25.mkdir(path33__default.dirname(target), { recursive: true });
6190
+ await fs27.mkdir(path34__default.dirname(target), { recursive: true });
6049
6191
  } catch (err3) {
6050
6192
  const message = err3 instanceof Error ? err3.message : String(err3);
6051
6193
  config.logger.error(
@@ -6055,7 +6197,7 @@ async function emitAppFile(appDir, relPath, template, vars, config, report, resu
6055
6197
  return "error";
6056
6198
  }
6057
6199
  }
6058
- recordStatus2(
6200
+ recordWriteStatus(
6059
6201
  result,
6060
6202
  target,
6061
6203
  await safeWriteFileAtomic(target, content, config, report)
@@ -6136,12 +6278,12 @@ async function generateApps(config, report) {
6136
6278
  version: app.version ?? "",
6137
6279
  depends_on: (app.depends_on ?? []).join(", ")
6138
6280
  };
6139
- const appDir = path33__default.join(config.workspaceRoot, "apps", app.name);
6140
- const srcDir = path33__default.join(appDir, "src");
6141
- if (isInScope(appDir, config)) {
6281
+ const appDir = path34__default.join(config.workspaceRoot, "apps", app.name);
6282
+ const srcDir = path34__default.join(appDir, "src");
6283
+ if (!config.dryRun && isInScope(appDir, config)) {
6142
6284
  try {
6143
- await fs25.mkdir(appDir, { recursive: true });
6144
- await fs25.mkdir(srcDir, { recursive: true });
6285
+ await fs27.mkdir(appDir, { recursive: true });
6286
+ await fs27.mkdir(srcDir, { recursive: true });
6145
6287
  } catch (err3) {
6146
6288
  const message = err3 instanceof Error ? err3.message : String(err3);
6147
6289
  config.logger.error(
@@ -6159,14 +6301,14 @@ async function generateApps(config, report) {
6159
6301
  `apps/${app.name}/package.json`,
6160
6302
  config
6161
6303
  );
6162
- const pkgPath = path33__default.join(appDir, "package.json");
6304
+ const pkgPath = path34__default.join(appDir, "package.json");
6163
6305
  const status = await safeWriteFileAtomic(
6164
6306
  pkgPath,
6165
6307
  pkgContent,
6166
6308
  config,
6167
6309
  report
6168
6310
  );
6169
- recordStatus2(result, pkgPath, status);
6311
+ recordWriteStatus(result, pkgPath, status);
6170
6312
  } else {
6171
6313
  config.logger.warn(
6172
6314
  `[apps] framework "${framework}" has no package.json template — skipping package.json for "${app.name}"`
@@ -6175,14 +6317,14 @@ async function generateApps(config, report) {
6175
6317
  const tsConfig = frameworkConfig.tsConfig;
6176
6318
  if (tsConfig) {
6177
6319
  const tsContent = JSON.stringify(tsConfig, null, 2) + "\n";
6178
- const tsPath = path33__default.join(appDir, "tsconfig.json");
6320
+ const tsPath = path34__default.join(appDir, "tsconfig.json");
6179
6321
  const status = await safeWriteFileAtomic(
6180
6322
  tsPath,
6181
6323
  tsContent,
6182
6324
  config,
6183
6325
  report
6184
6326
  );
6185
- recordStatus2(result, tsPath, status);
6327
+ recordWriteStatus(result, tsPath, status);
6186
6328
  } else {
6187
6329
  config.logger.warn(
6188
6330
  `[apps] framework "${framework}" has no tsConfig — skipping tsconfig.json for "${app.name}"`
@@ -6236,18 +6378,20 @@ async function generateApps(config, report) {
6236
6378
  const message = err3 instanceof Error ? err3.message : String(err3);
6237
6379
  result.error = err3 instanceof Error ? err3 : new Error(`apps generation failed: ${message}`);
6238
6380
  result.summary = `apps generation failed: ${message}`;
6381
+ config.logger.error(result.summary);
6382
+ if (report) report.record("error", "apps", result.summary);
6239
6383
  return result;
6240
6384
  }
6241
6385
  }
6242
6386
  function relativeImportSpecifier(fromFile, toFile) {
6243
- let rel = path33__default.relative(path33__default.dirname(fromFile), toFile).split(path33__default.sep).join("/").replace(/\.tsx?$/, ".js");
6387
+ let rel = path34__default.relative(path34__default.dirname(fromFile), toFile).split(path34__default.sep).join("/").replace(/\.tsx?$/, ".js");
6244
6388
  if (!rel.startsWith(".")) rel = `./${rel}`;
6245
6389
  return rel;
6246
6390
  }
6247
6391
  function rewriteRelativeSpecifier(specifier, fromFile, toFile) {
6248
6392
  if (!specifier.startsWith(".")) return specifier;
6249
- const absolute = path33__default.resolve(path33__default.dirname(fromFile), specifier);
6250
- let rel = path33__default.relative(path33__default.dirname(toFile), absolute).split(path33__default.sep).join("/");
6393
+ const absolute = path34__default.resolve(path34__default.dirname(fromFile), specifier);
6394
+ let rel = path34__default.relative(path34__default.dirname(toFile), absolute).split(path34__default.sep).join("/");
6251
6395
  if (!rel.startsWith(".")) rel = `./${rel}`;
6252
6396
  return rel;
6253
6397
  }
@@ -6883,13 +7027,13 @@ function resolveNaming(kind, contextNaming, manifestNaming) {
6883
7027
  async function writeStubFile(filePath, content, config, report) {
6884
7028
  if (!isInScope(filePath, config)) {
6885
7029
  config.logger.debug(
6886
- `skipped (outside --only) ${path33__default.relative(config.workspaceRoot, filePath)}`
7030
+ `skipped (outside --only) ${path34__default.relative(config.workspaceRoot, filePath)}`
6887
7031
  );
6888
7032
  return "skipped";
6889
7033
  }
6890
7034
  try {
6891
- await fs25.stat(filePath);
6892
- const relative = path33__default.relative(config.workspaceRoot, filePath);
7035
+ await fs27.stat(filePath);
7036
+ const relative = path34__default.relative(config.workspaceRoot, filePath);
6893
7037
  config.logger.debug(`stub preserved ${relative}`);
6894
7038
  if (report) {
6895
7039
  report.record(
@@ -6904,7 +7048,9 @@ async function writeStubFile(filePath, content, config, report) {
6904
7048
  throw err3;
6905
7049
  }
6906
7050
  }
6907
- await fs25.mkdir(path33__default.dirname(filePath), { recursive: true });
7051
+ if (!config.dryRun) {
7052
+ await fs27.mkdir(path34__default.dirname(filePath), { recursive: true });
7053
+ }
6908
7054
  return safeWriteFileAtomic(filePath, content, config, report, false);
6909
7055
  }
6910
7056
  async function tryAnalyzeRelatedPort(moduleDir, name, kind, context, relatedPortNamingTemplate) {
@@ -6923,7 +7069,7 @@ async function tryAnalyzeRelatedPort(moduleDir, name, kind, context, relatedPort
6923
7069
  `${derivedPortName}.ts`
6924
7070
  ];
6925
7071
  for (const filename of possibleFilenames) {
6926
- const portFilePath = path33__default.join(moduleDir, "src", portSubdir, filename);
7072
+ const portFilePath = path34__default.join(moduleDir, "src", portSubdir, filename);
6927
7073
  const analysis = analyzePortFile(portFilePath);
6928
7074
  if (analysis) {
6929
7075
  return analysis;
@@ -6976,7 +7122,7 @@ async function generateStubs(moduleDir, moduleName, config, report) {
6976
7122
  `stubs.naming.${kind}`,
6977
7123
  config
6978
7124
  );
6979
- const filePath = path33__default.join(moduleDir, "src", subdir, filename);
7125
+ const filePath = path34__default.join(moduleDir, "src", subdir, filename);
6980
7126
  let content;
6981
7127
  if (kind === "adapter" || kind === "useCase") {
6982
7128
  const relatedPortNaming = resolveNaming(
@@ -7005,7 +7151,7 @@ async function generateStubs(moduleDir, moduleName, config, report) {
7005
7151
  contextNaming,
7006
7152
  manifestNaming
7007
7153
  );
7008
- const outPortDir = path33__default.join(
7154
+ const outPortDir = path34__default.join(
7009
7155
  moduleDir,
7010
7156
  "src",
7011
7157
  "application",
@@ -7020,7 +7166,7 @@ async function generateStubs(moduleDir, moduleName, config, report) {
7020
7166
  "stubs.naming.outPort",
7021
7167
  config
7022
7168
  );
7023
- const outPortPath = path33__default.join(outPortDir, outFile);
7169
+ const outPortPath = path34__default.join(outPortDir, outFile);
7024
7170
  const analyzed = analyzePortFile(outPortPath);
7025
7171
  return {
7026
7172
  interfaceName: analyzed?.interfaceName ?? `${base}Port`,
@@ -7054,24 +7200,13 @@ async function generateStubs(moduleDir, moduleName, config, report) {
7054
7200
  );
7055
7201
  }
7056
7202
  const status = await writeStubFile(filePath, content, config, report);
7057
- if (status === "created") result.created.push(filePath);
7058
- if (status === "updated") result.updated.push(filePath);
7059
- if (status === "skipped" || status === "protected")
7060
- result.skipped.push(filePath);
7061
- if (status === "created" || status === "updated") result.totalOps += 1;
7203
+ recordWriteStatus(result, filePath, status);
7062
7204
  }
7063
7205
  }
7064
7206
  return result;
7065
7207
  }
7066
7208
  var OHS_NOTE = "\n *\n * Open Host Service (open-host): this is this context's published language for consuming contexts — keep it stable.";
7067
7209
  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.";
7068
- function recordStatus3(result, filePath, status) {
7069
- if (status === "created") result.created.push(filePath);
7070
- else if (status === "updated") result.updated.push(filePath);
7071
- else if (status === "skipped" || status === "protected")
7072
- result.skipped.push(filePath);
7073
- if (status === "created" || status === "updated") result.totalOps += 1;
7074
- }
7075
7210
  function addAll(map, key, values) {
7076
7211
  const set = map.get(key) ?? /* @__PURE__ */ new Set();
7077
7212
  values.forEach((v) => set.add(v));
@@ -7137,27 +7272,29 @@ ${methodLines}
7137
7272
  `;
7138
7273
  }
7139
7274
  async function emitPortAndAdapter(result, config, report, scope, spec) {
7140
- const moduleRoot = path33__default.join(
7275
+ const moduleRoot = path34__default.join(
7141
7276
  config.workspaceRoot,
7142
7277
  "packages",
7143
7278
  spec.contextName
7144
7279
  );
7145
- const portDir = path33__default.join(
7280
+ const portDir = path34__default.join(
7146
7281
  moduleRoot,
7147
7282
  "src",
7148
7283
  "application",
7149
7284
  "ports",
7150
7285
  spec.portKind
7151
7286
  );
7152
- const portPath = path33__default.join(
7287
+ const portPath = path34__default.join(
7153
7288
  portDir,
7154
7289
  `${spec.portBase}.${spec.portKind}-port.ts`
7155
7290
  );
7156
7291
  if (!isInScope(portPath, config)) {
7157
7292
  return;
7158
7293
  }
7159
- await fs25.mkdir(portDir, { recursive: true });
7160
- recordStatus3(
7294
+ if (!config.dryRun) {
7295
+ await fs27.mkdir(portDir, { recursive: true });
7296
+ }
7297
+ recordWriteStatus(
7161
7298
  result,
7162
7299
  portPath,
7163
7300
  await safeWriteFileAtomic(
@@ -7180,15 +7317,17 @@ async function emitPortAndAdapter(result, config, report, scope, spec) {
7180
7317
  );
7181
7318
  return;
7182
7319
  }
7183
- const adapterDir = path33__default.join(moduleRoot, "src", "infrastructure", "adapters");
7184
- const adapterPath = path33__default.join(adapterDir, `${spec.portBase}.adapter.ts`);
7320
+ const adapterDir = path34__default.join(moduleRoot, "src", "infrastructure", "adapters");
7321
+ const adapterPath = path34__default.join(adapterDir, `${spec.portBase}.adapter.ts`);
7185
7322
  if (!isInScope(adapterPath, config)) {
7186
7323
  return;
7187
7324
  }
7188
- await fs25.mkdir(adapterDir, { recursive: true });
7325
+ if (!config.dryRun) {
7326
+ await fs27.mkdir(adapterDir, { recursive: true });
7327
+ }
7189
7328
  const adapterClassName = `${toPascalCase2(spec.portBase)}Adapter`;
7190
7329
  const portSpecifier = relativeImportSpecifier(adapterPath, portPath);
7191
- recordStatus3(
7330
+ recordWriteStatus(
7192
7331
  result,
7193
7332
  adapterPath,
7194
7333
  await safeWriteFileAtomic(
@@ -7211,15 +7350,17 @@ function operationImports(ops) {
7211
7350
  return ops.flatMap((op) => [`${op}Request`, `${op}Response`]);
7212
7351
  }
7213
7352
  async function writeSharedContract(result, config, report, relSegments, content) {
7214
- const contractPath = path33__default.join(
7353
+ const contractPath = path34__default.join(
7215
7354
  config.workspaceRoot,
7216
7355
  "packages",
7217
7356
  "shared",
7218
7357
  "src",
7219
7358
  ...relSegments
7220
7359
  );
7221
- await fs25.mkdir(path33__default.dirname(contractPath), { recursive: true });
7222
- recordStatus3(
7360
+ if (!config.dryRun) {
7361
+ await fs27.mkdir(path34__default.dirname(contractPath), { recursive: true });
7362
+ }
7363
+ recordWriteStatus(
7223
7364
  result,
7224
7365
  contractPath,
7225
7366
  await safeWriteFileAtomic(contractPath, content, config, report)
@@ -7369,7 +7510,7 @@ async function generateSharedKernel(config, report) {
7369
7510
  (bc) => bc.name?.toLowerCase() === "shared"
7370
7511
  );
7371
7512
  if (!hasShared) return result;
7372
- const kernelPath = path33__default.join(
7513
+ const kernelPath = path34__default.join(
7373
7514
  config.workspaceRoot,
7374
7515
  "packages",
7375
7516
  "shared",
@@ -7382,13 +7523,15 @@ async function generateSharedKernel(config, report) {
7382
7523
  return result;
7383
7524
  }
7384
7525
  try {
7385
- await fs25.stat(kernelPath);
7526
+ await fs27.stat(kernelPath);
7386
7527
  result.skipped.push(kernelPath);
7387
7528
  return result;
7388
7529
  } catch (err3) {
7389
7530
  if (err3.code !== "ENOENT") throw err3;
7390
7531
  }
7391
- await fs25.mkdir(path33__default.dirname(kernelPath), { recursive: true });
7532
+ if (!config.dryRun) {
7533
+ await fs27.mkdir(path34__default.dirname(kernelPath), { recursive: true });
7534
+ }
7392
7535
  const status = await safeWriteFileAtomic(
7393
7536
  kernelPath,
7394
7537
  RESULT_KERNEL,
@@ -7396,12 +7539,7 @@ async function generateSharedKernel(config, report) {
7396
7539
  report,
7397
7540
  false
7398
7541
  );
7399
- if (status === "created" || status === "updated") {
7400
- result.created.push(kernelPath);
7401
- result.totalOps += 1;
7402
- } else {
7403
- result.skipped.push(kernelPath);
7404
- }
7542
+ recordWriteStatus(result, kernelPath, status);
7405
7543
  return result;
7406
7544
  }
7407
7545
  var execAsync = promisify(exec);
@@ -7435,14 +7573,27 @@ function mergeResult2(dest, src) {
7435
7573
  dest.created.push(...src.created);
7436
7574
  dest.updated.push(...src.updated);
7437
7575
  dest.skipped.push(...src.skipped);
7576
+ dest.deleted.push(...src.deleted);
7577
+ dest.unchanged.push(...src.unchanged);
7438
7578
  dest.totalOps += src.totalOps;
7579
+ if (src.error && !dest.error) {
7580
+ dest.error = src.error;
7581
+ dest.summary = src.summary;
7582
+ }
7439
7583
  }
7440
7584
  function mergeBarrelPasses(firstPass, secondPass) {
7441
7585
  const combined = createEmptyResult();
7442
7586
  const secondPaths = /* @__PURE__ */ new Set([
7443
7587
  ...secondPass.created,
7444
7588
  ...secondPass.updated,
7445
- ...secondPass.skipped
7589
+ ...secondPass.skipped,
7590
+ ...secondPass.deleted
7591
+ ]);
7592
+ const secondAll = /* @__PURE__ */ new Set([...secondPaths, ...secondPass.unchanged]);
7593
+ const firstMutations = /* @__PURE__ */ new Set([
7594
+ ...firstPass.created,
7595
+ ...firstPass.updated,
7596
+ ...firstPass.deleted
7446
7597
  ]);
7447
7598
  for (const p of firstPass.created) {
7448
7599
  if (!secondPaths.has(p)) combined.created.push(p);
@@ -7451,12 +7602,29 @@ function mergeBarrelPasses(firstPass, secondPass) {
7451
7602
  if (!secondPaths.has(p)) combined.updated.push(p);
7452
7603
  }
7453
7604
  for (const p of firstPass.skipped) {
7454
- if (!secondPaths.has(p)) combined.skipped.push(p);
7605
+ if (!secondAll.has(p)) combined.skipped.push(p);
7606
+ }
7607
+ for (const p of firstPass.deleted) {
7608
+ if (!secondPaths.has(p)) combined.deleted.push(p);
7609
+ }
7610
+ for (const p of firstPass.unchanged) {
7611
+ if (!secondAll.has(p)) combined.unchanged.push(p);
7455
7612
  }
7456
7613
  combined.created.push(...secondPass.created);
7457
7614
  combined.updated.push(...secondPass.updated);
7458
7615
  combined.skipped.push(...secondPass.skipped);
7459
- combined.totalOps = firstPass.totalOps + secondPass.totalOps;
7616
+ combined.deleted.push(...secondPass.deleted);
7617
+ for (const p of secondPass.unchanged) {
7618
+ if (!firstMutations.has(p)) combined.unchanged.push(p);
7619
+ }
7620
+ combined.totalOps = combined.created.length + combined.updated.length + combined.deleted.length;
7621
+ if (firstPass.error) {
7622
+ combined.error = firstPass.error;
7623
+ combined.summary = firstPass.summary;
7624
+ } else if (secondPass.error) {
7625
+ combined.error = secondPass.error;
7626
+ combined.summary = secondPass.summary;
7627
+ }
7460
7628
  return combined;
7461
7629
  }
7462
7630
 
@@ -7465,14 +7633,15 @@ function caseInsensitiveEnum(schema, dir = "lower") {
7465
7633
  return external_exports.preprocess((value) => typeof value === "string" ? dir === "lower" ? value.trim().toLowerCase() : value.trim().toUpperCase() : value, schema);
7466
7634
  }
7467
7635
  var BoundedContextTypeSchema = boundedContextTypeSchema;
7468
- var PlaneTypeSchema = caseInsensitiveEnum(external_exports.enum([
7636
+ var PLANE_NAMES = [
7469
7637
  "projection",
7470
7638
  "probabilistic",
7471
7639
  "infrastructure",
7472
7640
  "shared-kernel",
7473
7641
  "core",
7474
7642
  "supporting"
7475
- ]));
7643
+ ];
7644
+ var PlaneTypeSchema = caseInsensitiveEnum(external_exports.enum(PLANE_NAMES));
7476
7645
  var StatusTypeSchema = caseInsensitiveEnum(external_exports.enum(["active", "frozen", "deprecated", "experimental"]));
7477
7646
  var RelationshipPatternSchema = caseInsensitiveEnum(external_exports.enum(["U/D", "ACL", "SK", "P", "OHS"]), "upper");
7478
7647
  var RelationshipRoleSchema = caseInsensitiveEnum(external_exports.enum(["upstream", "downstream", "peer"]));
@@ -7542,6 +7711,10 @@ var AppSchema = external_exports.object({
7542
7711
  depends_on: external_exports.array(external_exports.string()).optional()
7543
7712
  }).strip();
7544
7713
  var IndexManifestSchema = external_exports.object({
7714
+ // Toolchain-compatibility stamp (see manifest-schema-version.ts). Note
7715
+ // `version` below is a DIFFERENT field — its `"2.0"` string is the
7716
+ // index-form discriminator (`isIndexManifest`), not a compatibility gate.
7717
+ schemaVersion: external_exports.number().int().positive().optional(),
7545
7718
  version: external_exports.string().optional(),
7546
7719
  description: external_exports.string(),
7547
7720
  system: external_exports.string().optional(),
@@ -7592,6 +7765,12 @@ var CrossContextEdgeSchema = external_exports.object({
7592
7765
  integrationPattern: external_exports.enum(["open-host", "acl"]).optional()
7593
7766
  });
7594
7767
  var ManifestSchema = external_exports.object({
7768
+ // Toolchain-compatibility stamp (positive int; absent = legacy). NOT the
7769
+ // freeform `version` string below. Compatibility is asserted against the
7770
+ // RAW yaml BEFORE this `.strict()` parse (assertSupportedSchemaVersion in
7771
+ // manifest-schema-version.ts) — this entry only keeps strict mode from
7772
+ // rejecting stamped manifests as carrying an unknown key.
7773
+ schemaVersion: external_exports.number().int().positive().optional(),
7595
7774
  version: external_exports.string().optional(),
7596
7775
  description: external_exports.string().optional(),
7597
7776
  system: external_exports.string().optional(),
@@ -7627,6 +7806,28 @@ var ManifestSchema = external_exports.object({
7627
7806
  legacy_config: external_exports.string().optional()
7628
7807
  }).strict();
7629
7808
 
7809
+ // ../project-configuration/dist/domain/model/manifest-schema/manifest-schema-version.js
7810
+ var CURRENT_MANIFEST_SCHEMA_VERSION = 1;
7811
+ function readManifestSchemaVersion(parsed) {
7812
+ if (parsed === null || typeof parsed !== "object")
7813
+ return void 0;
7814
+ const raw = parsed.schemaVersion;
7815
+ if (raw === void 0)
7816
+ return void 0;
7817
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 1) {
7818
+ throw new Error(`Invalid manifest schemaVersion: expected a positive integer, got ${JSON.stringify(raw)}.`);
7819
+ }
7820
+ return raw;
7821
+ }
7822
+ function assertSupportedSchemaVersion(parsed) {
7823
+ const version = readManifestSchemaVersion(parsed);
7824
+ if (version === void 0)
7825
+ return;
7826
+ if (version > CURRENT_MANIFEST_SCHEMA_VERSION) {
7827
+ throw new Error(`Manifest schemaVersion ${version} is newer than this toolchain supports (reads ≤ ${CURRENT_MANIFEST_SCHEMA_VERSION}). This manifest requires a newer @hexagen-monaco/sync — upgrade it. (Upgrading is always safe: a newer toolchain reads every older manifest, and \`hexagen manifest migrate\` brings one forward on demand.)`);
7828
+ }
7829
+ }
7830
+
7630
7831
  // ../project-configuration/dist/domain/model/manifest-schema/is-index-manifest.js
7631
7832
  function isIndexManifest(parsed) {
7632
7833
  if (typeof parsed !== "object" || parsed === null) {
@@ -7776,21 +7977,21 @@ external_exports.object({
7776
7977
  turboConfig: external_exports.record(external_exports.unknown()).optional()
7777
7978
  });
7778
7979
  function assertPathWithinArchitecture(workspaceRoot, relativePath) {
7779
- const resolved = path33__default.resolve(workspaceRoot, ".architecture", relativePath);
7780
- const archRoot = path33__default.resolve(workspaceRoot, ".architecture");
7980
+ const resolved = path34__default.resolve(workspaceRoot, ".architecture", relativePath);
7981
+ const archRoot = path34__default.resolve(workspaceRoot, ".architecture");
7781
7982
  try {
7782
7983
  const realResolved = realpathSync(resolved);
7783
7984
  const realArchRoot = realpathSync(archRoot);
7784
- const archRootWithSep = realArchRoot + path33__default.sep;
7985
+ const archRootWithSep = realArchRoot + path34__default.sep;
7785
7986
  if (realResolved !== realArchRoot && !realResolved.startsWith(archRootWithSep)) {
7786
7987
  throw new Error(`Path traversal detected: "${relativePath}" resolves outside .architecture/`);
7787
7988
  }
7788
7989
  } catch (err3) {
7789
7990
  if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
7790
7991
  let checkPath = archRoot;
7791
- const pathSegments = path33__default.relative(archRoot, resolved).split(path33__default.sep);
7992
+ const pathSegments = path34__default.relative(archRoot, resolved).split(path34__default.sep);
7792
7993
  for (const segment of pathSegments) {
7793
- checkPath = path33__default.join(checkPath, segment);
7994
+ checkPath = path34__default.join(checkPath, segment);
7794
7995
  try {
7795
7996
  const stat = lstatSync(checkPath);
7796
7997
  if (stat.isSymbolicLink()) {
@@ -7806,7 +8007,7 @@ function assertPathWithinArchitecture(workspaceRoot, relativePath) {
7806
8007
  throw statErr;
7807
8008
  }
7808
8009
  }
7809
- const archRootWithSep = archRoot + path33__default.sep;
8010
+ const archRootWithSep = archRoot + path34__default.sep;
7810
8011
  if (resolved !== archRoot && !resolved.startsWith(archRootWithSep)) {
7811
8012
  throw new Error(`Path traversal detected: "${relativePath}" resolves outside .architecture/`);
7812
8013
  }
@@ -7816,11 +8017,12 @@ function assertPathWithinArchitecture(workspaceRoot, relativePath) {
7816
8017
  }
7817
8018
  }
7818
8019
  async function mergeSplitManifest(workspaceRoot, manifestPath) {
7819
- const content = await fs25.readFile(manifestPath, "utf-8");
8020
+ const content = await fs27.readFile(manifestPath, "utf-8");
7820
8021
  const parsed = yaml9.load(content);
7821
8022
  if (parsed == null) {
7822
8023
  throw new Error("Manifest file is empty");
7823
8024
  }
8025
+ assertSupportedSchemaVersion(parsed);
7824
8026
  if (!isIndexManifest(parsed)) {
7825
8027
  const manifestData = {
7826
8028
  ...parsed,
@@ -7835,6 +8037,9 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7835
8037
  }
7836
8038
  const index = indexResult.data;
7837
8039
  const result = {
8040
+ // Carry the (already-validated) stamp into the merged form so consumers
8041
+ // of the merge see the same version the root file declares.
8042
+ schemaVersion: index.schemaVersion,
7838
8043
  description: index.description ?? "Auto-generated manifest",
7839
8044
  system: index.system,
7840
8045
  scope: index.scope,
@@ -7849,10 +8054,10 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7849
8054
  continue;
7850
8055
  }
7851
8056
  assertPathWithinArchitecture(workspaceRoot, indexEntry.file);
7852
- const contextFilePath = path33__default.join(workspaceRoot, ".architecture", indexEntry.file);
8057
+ const contextFilePath = path34__default.join(workspaceRoot, ".architecture", indexEntry.file);
7853
8058
  let contextContent;
7854
8059
  try {
7855
- contextContent = await fs25.readFile(contextFilePath, "utf-8");
8060
+ contextContent = await fs27.readFile(contextFilePath, "utf-8");
7856
8061
  } catch (err3) {
7857
8062
  if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
7858
8063
  throw new Error(`Context file not found: ${contextFilePath}`);
@@ -7884,10 +8089,10 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7884
8089
  continue;
7885
8090
  }
7886
8091
  assertPathWithinArchitecture(workspaceRoot, appEntry.file);
7887
- const appFilePath = path33__default.join(workspaceRoot, ".architecture", appEntry.file);
8092
+ const appFilePath = path34__default.join(workspaceRoot, ".architecture", appEntry.file);
7888
8093
  let appContent;
7889
8094
  try {
7890
- appContent = await fs25.readFile(appFilePath, "utf-8");
8095
+ appContent = await fs27.readFile(appFilePath, "utf-8");
7891
8096
  } catch (err3) {
7892
8097
  if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
7893
8098
  throw new Error(`App file not found: ${appFilePath}`);
@@ -7906,34 +8111,52 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7906
8111
 
7907
8112
  // src/sync-engine-init.ts
7908
8113
  var __filename$1 = fileURLToPath(import.meta.url);
7909
- var __dirname$1 = path33__default.dirname(__filename$1);
7910
- async function findWorkspaceRoot(options) {
7911
- if (options.targetRoot) {
7912
- return options.targetRoot;
7913
- }
7914
- let currentDir = __dirname$1;
7915
- while (currentDir !== path33__default.parse(currentDir).root) {
8114
+ var __dirname$1 = path34__default.dirname(__filename$1);
8115
+ function isENOENT(err3) {
8116
+ return err3 instanceof Error && "code" in err3 && err3.code === "ENOENT";
8117
+ }
8118
+ async function findRootFrom(startDir, problems) {
8119
+ let currentDir = startDir;
8120
+ while (currentDir !== path34__default.parse(currentDir).root) {
8121
+ const pkgPath = path34__default.join(currentDir, "package.json");
7916
8122
  try {
7917
- const pkgPath = path33__default.join(currentDir, "package.json");
7918
- const pkgContent = await fs25.readFile(pkgPath, "utf-8");
8123
+ const pkgContent = await fs27.readFile(pkgPath, "utf-8");
7919
8124
  const pkg = JSON.parse(pkgContent);
7920
8125
  if (pkg.workspaces && Array.isArray(pkg.workspaces)) {
7921
8126
  return currentDir;
7922
8127
  }
7923
- } catch {
8128
+ } catch (err3) {
8129
+ if (!isENOENT(err3)) {
8130
+ const reason = err3 instanceof Error ? err3.message : String(err3);
8131
+ problems.push(new Error(`${pkgPath}: ${reason}`));
8132
+ }
7924
8133
  }
7925
- currentDir = path33__default.dirname(currentDir);
8134
+ currentDir = path34__default.dirname(currentDir);
7926
8135
  }
8136
+ return null;
8137
+ }
8138
+ async function findWorkspaceRoot(options, probeStarts = [process.cwd(), __dirname$1]) {
8139
+ if (options.targetRoot) {
8140
+ return options.targetRoot;
8141
+ }
8142
+ const problems = [];
8143
+ for (const start of probeStarts) {
8144
+ const root = await findRootFrom(start, problems);
8145
+ if (root !== null) {
8146
+ return root;
8147
+ }
8148
+ }
8149
+ const detail = problems.length > 0 ? ` A package.json was found but could not be read or parsed: ${problems[0].message}.` : "";
7927
8150
  throw new Error(
7928
- 'Could not locate monorepo root. No package.json with "workspaces" field found.'
8151
+ `Could not locate monorepo root: no package.json with a "workspaces" array found walking up from ${probeStarts.join(" or ")}.${detail} Run the command from inside your workspace (any subdirectory works), and check that the root package.json declares "workspaces". Note: a globally- or npx-installed CLI can only resolve the root from your current directory.`
7929
8152
  );
7930
8153
  }
7931
8154
  async function loadManifest(workspaceRoot, flags, options) {
7932
8155
  if (options.manifest) {
7933
- return options.manifest;
8156
+ return { manifest: options.manifest, manifestMissing: false };
7934
8157
  }
7935
8158
  const { logger: logger2, dryRun } = flags;
7936
- const manifestPath = path33__default.join(workspaceRoot, ".architecture/manifest.yaml");
8159
+ const manifestPath = path34__default.join(workspaceRoot, ".architecture/manifest.yaml");
7937
8160
  logger2.debug(`[debug] __dirname (ESM): ${__dirname$1}`);
7938
8161
  logger2.debug(`[debug] resolved workspaceRoot: ${workspaceRoot}`);
7939
8162
  logger2.debug(`[debug] resolved manifestPath: ${manifestPath}`);
@@ -7943,11 +8166,14 @@ async function loadManifest(workspaceRoot, flags, options) {
7943
8166
  manifestPath
7944
8167
  );
7945
8168
  logger2.info(`Loaded manifest from ${manifestPath}`);
7946
- return manifest;
8169
+ return { manifest, manifestMissing: false };
7947
8170
  } catch (err3) {
7948
- if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT" && dryRun) {
8171
+ if (isENOENT(err3) && dryRun) {
7949
8172
  logger2.warn(`Manifest not found — using empty for dry-run`);
7950
- return { description: "Empty manifest", bounded_contexts: [] };
8173
+ return {
8174
+ manifest: { description: "Empty manifest", bounded_contexts: [] },
8175
+ manifestMissing: true
8176
+ };
7951
8177
  }
7952
8178
  const message = err3 instanceof Error ? err3.message : "Unknown parse error";
7953
8179
  throw new Error(`Failed to parse manifest: ${message}`);
@@ -7987,9 +8213,27 @@ function validateManifest(manifest, flags) {
7987
8213
  var execAsync2 = promisify(exec);
7988
8214
  var SyncEngine = class {
7989
8215
  report = new MigrationReport();
8216
+ // PR-B1 (RCA #4): per-run mutation journal — pre-images of every file sync
8217
+ // touches, replayed in reverse on failure (see journal.ts). The lifetime is
8218
+ // one RUN, not one instance: run() re-news it on entry, so a reused engine
8219
+ // can never replay a previous run's pre-images into a later rollback.
8220
+ journal = new SyncJournal();
8221
+ // B-1 (PR-B2 review): generators that failed-soft this run. Four generators
8222
+ // catch their own exceptions into `result.error` by contract (Wave-2e: skip
8223
+ // the package, do not abort the run) — but a swallowed failure plans zero
8224
+ // ops, so a run that could not even read a target still summarized as
8225
+ // `Total ops : 0` and the CLI exited 0: errors masqueraded as convergence,
8226
+ // silently breaking `--check`'s "exit 0 ⇒ converged" promise. Failures are
8227
+ // recorded at each production site (NOT off the merged rows — mergeResult
8228
+ // keeps only the first error, so row-level counting would under-report
8229
+ // multi-module failures), printed as FAILED rows under the summary, and
8230
+ // surfaced as `SyncRunSummary.errors` for cli.ts to turn into exit ≠ 0.
8231
+ // Per-run lifetime, same reset discipline as the journal.
8232
+ failures = [];
7990
8233
  partialConfig;
7991
8234
  fullConfig = null;
7992
8235
  manifest = {};
8236
+ manifestMissing = false;
7993
8237
  workspaceRoot = "";
7994
8238
  options;
7995
8239
  constructor(flags, options) {
@@ -8008,6 +8252,19 @@ var SyncEngine = class {
8008
8252
  }
8009
8253
  return this.fullConfig;
8010
8254
  }
8255
+ /**
8256
+ * Record a failed-soft generator result (B-1). Called at every site that
8257
+ * receives a GeneratorResult, including the ones that never set `error`
8258
+ * today — the check is one truthy test, and a future generator adopting the
8259
+ * catch-into-result contract is then surfaced without anyone remembering
8260
+ * this seam. `row` matches the summary-table label so the FAILED line and
8261
+ * the table read as one report.
8262
+ */
8263
+ noteFailure(row, result) {
8264
+ if (result.error) {
8265
+ this.failures.push({ row, message: result.error.message });
8266
+ }
8267
+ }
8011
8268
  async ensureDirectories() {
8012
8269
  const config = this.getConfig();
8013
8270
  const result = createEmptyResult();
@@ -8022,20 +8279,12 @@ var SyncEngine = class {
8022
8279
  );
8023
8280
  continue;
8024
8281
  }
8025
- const moduleDir = path33__default.join(this.workspaceRoot, "packages", mod.name);
8282
+ const moduleDir = path34__default.join(this.workspaceRoot, "packages", mod.name);
8026
8283
  logger2.info(
8027
8284
  `Ensuring directories for module: ${mod.name} at ${moduleDir}`
8028
8285
  );
8029
- const layerResult = await ensureLayerFolders(
8030
- moduleDir,
8031
- layers,
8032
- config,
8033
- this.report
8034
- );
8035
- result.created.push(...layerResult.created);
8036
- result.skipped.push(...layerResult.skipped);
8037
- result.updated.push(...layerResult.updated);
8038
- result.totalOps += layerResult.totalOps;
8286
+ const layerResult = await ensureLayerFolders(moduleDir, layers, config);
8287
+ mergeResult2(result, layerResult);
8039
8288
  }
8040
8289
  return result;
8041
8290
  }
@@ -8050,7 +8299,7 @@ var SyncEngine = class {
8050
8299
  const stubs = createEmptyResult();
8051
8300
  for (const module of modules) {
8052
8301
  const moduleName = module.name;
8053
- const moduleDir = path33__default.join(this.workspaceRoot, "packages", moduleName);
8302
+ const moduleDir = path34__default.join(this.workspaceRoot, "packages", moduleName);
8054
8303
  if (moduleName.includes("..") || moduleName.includes("/") || moduleName.startsWith(".")) {
8055
8304
  logger2.warn(
8056
8305
  `Skipping invalid module name (potential path traversal): ${moduleName}`
@@ -8087,6 +8336,11 @@ var SyncEngine = class {
8087
8336
  config,
8088
8337
  this.report
8089
8338
  );
8339
+ this.noteFailure("Barrels", barrelResult);
8340
+ this.noteFailure("package.json", pkgResult);
8341
+ this.noteFailure("tsconfig.json", tsResult);
8342
+ this.noteFailure("ESLint", eslintResult);
8343
+ this.noteFailure("Stubs", stubResult);
8090
8344
  if (this.partialConfig.mode === "self-regen") {
8091
8345
  await reapLegacyFolders(moduleDir, config, this.report);
8092
8346
  }
@@ -8112,6 +8366,9 @@ var SyncEngine = class {
8112
8366
  const { logger: logger2, dryRun, allowDirty, mode } = this.partialConfig;
8113
8367
  const start = Date.now();
8114
8368
  let lockFile = null;
8369
+ this.journal = new SyncJournal();
8370
+ this.failures = [];
8371
+ this.manifestMissing = false;
8115
8372
  logger2.info(
8116
8373
  dryRun ? "[DRY-RUN MODE] Starting sync..." : "Starting sync..."
8117
8374
  );
@@ -8151,16 +8408,19 @@ var SyncEngine = class {
8151
8408
  try {
8152
8409
  const initOptions = this.getInitOptions();
8153
8410
  this.workspaceRoot = await findWorkspaceRoot(initOptions);
8154
- this.manifest = await loadManifest(
8411
+ const loaded = await loadManifest(
8155
8412
  this.workspaceRoot,
8156
8413
  this.partialConfig,
8157
8414
  initOptions
8158
8415
  );
8416
+ this.manifest = loaded.manifest;
8417
+ this.manifestMissing = loaded.manifestMissing;
8159
8418
  validateManifest(this.manifest, this.partialConfig);
8160
8419
  this.fullConfig = {
8161
8420
  ...this.partialConfig,
8162
8421
  workspaceRoot: this.workspaceRoot,
8163
- manifest: this.manifest
8422
+ manifest: this.manifest,
8423
+ journal: this.journal
8164
8424
  };
8165
8425
  if (!dryRun && mode === "self-regen") {
8166
8426
  lockFile = new LockFile(this.workspaceRoot);
@@ -8186,23 +8446,29 @@ var SyncEngine = class {
8186
8446
  this.fullConfig,
8187
8447
  this.report
8188
8448
  );
8449
+ this.noteFailure("RootFiles", rootFilesResult);
8189
8450
  const archFilesResult = await generateArchitectureFiles(
8190
8451
  this.fullConfig,
8191
8452
  this.report
8192
8453
  );
8454
+ this.noteFailure("ArchFiles", archFilesResult);
8193
8455
  const layerResult = await this.ensureDirectories();
8456
+ this.noteFailure("Layers", layerResult);
8194
8457
  const coreResults = await this.generateCoreArtifacts();
8195
8458
  const { pkgs, tsconfigs, eslint, stubs } = coreResults;
8196
8459
  const firstPassBarrels = coreResults.barrels;
8197
8460
  const appsResult = await generateApps(this.fullConfig, this.report);
8461
+ this.noteFailure("Apps", appsResult);
8198
8462
  const crossContextResult = await generateCrossContext(
8199
8463
  this.fullConfig,
8200
8464
  this.report
8201
8465
  );
8466
+ this.noteFailure("CrossContext", crossContextResult);
8202
8467
  const sharedKernelResult = await generateSharedKernel(
8203
8468
  this.fullConfig,
8204
8469
  this.report
8205
8470
  );
8471
+ this.noteFailure("SharedKernel", sharedKernelResult);
8206
8472
  const secondPassBarrels = createEmptyResult();
8207
8473
  const modules = this.fullConfig.manifest.bounded_contexts ?? [];
8208
8474
  for (const module of modules) {
@@ -8210,16 +8476,48 @@ var SyncEngine = class {
8210
8476
  if (!moduleName || moduleName.includes("..") || moduleName.includes("/") || moduleName.startsWith(".")) {
8211
8477
  continue;
8212
8478
  }
8213
- const moduleDir = path33__default.join(this.workspaceRoot, "packages", moduleName);
8479
+ const moduleDir = path34__default.join(this.workspaceRoot, "packages", moduleName);
8214
8480
  const pass2 = await generateBarrels(
8215
8481
  moduleDir,
8216
8482
  this.fullConfig,
8217
8483
  this.report
8218
8484
  );
8485
+ this.noteFailure("Barrels", pass2);
8219
8486
  mergeResult2(secondPassBarrels, pass2);
8220
8487
  }
8221
8488
  const barrels = mergeBarrelPasses(firstPassBarrels, secondPassBarrels);
8222
- const totalOps = rootFilesResult.totalOps + archFilesResult.totalOps + layerResult.totalOps + barrels.totalOps + pkgs.totalOps + tsconfigs.totalOps + eslint.totalOps + stubs.totalOps + appsResult.totalOps + crossContextResult.totalOps + sharedKernelResult.totalOps;
8489
+ const rows = [
8490
+ ["RootFiles", rootFilesResult],
8491
+ ["ArchFiles", archFilesResult],
8492
+ ["Layers", layerResult],
8493
+ ["Barrels", barrels],
8494
+ ["CrossContext", crossContextResult],
8495
+ ["SharedKernel", sharedKernelResult],
8496
+ ["package.json", pkgs],
8497
+ ["tsconfig.json", tsconfigs],
8498
+ ["ESLint", eslint],
8499
+ ["Stubs", stubs],
8500
+ ["Apps", appsResult]
8501
+ ];
8502
+ const runSummary = {
8503
+ created: 0,
8504
+ updated: 0,
8505
+ deleted: 0,
8506
+ unchanged: 0,
8507
+ skipped: 0,
8508
+ totalOps: 0,
8509
+ errors: this.failures.length,
8510
+ manifestMissing: this.manifestMissing,
8511
+ durationMs: 0
8512
+ };
8513
+ for (const [, r] of rows) {
8514
+ runSummary.created += r.created.length;
8515
+ runSummary.updated += r.updated.length;
8516
+ runSummary.deleted += r.deleted.length;
8517
+ runSummary.unchanged += r.unchanged.length;
8518
+ runSummary.skipped += r.skipped.length;
8519
+ runSummary.totalOps += r.totalOps;
8520
+ }
8223
8521
  if (mode === "self-regen") {
8224
8522
  await runArchLinter(this.fullConfig);
8225
8523
  await this.report.writeReport(this.fullConfig);
@@ -8227,62 +8525,70 @@ var SyncEngine = class {
8227
8525
  logger2.info("Skipping arch-linter and report (external mode)");
8228
8526
  }
8229
8527
  const duration = Date.now() - start;
8230
- logger2.info("\nSync completed successfully.");
8528
+ runSummary.durationMs = duration;
8529
+ if (this.failures.length === 0) {
8530
+ logger2.info("\nSync completed successfully.");
8531
+ } else {
8532
+ logger2.error(
8533
+ `
8534
+ Sync completed with ${this.failures.length} generator failure(s) — see the FAILED row(s) below.`
8535
+ );
8536
+ }
8231
8537
  logger2.info(
8232
8538
  `Processed ${this.manifest.bounded_contexts?.length ?? 0} modules in ${duration}ms`
8233
8539
  );
8234
8540
  logger2.info(`
8235
8541
  === Generator Summary ===`);
8236
- logger2.info(
8237
- `• RootFiles : ${rootFilesResult.created.length} created, ${rootFilesResult.updated.length} updated, ${rootFilesResult.skipped.length} skipped`
8238
- );
8239
- logger2.info(
8240
- `• ArchFiles : ${archFilesResult.created.length} created, ${archFilesResult.updated.length} updated, ${archFilesResult.skipped.length} skipped`
8241
- );
8242
- logger2.info(
8243
- `• Layers : ${layerResult.created.length} created, ${layerResult.updated.length} updated, ${layerResult.skipped.length} skipped`
8244
- );
8245
- logger2.info(
8246
- `• Barrels : ${barrels.created.length} created, ${barrels.updated.length} updated, ${barrels.skipped.length} skipped`
8247
- );
8248
- logger2.info(
8249
- `• CrossContext : ${crossContextResult.created.length} created, ${crossContextResult.updated.length} updated, ${crossContextResult.skipped.length} skipped`
8250
- );
8251
- logger2.info(
8252
- `• SharedKernel : ${sharedKernelResult.created.length} created, ${sharedKernelResult.updated.length} updated, ${sharedKernelResult.skipped.length} skipped`
8253
- );
8254
- logger2.info(
8255
- `• package.json : ${pkgs.created.length} created, ${pkgs.updated.length} updated, ${pkgs.skipped.length} skipped`
8256
- );
8257
- logger2.info(
8258
- `• tsconfig.json : ${tsconfigs.created.length} created, ${tsconfigs.updated.length} updated, ${tsconfigs.skipped.length} skipped`
8259
- );
8260
- logger2.info(
8261
- `• ESLint : ${eslint.created.length} created, ${eslint.updated.length} updated, ${eslint.skipped.length} skipped`
8262
- );
8263
- logger2.info(
8264
- `• Stubs : ${stubs.created.length} created, ${stubs.updated.length} updated, ${stubs.skipped.length} skipped`
8265
- );
8266
- logger2.info(
8267
- `• Apps : ${appsResult.created.length} created, ${appsResult.updated.length} updated, ${appsResult.skipped.length} skipped`
8268
- );
8269
- logger2.info(`• Total ops : ${totalOps}`);
8542
+ for (const [label, r] of rows) {
8543
+ logger2.info(
8544
+ `• ${label} : ${r.created.length} created, ${r.updated.length} updated, ${r.deleted.length} deleted, ${r.unchanged.length} unchanged, ${r.skipped.length} skipped`
8545
+ );
8546
+ }
8547
+ for (const f of this.failures) {
8548
+ logger2.error(`• ${f.row} : FAILED — ${f.message}`);
8549
+ }
8550
+ logger2.info(`• Total ops : ${runSummary.totalOps}`);
8551
+ return runSummary;
8270
8552
  } catch (err3) {
8271
8553
  const message = err3 instanceof Error ? err3.message : "Unknown sync error";
8272
8554
  logger2.error(`Sync failed: ${message}`);
8273
8555
  if (!dryRun) {
8274
- try {
8275
- await execAsync2("git reset --hard HEAD && git clean -fd", {
8276
- cwd: this.workspaceRoot
8277
- });
8278
- logger2.info("Rollback completed after failure.");
8279
- } catch (rollbackErr) {
8556
+ if (this.journal.size === 0) {
8557
+ logger2.info(
8558
+ "No files were touched before the failure — nothing to roll back."
8559
+ );
8560
+ } else if (allowDirty) {
8280
8561
  logger2.warn(
8281
- `Rollback failed: ${rollbackErr instanceof Error ? rollbackErr.message : rollbackErr}`
8562
+ `Sync failed after touching ${this.journal.size} path(s) — NO rollback under --allow-dirty; the tree is left as-is:`
8282
8563
  );
8564
+ for (const line of this.journal.describeEntries(this.workspaceRoot)) {
8565
+ logger2.warn(` ${line}`);
8566
+ }
8567
+ } else {
8568
+ logger2.info(
8569
+ `Rolling back ${this.journal.size} journaled path(s) (inverse-ops; never git reset/clean)...`
8570
+ );
8571
+ const outcome = await this.journal.rollback(
8572
+ logger2,
8573
+ this.workspaceRoot
8574
+ );
8575
+ if (outcome.failures.length === 0) {
8576
+ logger2.info(
8577
+ `Rollback completed: ${outcome.restored}/${outcome.attempted} path(s) restored.`
8578
+ );
8579
+ } else {
8580
+ for (const f of outcome.failures) {
8581
+ logger2.error(
8582
+ `Rollback failed for ${path34__default.relative(this.workspaceRoot, f.path)}: intended to ${f.intended} — ${f.error}`
8583
+ );
8584
+ }
8585
+ logger2.error(
8586
+ `Rollback incomplete: ${outcome.failures.length} of ${outcome.attempted} path(s) NOT restored — inspect the paths above.`
8587
+ );
8588
+ }
8283
8589
  }
8284
- process.exit(1);
8285
8590
  }
8591
+ throw err3;
8286
8592
  } finally {
8287
8593
  if (lockFile) {
8288
8594
  try {
@@ -8309,7 +8615,7 @@ function err2(error) {
8309
8615
  var execAsync3 = promisify(exec);
8310
8616
  async function loadManifest2(workspaceRoot) {
8311
8617
  try {
8312
- const manifestPath = path33__default.join(
8618
+ const manifestPath = path34__default.join(
8313
8619
  workspaceRoot,
8314
8620
  ".architecture/manifest.yaml"
8315
8621
  );
@@ -8468,7 +8774,9 @@ async function validateCommand() {
8468
8774
  process.exit(1);
8469
8775
  return;
8470
8776
  }
8471
- console.log("✅ Architecture is compliant with manifest.yaml");
8777
+ console.log(
8778
+ "✅ Architecture is compliant (arch-linter: cross-context imports via manifest depends_on + linter-config, layer rules, subpath conventions, server markers, required communication)."
8779
+ );
8472
8780
  }
8473
8781
  var YamlLoadError = class extends Error {
8474
8782
  constructor(message, filePath) {
@@ -8497,27 +8805,27 @@ var YamlSaveError = class extends Error {
8497
8805
  filePath;
8498
8806
  };
8499
8807
  var YamlService = class {
8500
- async loadManifest(path37) {
8808
+ async loadManifest(path39) {
8501
8809
  try {
8502
- const content = await readFile(path37, "utf-8");
8810
+ const content = await readFile(path39, "utf-8");
8503
8811
  const manifest = yaml9.load(content);
8504
8812
  return ok2(manifest);
8505
8813
  } catch (e) {
8506
8814
  const error = e;
8507
8815
  if (error.code === "ENOENT") {
8508
- return err2(new YamlLoadError(`File not found: ${path37}`, path37));
8816
+ return err2(new YamlLoadError(`File not found: ${path39}`, path39));
8509
8817
  }
8510
- return err2(new YamlLoadError(error.message, path37));
8818
+ return err2(new YamlLoadError(error.message, path39));
8511
8819
  }
8512
8820
  }
8513
- saveManifest(manifest, path37) {
8514
- const dir = dirname(path37);
8515
- const tempPath = `${path37}.tmp`;
8821
+ saveManifest(manifest, path39) {
8822
+ const dir = dirname(path39);
8823
+ const tempPath = `${path39}.tmp`;
8516
8824
  try {
8517
8825
  mkdirSync(dir, { recursive: true });
8518
8826
  const content = yaml9.dump(manifest, { indent: 2 });
8519
8827
  writeFileSync(tempPath, content, "utf-8");
8520
- renameSync(tempPath, path37);
8828
+ renameSync(tempPath, path39);
8521
8829
  return ok2(void 0);
8522
8830
  } catch (e) {
8523
8831
  const error = e;
@@ -8525,7 +8833,7 @@ var YamlService = class {
8525
8833
  if (existsSync(tempPath)) unlinkSync(tempPath);
8526
8834
  } catch {
8527
8835
  }
8528
- return err2(new YamlSaveError(error.message, path37));
8836
+ return err2(new YamlSaveError(error.message, path39));
8529
8837
  }
8530
8838
  }
8531
8839
  parse(content) {
@@ -8734,8 +9042,8 @@ function resolveTemplatesDir() {
8734
9042
  if (process.env.HEXAGEN_TEMPLATES_DIR) {
8735
9043
  return process.env.HEXAGEN_TEMPLATES_DIR;
8736
9044
  }
8737
- const cliDir = path33__default.dirname(fileURLToPath(import.meta.url));
8738
- return path33__default.resolve(cliDir, "templates");
9045
+ const cliDir = path34__default.dirname(fileURLToPath(import.meta.url));
9046
+ return path34__default.resolve(cliDir, "templates");
8739
9047
  }
8740
9048
 
8741
9049
  // src/commands/arch/port.ts
@@ -9363,8 +9671,8 @@ var removeCommander = new Command("remove").description("Remove a port or bounde
9363
9671
  function getManifestPath2(cwd) {
9364
9672
  return join(cwd, ".architecture", "manifest.yaml");
9365
9673
  }
9366
- async function loadManifestFromPath(path37) {
9367
- const result = await yamlService.loadManifest(path37);
9674
+ async function loadManifestFromPath(path39) {
9675
+ const result = await yamlService.loadManifest(path39);
9368
9676
  if (!result.success) {
9369
9677
  return err2(result.error);
9370
9678
  }
@@ -9782,7 +10090,7 @@ function isInstalled(config, templateId) {
9782
10090
  return templateId in config.templates;
9783
10091
  }
9784
10092
  function conflictFilePath(filePath) {
9785
- const ext = path33__default.extname(filePath);
10093
+ const ext = path34__default.extname(filePath);
9786
10094
  return ext ? filePath.slice(0, -ext.length) + ".hexagen-update" + ext : filePath + ".hexagen-update";
9787
10095
  }
9788
10096
 
@@ -9845,19 +10153,19 @@ function resolveDependencies(requested, registry) {
9845
10153
  }
9846
10154
  const sorted = [];
9847
10155
  const state = /* @__PURE__ */ new Map();
9848
- function visit(id, path37) {
10156
+ function visit(id, path39) {
9849
10157
  const s = state.get(id);
9850
10158
  if (s === "done")
9851
10159
  return;
9852
10160
  if (s === "visiting") {
9853
- const cycleStart = path37.indexOf(id);
9854
- throw new CyclicDependencyError([...path37.slice(cycleStart), id]);
10161
+ const cycleStart = path39.indexOf(id);
10162
+ throw new CyclicDependencyError([...path39.slice(cycleStart), id]);
9855
10163
  }
9856
10164
  state.set(id, "visiting");
9857
10165
  const manifest = registry.get(id);
9858
10166
  for (const dep of manifest.requires) {
9859
10167
  if (needed.has(dep))
9860
- visit(dep, [...path37, id]);
10168
+ visit(dep, [...path39, id]);
9861
10169
  }
9862
10170
  state.set(id, "done");
9863
10171
  sorted.push(id);
@@ -9985,9 +10293,9 @@ var ValidateTemplatesUseCase = class {
9985
10293
  if (!isOutputEnabled(output, answers))
9986
10294
  continue;
9987
10295
  const rel = outputPath(output);
9988
- const abs = path33__default.join(projectRoot, rel);
10296
+ const abs = path34__default.join(projectRoot, rel);
9989
10297
  try {
9990
- await fs25.access(abs);
10298
+ await fs27.access(abs);
9991
10299
  } catch {
9992
10300
  missingFiles.push(rel);
9993
10301
  }
@@ -10002,10 +10310,10 @@ var ValidateTemplatesUseCase = class {
10002
10310
  for (const output of manifest.outputs) {
10003
10311
  if (!isOutputEnabled(output, answers))
10004
10312
  continue;
10005
- const absConflict = conflictFilePath(path33__default.join(projectRoot, outputPath(output)));
10313
+ const absConflict = conflictFilePath(path34__default.join(projectRoot, outputPath(output)));
10006
10314
  try {
10007
- await fs25.access(absConflict);
10008
- conflictFiles.push(path33__default.relative(projectRoot, absConflict));
10315
+ await fs27.access(absConflict);
10316
+ conflictFiles.push(path34__default.relative(projectRoot, absConflict));
10009
10317
  } catch {
10010
10318
  }
10011
10319
  }
@@ -10024,25 +10332,25 @@ var ValidateTemplatesUseCase = class {
10024
10332
  return { results, totalWarnings, totalErrors };
10025
10333
  }
10026
10334
  };
10027
- var PACKAGE_ROOT = path33__default.resolve(path33__default.dirname(fileURLToPath(import.meta.url)), "..", "..");
10335
+ var PACKAGE_ROOT = path34__default.resolve(path34__default.dirname(fileURLToPath(import.meta.url)), "..", "..");
10028
10336
  var FileSystemTemplateRegistry = class {
10029
10337
  templatesDir;
10030
10338
  cache = null;
10031
10339
  constructor(templatesDir) {
10032
- this.templatesDir = templatesDir ?? path33__default.join(PACKAGE_ROOT, "templates");
10340
+ this.templatesDir = templatesDir ?? path34__default.join(PACKAGE_ROOT, "templates");
10033
10341
  }
10034
10342
  async loadAll() {
10035
10343
  if (this.cache)
10036
10344
  return this.cache;
10037
10345
  let entries;
10038
10346
  try {
10039
- entries = await fs25.readdir(this.templatesDir);
10347
+ entries = await fs27.readdir(this.templatesDir);
10040
10348
  } catch {
10041
10349
  return [];
10042
10350
  }
10043
10351
  const manifests = [];
10044
10352
  for (const entry of entries) {
10045
- const manifestPath = path33__default.join(this.templatesDir, entry, "manifest.json");
10353
+ const manifestPath = path34__default.join(this.templatesDir, entry, "manifest.json");
10046
10354
  const manifest = await this.readManifest(manifestPath);
10047
10355
  if (manifest)
10048
10356
  manifests.push(manifest);
@@ -10051,13 +10359,13 @@ var FileSystemTemplateRegistry = class {
10051
10359
  return manifests;
10052
10360
  }
10053
10361
  async loadOne(id) {
10054
- const manifestPath = path33__default.join(this.templatesDir, id, "manifest.json");
10362
+ const manifestPath = path34__default.join(this.templatesDir, id, "manifest.json");
10055
10363
  return this.readManifest(manifestPath);
10056
10364
  }
10057
10365
  async readManifest(manifestPath) {
10058
10366
  let raw;
10059
10367
  try {
10060
- raw = await fs25.readFile(manifestPath, "utf-8");
10368
+ raw = await fs27.readFile(manifestPath, "utf-8");
10061
10369
  } catch {
10062
10370
  return null;
10063
10371
  }
@@ -10193,31 +10501,31 @@ ${prompt} (comma-separated numbers)`);
10193
10501
  }
10194
10502
  }
10195
10503
  };
10196
- var PACKAGE_ROOT2 = path33__default.resolve(path33__default.dirname(fileURLToPath(import.meta.url)), "..", "..");
10504
+ var PACKAGE_ROOT2 = path34__default.resolve(path34__default.dirname(fileURLToPath(import.meta.url)), "..", "..");
10197
10505
  var FileSystemFileEmitter = class {
10198
10506
  templatesDir;
10199
10507
  constructor(templatesDir) {
10200
- this.templatesDir = templatesDir ?? path33__default.join(PACKAGE_ROOT2, "templates");
10508
+ this.templatesDir = templatesDir ?? path34__default.join(PACKAGE_ROOT2, "templates");
10201
10509
  }
10202
10510
  async emit(manifest, answers, projectRoot, config) {
10203
10511
  const warnings = [];
10204
10512
  const generatedFiles = [];
10205
- const templateFilesDir = path33__default.join(this.templatesDir, manifest.id, "files");
10206
- const resolvedRoot = path33__default.resolve(projectRoot);
10513
+ const templateFilesDir = path34__default.join(this.templatesDir, manifest.id, "files");
10514
+ const resolvedRoot = path34__default.resolve(projectRoot);
10207
10515
  for (const out of manifest.outputs) {
10208
10516
  if (!isOutputEnabled(out, answers))
10209
10517
  continue;
10210
10518
  const outputRelPath = outputPath(out);
10211
- const destFile = path33__default.resolve(projectRoot, outputRelPath);
10212
- if (!destFile.startsWith(resolvedRoot + path33__default.sep) && destFile !== resolvedRoot) {
10519
+ const destFile = path34__default.resolve(projectRoot, outputRelPath);
10520
+ if (!destFile.startsWith(resolvedRoot + path34__default.sep) && destFile !== resolvedRoot) {
10213
10521
  throw new Error(`Output path '${outputRelPath}' escapes the project root`);
10214
10522
  }
10215
- const sourceFile = path33__default.join(templateFilesDir, outputRelPath);
10523
+ const sourceFile = path34__default.join(templateFilesDir, outputRelPath);
10216
10524
  let templateContent;
10217
10525
  let sourceMode = 420;
10218
10526
  try {
10219
- const raw = await fs25.readFile(sourceFile, "utf-8");
10220
- sourceMode = (await fs25.stat(sourceFile)).mode & 511;
10527
+ const raw = await fs27.readFile(sourceFile, "utf-8");
10528
+ sourceMode = (await fs27.stat(sourceFile)).mode & 511;
10221
10529
  const { output, warnings: interpWarnings } = interpolate(raw, answers);
10222
10530
  templateContent = output;
10223
10531
  for (const key of interpWarnings) {
@@ -10232,7 +10540,7 @@ var FileSystemFileEmitter = class {
10232
10540
  const templateHash = sha256(templateContent);
10233
10541
  let existingContent = null;
10234
10542
  try {
10235
- existingContent = await fs25.readFile(destFile, "utf-8");
10543
+ existingContent = await fs27.readFile(destFile, "utf-8");
10236
10544
  } catch {
10237
10545
  }
10238
10546
  if (existingContent !== null) {
@@ -10242,7 +10550,7 @@ var FileSystemFileEmitter = class {
10242
10550
  if (!isAlreadyIdentical && !wasGeneratedByHexagen) {
10243
10551
  const conflictDest = conflictFilePath(destFile);
10244
10552
  await atomicWrite(conflictDest, templateContent, sourceMode);
10245
- const rel = path33__default.relative(projectRoot, conflictDest);
10553
+ const rel = path34__default.relative(projectRoot, conflictDest);
10246
10554
  warnings.push(`⚠️ Conflict: ${outputRelPath} has local changes.
10247
10555
  New version written to ${rel}
10248
10556
  Review and merge manually, then delete the conflict file.`);
@@ -10256,18 +10564,18 @@ var FileSystemFileEmitter = class {
10256
10564
  }
10257
10565
  };
10258
10566
  async function atomicWrite(filePath, content, mode) {
10259
- await fs25.mkdir(path33__default.dirname(filePath), { recursive: true });
10567
+ await fs27.mkdir(path34__default.dirname(filePath), { recursive: true });
10260
10568
  const tmp = `${filePath}.tmp.${Date.now()}`;
10261
10569
  try {
10262
- await fs25.writeFile(tmp, content, "utf-8");
10570
+ await fs27.writeFile(tmp, content, "utf-8");
10263
10571
  if (mode !== void 0 && (mode & 73) !== 0) {
10264
- const created = (await fs25.stat(tmp)).mode & 511;
10572
+ const created = (await fs27.stat(tmp)).mode & 511;
10265
10573
  const execBits = mode & 73 & ~process.umask();
10266
- await fs25.chmod(tmp, created | execBits);
10574
+ await fs27.chmod(tmp, created | execBits);
10267
10575
  }
10268
- await fs25.rename(tmp, filePath);
10576
+ await fs27.rename(tmp, filePath);
10269
10577
  } catch (err3) {
10270
- await fs25.rm(tmp, { force: true }).catch(() => {
10578
+ await fs27.rm(tmp, { force: true }).catch(() => {
10271
10579
  });
10272
10580
  throw err3;
10273
10581
  }
@@ -10277,9 +10585,9 @@ function sha256(content) {
10277
10585
  }
10278
10586
  var FileSystemTemplateConfigStore = class {
10279
10587
  async load(projectRoot) {
10280
- const configPath = path33__default.join(projectRoot, TEMPLATE_CONFIG_FILE);
10588
+ const configPath = path34__default.join(projectRoot, TEMPLATE_CONFIG_FILE);
10281
10589
  try {
10282
- const raw = await fs25.readFile(configPath, "utf-8");
10590
+ const raw = await fs27.readFile(configPath, "utf-8");
10283
10591
  return JSON.parse(raw);
10284
10592
  } catch (err3) {
10285
10593
  if (err3.code === "ENOENT")
@@ -10288,10 +10596,10 @@ var FileSystemTemplateConfigStore = class {
10288
10596
  }
10289
10597
  }
10290
10598
  async save(projectRoot, config) {
10291
- const configPath = path33__default.join(projectRoot, TEMPLATE_CONFIG_FILE);
10599
+ const configPath = path34__default.join(projectRoot, TEMPLATE_CONFIG_FILE);
10292
10600
  const tmp = `${configPath}.tmp.${Date.now()}`;
10293
- await fs25.writeFile(tmp, JSON.stringify(config, null, 2), "utf-8");
10294
- await fs25.rename(tmp, configPath);
10601
+ await fs27.writeFile(tmp, JSON.stringify(config, null, 2), "utf-8");
10602
+ await fs27.rename(tmp, configPath);
10295
10603
  }
10296
10604
  };
10297
10605
 
@@ -10526,8 +10834,8 @@ Installed templates: ${installed}
10526
10834
  function getManifestPath3(cwd) {
10527
10835
  return join(cwd, ".architecture", "manifest.yaml");
10528
10836
  }
10529
- async function loadManifest4(path37) {
10530
- const result = await yamlService.loadManifest(path37);
10837
+ async function loadManifest4(path39) {
10838
+ const result = await yamlService.loadManifest(path39);
10531
10839
  if (!result.success) {
10532
10840
  throw result.error;
10533
10841
  }
@@ -10725,35 +11033,35 @@ var FileSystemWorkspaceAdapter = class {
10725
11033
  }
10726
11034
  workspaceRoot;
10727
11035
  listPackages() {
10728
- const packagesDir = path33.join(this.workspaceRoot, "packages");
10729
- if (!fs22.existsSync(packagesDir)) {
11036
+ const packagesDir = path34.join(this.workspaceRoot, "packages");
11037
+ if (!fs24.existsSync(packagesDir)) {
10730
11038
  return [];
10731
11039
  }
10732
- return fs22.readdirSync(packagesDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
11040
+ return fs24.readdirSync(packagesDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
10733
11041
  }
10734
11042
  listApps() {
10735
- const appsDir = path33.join(this.workspaceRoot, "apps");
10736
- if (!fs22.existsSync(appsDir)) {
11043
+ const appsDir = path34.join(this.workspaceRoot, "apps");
11044
+ if (!fs24.existsSync(appsDir)) {
10737
11045
  return [];
10738
11046
  }
10739
- return fs22.readdirSync(appsDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
11047
+ return fs24.readdirSync(appsDir, { withFileTypes: true }).filter((dirent) => dirent.isDirectory()).map((dirent) => dirent.name);
10740
11048
  }
10741
11049
  getSourceFiles(dir) {
10742
- if (!fs22.existsSync(dir)) {
11050
+ if (!fs24.existsSync(dir)) {
10743
11051
  return [];
10744
11052
  }
10745
- const entries = fs22.readdirSync(dir, { withFileTypes: true });
11053
+ const entries = fs24.readdirSync(dir, { withFileTypes: true });
10746
11054
  return entries.map((entry) => ({
10747
- path: path33.join(dir, entry.name),
11055
+ path: path34.join(dir, entry.name),
10748
11056
  isDirectory: entry.isDirectory()
10749
11057
  }));
10750
11058
  }
10751
11059
  fileExists(filePath) {
10752
- return fs22.existsSync(filePath);
11060
+ return fs24.existsSync(filePath);
10753
11061
  }
10754
11062
  readFile(filePath) {
10755
11063
  try {
10756
- return fs22.readFileSync(filePath, "utf-8");
11064
+ return fs24.readFileSync(filePath, "utf-8");
10757
11065
  } catch {
10758
11066
  return null;
10759
11067
  }
@@ -11172,15 +11480,15 @@ async function updateBarrelExport(sourceFile, oldName, newName) {
11172
11480
  }
11173
11481
  async function updateManifestEntry(workspaceRoot, updateFn) {
11174
11482
  try {
11175
- const manifestPath = path33__default.join(
11483
+ const manifestPath = path34__default.join(
11176
11484
  workspaceRoot,
11177
11485
  ".architecture/manifest.yaml"
11178
11486
  );
11179
- const content = await fs25.readFile(manifestPath, "utf-8");
11487
+ const content = await fs27.readFile(manifestPath, "utf-8");
11180
11488
  const manifest = yaml9.load(content);
11181
11489
  updateFn(manifest);
11182
11490
  const updatedContent = yaml9.dump(manifest, { indent: 2 });
11183
- await fs25.writeFile(manifestPath, updatedContent, "utf-8");
11491
+ await fs27.writeFile(manifestPath, updatedContent, "utf-8");
11184
11492
  return ok2(void 0);
11185
11493
  } catch (error) {
11186
11494
  return err2(error);
@@ -11244,7 +11552,7 @@ var RenamePortPattern = class {
11244
11552
  (f) => f.reason.includes("Declares")
11245
11553
  );
11246
11554
  for (const file of portFiles) {
11247
- const filePath = path33__default.join(this.workspaceRoot, file.path);
11555
+ const filePath = path34__default.join(this.workspaceRoot, file.path);
11248
11556
  const sourceFile = this.project.addSourceFileAtPath(filePath);
11249
11557
  const existingInterface = sourceFile.getInterface(request.newName);
11250
11558
  if (existingInterface) {
@@ -11266,7 +11574,7 @@ var RenamePortPattern = class {
11266
11574
  const warnings = [];
11267
11575
  try {
11268
11576
  for (const file of impact.filesToModify) {
11269
- const filePath = path33__default.join(this.workspaceRoot, file.path);
11577
+ const filePath = path34__default.join(this.workspaceRoot, file.path);
11270
11578
  if (file.path.endsWith(".ts") || file.path.endsWith(".tsx")) {
11271
11579
  try {
11272
11580
  this.project.addSourceFileAtPath(filePath);
@@ -11369,7 +11677,7 @@ var RenamePortPattern = class {
11369
11677
  */
11370
11678
  async renamePortFile(relativePath, oldName, newName) {
11371
11679
  try {
11372
- const filePath = path33__default.join(this.workspaceRoot, relativePath);
11680
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
11373
11681
  const sourceFile = this.project.getSourceFile(filePath);
11374
11682
  if (!sourceFile) {
11375
11683
  return err2(new Error(`Source file not found: ${relativePath}`));
@@ -11382,17 +11690,17 @@ var RenamePortPattern = class {
11382
11690
  if (typeAlias) {
11383
11691
  typeAlias.rename(newName);
11384
11692
  }
11385
- const oldFileName = path33__default.basename(relativePath);
11693
+ const oldFileName = path34__default.basename(relativePath);
11386
11694
  const newFileName = oldFileName.replace(
11387
11695
  toKebabCase(oldName),
11388
11696
  toKebabCase(newName)
11389
11697
  );
11390
11698
  if (oldFileName !== newFileName) {
11391
- const newFilePath = path33__default.join(path33__default.dirname(filePath), newFileName);
11699
+ const newFilePath = path34__default.join(path34__default.dirname(filePath), newFileName);
11392
11700
  await sourceFile.move(newFilePath);
11393
11701
  return ok2([
11394
11702
  relativePath,
11395
- path33__default.relative(this.workspaceRoot, newFilePath)
11703
+ path34__default.relative(this.workspaceRoot, newFilePath)
11396
11704
  ]);
11397
11705
  }
11398
11706
  return ok2([relativePath]);
@@ -11405,7 +11713,7 @@ var RenamePortPattern = class {
11405
11713
  */
11406
11714
  async updateImports(relativePath, oldName, newName) {
11407
11715
  try {
11408
- const filePath = path33__default.join(this.workspaceRoot, relativePath);
11716
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
11409
11717
  const sourceFile = this.project.getSourceFile(filePath);
11410
11718
  if (!sourceFile) {
11411
11719
  return ok2([]);
@@ -11421,7 +11729,7 @@ var RenamePortPattern = class {
11421
11729
  */
11422
11730
  async updateBarrelExport(relativePath, oldName, newName) {
11423
11731
  try {
11424
- const filePath = path33__default.join(this.workspaceRoot, relativePath);
11732
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
11425
11733
  const sourceFile = this.project.getSourceFile(filePath);
11426
11734
  if (!sourceFile) {
11427
11735
  return ok2([]);
@@ -11464,7 +11772,7 @@ var RenamePortPattern = class {
11464
11772
  */
11465
11773
  async updateTestDouble(relativePath, oldName, newName) {
11466
11774
  try {
11467
- const filePath = path33__default.join(this.workspaceRoot, relativePath);
11775
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
11468
11776
  const sourceFile = this.project.getSourceFile(filePath);
11469
11777
  if (!sourceFile) {
11470
11778
  return ok2([]);
@@ -11494,17 +11802,17 @@ var RenamePortPattern = class {
11494
11802
  );
11495
11803
  modified = modified || importsModified;
11496
11804
  if (modified) {
11497
- const oldFileName = path33__default.basename(relativePath);
11805
+ const oldFileName = path34__default.basename(relativePath);
11498
11806
  const newFileName = oldFileName.replace(
11499
11807
  toKebabCase(oldName),
11500
11808
  toKebabCase(newName)
11501
11809
  );
11502
11810
  if (oldFileName !== newFileName) {
11503
- const newFilePath = path33__default.join(path33__default.dirname(filePath), newFileName);
11811
+ const newFilePath = path34__default.join(path34__default.dirname(filePath), newFileName);
11504
11812
  await sourceFile.move(newFilePath);
11505
11813
  return ok2([
11506
11814
  relativePath,
11507
- path33__default.relative(this.workspaceRoot, newFilePath)
11815
+ path34__default.relative(this.workspaceRoot, newFilePath)
11508
11816
  ]);
11509
11817
  }
11510
11818
  }
@@ -11577,7 +11885,7 @@ var RenameUseCasePattern = class {
11577
11885
  const warnings = [];
11578
11886
  try {
11579
11887
  for (const file of impact.filesToModify) {
11580
- const filePath = path33__default.join(this.workspaceRoot, file.path);
11888
+ const filePath = path34__default.join(this.workspaceRoot, file.path);
11581
11889
  if (file.path.endsWith(".ts") || file.path.endsWith(".tsx")) {
11582
11890
  try {
11583
11891
  this.project.addSourceFileAtPath(filePath);
@@ -11688,7 +11996,7 @@ var RenameUseCasePattern = class {
11688
11996
  */
11689
11997
  async renameUseCaseFile(relativePath, oldName, newName) {
11690
11998
  try {
11691
- const filePath = path33__default.join(this.workspaceRoot, relativePath);
11999
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
11692
12000
  const sourceFile = this.project.getSourceFile(filePath);
11693
12001
  if (!sourceFile) {
11694
12002
  return err2(new Error(`Source file not found: ${relativePath}`));
@@ -11697,17 +12005,17 @@ var RenameUseCasePattern = class {
11697
12005
  if (classDecl) {
11698
12006
  classDecl.rename(newName);
11699
12007
  }
11700
- const oldFileName = path33__default.basename(relativePath);
12008
+ const oldFileName = path34__default.basename(relativePath);
11701
12009
  const newFileName = oldFileName.replace(
11702
12010
  toKebabCase(oldName),
11703
12011
  toKebabCase(newName)
11704
12012
  );
11705
12013
  if (oldFileName !== newFileName) {
11706
- const newFilePath = path33__default.join(path33__default.dirname(filePath), newFileName);
12014
+ const newFilePath = path34__default.join(path34__default.dirname(filePath), newFileName);
11707
12015
  await sourceFile.move(newFilePath);
11708
12016
  return ok2([
11709
12017
  relativePath,
11710
- path33__default.relative(this.workspaceRoot, newFilePath)
12018
+ path34__default.relative(this.workspaceRoot, newFilePath)
11711
12019
  ]);
11712
12020
  }
11713
12021
  return ok2([relativePath]);
@@ -11717,7 +12025,7 @@ var RenameUseCasePattern = class {
11717
12025
  }
11718
12026
  async updateImports(relativePath, oldName, newName) {
11719
12027
  try {
11720
- const filePath = path33__default.join(this.workspaceRoot, relativePath);
12028
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
11721
12029
  const sourceFile = this.project.getSourceFile(filePath);
11722
12030
  if (!sourceFile) {
11723
12031
  return ok2([]);
@@ -11733,7 +12041,7 @@ var RenameUseCasePattern = class {
11733
12041
  */
11734
12042
  async updateBarrelExport(relativePath, oldName, newName) {
11735
12043
  try {
11736
- const filePath = path33__default.join(this.workspaceRoot, relativePath);
12044
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
11737
12045
  const sourceFile = this.project.getSourceFile(filePath);
11738
12046
  if (!sourceFile) {
11739
12047
  return ok2([]);
@@ -11770,24 +12078,24 @@ var RenameUseCasePattern = class {
11770
12078
  */
11771
12079
  async updateTestFile(relativePath, oldName, newName) {
11772
12080
  try {
11773
- const filePath = path33__default.join(this.workspaceRoot, relativePath);
12081
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
11774
12082
  const sourceFile = this.project.getSourceFile(filePath);
11775
12083
  if (!sourceFile) {
11776
12084
  return ok2([]);
11777
12085
  }
11778
12086
  const modified = await updateImports(sourceFile, oldName, newName);
11779
12087
  if (modified) {
11780
- const oldFileName = path33__default.basename(relativePath);
12088
+ const oldFileName = path34__default.basename(relativePath);
11781
12089
  const newFileName = oldFileName.replace(
11782
12090
  toKebabCase(oldName),
11783
12091
  toKebabCase(newName)
11784
12092
  );
11785
12093
  if (oldFileName !== newFileName) {
11786
- const newFilePath = path33__default.join(path33__default.dirname(filePath), newFileName);
12094
+ const newFilePath = path34__default.join(path34__default.dirname(filePath), newFileName);
11787
12095
  await sourceFile.move(newFilePath);
11788
12096
  return ok2([
11789
12097
  relativePath,
11790
- path33__default.relative(this.workspaceRoot, newFilePath)
12098
+ path34__default.relative(this.workspaceRoot, newFilePath)
11791
12099
  ]);
11792
12100
  }
11793
12101
  }
@@ -11798,7 +12106,7 @@ var RenameUseCasePattern = class {
11798
12106
  }
11799
12107
  async updateCompositionRoot(relativePath, oldName, newName) {
11800
12108
  try {
11801
- const filePath = path33__default.join(this.workspaceRoot, relativePath);
12109
+ const filePath = path34__default.join(this.workspaceRoot, relativePath);
11802
12110
  const sourceFile = this.project.getSourceFile(filePath);
11803
12111
  if (!sourceFile) {
11804
12112
  return ok2([]);
@@ -11868,7 +12176,7 @@ var RenameEntityPattern = class {
11868
12176
  if (file.path.endsWith(".ts") || file.path.endsWith(".tsx")) {
11869
12177
  try {
11870
12178
  this.project.addSourceFileAtPath(
11871
- path33__default.join(this.workspaceRoot, file.path)
12179
+ path34__default.join(this.workspaceRoot, file.path)
11872
12180
  );
11873
12181
  } catch {
11874
12182
  }
@@ -11926,7 +12234,7 @@ var RenameEntityPattern = class {
11926
12234
  async renameEntityFile(relativePath, oldName, newName) {
11927
12235
  try {
11928
12236
  const sourceFile = this.project.getSourceFile(
11929
- path33__default.join(this.workspaceRoot, relativePath)
12237
+ path34__default.join(this.workspaceRoot, relativePath)
11930
12238
  );
11931
12239
  if (!sourceFile) return err2(new Error(`File not found: ${relativePath}`));
11932
12240
  const classDecl = sourceFile.getClass(oldName);
@@ -11943,7 +12251,7 @@ var RenameEntityPattern = class {
11943
12251
  async updateReferences(relativePath, oldName, newName) {
11944
12252
  try {
11945
12253
  const sourceFile = this.project.getSourceFile(
11946
- path33__default.join(this.workspaceRoot, relativePath)
12254
+ path34__default.join(this.workspaceRoot, relativePath)
11947
12255
  );
11948
12256
  if (!sourceFile) return ok2([]);
11949
12257
  let modified = false;
@@ -11962,11 +12270,11 @@ var RenameEntityPattern = class {
11962
12270
  }
11963
12271
  async updateManifest(oldName, newName) {
11964
12272
  try {
11965
- const manifestPath = path33__default.join(
12273
+ const manifestPath = path34__default.join(
11966
12274
  this.workspaceRoot,
11967
12275
  ".architecture/manifest.yaml"
11968
12276
  );
11969
- const content = await fs25.readFile(manifestPath, "utf-8");
12277
+ const content = await fs27.readFile(manifestPath, "utf-8");
11970
12278
  const manifest = yaml9.load(content);
11971
12279
  if (manifest.bounded_contexts) {
11972
12280
  for (const context of manifest.bounded_contexts) {
@@ -11978,7 +12286,7 @@ var RenameEntityPattern = class {
11978
12286
  }
11979
12287
  }
11980
12288
  }
11981
- await fs25.writeFile(
12289
+ await fs27.writeFile(
11982
12290
  manifestPath,
11983
12291
  yaml9.dump(manifest, { indent: 2 }),
11984
12292
  "utf-8"
@@ -12662,7 +12970,7 @@ var manifestSplitCommander = new Command("split").description("Split monolithic
12662
12970
  const dryRun = options.dryRun ?? false;
12663
12971
  try {
12664
12972
  const workspaceRoot = await findWorkspaceRoot({});
12665
- const monolithicManifestPath = path33__default.join(
12973
+ const monolithicManifestPath = path34__default.join(
12666
12974
  workspaceRoot,
12667
12975
  ".architecture/manifest.yaml"
12668
12976
  );
@@ -12671,7 +12979,7 @@ var manifestSplitCommander = new Command("split").description("Split monolithic
12671
12979
  );
12672
12980
  let manifestContent;
12673
12981
  try {
12674
- manifestContent = await fs25.readFile(monolithicManifestPath, "utf-8");
12982
+ manifestContent = await fs27.readFile(monolithicManifestPath, "utf-8");
12675
12983
  } catch {
12676
12984
  throw new Error(`Failed to read manifest.yaml. Does it exist?`);
12677
12985
  }
@@ -12699,14 +13007,14 @@ Validation successful. Found ${contexts.length} bounded contexts.`
12699
13007
  const planes = rawYaml.planes ?? {};
12700
13008
  const planeLookup = buildPlaneLookup(planes);
12701
13009
  console.log("Splitting manifest into the new directory structure...");
12702
- const archDir = path33__default.join(workspaceRoot, ".architecture");
12703
- const contextsDir = path33__default.join(archDir, "contexts");
12704
- const appsDir = path33__default.join(archDir, "apps");
12705
- const invariantsDir = path33__default.join(archDir, "invariants");
13010
+ const archDir = path34__default.join(workspaceRoot, ".architecture");
13011
+ const contextsDir = path34__default.join(archDir, "contexts");
13012
+ const appsDir = path34__default.join(archDir, "apps");
13013
+ const invariantsDir = path34__default.join(archDir, "invariants");
12706
13014
  if (!dryRun) {
12707
- await fs25.mkdir(contextsDir, { recursive: true });
12708
- await fs25.mkdir(appsDir, { recursive: true });
12709
- await fs25.mkdir(invariantsDir, { recursive: true });
13015
+ await fs27.mkdir(contextsDir, { recursive: true });
13016
+ await fs27.mkdir(appsDir, { recursive: true });
13017
+ await fs27.mkdir(invariantsDir, { recursive: true });
12710
13018
  }
12711
13019
  const CATEGORY_B_KEYS = /* @__PURE__ */ new Set(["monorepo", "generator"]);
12712
13020
  const workspaceConfig = {};
@@ -12746,12 +13054,12 @@ Validation successful. Found ${contexts.length} bounded contexts.`
12746
13054
  }
12747
13055
  for (const ctx of contexts) {
12748
13056
  const plane = planeLookup.get(ctx.name) ?? ctx.plane ?? "core";
12749
- const ctxDir = path33__default.join(contextsDir, plane, ctx.name);
13057
+ const ctxDir = path34__default.join(contextsDir, plane, ctx.name);
12750
13058
  const contextData = normalizeContextData(
12751
13059
  extractContextData(ctx)
12752
13060
  );
12753
13061
  contextData.plane = plane;
12754
- const ctxFilePath = path33__default.join(ctxDir, "context.yaml");
13062
+ const ctxFilePath = path34__default.join(ctxDir, "context.yaml");
12755
13063
  const ctxYaml = yaml9.dump(contextData, {
12756
13064
  noRefs: true,
12757
13065
  sortKeys: false,
@@ -12760,8 +13068,8 @@ Validation successful. Found ${contexts.length} bounded contexts.`
12760
13068
  if (dryRun) {
12761
13069
  console.log(`[dry-run] Would create: ${ctxFilePath}`);
12762
13070
  } else {
12763
- await fs25.mkdir(ctxDir, { recursive: true });
12764
- await fs25.writeFile(ctxFilePath, ctxYaml, "utf-8");
13071
+ await fs27.mkdir(ctxDir, { recursive: true });
13072
+ await fs27.writeFile(ctxFilePath, ctxYaml, "utf-8");
12765
13073
  }
12766
13074
  indexManifest.bounded_contexts.push({
12767
13075
  name: ctx.name,
@@ -12777,7 +13085,7 @@ Validation successful. Found ${contexts.length} bounded contexts.`
12777
13085
  if (typeof app === "object" && app !== null && "name" in app) {
12778
13086
  const typedApp = app;
12779
13087
  const appName = typedApp.name;
12780
- const appFilePath = path33__default.join(appsDir, `${appName}.app.yaml`);
13088
+ const appFilePath = path34__default.join(appsDir, `${appName}.app.yaml`);
12781
13089
  const appYaml = yaml9.dump(app, {
12782
13090
  noRefs: true,
12783
13091
  sortKeys: false,
@@ -12786,7 +13094,7 @@ Validation successful. Found ${contexts.length} bounded contexts.`
12786
13094
  if (dryRun) {
12787
13095
  console.log(`[dry-run] Would create: ${appFilePath}`);
12788
13096
  } else {
12789
- await fs25.writeFile(appFilePath, appYaml, "utf-8");
13097
+ await fs27.writeFile(appFilePath, appYaml, "utf-8");
12790
13098
  }
12791
13099
  indexManifest.apps.push({
12792
13100
  name: appName,
@@ -12794,7 +13102,7 @@ Validation successful. Found ${contexts.length} bounded contexts.`
12794
13102
  });
12795
13103
  }
12796
13104
  }
12797
- const workspaceConfigPath = path33__default.join(archDir, "workspace.config.yaml");
13105
+ const workspaceConfigPath = path34__default.join(archDir, "workspace.config.yaml");
12798
13106
  const workspaceConfigYaml = yaml9.dump(workspaceConfig, {
12799
13107
  noRefs: true,
12800
13108
  sortKeys: false,
@@ -12805,7 +13113,7 @@ Validation successful. Found ${contexts.length} bounded contexts.`
12805
13113
  console.log("\n--- Preview of workspace.config.yaml ---\n");
12806
13114
  console.log(workspaceConfigYaml);
12807
13115
  } else {
12808
- await fs25.writeFile(workspaceConfigPath, workspaceConfigYaml, "utf-8");
13116
+ await fs27.writeFile(workspaceConfigPath, workspaceConfigYaml, "utf-8");
12809
13117
  }
12810
13118
  const indexYaml = yaml9.dump(indexManifest, {
12811
13119
  noRefs: true,
@@ -12826,9 +13134,9 @@ Validation successful. Found ${contexts.length} bounded contexts.`
12826
13134
  console.log(header + indexYaml);
12827
13135
  } else {
12828
13136
  const backupPath = monolithicManifestPath + ".pre-split-backup";
12829
- await fs25.copyFile(monolithicManifestPath, backupPath);
13137
+ await fs27.copyFile(monolithicManifestPath, backupPath);
12830
13138
  console.log(`Backup created at ${backupPath}`);
12831
- await fs25.writeFile(monolithicManifestPath, header + indexYaml, "utf-8");
13139
+ await fs27.writeFile(monolithicManifestPath, header + indexYaml, "utf-8");
12832
13140
  }
12833
13141
  console.log("\n✅ Manifest split completed successfully!");
12834
13142
  if (dryRun) {
@@ -12849,12 +13157,161 @@ Validation successful. Found ${contexts.length} bounded contexts.`
12849
13157
  process.exit(1);
12850
13158
  }
12851
13159
  });
13160
+ var MANIFEST_MIGRATIONS = [];
13161
+ var MigrateManifestUseCase = class {
13162
+ constructor(currentVersion = CURRENT_MANIFEST_SCHEMA_VERSION, migrations = MANIFEST_MIGRATIONS) {
13163
+ this.currentVersion = currentVersion;
13164
+ this.migrations = migrations;
13165
+ }
13166
+ currentVersion;
13167
+ migrations;
13168
+ execute(content) {
13169
+ const parsed = yaml9.load(content);
13170
+ if (parsed == null) {
13171
+ throw new Error("Manifest file is empty");
13172
+ }
13173
+ if (typeof parsed !== "object" || Array.isArray(parsed)) {
13174
+ throw new Error(
13175
+ "Manifest root must be a YAML mapping — nothing to migrate."
13176
+ );
13177
+ }
13178
+ const fromVersion = readManifestSchemaVersion(parsed);
13179
+ if (fromVersion !== void 0 && fromVersion > this.currentVersion) {
13180
+ throw new Error(
13181
+ `Manifest schemaVersion ${fromVersion} is newer than this toolchain supports (reads ≤ ${this.currentVersion}). Migration only goes forward — upgrade @hexagen-monaco/sync instead.`
13182
+ );
13183
+ }
13184
+ const steps = [...this.migrations].filter(
13185
+ (m) => m.toVersion > (fromVersion ?? 0) && m.toVersion <= this.currentVersion
13186
+ ).sort((a, b) => a.toVersion - b.toVersion);
13187
+ let migrated = content;
13188
+ const applied = [];
13189
+ for (const step of steps) {
13190
+ migrated = step.apply(migrated);
13191
+ applied.push(`v${step.toVersion}: ${step.description}`);
13192
+ }
13193
+ const stamped = this.stamp(migrated, fromVersion);
13194
+ this.assertStampOnlyAddedTheVersion(migrated, stamped);
13195
+ return {
13196
+ content: stamped,
13197
+ fromVersion,
13198
+ toVersion: this.currentVersion,
13199
+ applied,
13200
+ changed: stamped !== content
13201
+ };
13202
+ }
13203
+ /**
13204
+ * Textually stamp `schemaVersion: <current>` — replace an existing
13205
+ * top-level stamp line in place, or insert one above the first content
13206
+ * line. YAML nesting is indentation, so a top-level key is exactly a
13207
+ * column-0 `schemaVersion:` line; comments (`# …`) and the document-start
13208
+ * marker (`---`) never match it.
13209
+ */
13210
+ stamp(content, fromVersion) {
13211
+ const stampLine = `schemaVersion: ${this.currentVersion}`;
13212
+ if (fromVersion === this.currentVersion) return content;
13213
+ if (fromVersion !== void 0) {
13214
+ return content.replace(/^schemaVersion:[^\n]*$/m, stampLine);
13215
+ }
13216
+ const lines = content.split("\n");
13217
+ const firstContent = lines.findIndex(
13218
+ (line) => line.trim() !== "" && !line.trimStart().startsWith("#") && line.trim() !== "---"
13219
+ );
13220
+ lines.splice(firstContent, 0, stampLine);
13221
+ return lines.join("\n");
13222
+ }
13223
+ /**
13224
+ * The refusal that makes the textual edit safe: re-parse and require the
13225
+ * result to be the input plus (only) the current `schemaVersion`. A result
13226
+ * that no longer parses at all (e.g. a stamp inserted above a flow-style
13227
+ * root mapping) is the same failure, not a parser stack trace.
13228
+ */
13229
+ assertStampOnlyAddedTheVersion(before, after) {
13230
+ let stampedCleanly = false;
13231
+ try {
13232
+ const reparsed = yaml9.load(after);
13233
+ stampedCleanly = readManifestSchemaVersion(reparsed) === this.currentVersion && isDeepStrictEqual(
13234
+ {
13235
+ ...yaml9.load(before),
13236
+ schemaVersion: this.currentVersion
13237
+ },
13238
+ reparsed
13239
+ );
13240
+ } catch {
13241
+ }
13242
+ if (!stampedCleanly) {
13243
+ throw new Error(
13244
+ `Could not stamp schemaVersion ${this.currentVersion} without altering the manifest (unsupported YAML layout — e.g. a flow-style root mapping). Add \`schemaVersion: ${this.currentVersion}\` as a top-level key by hand.`
13245
+ );
13246
+ }
13247
+ }
13248
+ };
13249
+
13250
+ // src/commands/manifest/migrate.ts
13251
+ var manifestMigrateCommander = new Command("migrate").description(
13252
+ "Bring .architecture/manifest.yaml to the current schema version (stamps schemaVersion, applies registered migrations)"
13253
+ ).option("--dry-run", "Preview changes without writing files").action(async (options) => {
13254
+ const dryRun = options.dryRun ?? false;
13255
+ try {
13256
+ const workspaceRoot = await findWorkspaceRoot({});
13257
+ const manifestPath = path34__default.join(
13258
+ workspaceRoot,
13259
+ ".architecture/manifest.yaml"
13260
+ );
13261
+ let content;
13262
+ try {
13263
+ content = await fs27.readFile(manifestPath, "utf-8");
13264
+ } catch {
13265
+ throw new Error(`Failed to read ${manifestPath}. Does it exist?`);
13266
+ }
13267
+ const result = new MigrateManifestUseCase().execute(content);
13268
+ const from = result.fromVersion === void 0 ? "legacy (no schemaVersion)" : `schemaVersion ${result.fromVersion}`;
13269
+ console.log(`Manifest: ${manifestPath}`);
13270
+ console.log(`From : ${from}`);
13271
+ console.log(`To : schemaVersion ${result.toVersion}`);
13272
+ for (const step of result.applied) {
13273
+ console.log(`Applied : ${step}`);
13274
+ }
13275
+ if (!result.changed) {
13276
+ console.log(
13277
+ "\n✅ Already at the current schema version — nothing to do."
13278
+ );
13279
+ return;
13280
+ }
13281
+ if (dryRun) {
13282
+ console.log(
13283
+ "\n[dry-run] Would rewrite the manifest. No files written."
13284
+ );
13285
+ return;
13286
+ }
13287
+ const backupPath = manifestPath + ".pre-migrate-backup";
13288
+ await fs27.copyFile(manifestPath, backupPath);
13289
+ console.log(`
13290
+ Backup created at ${backupPath}`);
13291
+ const tempPath = manifestPath + ".tmp";
13292
+ try {
13293
+ await fs27.writeFile(tempPath, result.content, "utf-8");
13294
+ await fs27.rename(tempPath, manifestPath);
13295
+ } catch (writeErr) {
13296
+ await fs27.rm(tempPath, { force: true });
13297
+ throw writeErr;
13298
+ }
13299
+ console.log("✅ Manifest migrated successfully.");
13300
+ } catch (err3) {
13301
+ console.error(
13302
+ `
13303
+ ❌ Migration failed: ${err3 instanceof Error ? err3.message : String(err3)}`
13304
+ );
13305
+ process.exit(1);
13306
+ }
13307
+ });
12852
13308
 
12853
13309
  // src/commands/manifest/index.ts
12854
13310
  var manifestCommander = new Command("manifest").description(
12855
13311
  "Manage the architecture manifest lifecycle"
12856
13312
  );
12857
13313
  manifestCommander.addCommand(manifestSplitCommander);
13314
+ manifestCommander.addCommand(manifestMigrateCommander);
12858
13315
 
12859
13316
  // src/cli.ts
12860
13317
  function createLogger() {
@@ -12875,45 +13332,59 @@ function createLogger() {
12875
13332
  };
12876
13333
  }
12877
13334
  var logger = createLogger();
12878
- function readVersion() {
12879
- try {
12880
- const pkgPath = join(
12881
- dirname(fileURLToPath(import.meta.url)),
12882
- "..",
12883
- "package.json"
12884
- );
12885
- return JSON.parse(readFileSync(pkgPath, "utf8")).version ?? "0.0.0";
12886
- } catch {
12887
- return "0.0.0";
12888
- }
12889
- }
12890
13335
  function buildProgram() {
12891
13336
  const program2 = new Command();
12892
- program2.name("hexagen").description("HexaGen Monaco — Generate and sync modular monorepos").version(readVersion());
12893
- 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(
13337
+ program2.name("hexagen").description("HexaGen Monaco — Generate and sync modular monorepos").version(resolveToolchainVersion());
13338
+ program2.command("sync").description("Run the HexaGen sync engine to generate artifacts").option("--dry-run", "Preview changes without writing files").option(
13339
+ "--check",
13340
+ "CI drift gate: implies --dry-run and exits non-zero iff any change would be made (created/updated/deleted). A converged tree exits 0."
13341
+ ).option("--force", "Overwrite non-generated files in packages").option(
12894
13342
  "--force-root",
12895
13343
  "Overwrite protected root files (turbo.json, .gitignore)"
12896
13344
  ).option("--allow-dirty", "Skip git clean check (for development)").option("--strict", "Fail on architecture linter warnings").option(
12897
13345
  "--only <pattern...>",
12898
13346
  "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."
13347
+ ).option(
13348
+ "--report <path>",
13349
+ "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."
12899
13350
  ).action(async (options) => {
13351
+ const check = options.check ?? false;
12900
13352
  const flags = {
12901
- dryRun: options.dryRun ?? false,
13353
+ dryRun: (options.dryRun || options.check) ?? false,
12902
13354
  force: options.force ?? false,
12903
13355
  forceRoot: options.forceRoot ?? false,
12904
13356
  allowDirty: options.allowDirty ?? false,
12905
13357
  strict: options.strict ?? false,
12906
13358
  only: options.only,
13359
+ report: options.report,
12907
13360
  mode: "self-regen",
12908
13361
  logger
12909
13362
  };
12910
13363
  try {
12911
13364
  const engine = new SyncEngine(flags);
12912
- await engine.run();
13365
+ const summary = await engine.run();
13366
+ if (summary.errors > 0) {
13367
+ console.error(
13368
+ `Sync incomplete: ${summary.errors} generator failure(s) — see the FAILED row(s) above.`
13369
+ );
13370
+ process.exitCode = 1;
13371
+ }
13372
+ if (check && summary.manifestMissing) {
13373
+ console.error(
13374
+ "Manifest not found — `--check` cannot verify drift without a manifest at `.architecture/manifest.yaml`. Check you are running from inside the intended workspace (cwd is resolved first)."
13375
+ );
13376
+ process.exitCode = 1;
13377
+ }
13378
+ if (check && summary.totalOps > 0) {
13379
+ console.error(
13380
+ `Drift detected: ${summary.totalOps} pending change(s) (${summary.created} to create, ${summary.updated} to update, ${summary.deleted} to delete). Run \`hexagen sync\` to converge.`
13381
+ );
13382
+ process.exitCode = 1;
13383
+ }
12913
13384
  } catch (err3) {
12914
13385
  const message = err3 instanceof Error ? err3.message : "Unknown fatal error";
12915
13386
  console.error(`Fatal sync error: ${message}`);
12916
- process.exit(1);
13387
+ process.exitCode = 1;
12917
13388
  }
12918
13389
  });
12919
13390
  const archCommand = program2.command("arch").description("Manage architecture manifest.yaml");
@@ -12949,11 +13420,11 @@ function buildProgram() {
12949
13420
  }
12950
13421
  var program = buildProgram();
12951
13422
  try {
12952
- program.parse(process.argv);
13423
+ await program.parseAsync(process.argv);
12953
13424
  } catch (err3) {
12954
13425
  const message = err3 instanceof Error ? err3.message : "Unknown CLI error";
12955
13426
  console.error(`CLI error: ${message}`);
12956
- process.exit(1);
13427
+ process.exitCode = 1;
12957
13428
  }
12958
13429
  //# sourceMappingURL=cli.js.map
12959
13430
  //# sourceMappingURL=cli.js.map