@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/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import path6 from 'path';
2
- import fs2, { realpathSync, lstatSync, createWriteStream } from 'fs';
3
- import fs3 from 'fs/promises';
1
+ import path7 from 'path';
2
+ import fs4, { realpathSync, lstatSync, createWriteStream } from 'fs';
3
+ import fs5 from 'fs/promises';
4
4
  import { promisify } from 'util';
5
5
  import { exec } from 'child_process';
6
6
  import yaml3 from 'js-yaml';
7
7
  import crypto from 'crypto';
8
- import { Project, MethodSignature } from 'ts-morph';
9
8
  import { fileURLToPath } from 'url';
9
+ import { Project, MethodSignature } from 'ts-morph';
10
10
 
11
11
  var __defProp = Object.defineProperty;
12
12
  var __export = (target, all) => {
@@ -19,26 +19,132 @@ var MigrationReport = class {
19
19
  this.entries.push({ type, target, message });
20
20
  }
21
21
  async writeReport(config) {
22
- const reportPath = path6.join(
23
- config.workspaceRoot,
24
- "SYNC-MIGRATION-REPORT.md"
25
- );
22
+ if (config.dryRun && !config.report) {
23
+ const counts = /* @__PURE__ */ new Map();
24
+ for (const e of this.entries) {
25
+ counts.set(e.type, (counts.get(e.type) ?? 0) + 1);
26
+ }
27
+ const breakdown = [...counts.entries()].map(([type, n]) => `${n} ${type}`).join(", ");
28
+ config.logger.info(
29
+ `[DRY-RUN] skipping migration report file (${this.entries.length} entries${breakdown ? `: ${breakdown}` : ""}) — pass --report <path> to write it anyway`
30
+ );
31
+ return;
32
+ }
33
+ const reportPath = config.report ? path7.resolve(config.workspaceRoot, config.report) : path7.join(config.workspaceRoot, "SYNC-MIGRATION-REPORT.md");
34
+ await fs5.mkdir(path7.dirname(reportPath), { recursive: true });
35
+ let preContent = null;
36
+ try {
37
+ preContent = await fs5.readFile(reportPath, "utf8");
38
+ } catch (e) {
39
+ if (!(e instanceof Error && "code" in e && e.code === "ENOENT"))
40
+ throw e;
41
+ }
42
+ config.journal?.recordWrite(reportPath, preContent);
26
43
  const stream = createWriteStream(reportPath, { flags: "w" });
27
- stream.write("# Sync Migration Report\n\n");
28
- for (const e of this.entries) {
29
- stream.write(
30
- `- ${e.type.toUpperCase()}: ${e.target}${e.message ? ` – ${e.message}` : ""}
44
+ await new Promise((resolve, reject) => {
45
+ stream.on("error", reject);
46
+ stream.write("# Sync Migration Report\n\n");
47
+ for (const e of this.entries) {
48
+ stream.write(
49
+ `- ${e.type.toUpperCase()}: ${e.target}${e.message ? ` – ${e.message}` : ""}
31
50
  `
32
- );
51
+ );
52
+ }
53
+ stream.end(resolve);
54
+ });
55
+ }
56
+ };
57
+ var SyncJournal = class {
58
+ entries = [];
59
+ /**
60
+ * Record a write BEFORE it is attempted. `preContent: null` means the file
61
+ * did not exist (a create); a string is the full pre-image of an overwrite.
62
+ * Over-recording is safe: rolling back a write that never happened either
63
+ * restores identical content or unlinks a file that is not there (ENOENT
64
+ * tolerated below). Under-recording loses user data — so mutation sites
65
+ * record first, mutate second.
66
+ */
67
+ recordWrite(filePath, preContent) {
68
+ this.entries.push({
69
+ path: filePath,
70
+ kind: preContent === null ? "created" : "overwritten",
71
+ preContent
72
+ });
73
+ }
74
+ /** Record a deletion BEFORE the unlink, with the full pre-image. */
75
+ recordDelete(filePath, preContent) {
76
+ this.entries.push({ path: filePath, kind: "deleted", preContent });
77
+ }
78
+ get size() {
79
+ return this.entries.length;
80
+ }
81
+ /**
82
+ * Human-readable journal lines (workspace-relative), oldest first — printed
83
+ * verbatim when a failed run must NOT roll back (--allow-dirty).
84
+ */
85
+ describeEntries(workspaceRoot) {
86
+ return this.entries.map(
87
+ (e) => `${e.kind} ${path7.relative(workspaceRoot, e.path)}`
88
+ );
89
+ }
90
+ /**
91
+ * Replay the journal in REVERSE order: restore pre-images, unlink created
92
+ * files. Reverse order makes repeated writes to the same path converge on
93
+ * the OLDEST pre-image (pass-1 barrel pre-image is restored last), i.e. the
94
+ * true pre-sync state.
95
+ *
96
+ * Per-entry best-effort: a failing inverse op is collected and replay
97
+ * CONTINUES — restoring nine of ten files beats aborting at the first
98
+ * error. The caller prints the failures; nothing here (or anywhere) falls
99
+ * back to a git-wide reset/clean.
100
+ *
101
+ * Restores use a plain writeFile, not the atomic tmp+rename protocol: the
102
+ * rollback may be running on the same broken substrate that failed the
103
+ * sync, and the simplest possible write maximizes the odds of getting the
104
+ * user's bytes back on disk.
105
+ */
106
+ async rollback(logger, workspaceRoot) {
107
+ const outcome = {
108
+ attempted: this.entries.length,
109
+ restored: 0,
110
+ failures: []
111
+ };
112
+ for (const entry of [...this.entries].reverse()) {
113
+ const relative = path7.relative(workspaceRoot, entry.path);
114
+ try {
115
+ if (entry.preContent === null) {
116
+ try {
117
+ await fs5.unlink(entry.path);
118
+ } catch (err3) {
119
+ if (!(err3 instanceof Error && "code" in err3 && err3.code === "ENOENT")) {
120
+ throw err3;
121
+ }
122
+ }
123
+ logger.info(`rolled back (removed) ${relative}`);
124
+ } else {
125
+ await fs5.mkdir(path7.dirname(entry.path), { recursive: true });
126
+ await fs5.writeFile(entry.path, entry.preContent, {
127
+ encoding: "utf8"
128
+ });
129
+ logger.info(`rolled back (restored) ${relative}`);
130
+ }
131
+ outcome.restored += 1;
132
+ } catch (err3) {
133
+ outcome.failures.push({
134
+ path: entry.path,
135
+ intended: entry.preContent === null ? "remove created file" : "restore pre-image",
136
+ error: err3 instanceof Error ? err3.message : String(err3)
137
+ });
138
+ }
33
139
  }
34
- stream.end();
140
+ return outcome;
35
141
  }
36
142
  };
37
143
  var LOCK_FILE = ".architecture/.sync.lock";
38
144
  var LockFile = class {
39
- constructor(workspaceRoot, fsImpl = fs3, logger = console) {
145
+ constructor(workspaceRoot, fsImpl = fs5, logger = console) {
40
146
  this.workspaceRoot = workspaceRoot;
41
- this.lockPath = path6.join(workspaceRoot, LOCK_FILE);
147
+ this.lockPath = path7.join(workspaceRoot, LOCK_FILE);
42
148
  this.fsImpl = fsImpl;
43
149
  this.logger = logger;
44
150
  }
@@ -105,11 +211,11 @@ var LockFile = class {
105
211
  };
106
212
  var BIN_NAME = process.platform === "win32" ? "hexagen-lint.cmd" : "hexagen-lint";
107
213
  function resolveArchLinterBin(startDir) {
108
- let dir = path6.resolve(startDir);
214
+ let dir = path7.resolve(startDir);
109
215
  for (; ; ) {
110
- const candidate = path6.join(dir, "node_modules", ".bin", BIN_NAME);
111
- if (fs2.existsSync(candidate)) return candidate;
112
- const parent = path6.dirname(dir);
216
+ const candidate = path7.join(dir, "node_modules", ".bin", BIN_NAME);
217
+ if (fs4.existsSync(candidate)) return candidate;
218
+ const parent = path7.dirname(dir);
113
219
  if (parent === dir) return null;
114
220
  dir = parent;
115
221
  }
@@ -138,7 +244,7 @@ async function runArchLinter(config) {
138
244
  });
139
245
  if (stdout) logger.info(stdout.trim());
140
246
  if (stderr) logger.error(stderr.trim());
141
- logger.info("✅ Architecture is compliant with manifest.yaml.");
247
+ logger.info("✅ Architecture check passed (arch-linter).");
142
248
  } catch (error) {
143
249
  const message = error instanceof Error && "stderr" in error && error.stderr || error instanceof Error && error.message || "Unknown linter error";
144
250
  logger.error(`Architectural Integrity Check Failed:
@@ -155,9 +261,24 @@ function createEmptyResult() {
155
261
  created: [],
156
262
  skipped: [],
157
263
  updated: [],
264
+ deleted: [],
265
+ unchanged: [],
158
266
  totalOps: 0
159
267
  };
160
268
  }
269
+ function recordWriteStatus(result, filePath, status) {
270
+ if (status === "created") {
271
+ result.created.push(filePath);
272
+ result.totalOps += 1;
273
+ } else if (status === "updated") {
274
+ result.updated.push(filePath);
275
+ result.totalOps += 1;
276
+ } else if (status === "unchanged") {
277
+ result.unchanged.push(filePath);
278
+ } else {
279
+ result.skipped.push(filePath);
280
+ }
281
+ }
161
282
 
162
283
  // src/scope-filter.ts
163
284
  var GLOB_META = /[*?]/;
@@ -224,7 +345,7 @@ function isGeneratedFile(content) {
224
345
  return content.includes(GENERATED_MARKER);
225
346
  }
226
347
  function isProtectedRoot(filePath, config) {
227
- const relative = path6.relative(config.workspaceRoot, filePath);
348
+ const relative = path7.relative(config.workspaceRoot, filePath);
228
349
  const isRootLevel = !relative.startsWith("packages/") && !relative.startsWith("tools/") && !relative.startsWith("apps/");
229
350
  return isRootLevel && Array.from(protectedFiles).some(
230
351
  (f) => relative.endsWith(f) || relative.includes(f)
@@ -232,12 +353,12 @@ function isProtectedRoot(filePath, config) {
232
353
  }
233
354
  function isInScope(filePath, config) {
234
355
  if (!config.only || config.only.length === 0) return true;
235
- const relativePath = path6.relative(config.workspaceRoot, filePath);
356
+ const relativePath = path7.relative(config.workspaceRoot, filePath);
236
357
  return matchesScope(relativePath, config.only);
237
358
  }
238
359
  async function safeWriteFileAtomic(filePath, content, config, report, skipGeneratedCheck = false) {
239
360
  const { dryRun, forceRoot, logger, workspaceRoot } = config;
240
- const relativePath = path6.relative(workspaceRoot, filePath);
361
+ const relativePath = path7.relative(workspaceRoot, filePath);
241
362
  if (!isInScope(filePath, config)) {
242
363
  logger.debug(`skipped (outside --only) ${relativePath}`);
243
364
  return "skipped";
@@ -246,7 +367,7 @@ async function safeWriteFileAtomic(filePath, content, config, report, skipGenera
246
367
  let currentContent = "";
247
368
  let currentHash = "";
248
369
  try {
249
- currentContent = await fs3.readFile(filePath, "utf8");
370
+ currentContent = await fs5.readFile(filePath, "utf8");
250
371
  currentHash = contentHash(currentContent);
251
372
  exists = true;
252
373
  } catch (e) {
@@ -276,20 +397,21 @@ async function safeWriteFileAtomic(filePath, content, config, report, skipGenera
276
397
  logger.info(`[DRY-RUN] would ${action} ${relativePath}`);
277
398
  return exists ? "updated" : "created";
278
399
  }
279
- await fs3.mkdir(path6.dirname(filePath), { recursive: true });
280
- const tmpName = `.${path6.basename(filePath)}.${crypto.randomUUID()}.tmp`;
281
- const tmpPath = path6.join(path6.dirname(filePath), tmpName);
282
- await fs3.writeFile(tmpPath, content, { encoding: "utf8" });
400
+ config.journal?.recordWrite(filePath, exists ? currentContent : null);
401
+ await fs5.mkdir(path7.dirname(filePath), { recursive: true });
402
+ const tmpName = `.${path7.basename(filePath)}.${crypto.randomUUID()}.tmp`;
403
+ const tmpPath = path7.join(path7.dirname(filePath), tmpName);
404
+ await fs5.writeFile(tmpPath, content, { encoding: "utf8" });
283
405
  try {
284
- await fs3.rename(tmpPath, filePath);
406
+ await fs5.rename(tmpPath, filePath);
285
407
  const status = exists ? "updated" : "created";
286
408
  logger.info(`${status} ${relativePath}`);
287
409
  return status;
288
410
  } catch (err3) {
289
411
  if (err3 instanceof Error && "code" in err3 && err3.code === "EXDEV") {
290
412
  try {
291
- await fs3.copyFile(tmpPath, filePath);
292
- await fs3.unlink(tmpPath);
413
+ await fs5.copyFile(tmpPath, filePath);
414
+ await fs5.unlink(tmpPath);
293
415
  const status = exists ? "updated" : "created";
294
416
  logger.info(`${status} ${relativePath}`);
295
417
  return status;
@@ -297,7 +419,7 @@ async function safeWriteFileAtomic(filePath, content, config, report, skipGenera
297
419
  logger.warn(`EXDEV fallback failed for ${relativePath}: ${copyErr}`);
298
420
  }
299
421
  }
300
- await fs3.unlink(tmpPath).catch(() => {
422
+ await fs5.unlink(tmpPath).catch(() => {
301
423
  });
302
424
  throw err3;
303
425
  }
@@ -313,48 +435,72 @@ async function safeWriteFile(filePath, content, config, skipGeneratedCheck = fal
313
435
  }
314
436
 
315
437
  // src/generators/layer-folders.ts
316
- var GENERATED_MARKER2 = "// @generated by @hexagen/sync";
317
- async function loadYamlSafe(filePath) {
438
+ async function directoryExists(dirPath) {
318
439
  try {
319
- const content = await fs3.readFile(filePath, "utf8");
320
- return yaml3.load(content);
440
+ const stats = await fs5.stat(dirPath);
441
+ return stats.isDirectory();
321
442
  } catch (e) {
322
443
  if (e instanceof Error && "code" in e && e.code === "ENOENT") {
323
- return null;
444
+ return false;
324
445
  }
325
446
  throw e;
326
447
  }
327
448
  }
328
- async function generateBarrelContent(dirPath) {
329
- const exportLines = [];
330
- try {
331
- const entries = await fs3.readdir(dirPath, { withFileTypes: true });
332
- for (const entry of entries) {
333
- if (entry.name === "index.ts" || entry.name.startsWith(".")) continue;
334
- if (entry.isFile() && entry.name.endsWith(".ts")) {
335
- const base = entry.name.replace(/\.ts$/, "");
336
- exportLines.push(`export * from './${base}.js';`);
337
- } else if (entry.isDirectory()) {
338
- exportLines.push(`export * from './${entry.name}/index.js';`);
449
+ async function ensureDirectoryCounted(dirPath, config, result) {
450
+ const existed = await directoryExists(dirPath);
451
+ if (existed) return;
452
+ const relativePath = path7.relative(config.workspaceRoot, dirPath);
453
+ if (config.dryRun) {
454
+ config.logger.info(`[DRY-RUN] would create directory ${relativePath}`);
455
+ } else {
456
+ await fs5.mkdir(dirPath, { recursive: true });
457
+ config.logger.info(`created directory ${relativePath}`);
458
+ }
459
+ result.created.push(dirPath);
460
+ result.totalOps += 1;
461
+ }
462
+ async function ensureGitkeepCounted(dirPath, config, result) {
463
+ const keepPath = path7.join(dirPath, ".gitkeep");
464
+ let entries = null;
465
+ if (await directoryExists(dirPath)) {
466
+ entries = await fs5.readdir(dirPath);
467
+ }
468
+ if (entries !== null) {
469
+ const keepIsOnlyEntry = entries.length === 1 && entries[0] === ".gitkeep";
470
+ if (entries.length > 0 && !keepIsOnlyEntry) {
471
+ return;
472
+ }
473
+ if (keepIsOnlyEntry) {
474
+ const existing = await fs5.readFile(keepPath, "utf8").catch(() => null);
475
+ if (existing !== null && existing !== "") {
476
+ return;
339
477
  }
340
478
  }
479
+ }
480
+ const status = await safeWriteFileAtomic(
481
+ keepPath,
482
+ "",
483
+ config,
484
+ void 0,
485
+ true
486
+ );
487
+ recordWriteStatus(result, keepPath, status);
488
+ }
489
+ async function loadYamlSafe(filePath) {
490
+ try {
491
+ const content = await fs5.readFile(filePath, "utf8");
492
+ return yaml3.load(content);
341
493
  } catch (e) {
342
- if (e instanceof Error && "code" in e && e.code === "ENOENT") ; else {
343
- throw e;
494
+ if (e instanceof Error && "code" in e && e.code === "ENOENT") {
495
+ return null;
344
496
  }
497
+ throw e;
345
498
  }
346
- return exportLines.length > 0 ? `${GENERATED_MARKER2}
347
-
348
- ${exportLines.join("\n")}
349
- ` : `${GENERATED_MARKER2}
350
-
351
- // No exports yet
352
- `;
353
499
  }
354
- async function ensureLayerFolders(moduleDir, layers, config, report) {
500
+ async function ensureLayerFolders(moduleDir, layers, config) {
355
501
  const result = createEmptyResult();
356
502
  const { logger } = config;
357
- const layerRulesPath = path6.join(
503
+ const layerRulesPath = path7.join(
358
504
  config.workspaceRoot,
359
505
  ".architecture",
360
506
  "invariants",
@@ -365,64 +511,22 @@ async function ensureLayerFolders(moduleDir, layers, config, report) {
365
511
  logger.warn("layer-rules.yaml not found — skipping layer rule enforcement");
366
512
  }
367
513
  for (const [, layerConfig] of Object.entries(layers)) {
368
- const layerPath = path6.join(moduleDir, layerConfig.folder);
369
- const barrelPath = path6.join(layerPath, "index.ts");
370
- if (!isInScope(barrelPath, config)) {
514
+ const layerPath = path7.join(moduleDir, layerConfig.folder);
515
+ if (!isInScope(layerPath, config) && !isInScope(path7.join(layerPath, "index.ts"), config)) {
371
516
  continue;
372
517
  }
373
- try {
374
- await fs3.mkdir(layerPath, { recursive: true });
375
- result.created.push(layerPath);
376
- result.totalOps += 1;
377
- } catch (e) {
378
- if (e instanceof Error && "code" in e && e.code === "EEXIST") {
379
- result.skipped.push(layerPath);
380
- } else {
381
- throw e;
382
- }
383
- }
384
- const barrelContent = await generateBarrelContent(layerPath);
385
- const barrelStatus = await safeWriteFileAtomic(
386
- barrelPath,
387
- barrelContent,
388
- config,
389
- report
390
- );
391
- if (barrelStatus === "created") result.created.push(barrelPath);
392
- if (barrelStatus === "updated") result.updated.push(barrelPath);
393
- if (barrelStatus === "skipped" || barrelStatus === "protected")
394
- result.skipped.push(barrelPath);
395
- result.totalOps += barrelStatus === "created" || barrelStatus === "updated" ? 1 : 0;
518
+ await ensureDirectoryCounted(layerPath, config, result);
396
519
  const subfolders = layerConfig.subfolders ?? [];
520
+ if (subfolders.length === 0) {
521
+ await ensureGitkeepCounted(layerPath, config, result);
522
+ }
397
523
  for (const sub of subfolders) {
398
- const subPath = path6.join(layerPath, sub);
399
- const subBarrelPath = path6.join(subPath, "index.ts");
400
- if (!isInScope(subBarrelPath, config)) {
524
+ const subPath = path7.join(layerPath, sub);
525
+ if (!isInScope(subPath, config) && !isInScope(path7.join(subPath, "index.ts"), config)) {
401
526
  continue;
402
527
  }
403
- try {
404
- await fs3.mkdir(subPath, { recursive: true });
405
- result.created.push(subPath);
406
- result.totalOps += 1;
407
- } catch (e) {
408
- if (e instanceof Error && "code" in e && e.code === "EEXIST") {
409
- result.skipped.push(subPath);
410
- } else {
411
- throw e;
412
- }
413
- }
414
- const subBarrelContent = await generateBarrelContent(subPath);
415
- const subBarrelStatus = await safeWriteFileAtomic(
416
- subBarrelPath,
417
- subBarrelContent,
418
- config,
419
- report
420
- );
421
- if (subBarrelStatus === "created") result.created.push(subBarrelPath);
422
- if (subBarrelStatus === "updated") result.updated.push(subBarrelPath);
423
- if (subBarrelStatus === "skipped" || subBarrelStatus === "protected")
424
- result.skipped.push(subBarrelPath);
425
- result.totalOps += subBarrelStatus === "created" || subBarrelStatus === "updated" ? 1 : 0;
528
+ await ensureDirectoryCounted(subPath, config, result);
529
+ await ensureGitkeepCounted(subPath, config, result);
426
530
  }
427
531
  }
428
532
  return result;
@@ -443,10 +547,10 @@ var BARREL_EXCLUSIONS = /* @__PURE__ */ new Set([
443
547
  function isExcludedDirectory(name) {
444
548
  return BARREL_EXCLUSIONS.has(name) || name.startsWith(".");
445
549
  }
446
- var GENERATED_MARKER3 = "// @generated by @hexagen/sync";
550
+ var GENERATED_MARKER2 = "// @generated by @hexagen/sync";
447
551
  var LEGACY_GENERATED_MARKER = "— generated by sync.ts";
448
552
  function isGeneratedFile2(content) {
449
- return content.includes(GENERATED_MARKER3) || content.includes(LEGACY_GENERATED_MARKER);
553
+ return content.includes(GENERATED_MARKER2) || content.includes(LEGACY_GENERATED_MARKER);
450
554
  }
451
555
  function contentHash2(content) {
452
556
  return crypto.createHash("sha256").update(content).digest("hex");
@@ -454,18 +558,18 @@ function contentHash2(content) {
454
558
  function detectCircularExports(exportGraph) {
455
559
  const visited = /* @__PURE__ */ new Set();
456
560
  const recursionStack = /* @__PURE__ */ new Set();
457
- const path24 = [];
561
+ const path25 = [];
458
562
  function dfs(node) {
459
563
  if (recursionStack.has(node)) {
460
- const cycleStart = path24.indexOf(node);
461
- return [...path24.slice(cycleStart), node];
564
+ const cycleStart = path25.indexOf(node);
565
+ return [...path25.slice(cycleStart), node];
462
566
  }
463
567
  if (visited.has(node)) {
464
568
  return null;
465
569
  }
466
570
  visited.add(node);
467
571
  recursionStack.add(node);
468
- path24.push(node);
572
+ path25.push(node);
469
573
  const exports$1 = exportGraph.get(node) ?? [];
470
574
  for (const exportPath of exports$1) {
471
575
  const cycle = dfs(exportPath);
@@ -473,7 +577,7 @@ function detectCircularExports(exportGraph) {
473
577
  return cycle;
474
578
  }
475
579
  }
476
- path24.pop();
580
+ path25.pop();
477
581
  recursionStack.delete(node);
478
582
  return null;
479
583
  }
@@ -485,15 +589,15 @@ function detectCircularExports(exportGraph) {
485
589
  }
486
590
  return { hasCircular: false, cycle: null };
487
591
  }
488
- function generateBarrelContent2(entries) {
592
+ function generateBarrelContent(entries) {
489
593
  if (entries.length === 0) {
490
594
  return null;
491
595
  }
492
596
  const exportLines = entries.sort((a, b) => a.name.localeCompare(b.name)).map((entry) => {
493
- const path24 = entry.isDirectory ? `./${entry.name}/index.js` : `./${entry.name}.js`;
494
- return `export * from "${path24}";`;
597
+ const path25 = entry.isDirectory ? `./${entry.name}/index.js` : `./${entry.name}.js`;
598
+ return `export * from "${path25}";`;
495
599
  });
496
- return `${GENERATED_MARKER3}
600
+ return `${GENERATED_MARKER2}
497
601
 
498
602
  ${exportLines.join("\n")}
499
603
  `;
@@ -513,16 +617,16 @@ var CircularExportError = class extends Error {
513
617
  };
514
618
  async function generateRecursiveBarrels(moduleDir, config, report) {
515
619
  const result = createEmptyResult();
516
- const srcDir = path6.join(moduleDir, "src");
620
+ const srcDir = path7.join(moduleDir, "src");
517
621
  const layers = ["domain", "application", "infrastructure"];
518
622
  const pendingWrites = [];
519
623
  const preserved = [];
520
624
  const exportGraph = /* @__PURE__ */ new Map();
521
625
  const layersWithContent = [];
522
626
  for (const layer of layers) {
523
- const layerDir = path6.join(srcDir, layer);
627
+ const layerDir = path7.join(srcDir, layer);
524
628
  try {
525
- await fs3.access(layerDir);
629
+ await fs5.access(layerDir);
526
630
  } catch {
527
631
  continue;
528
632
  }
@@ -536,9 +640,9 @@ async function generateRecursiveBarrels(moduleDir, config, report) {
536
640
  if (layerExports.length > 0) layersWithContent.push(layer);
537
641
  }
538
642
  if (config.mode === "external" && layersWithContent.length > 0) {
539
- const rootBarrelPath = path6.join(srcDir, "index.ts");
643
+ const rootBarrelPath = path7.join(srcDir, "index.ts");
540
644
  if (await shouldGenerateBarrel(rootBarrelPath, preserved, config.logger)) {
541
- const content = generateBarrelContent2(
645
+ const content = generateBarrelContent(
542
646
  layersWithContent.map((name) => ({ name, isDirectory: true }))
543
647
  );
544
648
  const existing = await readFileIfExists(rootBarrelPath);
@@ -550,7 +654,7 @@ async function generateRecursiveBarrels(moduleDir, config, report) {
550
654
  });
551
655
  exportGraph.set(
552
656
  rootBarrelPath,
553
- layersWithContent.map((name) => path6.join(srcDir, name, "index.ts"))
657
+ layersWithContent.map((name) => path7.join(srcDir, name, "index.ts"))
554
658
  );
555
659
  }
556
660
  }
@@ -561,9 +665,19 @@ async function generateRecursiveBarrels(moduleDir, config, report) {
561
665
  }
562
666
  for (const pending of pendingWrites) {
563
667
  if (pending.content === "") {
668
+ if (config.dryRun) {
669
+ config.logger.info(
670
+ `[DRY-RUN] would delete empty barrel ${pending.filePath}`
671
+ );
672
+ result.deleted.push(pending.filePath);
673
+ result.totalOps++;
674
+ continue;
675
+ }
564
676
  try {
565
- await fs3.unlink(pending.filePath);
566
- result.created.push(pending.filePath);
677
+ const preContent = await fs5.readFile(pending.filePath, "utf8");
678
+ config.journal?.recordDelete(pending.filePath, preContent);
679
+ await fs5.unlink(pending.filePath);
680
+ result.deleted.push(pending.filePath);
567
681
  result.totalOps++;
568
682
  continue;
569
683
  } catch (err3) {
@@ -579,15 +693,7 @@ async function generateRecursiveBarrels(moduleDir, config, report) {
579
693
  config,
580
694
  report
581
695
  );
582
- if (status === "created") {
583
- result.created.push(pending.filePath);
584
- result.totalOps++;
585
- } else if (status === "updated") {
586
- result.updated.push(pending.filePath);
587
- result.totalOps++;
588
- } else if (status === "skipped" || status === "protected") {
589
- result.skipped.push(pending.filePath);
590
- }
696
+ recordWriteStatus(result, pending.filePath, status);
591
697
  }
592
698
  result.skipped.push(...preserved);
593
699
  return result;
@@ -597,7 +703,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
597
703
  const exportEntries = [];
598
704
  let entries;
599
705
  try {
600
- entries = await fs3.readdir(dirPath, { withFileTypes: true });
706
+ entries = await fs5.readdir(dirPath, { withFileTypes: true });
601
707
  } catch {
602
708
  return exportEntries;
603
709
  }
@@ -614,7 +720,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
614
720
  }
615
721
  }
616
722
  for (const dir of directories) {
617
- const subDirPath = path6.join(dirPath, dir);
723
+ const subDirPath = path7.join(dirPath, dir);
618
724
  const subExports = await walkDirectory(
619
725
  subDirPath,
620
726
  pendingWrites,
@@ -622,7 +728,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
622
728
  exportGraph,
623
729
  config
624
730
  );
625
- const subBarrelPath = path6.join(subDirPath, "index.ts");
731
+ const subBarrelPath = path7.join(subDirPath, "index.ts");
626
732
  const isQueuedForDeletion = pendingWrites.some(
627
733
  (p) => p.filePath === subBarrelPath && p.content === ""
628
734
  );
@@ -634,9 +740,9 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
634
740
  exportEntries.push({ name: file, isDirectory: false });
635
741
  }
636
742
  if (exportEntries.length === 0) {
637
- const barrelPath2 = path6.join(dirPath, "index.ts");
743
+ const barrelPath2 = path7.join(dirPath, "index.ts");
638
744
  const existingBarrel = await readFileIfExists(barrelPath2);
639
- const dirName = path6.basename(dirPath);
745
+ const dirName = path7.basename(dirPath);
640
746
  const isLayerDir = ["domain", "application", "infrastructure"].includes(
641
747
  dirName
642
748
  );
@@ -651,7 +757,7 @@ async function walkDirectory(dirPath, pendingWrites, preserved, exportGraph, con
651
757
  isNew: false
652
758
  });
653
759
  } else if (isEmptyStub && isLayerDir) {
654
- const newContent = `${GENERATED_MARKER3}
760
+ const newContent = `${GENERATED_MARKER2}
655
761
 
656
762
  export {};
657
763
  `;
@@ -663,7 +769,7 @@ export {};
663
769
  });
664
770
  }
665
771
  } else if (!existingBarrel.includes("export {}") && isLayerDir) {
666
- const newContent = `${GENERATED_MARKER3}
772
+ const newContent = `${GENERATED_MARKER2}
667
773
 
668
774
  export {};
669
775
  `;
@@ -674,7 +780,7 @@ export {};
674
780
  });
675
781
  }
676
782
  } else if (isLayerDir) {
677
- const newContent = `${GENERATED_MARKER3}
783
+ const newContent = `${GENERATED_MARKER2}
678
784
 
679
785
  export {};
680
786
  `;
@@ -686,14 +792,14 @@ export {};
686
792
  }
687
793
  return [];
688
794
  }
689
- const barrelPath = path6.join(dirPath, "index.ts");
795
+ const barrelPath = path7.join(dirPath, "index.ts");
690
796
  const shouldCreateBarrel = await shouldGenerateBarrel(
691
797
  barrelPath,
692
798
  preserved,
693
799
  logger
694
800
  );
695
801
  if (shouldCreateBarrel) {
696
- const content = generateBarrelContent2(exportEntries);
802
+ const content = generateBarrelContent(exportEntries);
697
803
  if (content === null) {
698
804
  return [];
699
805
  }
@@ -706,14 +812,14 @@ export {};
706
812
  content,
707
813
  isNew: !existingContent
708
814
  });
709
- const exportPaths = exportEntries.filter((e) => e.isDirectory).map((e) => path6.join(dirPath, e.name, "index.ts"));
815
+ const exportPaths = exportEntries.filter((e) => e.isDirectory).map((e) => path7.join(dirPath, e.name, "index.ts"));
710
816
  exportGraph.set(barrelPath, exportPaths);
711
817
  }
712
818
  return exportEntries;
713
819
  }
714
820
  async function hasBarrel(dirPath) {
715
821
  try {
716
- await fs3.access(path6.join(dirPath, "index.ts"));
822
+ await fs5.access(path7.join(dirPath, "index.ts"));
717
823
  return true;
718
824
  } catch {
719
825
  return false;
@@ -733,7 +839,7 @@ async function shouldGenerateBarrel(barrelPath, preserved, logger) {
733
839
  }
734
840
  async function readFileIfExists(filePath) {
735
841
  try {
736
- return await fs3.readFile(filePath, "utf8");
842
+ return await fs5.readFile(filePath, "utf8");
737
843
  } catch (err3) {
738
844
  if (err3 && typeof err3 === "object" && "code" in err3 && err3.code === "ENOENT") {
739
845
  return null;
@@ -778,7 +884,12 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
778
884
  const moduleOverrides = context?.packageJson ?? {};
779
885
  const scope = config.manifest ? resolveScope(config.manifest) : "generated-project";
780
886
  const dependsOnDeps = context ? expandDependsOn(context, scope) : {};
781
- const pkgPath = path6.join(modulePath, "package.json");
887
+ const pkgPath = path7.join(modulePath, "package.json");
888
+ const dependencies = {
889
+ ...dependsOnDeps,
890
+ ...defaults.dependencies ?? {},
891
+ ...moduleOverrides.dependencies ?? {}
892
+ };
782
893
  const desiredPkg = {
783
894
  name: `@${scope}/${moduleName}`,
784
895
  version: "0.1.0",
@@ -799,11 +910,17 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
799
910
  ...defaults.scripts ?? {},
800
911
  ...moduleOverrides.scripts ?? {}
801
912
  },
802
- dependencies: {
803
- ...dependsOnDeps,
804
- ...defaults.dependencies ?? {},
805
- ...moduleOverrides.dependencies ?? {}
806
- },
913
+ // Emitted only when non-empty (PR-B2, capstone 6f): Yarn 4 deletes an
914
+ // empty `"dependencies": {}` from workspace manifests during install, so
915
+ // emitting one creates a permanent install↔sync churn loop — install
916
+ // strips the key, the next sync re-injects it (`dependencies` is
917
+ // protected, but a protected key MISSING from the current file is
918
+ // re-added), and the tree never converges across the consumer's
919
+ // sync → install → sync workflow. A dependency-less package carries no
920
+ // block at all, matching yarn's normalized form. Existing trees that
921
+ // still carry `{}` on disk stay untouched via the protected-key merge.
922
+ // devDependencies/scripts can't go empty (both have built-in entries).
923
+ ...Object.keys(dependencies).length > 0 ? { dependencies } : {},
807
924
  devDependencies: {
808
925
  typescript: "^5.0.0",
809
926
  ...defaults.devDependencies ?? {},
@@ -812,7 +929,7 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
812
929
  };
813
930
  let currentPkg = {};
814
931
  try {
815
- const currentContent = await fs3.readFile(pkgPath, "utf8");
932
+ const currentContent = await fs5.readFile(pkgPath, "utf8");
816
933
  currentPkg = JSON.parse(currentContent);
817
934
  } catch (e) {
818
935
  if (!(e instanceof Error && "code" in e && e.code === "ENOENT")) {
@@ -852,11 +969,7 @@ async function generatePackageJson(modulePath, moduleName, config, report) {
852
969
  report,
853
970
  true
854
971
  );
855
- if (status === "created") result.created.push(pkgPath);
856
- if (status === "updated") result.updated.push(pkgPath);
857
- if (status === "skipped" || status === "protected")
858
- result.skipped.push(pkgPath);
859
- result.totalOps += status === "created" || status === "updated" ? 1 : 0;
972
+ recordWriteStatus(result, pkgPath, status);
860
973
  return result;
861
974
  }
862
975
  var BUILTIN_FALLBACK_TEMPLATE = {
@@ -926,7 +1039,7 @@ function buildTemplate(base, context, scope) {
926
1039
  }
927
1040
  async function generateTsconfig(moduleDir, moduleName, config, report) {
928
1041
  const result = createEmptyResult();
929
- const filePath = path6.join(moduleDir, "tsconfig.json");
1042
+ const filePath = path7.join(moduleDir, "tsconfig.json");
930
1043
  try {
931
1044
  const base = resolveWorkspaceTemplate(config.manifest);
932
1045
  const context = config.manifest.bounded_contexts?.find(
@@ -941,16 +1054,14 @@ async function generateTsconfig(moduleDir, moduleName, config, report) {
941
1054
  config,
942
1055
  report
943
1056
  );
944
- if (status === "created") result.created.push(filePath);
945
- if (status === "updated") result.updated.push(filePath);
946
- if (status === "skipped" || status === "protected")
947
- result.skipped.push(filePath);
948
- result.totalOps += status === "created" || status === "updated" ? 1 : 0;
1057
+ recordWriteStatus(result, filePath, status);
949
1058
  return result;
950
1059
  } catch (err3) {
951
1060
  const message = err3 instanceof Error ? err3.message : String(err3);
952
1061
  result.error = err3 instanceof Error ? err3 : new Error(`tsconfig generation failed for ${moduleName}: ${message}`);
953
1062
  result.summary = `tsconfig generation failed for ${moduleName}: ${message}`;
1063
+ config.logger.error(result.summary);
1064
+ if (report) report.record("error", filePath, result.summary);
954
1065
  return result;
955
1066
  }
956
1067
  }
@@ -958,15 +1069,15 @@ async function reapLegacyFolders(moduleDir, config, report) {
958
1069
  const { dryRun, logger } = config;
959
1070
  const legacyLayers = ["domain", "application", "infrastructure"];
960
1071
  for (const layer of legacyLayers) {
961
- const layerPath = path6.join(moduleDir, layer);
962
- const relativePath = path6.relative(config.workspaceRoot, layerPath);
1072
+ const layerPath = path7.join(moduleDir, layer);
1073
+ const relativePath = path7.relative(config.workspaceRoot, layerPath);
963
1074
  try {
964
- const entries = await fs3.readdir(layerPath);
1075
+ const entries = await fs5.readdir(layerPath);
965
1076
  if (entries.length === 0) {
966
1077
  if (dryRun) {
967
1078
  logger.info(`[DRY-RUN] would delete empty folder ${relativePath}`);
968
1079
  } else {
969
- await fs3.rm(layerPath, { recursive: true, force: true });
1080
+ await fs5.rmdir(layerPath);
970
1081
  logger.info(`deleted empty folder ${relativePath}`);
971
1082
  if (report) report.record("deleted", layerPath);
972
1083
  }
@@ -1456,8 +1567,8 @@ function getErrorMap() {
1456
1567
 
1457
1568
  // ../../node_modules/zod/v3/helpers/parseUtil.js
1458
1569
  var makeIssue = (params) => {
1459
- const { data, path: path24, errorMaps, issueData } = params;
1460
- const fullPath = [...path24, ...issueData.path || []];
1570
+ const { data, path: path25, errorMaps, issueData } = params;
1571
+ const fullPath = [...path25, ...issueData.path || []];
1461
1572
  const fullIssue = {
1462
1573
  ...issueData,
1463
1574
  path: fullPath
@@ -1573,11 +1684,11 @@ var errorUtil;
1573
1684
 
1574
1685
  // ../../node_modules/zod/v3/types.js
1575
1686
  var ParseInputLazyPath = class {
1576
- constructor(parent, value, path24, key) {
1687
+ constructor(parent, value, path25, key) {
1577
1688
  this._cachedPath = [];
1578
1689
  this.parent = parent;
1579
1690
  this.data = value;
1580
- this._path = path24;
1691
+ this._path = path25;
1581
1692
  this._key = key;
1582
1693
  }
1583
1694
  get path() {
@@ -5088,6 +5199,7 @@ var BUILTIN_PACKAGE_JSON_TEMPLATE = `{
5088
5199
  "sync": "hexagen sync",
5089
5200
  "sync:dry": "hexagen sync --dry-run",
5090
5201
  "sync:force": "hexagen sync --force",
5202
+ "sync:check": "hexagen sync --check",
5091
5203
  "lint:arch": "hexagen arch validate",
5092
5204
  "templates:add": "hexagen add",
5093
5205
  "templates:validate": "hexagen validate-templates",
@@ -5098,8 +5210,8 @@ var BUILTIN_PACKAGE_JSON_TEMPLATE = `{
5098
5210
  "typescript": "^5.5.4",
5099
5211
  "eslint": "^9.0.0",
5100
5212
  "prettier": "^3.0.0",
5101
- "@hexagen-monaco/sync": "^0.4.0",
5102
- "@hexagen-monaco/arch-linter": "^0.4.0"
5213
+ "@hexagen-monaco/sync": "^{toolchainVersion}",
5214
+ "@hexagen-monaco/arch-linter": "^{toolchainVersion}"
5103
5215
  }
5104
5216
  }`;
5105
5217
  var BUILTIN_TSCONFIG_BASE_TEMPLATE = `{
@@ -5211,15 +5323,33 @@ adding \`--immutable\` to the \`yarn install\` step in
5211
5323
  Its pre-lockfile guidance goes stale once \`yarn.lock\` is committed. (Run
5212
5324
  \`hexagen sync\` won't bring it back — it's a protected root file.)
5213
5325
  `;
5326
+ 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-]+)*))?$/;
5327
+ function assertValidToolchainVersion(version, source) {
5328
+ const invalid = !SEMVER_2_0_0.test(version) || /^0\.0\.0(?:$|[-+])/.test(version);
5329
+ if (invalid) {
5330
+ throw new Error(
5331
+ `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).`
5332
+ );
5333
+ }
5334
+ return version;
5335
+ }
5336
+ function resolveToolchainVersion() {
5337
+ {
5338
+ return assertValidToolchainVersion(
5339
+ "0.7.1",
5340
+ "build-injected __HEXAGEN_TOOLCHAIN_VERSION__"
5341
+ );
5342
+ }
5343
+ }
5214
5344
 
5215
5345
  // src/generators/root-files.ts
5216
- function buildVars(manifest) {
5346
+ function buildVars(manifest, toolchainVersion) {
5217
5347
  const system = typeof manifest.system === "string" && manifest.system.length > 0 ? manifest.system : "generated-project";
5218
5348
  const scope = resolveScope(manifest);
5219
5349
  const packageManager = typeof manifest.monorepo?.packageManager === "string" && manifest.monorepo.packageManager.length > 0 ? manifest.monorepo.packageManager : "yarn@4.12.0";
5220
5350
  const workspacesArray = Array.isArray(manifest.monorepo?.workspaces) && manifest.monorepo.workspaces.length > 0 ? manifest.monorepo.workspaces : ["apps/*", "packages/*"];
5221
5351
  const workspaces = "[\n" + workspacesArray.map((w) => ` ${JSON.stringify(w)}`).join(",\n") + "\n ]";
5222
- return { system, scope, packageManager, workspaces };
5352
+ return { system, scope, packageManager, workspaces, toolchainVersion };
5223
5353
  }
5224
5354
  function resolveTemplate(manifestTemplate, builtin) {
5225
5355
  if (typeof manifestTemplate === "string" && manifestTemplate.length > 0) {
@@ -5245,17 +5375,14 @@ async function writeRootFile(filePath, content, config, report, result) {
5245
5375
  report,
5246
5376
  true
5247
5377
  );
5248
- if (status === "created") result.created.push(filePath);
5249
- if (status === "updated") result.updated.push(filePath);
5250
- if (status === "skipped" || status === "protected")
5251
- result.skipped.push(filePath);
5252
- if (status === "created" || status === "updated") result.totalOps += 1;
5378
+ recordWriteStatus(result, filePath, status);
5253
5379
  }
5254
5380
  async function generateRootFiles(config, report) {
5255
5381
  const result = createEmptyResult();
5382
+ const toolchainVersion = resolveToolchainVersion();
5256
5383
  try {
5257
5384
  const rootFiles = config.manifest.monorepo?.rootFiles;
5258
- const vars = buildVars(config.manifest);
5385
+ const vars = buildVars(config.manifest, toolchainVersion);
5259
5386
  const packageJsonTemplate = resolveTemplate(
5260
5387
  rootFiles?.packageJson?.template,
5261
5388
  BUILTIN_PACKAGE_JSON_TEMPLATE
@@ -5267,7 +5394,7 @@ async function generateRootFiles(config, report) {
5267
5394
  "package.json"
5268
5395
  );
5269
5396
  await writeRootFile(
5270
- path6.join(config.workspaceRoot, "package.json"),
5397
+ path7.join(config.workspaceRoot, "package.json"),
5271
5398
  packageJsonContent,
5272
5399
  config,
5273
5400
  report,
@@ -5284,7 +5411,7 @@ async function generateRootFiles(config, report) {
5284
5411
  "tsconfig.base.json"
5285
5412
  );
5286
5413
  await writeRootFile(
5287
- path6.join(config.workspaceRoot, "tsconfig.base.json"),
5414
+ path7.join(config.workspaceRoot, "tsconfig.base.json"),
5288
5415
  tsconfigContent,
5289
5416
  config,
5290
5417
  report,
@@ -5301,7 +5428,7 @@ async function generateRootFiles(config, report) {
5301
5428
  "turbo.json"
5302
5429
  );
5303
5430
  await writeRootFile(
5304
- path6.join(config.workspaceRoot, "turbo.json"),
5431
+ path7.join(config.workspaceRoot, "turbo.json"),
5305
5432
  turboContent,
5306
5433
  config,
5307
5434
  report,
@@ -5312,7 +5439,7 @@ async function generateRootFiles(config, report) {
5312
5439
  BUILTIN_GITIGNORE_TEMPLATE
5313
5440
  );
5314
5441
  await writeRootFile(
5315
- path6.join(config.workspaceRoot, ".gitignore"),
5442
+ path7.join(config.workspaceRoot, ".gitignore"),
5316
5443
  interpolateAndWarn(gitignoreTemplate, vars, config, ".gitignore"),
5317
5444
  config,
5318
5445
  report,
@@ -5323,7 +5450,7 @@ async function generateRootFiles(config, report) {
5323
5450
  BUILTIN_YARNRC_TEMPLATE
5324
5451
  );
5325
5452
  await writeRootFile(
5326
- path6.join(config.workspaceRoot, ".yarnrc.yml"),
5453
+ path7.join(config.workspaceRoot, ".yarnrc.yml"),
5327
5454
  interpolateAndWarn(yarnrcTemplate, vars, config, ".yarnrc.yml"),
5328
5455
  config,
5329
5456
  report,
@@ -5334,7 +5461,7 @@ async function generateRootFiles(config, report) {
5334
5461
  BUILTIN_SETUP_MD_TEMPLATE
5335
5462
  );
5336
5463
  await writeRootFile(
5337
- path6.join(config.workspaceRoot, "SETUP.md"),
5464
+ path7.join(config.workspaceRoot, "SETUP.md"),
5338
5465
  interpolateAndWarn(setupTemplate, vars, config, "SETUP.md"),
5339
5466
  config,
5340
5467
  report,
@@ -5345,6 +5472,8 @@ async function generateRootFiles(config, report) {
5345
5472
  const message = err3 instanceof Error ? err3.message : String(err3);
5346
5473
  result.error = err3 instanceof Error ? err3 : new Error(`root-files generation failed: ${message}`);
5347
5474
  result.summary = `root-files generation failed: ${message}`;
5475
+ config.logger.error(result.summary);
5476
+ if (report) report.record("error", "root-files", result.summary);
5348
5477
  return result;
5349
5478
  }
5350
5479
  }
@@ -5420,7 +5549,7 @@ test_double_rules:
5420
5549
  var GENERATOR_CONFIG_TEMPLATE = `generator:
5421
5550
  version: "1.0"
5422
5551
  description: "Global invariants and safety rules"
5423
- workspace_template: "{workspaceTemplate}"
5552
+ workspaceTemplate: "{workspaceTemplate}"
5424
5553
 
5425
5554
  invariants:
5426
5555
  - name: composite-safety
@@ -5501,37 +5630,65 @@ function resolveWorkspaceTemplate2(manifest) {
5501
5630
  function toPascalCase(stem) {
5502
5631
  return stem.split(/[-.]/).filter((part) => part.length > 0).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
5503
5632
  }
5633
+ function yamlScalar(value) {
5634
+ const plainSafe = /^[A-Za-z][A-Za-z0-9._-]*$/.test(value);
5635
+ const reserved = /^(?:true|false|null|yes|no|on|off)$/i.test(value);
5636
+ return plainSafe && !reserved ? value : JSON.stringify(value);
5637
+ }
5504
5638
  function buildOwnershipBlock(manifest) {
5505
5639
  const contexts = manifest.bounded_contexts ?? [];
5506
5640
  const entries = [];
5641
+ const seen = /* @__PURE__ */ new Set();
5642
+ const owners = /* @__PURE__ */ new Map();
5643
+ const add = (name, context) => {
5644
+ const key = JSON.stringify([name, context]);
5645
+ if (seen.has(key)) return;
5646
+ seen.add(key);
5647
+ entries.push({ name, context });
5648
+ let contextsForName = owners.get(name);
5649
+ if (!contextsForName) {
5650
+ contextsForName = /* @__PURE__ */ new Set();
5651
+ owners.set(name, contextsForName);
5652
+ }
5653
+ contextsForName.add(context);
5654
+ };
5507
5655
  for (const bc of contexts) {
5508
5656
  if (bc.name === "shared") continue;
5509
5657
  const application = bc.layers?.application;
5510
5658
  const infrastructure = bc.layers?.infrastructure;
5511
5659
  for (const p of application?.ports?.in ?? []) {
5512
- const name = toPascalCase(portName(p).replace(/\.in-port\.ts$/, ""));
5513
- entries.push(` ${name}: ${bc.name}`);
5660
+ add(toPascalCase(portName(p).replace(/\.in-port\.ts$/, "")), bc.name);
5514
5661
  }
5515
5662
  for (const p of application?.ports?.out ?? []) {
5516
- const name = toPascalCase(portName(p).replace(/\.out-port\.ts$/, ""));
5517
- entries.push(` ${name}: ${bc.name}`);
5663
+ add(toPascalCase(portName(p).replace(/\.out-port\.ts$/, "")), bc.name);
5518
5664
  }
5519
5665
  for (const a of infrastructure?.adapters ?? []) {
5520
- const name = toPascalCase(a.replace(/\.adapter\.ts$/, ""));
5521
- entries.push(` ${name}: ${bc.name}`);
5666
+ add(toPascalCase(a.replace(/\.adapter\.ts$/, "")), bc.name);
5522
5667
  }
5523
5668
  }
5524
- return entries.length > 0 ? entries.join("\n") : " # No ports declared";
5669
+ const collisions = [...owners.entries()].filter(([, contextsForName]) => contextsForName.size > 1).map(([name]) => name);
5670
+ const contested = new Set(collisions);
5671
+ const lines = entries.map(
5672
+ ({ name, context }) => contested.has(name) ? ` ${JSON.stringify(`${context}.${name}`)}: ${yamlScalar(context)}` : ` ${name}: ${yamlScalar(context)}`
5673
+ );
5674
+ return {
5675
+ block: lines.length > 0 ? lines.join("\n") : " # No ports declared",
5676
+ collisions
5677
+ };
5525
5678
  }
5526
5679
  function buildInterpolationVars(manifest) {
5527
5680
  const scope = resolveScope(manifest);
5528
5681
  const workspaceTemplate = resolveWorkspaceTemplate2(manifest);
5682
+ const { block, collisions } = buildOwnershipBlock(manifest);
5529
5683
  return {
5530
- scope,
5531
- template: workspaceTemplate,
5532
- workspaceTemplate,
5533
- system: typeof manifest.system === "string" ? manifest.system : "",
5534
- ownershipBlock: buildOwnershipBlock(manifest)
5684
+ vars: {
5685
+ scope,
5686
+ template: workspaceTemplate,
5687
+ workspaceTemplate,
5688
+ system: typeof manifest.system === "string" ? manifest.system : "",
5689
+ ownershipBlock: block
5690
+ },
5691
+ ownershipCollisions: collisions
5535
5692
  };
5536
5693
  }
5537
5694
  function builtInLayerRules(workspaceTemplate) {
@@ -5560,20 +5717,13 @@ function interpolateWithLogging(label, template, vars, config) {
5560
5717
  }
5561
5718
  return output;
5562
5719
  }
5563
- function recordStatus(result, filePath, status) {
5564
- if (status === "created") result.created.push(filePath);
5565
- else if (status === "updated") result.updated.push(filePath);
5566
- else if (status === "skipped" || status === "protected")
5567
- result.skipped.push(filePath);
5568
- if (status === "created" || status === "updated") result.totalOps += 1;
5569
- }
5570
5720
  async function writeManifestIfFreshExternal(config, result, report) {
5571
5721
  if (config.mode !== "external") {
5572
5722
  return;
5573
5723
  }
5574
- const archDir = path6.join(config.workspaceRoot, ".architecture");
5575
- const manifestPath = path6.join(archDir, "manifest.yaml");
5576
- const relative = path6.relative(config.workspaceRoot, manifestPath);
5724
+ const archDir = path7.join(config.workspaceRoot, ".architecture");
5725
+ const manifestPath = path7.join(archDir, "manifest.yaml");
5726
+ const relative = path7.relative(config.workspaceRoot, manifestPath);
5577
5727
  if (!isInScope(manifestPath, config)) {
5578
5728
  config.logger.debug(`skipped (outside --only) ${relative}`);
5579
5729
  result.skipped.push(manifestPath);
@@ -5581,7 +5731,7 @@ async function writeManifestIfFreshExternal(config, result, report) {
5581
5731
  }
5582
5732
  let exists = false;
5583
5733
  try {
5584
- await fs3.access(manifestPath);
5734
+ await fs5.access(manifestPath);
5585
5735
  exists = true;
5586
5736
  } catch {
5587
5737
  exists = false;
@@ -5600,8 +5750,9 @@ async function writeManifestIfFreshExternal(config, result, report) {
5600
5750
  return;
5601
5751
  }
5602
5752
  const content = yaml3.dump(config.manifest);
5603
- await fs3.mkdir(archDir, { recursive: true });
5604
- await fs3.writeFile(manifestPath, content, { encoding: "utf8" });
5753
+ config.journal?.recordWrite(manifestPath, null);
5754
+ await fs5.mkdir(archDir, { recursive: true });
5755
+ await fs5.writeFile(manifestPath, content, { encoding: "utf8" });
5605
5756
  config.logger.info(`created ${relative}`);
5606
5757
  if (report)
5607
5758
  report.record(
@@ -5615,12 +5766,17 @@ async function writeManifestIfFreshExternal(config, result, report) {
5615
5766
  async function generateArchitectureFiles(config, report) {
5616
5767
  const result = createEmptyResult();
5617
5768
  const manifest = config.manifest;
5618
- const archRoot = path6.join(config.workspaceRoot, ".architecture");
5769
+ const archRoot = path7.join(config.workspaceRoot, ".architecture");
5619
5770
  const archInvariants = manifest.monorepo?.archInvariants;
5620
- const vars = buildInterpolationVars(manifest);
5771
+ const { vars, ownershipCollisions } = buildInterpolationVars(manifest);
5621
5772
  const workspaceTemplate = vars.workspaceTemplate ?? "modular-monolith";
5773
+ if (ownershipCollisions.length > 0) {
5774
+ config.logger.warn(
5775
+ `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).`
5776
+ );
5777
+ }
5622
5778
  await writeManifestIfFreshExternal(config, result, report);
5623
- const layerRulesPath = path6.join(archRoot, "invariants", "layer-rules.yaml");
5779
+ const layerRulesPath = path7.join(archRoot, "invariants", "layer-rules.yaml");
5624
5780
  const layerRulesTemplate = resolveTemplate2(
5625
5781
  archInvariants?.layerRules,
5626
5782
  builtInLayerRules(workspaceTemplate)
@@ -5638,8 +5794,8 @@ async function generateArchitectureFiles(config, report) {
5638
5794
  report,
5639
5795
  true
5640
5796
  );
5641
- recordStatus(result, layerRulesPath, layerRulesStatus);
5642
- const linterConfigPath = path6.join(
5797
+ recordWriteStatus(result, layerRulesPath, layerRulesStatus);
5798
+ const linterConfigPath = path7.join(
5643
5799
  archRoot,
5644
5800
  "invariants",
5645
5801
  "linter-config.yaml"
@@ -5661,8 +5817,8 @@ async function generateArchitectureFiles(config, report) {
5661
5817
  report,
5662
5818
  true
5663
5819
  );
5664
- recordStatus(result, linterConfigPath, linterConfigStatus);
5665
- const generatorConfigPath = path6.join(archRoot, "generator.config.yaml");
5820
+ recordWriteStatus(result, linterConfigPath, linterConfigStatus);
5821
+ const generatorConfigPath = path7.join(archRoot, "generator.config.yaml");
5666
5822
  const generatorConfigTemplate = resolveTemplate2(
5667
5823
  archInvariants?.generatorConfig,
5668
5824
  GENERATOR_CONFIG_TEMPLATE
@@ -5680,7 +5836,7 @@ async function generateArchitectureFiles(config, report) {
5680
5836
  report,
5681
5837
  true
5682
5838
  );
5683
- recordStatus(result, generatorConfigPath, generatorConfigStatus);
5839
+ recordWriteStatus(result, generatorConfigPath, generatorConfigStatus);
5684
5840
  return result;
5685
5841
  }
5686
5842
 
@@ -5784,7 +5940,6 @@ var PLAIN_TS_PACKAGE_JSON_TEMPLATE = `{
5784
5940
  "lint": "eslint src --ext .ts,.tsx",
5785
5941
  "typecheck": "tsc --noEmit"
5786
5942
  },
5787
- "dependencies": {},
5788
5943
  "devDependencies": {
5789
5944
  "typescript": "^5.5.4",
5790
5945
  "eslint": "^9.0.0",
@@ -5931,7 +6086,7 @@ ${content}`;
5931
6086
  }
5932
6087
  async function generateEslintConfig(moduleDir, moduleName, config, report, options = {}) {
5933
6088
  const result = createEmptyResult();
5934
- const filePath = path6.join(moduleDir, "eslint.config.js");
6089
+ const filePath = path7.join(moduleDir, "eslint.config.js");
5935
6090
  try {
5936
6091
  const { template, source } = resolveTemplate3(
5937
6092
  config.manifest,
@@ -5964,11 +6119,7 @@ async function generateEslintConfig(moduleDir, moduleName, config, report, optio
5964
6119
  report,
5965
6120
  false
5966
6121
  );
5967
- if (status === "created") result.created.push(filePath);
5968
- if (status === "updated") result.updated.push(filePath);
5969
- if (status === "skipped" || status === "protected")
5970
- result.skipped.push(filePath);
5971
- result.totalOps += status === "created" || status === "updated" ? 1 : 0;
6122
+ recordWriteStatus(result, filePath, status);
5972
6123
  return result;
5973
6124
  } catch (err3) {
5974
6125
  const message = err3 instanceof Error ? err3.message : String(err3);
@@ -6003,21 +6154,12 @@ function interpolateWithLogging2(template, vars, context, config) {
6003
6154
  }
6004
6155
  return output;
6005
6156
  }
6006
- function recordStatus2(result, filePath, status) {
6007
- if (status === "created") {
6008
- result.created.push(filePath);
6009
- result.totalOps += 1;
6010
- } else if (status === "updated") {
6011
- result.updated.push(filePath);
6012
- result.totalOps += 1;
6013
- } else {
6014
- result.skipped.push(filePath);
6015
- }
6016
- }
6017
6157
  function mergeResult(result, sub) {
6018
6158
  result.created.push(...sub.created);
6019
6159
  result.updated.push(...sub.updated);
6020
6160
  result.skipped.push(...sub.skipped);
6161
+ result.deleted.push(...sub.deleted);
6162
+ result.unchanged.push(...sub.unchanged);
6021
6163
  result.totalOps += sub.totalOps;
6022
6164
  if (sub.error && !result.error) {
6023
6165
  result.error = sub.error;
@@ -6031,9 +6173,9 @@ async function emitAppFile(appDir, relPath, template, vars, config, report, resu
6031
6173
  `apps/${appName}/${relPath}`,
6032
6174
  config
6033
6175
  );
6034
- const target = path6.resolve(appDir, relPath);
6035
- const relative = path6.relative(appDir, target);
6036
- if (relative === "" || relative.startsWith("..") || path6.isAbsolute(relative)) {
6176
+ const target = path7.resolve(appDir, relPath);
6177
+ const relative = path7.relative(appDir, target);
6178
+ if (relative === "" || relative.startsWith("..") || path7.isAbsolute(relative)) {
6037
6179
  config.logger.warn(
6038
6180
  `[apps] skipping file with unsafe path (escapes apps/${appName}): ${relPath}`
6039
6181
  );
@@ -6046,9 +6188,9 @@ async function emitAppFile(appDir, relPath, template, vars, config, report, resu
6046
6188
  }
6047
6189
  return "unsafe";
6048
6190
  }
6049
- if (isInScope(target, config)) {
6191
+ if (!config.dryRun && isInScope(target, config)) {
6050
6192
  try {
6051
- await fs3.mkdir(path6.dirname(target), { recursive: true });
6193
+ await fs5.mkdir(path7.dirname(target), { recursive: true });
6052
6194
  } catch (err3) {
6053
6195
  const message = err3 instanceof Error ? err3.message : String(err3);
6054
6196
  config.logger.error(
@@ -6058,7 +6200,7 @@ async function emitAppFile(appDir, relPath, template, vars, config, report, resu
6058
6200
  return "error";
6059
6201
  }
6060
6202
  }
6061
- recordStatus2(
6203
+ recordWriteStatus(
6062
6204
  result,
6063
6205
  target,
6064
6206
  await safeWriteFileAtomic(target, content, config, report)
@@ -6139,12 +6281,12 @@ async function generateApps(config, report) {
6139
6281
  version: app.version ?? "",
6140
6282
  depends_on: (app.depends_on ?? []).join(", ")
6141
6283
  };
6142
- const appDir = path6.join(config.workspaceRoot, "apps", app.name);
6143
- const srcDir = path6.join(appDir, "src");
6144
- if (isInScope(appDir, config)) {
6284
+ const appDir = path7.join(config.workspaceRoot, "apps", app.name);
6285
+ const srcDir = path7.join(appDir, "src");
6286
+ if (!config.dryRun && isInScope(appDir, config)) {
6145
6287
  try {
6146
- await fs3.mkdir(appDir, { recursive: true });
6147
- await fs3.mkdir(srcDir, { recursive: true });
6288
+ await fs5.mkdir(appDir, { recursive: true });
6289
+ await fs5.mkdir(srcDir, { recursive: true });
6148
6290
  } catch (err3) {
6149
6291
  const message = err3 instanceof Error ? err3.message : String(err3);
6150
6292
  config.logger.error(
@@ -6162,14 +6304,14 @@ async function generateApps(config, report) {
6162
6304
  `apps/${app.name}/package.json`,
6163
6305
  config
6164
6306
  );
6165
- const pkgPath = path6.join(appDir, "package.json");
6307
+ const pkgPath = path7.join(appDir, "package.json");
6166
6308
  const status = await safeWriteFileAtomic(
6167
6309
  pkgPath,
6168
6310
  pkgContent,
6169
6311
  config,
6170
6312
  report
6171
6313
  );
6172
- recordStatus2(result, pkgPath, status);
6314
+ recordWriteStatus(result, pkgPath, status);
6173
6315
  } else {
6174
6316
  config.logger.warn(
6175
6317
  `[apps] framework "${framework}" has no package.json template — skipping package.json for "${app.name}"`
@@ -6178,14 +6320,14 @@ async function generateApps(config, report) {
6178
6320
  const tsConfig = frameworkConfig.tsConfig;
6179
6321
  if (tsConfig) {
6180
6322
  const tsContent = JSON.stringify(tsConfig, null, 2) + "\n";
6181
- const tsPath = path6.join(appDir, "tsconfig.json");
6323
+ const tsPath = path7.join(appDir, "tsconfig.json");
6182
6324
  const status = await safeWriteFileAtomic(
6183
6325
  tsPath,
6184
6326
  tsContent,
6185
6327
  config,
6186
6328
  report
6187
6329
  );
6188
- recordStatus2(result, tsPath, status);
6330
+ recordWriteStatus(result, tsPath, status);
6189
6331
  } else {
6190
6332
  config.logger.warn(
6191
6333
  `[apps] framework "${framework}" has no tsConfig — skipping tsconfig.json for "${app.name}"`
@@ -6239,18 +6381,20 @@ async function generateApps(config, report) {
6239
6381
  const message = err3 instanceof Error ? err3.message : String(err3);
6240
6382
  result.error = err3 instanceof Error ? err3 : new Error(`apps generation failed: ${message}`);
6241
6383
  result.summary = `apps generation failed: ${message}`;
6384
+ config.logger.error(result.summary);
6385
+ if (report) report.record("error", "apps", result.summary);
6242
6386
  return result;
6243
6387
  }
6244
6388
  }
6245
6389
  function relativeImportSpecifier(fromFile, toFile) {
6246
- let rel = path6.relative(path6.dirname(fromFile), toFile).split(path6.sep).join("/").replace(/\.tsx?$/, ".js");
6390
+ let rel = path7.relative(path7.dirname(fromFile), toFile).split(path7.sep).join("/").replace(/\.tsx?$/, ".js");
6247
6391
  if (!rel.startsWith(".")) rel = `./${rel}`;
6248
6392
  return rel;
6249
6393
  }
6250
6394
  function rewriteRelativeSpecifier(specifier, fromFile, toFile) {
6251
6395
  if (!specifier.startsWith(".")) return specifier;
6252
- const absolute = path6.resolve(path6.dirname(fromFile), specifier);
6253
- let rel = path6.relative(path6.dirname(toFile), absolute).split(path6.sep).join("/");
6396
+ const absolute = path7.resolve(path7.dirname(fromFile), specifier);
6397
+ let rel = path7.relative(path7.dirname(toFile), absolute).split(path7.sep).join("/");
6254
6398
  if (!rel.startsWith(".")) rel = `./${rel}`;
6255
6399
  return rel;
6256
6400
  }
@@ -6886,13 +7030,13 @@ function resolveNaming(kind, contextNaming, manifestNaming) {
6886
7030
  async function writeStubFile(filePath, content, config, report) {
6887
7031
  if (!isInScope(filePath, config)) {
6888
7032
  config.logger.debug(
6889
- `skipped (outside --only) ${path6.relative(config.workspaceRoot, filePath)}`
7033
+ `skipped (outside --only) ${path7.relative(config.workspaceRoot, filePath)}`
6890
7034
  );
6891
7035
  return "skipped";
6892
7036
  }
6893
7037
  try {
6894
- await fs3.stat(filePath);
6895
- const relative = path6.relative(config.workspaceRoot, filePath);
7038
+ await fs5.stat(filePath);
7039
+ const relative = path7.relative(config.workspaceRoot, filePath);
6896
7040
  config.logger.debug(`stub preserved ${relative}`);
6897
7041
  if (report) {
6898
7042
  report.record(
@@ -6907,7 +7051,9 @@ async function writeStubFile(filePath, content, config, report) {
6907
7051
  throw err3;
6908
7052
  }
6909
7053
  }
6910
- await fs3.mkdir(path6.dirname(filePath), { recursive: true });
7054
+ if (!config.dryRun) {
7055
+ await fs5.mkdir(path7.dirname(filePath), { recursive: true });
7056
+ }
6911
7057
  return safeWriteFileAtomic(filePath, content, config, report, false);
6912
7058
  }
6913
7059
  async function tryAnalyzeRelatedPort(moduleDir, name, kind, context, relatedPortNamingTemplate) {
@@ -6926,7 +7072,7 @@ async function tryAnalyzeRelatedPort(moduleDir, name, kind, context, relatedPort
6926
7072
  `${derivedPortName}.ts`
6927
7073
  ];
6928
7074
  for (const filename of possibleFilenames) {
6929
- const portFilePath = path6.join(moduleDir, "src", portSubdir, filename);
7075
+ const portFilePath = path7.join(moduleDir, "src", portSubdir, filename);
6930
7076
  const analysis = analyzePortFile(portFilePath);
6931
7077
  if (analysis) {
6932
7078
  return analysis;
@@ -6979,7 +7125,7 @@ async function generateStubs(moduleDir, moduleName, config, report) {
6979
7125
  `stubs.naming.${kind}`,
6980
7126
  config
6981
7127
  );
6982
- const filePath = path6.join(moduleDir, "src", subdir, filename);
7128
+ const filePath = path7.join(moduleDir, "src", subdir, filename);
6983
7129
  let content;
6984
7130
  if (kind === "adapter" || kind === "useCase") {
6985
7131
  const relatedPortNaming = resolveNaming(
@@ -7008,7 +7154,7 @@ async function generateStubs(moduleDir, moduleName, config, report) {
7008
7154
  contextNaming,
7009
7155
  manifestNaming
7010
7156
  );
7011
- const outPortDir = path6.join(
7157
+ const outPortDir = path7.join(
7012
7158
  moduleDir,
7013
7159
  "src",
7014
7160
  "application",
@@ -7023,7 +7169,7 @@ async function generateStubs(moduleDir, moduleName, config, report) {
7023
7169
  "stubs.naming.outPort",
7024
7170
  config
7025
7171
  );
7026
- const outPortPath = path6.join(outPortDir, outFile);
7172
+ const outPortPath = path7.join(outPortDir, outFile);
7027
7173
  const analyzed = analyzePortFile(outPortPath);
7028
7174
  return {
7029
7175
  interfaceName: analyzed?.interfaceName ?? `${base}Port`,
@@ -7057,24 +7203,13 @@ async function generateStubs(moduleDir, moduleName, config, report) {
7057
7203
  );
7058
7204
  }
7059
7205
  const status = await writeStubFile(filePath, content, config, report);
7060
- if (status === "created") result.created.push(filePath);
7061
- if (status === "updated") result.updated.push(filePath);
7062
- if (status === "skipped" || status === "protected")
7063
- result.skipped.push(filePath);
7064
- if (status === "created" || status === "updated") result.totalOps += 1;
7206
+ recordWriteStatus(result, filePath, status);
7065
7207
  }
7066
7208
  }
7067
7209
  return result;
7068
7210
  }
7069
7211
  var OHS_NOTE = "\n *\n * Open Host Service (open-host): this is this context's published language for consuming contexts — keep it stable.";
7070
7212
  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.";
7071
- function recordStatus3(result, filePath, status) {
7072
- if (status === "created") result.created.push(filePath);
7073
- else if (status === "updated") result.updated.push(filePath);
7074
- else if (status === "skipped" || status === "protected")
7075
- result.skipped.push(filePath);
7076
- if (status === "created" || status === "updated") result.totalOps += 1;
7077
- }
7078
7213
  function addAll(map, key, values) {
7079
7214
  const set = map.get(key) ?? /* @__PURE__ */ new Set();
7080
7215
  values.forEach((v) => set.add(v));
@@ -7140,27 +7275,29 @@ ${methodLines}
7140
7275
  `;
7141
7276
  }
7142
7277
  async function emitPortAndAdapter(result, config, report, scope, spec) {
7143
- const moduleRoot = path6.join(
7278
+ const moduleRoot = path7.join(
7144
7279
  config.workspaceRoot,
7145
7280
  "packages",
7146
7281
  spec.contextName
7147
7282
  );
7148
- const portDir = path6.join(
7283
+ const portDir = path7.join(
7149
7284
  moduleRoot,
7150
7285
  "src",
7151
7286
  "application",
7152
7287
  "ports",
7153
7288
  spec.portKind
7154
7289
  );
7155
- const portPath = path6.join(
7290
+ const portPath = path7.join(
7156
7291
  portDir,
7157
7292
  `${spec.portBase}.${spec.portKind}-port.ts`
7158
7293
  );
7159
7294
  if (!isInScope(portPath, config)) {
7160
7295
  return;
7161
7296
  }
7162
- await fs3.mkdir(portDir, { recursive: true });
7163
- recordStatus3(
7297
+ if (!config.dryRun) {
7298
+ await fs5.mkdir(portDir, { recursive: true });
7299
+ }
7300
+ recordWriteStatus(
7164
7301
  result,
7165
7302
  portPath,
7166
7303
  await safeWriteFileAtomic(
@@ -7183,15 +7320,17 @@ async function emitPortAndAdapter(result, config, report, scope, spec) {
7183
7320
  );
7184
7321
  return;
7185
7322
  }
7186
- const adapterDir = path6.join(moduleRoot, "src", "infrastructure", "adapters");
7187
- const adapterPath = path6.join(adapterDir, `${spec.portBase}.adapter.ts`);
7323
+ const adapterDir = path7.join(moduleRoot, "src", "infrastructure", "adapters");
7324
+ const adapterPath = path7.join(adapterDir, `${spec.portBase}.adapter.ts`);
7188
7325
  if (!isInScope(adapterPath, config)) {
7189
7326
  return;
7190
7327
  }
7191
- await fs3.mkdir(adapterDir, { recursive: true });
7328
+ if (!config.dryRun) {
7329
+ await fs5.mkdir(adapterDir, { recursive: true });
7330
+ }
7192
7331
  const adapterClassName = `${toPascalCase2(spec.portBase)}Adapter`;
7193
7332
  const portSpecifier = relativeImportSpecifier(adapterPath, portPath);
7194
- recordStatus3(
7333
+ recordWriteStatus(
7195
7334
  result,
7196
7335
  adapterPath,
7197
7336
  await safeWriteFileAtomic(
@@ -7214,15 +7353,17 @@ function operationImports(ops) {
7214
7353
  return ops.flatMap((op) => [`${op}Request`, `${op}Response`]);
7215
7354
  }
7216
7355
  async function writeSharedContract(result, config, report, relSegments, content) {
7217
- const contractPath = path6.join(
7356
+ const contractPath = path7.join(
7218
7357
  config.workspaceRoot,
7219
7358
  "packages",
7220
7359
  "shared",
7221
7360
  "src",
7222
7361
  ...relSegments
7223
7362
  );
7224
- await fs3.mkdir(path6.dirname(contractPath), { recursive: true });
7225
- recordStatus3(
7363
+ if (!config.dryRun) {
7364
+ await fs5.mkdir(path7.dirname(contractPath), { recursive: true });
7365
+ }
7366
+ recordWriteStatus(
7226
7367
  result,
7227
7368
  contractPath,
7228
7369
  await safeWriteFileAtomic(contractPath, content, config, report)
@@ -7372,7 +7513,7 @@ async function generateSharedKernel(config, report) {
7372
7513
  (bc) => bc.name?.toLowerCase() === "shared"
7373
7514
  );
7374
7515
  if (!hasShared) return result;
7375
- const kernelPath = path6.join(
7516
+ const kernelPath = path7.join(
7376
7517
  config.workspaceRoot,
7377
7518
  "packages",
7378
7519
  "shared",
@@ -7385,13 +7526,15 @@ async function generateSharedKernel(config, report) {
7385
7526
  return result;
7386
7527
  }
7387
7528
  try {
7388
- await fs3.stat(kernelPath);
7529
+ await fs5.stat(kernelPath);
7389
7530
  result.skipped.push(kernelPath);
7390
7531
  return result;
7391
7532
  } catch (err3) {
7392
7533
  if (err3.code !== "ENOENT") throw err3;
7393
7534
  }
7394
- await fs3.mkdir(path6.dirname(kernelPath), { recursive: true });
7535
+ if (!config.dryRun) {
7536
+ await fs5.mkdir(path7.dirname(kernelPath), { recursive: true });
7537
+ }
7395
7538
  const status = await safeWriteFileAtomic(
7396
7539
  kernelPath,
7397
7540
  RESULT_KERNEL,
@@ -7399,12 +7542,7 @@ async function generateSharedKernel(config, report) {
7399
7542
  report,
7400
7543
  false
7401
7544
  );
7402
- if (status === "created" || status === "updated") {
7403
- result.created.push(kernelPath);
7404
- result.totalOps += 1;
7405
- } else {
7406
- result.skipped.push(kernelPath);
7407
- }
7545
+ recordWriteStatus(result, kernelPath, status);
7408
7546
  return result;
7409
7547
  }
7410
7548
  var execAsync = promisify(exec);
@@ -7438,14 +7576,27 @@ function mergeResult2(dest, src) {
7438
7576
  dest.created.push(...src.created);
7439
7577
  dest.updated.push(...src.updated);
7440
7578
  dest.skipped.push(...src.skipped);
7579
+ dest.deleted.push(...src.deleted);
7580
+ dest.unchanged.push(...src.unchanged);
7441
7581
  dest.totalOps += src.totalOps;
7582
+ if (src.error && !dest.error) {
7583
+ dest.error = src.error;
7584
+ dest.summary = src.summary;
7585
+ }
7442
7586
  }
7443
7587
  function mergeBarrelPasses(firstPass, secondPass) {
7444
7588
  const combined = createEmptyResult();
7445
7589
  const secondPaths = /* @__PURE__ */ new Set([
7446
7590
  ...secondPass.created,
7447
7591
  ...secondPass.updated,
7448
- ...secondPass.skipped
7592
+ ...secondPass.skipped,
7593
+ ...secondPass.deleted
7594
+ ]);
7595
+ const secondAll = /* @__PURE__ */ new Set([...secondPaths, ...secondPass.unchanged]);
7596
+ const firstMutations = /* @__PURE__ */ new Set([
7597
+ ...firstPass.created,
7598
+ ...firstPass.updated,
7599
+ ...firstPass.deleted
7449
7600
  ]);
7450
7601
  for (const p of firstPass.created) {
7451
7602
  if (!secondPaths.has(p)) combined.created.push(p);
@@ -7454,12 +7605,29 @@ function mergeBarrelPasses(firstPass, secondPass) {
7454
7605
  if (!secondPaths.has(p)) combined.updated.push(p);
7455
7606
  }
7456
7607
  for (const p of firstPass.skipped) {
7457
- if (!secondPaths.has(p)) combined.skipped.push(p);
7608
+ if (!secondAll.has(p)) combined.skipped.push(p);
7609
+ }
7610
+ for (const p of firstPass.deleted) {
7611
+ if (!secondPaths.has(p)) combined.deleted.push(p);
7612
+ }
7613
+ for (const p of firstPass.unchanged) {
7614
+ if (!secondAll.has(p)) combined.unchanged.push(p);
7458
7615
  }
7459
7616
  combined.created.push(...secondPass.created);
7460
7617
  combined.updated.push(...secondPass.updated);
7461
7618
  combined.skipped.push(...secondPass.skipped);
7462
- combined.totalOps = firstPass.totalOps + secondPass.totalOps;
7619
+ combined.deleted.push(...secondPass.deleted);
7620
+ for (const p of secondPass.unchanged) {
7621
+ if (!firstMutations.has(p)) combined.unchanged.push(p);
7622
+ }
7623
+ combined.totalOps = combined.created.length + combined.updated.length + combined.deleted.length;
7624
+ if (firstPass.error) {
7625
+ combined.error = firstPass.error;
7626
+ combined.summary = firstPass.summary;
7627
+ } else if (secondPass.error) {
7628
+ combined.error = secondPass.error;
7629
+ combined.summary = secondPass.summary;
7630
+ }
7463
7631
  return combined;
7464
7632
  }
7465
7633
 
@@ -7468,14 +7636,15 @@ function caseInsensitiveEnum(schema, dir = "lower") {
7468
7636
  return external_exports.preprocess((value) => typeof value === "string" ? dir === "lower" ? value.trim().toLowerCase() : value.trim().toUpperCase() : value, schema);
7469
7637
  }
7470
7638
  var BoundedContextTypeSchema = boundedContextTypeSchema;
7471
- var PlaneTypeSchema = caseInsensitiveEnum(external_exports.enum([
7639
+ var PLANE_NAMES = [
7472
7640
  "projection",
7473
7641
  "probabilistic",
7474
7642
  "infrastructure",
7475
7643
  "shared-kernel",
7476
7644
  "core",
7477
7645
  "supporting"
7478
- ]));
7646
+ ];
7647
+ var PlaneTypeSchema = caseInsensitiveEnum(external_exports.enum(PLANE_NAMES));
7479
7648
  var StatusTypeSchema = caseInsensitiveEnum(external_exports.enum(["active", "frozen", "deprecated", "experimental"]));
7480
7649
  var RelationshipPatternSchema = caseInsensitiveEnum(external_exports.enum(["U/D", "ACL", "SK", "P", "OHS"]), "upper");
7481
7650
  var RelationshipRoleSchema = caseInsensitiveEnum(external_exports.enum(["upstream", "downstream", "peer"]));
@@ -7545,6 +7714,10 @@ var AppSchema = external_exports.object({
7545
7714
  depends_on: external_exports.array(external_exports.string()).optional()
7546
7715
  }).strip();
7547
7716
  var IndexManifestSchema = external_exports.object({
7717
+ // Toolchain-compatibility stamp (see manifest-schema-version.ts). Note
7718
+ // `version` below is a DIFFERENT field — its `"2.0"` string is the
7719
+ // index-form discriminator (`isIndexManifest`), not a compatibility gate.
7720
+ schemaVersion: external_exports.number().int().positive().optional(),
7548
7721
  version: external_exports.string().optional(),
7549
7722
  description: external_exports.string(),
7550
7723
  system: external_exports.string().optional(),
@@ -7595,6 +7768,12 @@ var CrossContextEdgeSchema = external_exports.object({
7595
7768
  integrationPattern: external_exports.enum(["open-host", "acl"]).optional()
7596
7769
  });
7597
7770
  var ManifestSchema = external_exports.object({
7771
+ // Toolchain-compatibility stamp (positive int; absent = legacy). NOT the
7772
+ // freeform `version` string below. Compatibility is asserted against the
7773
+ // RAW yaml BEFORE this `.strict()` parse (assertSupportedSchemaVersion in
7774
+ // manifest-schema-version.ts) — this entry only keeps strict mode from
7775
+ // rejecting stamped manifests as carrying an unknown key.
7776
+ schemaVersion: external_exports.number().int().positive().optional(),
7598
7777
  version: external_exports.string().optional(),
7599
7778
  description: external_exports.string().optional(),
7600
7779
  system: external_exports.string().optional(),
@@ -7630,6 +7809,28 @@ var ManifestSchema = external_exports.object({
7630
7809
  legacy_config: external_exports.string().optional()
7631
7810
  }).strict();
7632
7811
 
7812
+ // ../project-configuration/dist/domain/model/manifest-schema/manifest-schema-version.js
7813
+ var CURRENT_MANIFEST_SCHEMA_VERSION = 1;
7814
+ function readManifestSchemaVersion(parsed) {
7815
+ if (parsed === null || typeof parsed !== "object")
7816
+ return void 0;
7817
+ const raw = parsed.schemaVersion;
7818
+ if (raw === void 0)
7819
+ return void 0;
7820
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 1) {
7821
+ throw new Error(`Invalid manifest schemaVersion: expected a positive integer, got ${JSON.stringify(raw)}.`);
7822
+ }
7823
+ return raw;
7824
+ }
7825
+ function assertSupportedSchemaVersion(parsed) {
7826
+ const version = readManifestSchemaVersion(parsed);
7827
+ if (version === void 0)
7828
+ return;
7829
+ if (version > CURRENT_MANIFEST_SCHEMA_VERSION) {
7830
+ 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.)`);
7831
+ }
7832
+ }
7833
+
7633
7834
  // ../project-configuration/dist/domain/model/manifest-schema/is-index-manifest.js
7634
7835
  function isIndexManifest(parsed) {
7635
7836
  if (typeof parsed !== "object" || parsed === null) {
@@ -7779,21 +7980,21 @@ external_exports.object({
7779
7980
  turboConfig: external_exports.record(external_exports.unknown()).optional()
7780
7981
  });
7781
7982
  function assertPathWithinArchitecture(workspaceRoot, relativePath) {
7782
- const resolved = path6.resolve(workspaceRoot, ".architecture", relativePath);
7783
- const archRoot = path6.resolve(workspaceRoot, ".architecture");
7983
+ const resolved = path7.resolve(workspaceRoot, ".architecture", relativePath);
7984
+ const archRoot = path7.resolve(workspaceRoot, ".architecture");
7784
7985
  try {
7785
7986
  const realResolved = realpathSync(resolved);
7786
7987
  const realArchRoot = realpathSync(archRoot);
7787
- const archRootWithSep = realArchRoot + path6.sep;
7988
+ const archRootWithSep = realArchRoot + path7.sep;
7788
7989
  if (realResolved !== realArchRoot && !realResolved.startsWith(archRootWithSep)) {
7789
7990
  throw new Error(`Path traversal detected: "${relativePath}" resolves outside .architecture/`);
7790
7991
  }
7791
7992
  } catch (err3) {
7792
7993
  if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
7793
7994
  let checkPath = archRoot;
7794
- const pathSegments = path6.relative(archRoot, resolved).split(path6.sep);
7995
+ const pathSegments = path7.relative(archRoot, resolved).split(path7.sep);
7795
7996
  for (const segment of pathSegments) {
7796
- checkPath = path6.join(checkPath, segment);
7997
+ checkPath = path7.join(checkPath, segment);
7797
7998
  try {
7798
7999
  const stat = lstatSync(checkPath);
7799
8000
  if (stat.isSymbolicLink()) {
@@ -7809,7 +8010,7 @@ function assertPathWithinArchitecture(workspaceRoot, relativePath) {
7809
8010
  throw statErr;
7810
8011
  }
7811
8012
  }
7812
- const archRootWithSep = archRoot + path6.sep;
8013
+ const archRootWithSep = archRoot + path7.sep;
7813
8014
  if (resolved !== archRoot && !resolved.startsWith(archRootWithSep)) {
7814
8015
  throw new Error(`Path traversal detected: "${relativePath}" resolves outside .architecture/`);
7815
8016
  }
@@ -7819,11 +8020,12 @@ function assertPathWithinArchitecture(workspaceRoot, relativePath) {
7819
8020
  }
7820
8021
  }
7821
8022
  async function mergeSplitManifest(workspaceRoot, manifestPath) {
7822
- const content = await fs3.readFile(manifestPath, "utf-8");
8023
+ const content = await fs5.readFile(manifestPath, "utf-8");
7823
8024
  const parsed = yaml3.load(content);
7824
8025
  if (parsed == null) {
7825
8026
  throw new Error("Manifest file is empty");
7826
8027
  }
8028
+ assertSupportedSchemaVersion(parsed);
7827
8029
  if (!isIndexManifest(parsed)) {
7828
8030
  const manifestData = {
7829
8031
  ...parsed,
@@ -7838,6 +8040,9 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7838
8040
  }
7839
8041
  const index = indexResult.data;
7840
8042
  const result = {
8043
+ // Carry the (already-validated) stamp into the merged form so consumers
8044
+ // of the merge see the same version the root file declares.
8045
+ schemaVersion: index.schemaVersion,
7841
8046
  description: index.description ?? "Auto-generated manifest",
7842
8047
  system: index.system,
7843
8048
  scope: index.scope,
@@ -7852,10 +8057,10 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7852
8057
  continue;
7853
8058
  }
7854
8059
  assertPathWithinArchitecture(workspaceRoot, indexEntry.file);
7855
- const contextFilePath = path6.join(workspaceRoot, ".architecture", indexEntry.file);
8060
+ const contextFilePath = path7.join(workspaceRoot, ".architecture", indexEntry.file);
7856
8061
  let contextContent;
7857
8062
  try {
7858
- contextContent = await fs3.readFile(contextFilePath, "utf-8");
8063
+ contextContent = await fs5.readFile(contextFilePath, "utf-8");
7859
8064
  } catch (err3) {
7860
8065
  if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
7861
8066
  throw new Error(`Context file not found: ${contextFilePath}`);
@@ -7887,10 +8092,10 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7887
8092
  continue;
7888
8093
  }
7889
8094
  assertPathWithinArchitecture(workspaceRoot, appEntry.file);
7890
- const appFilePath = path6.join(workspaceRoot, ".architecture", appEntry.file);
8095
+ const appFilePath = path7.join(workspaceRoot, ".architecture", appEntry.file);
7891
8096
  let appContent;
7892
8097
  try {
7893
- appContent = await fs3.readFile(appFilePath, "utf-8");
8098
+ appContent = await fs5.readFile(appFilePath, "utf-8");
7894
8099
  } catch (err3) {
7895
8100
  if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT") {
7896
8101
  throw new Error(`App file not found: ${appFilePath}`);
@@ -7909,34 +8114,52 @@ async function mergeSplitManifest(workspaceRoot, manifestPath) {
7909
8114
 
7910
8115
  // src/sync-engine-init.ts
7911
8116
  var __filename$1 = fileURLToPath(import.meta.url);
7912
- var __dirname$1 = path6.dirname(__filename$1);
7913
- async function findWorkspaceRoot(options) {
7914
- if (options.targetRoot) {
7915
- return options.targetRoot;
7916
- }
7917
- let currentDir = __dirname$1;
7918
- while (currentDir !== path6.parse(currentDir).root) {
8117
+ var __dirname$1 = path7.dirname(__filename$1);
8118
+ function isENOENT(err3) {
8119
+ return err3 instanceof Error && "code" in err3 && err3.code === "ENOENT";
8120
+ }
8121
+ async function findRootFrom(startDir, problems) {
8122
+ let currentDir = startDir;
8123
+ while (currentDir !== path7.parse(currentDir).root) {
8124
+ const pkgPath = path7.join(currentDir, "package.json");
7919
8125
  try {
7920
- const pkgPath = path6.join(currentDir, "package.json");
7921
- const pkgContent = await fs3.readFile(pkgPath, "utf-8");
8126
+ const pkgContent = await fs5.readFile(pkgPath, "utf-8");
7922
8127
  const pkg = JSON.parse(pkgContent);
7923
8128
  if (pkg.workspaces && Array.isArray(pkg.workspaces)) {
7924
8129
  return currentDir;
7925
8130
  }
7926
- } catch {
8131
+ } catch (err3) {
8132
+ if (!isENOENT(err3)) {
8133
+ const reason = err3 instanceof Error ? err3.message : String(err3);
8134
+ problems.push(new Error(`${pkgPath}: ${reason}`));
8135
+ }
7927
8136
  }
7928
- currentDir = path6.dirname(currentDir);
8137
+ currentDir = path7.dirname(currentDir);
8138
+ }
8139
+ return null;
8140
+ }
8141
+ async function findWorkspaceRoot(options, probeStarts = [process.cwd(), __dirname$1]) {
8142
+ if (options.targetRoot) {
8143
+ return options.targetRoot;
7929
8144
  }
8145
+ const problems = [];
8146
+ for (const start of probeStarts) {
8147
+ const root = await findRootFrom(start, problems);
8148
+ if (root !== null) {
8149
+ return root;
8150
+ }
8151
+ }
8152
+ const detail = problems.length > 0 ? ` A package.json was found but could not be read or parsed: ${problems[0].message}.` : "";
7930
8153
  throw new Error(
7931
- 'Could not locate monorepo root. No package.json with "workspaces" field found.'
8154
+ `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.`
7932
8155
  );
7933
8156
  }
7934
8157
  async function loadManifest(workspaceRoot, flags, options) {
7935
8158
  if (options.manifest) {
7936
- return options.manifest;
8159
+ return { manifest: options.manifest, manifestMissing: false };
7937
8160
  }
7938
8161
  const { logger, dryRun } = flags;
7939
- const manifestPath = path6.join(workspaceRoot, ".architecture/manifest.yaml");
8162
+ const manifestPath = path7.join(workspaceRoot, ".architecture/manifest.yaml");
7940
8163
  logger.debug(`[debug] __dirname (ESM): ${__dirname$1}`);
7941
8164
  logger.debug(`[debug] resolved workspaceRoot: ${workspaceRoot}`);
7942
8165
  logger.debug(`[debug] resolved manifestPath: ${manifestPath}`);
@@ -7946,11 +8169,14 @@ async function loadManifest(workspaceRoot, flags, options) {
7946
8169
  manifestPath
7947
8170
  );
7948
8171
  logger.info(`Loaded manifest from ${manifestPath}`);
7949
- return manifest;
8172
+ return { manifest, manifestMissing: false };
7950
8173
  } catch (err3) {
7951
- if (err3 instanceof Error && "code" in err3 && err3.code === "ENOENT" && dryRun) {
8174
+ if (isENOENT(err3) && dryRun) {
7952
8175
  logger.warn(`Manifest not found — using empty for dry-run`);
7953
- return { description: "Empty manifest", bounded_contexts: [] };
8176
+ return {
8177
+ manifest: { description: "Empty manifest", bounded_contexts: [] },
8178
+ manifestMissing: true
8179
+ };
7954
8180
  }
7955
8181
  const message = err3 instanceof Error ? err3.message : "Unknown parse error";
7956
8182
  throw new Error(`Failed to parse manifest: ${message}`);
@@ -7990,9 +8216,27 @@ function validateManifest(manifest, flags) {
7990
8216
  var execAsync2 = promisify(exec);
7991
8217
  var SyncEngine = class {
7992
8218
  report = new MigrationReport();
8219
+ // PR-B1 (RCA #4): per-run mutation journal — pre-images of every file sync
8220
+ // touches, replayed in reverse on failure (see journal.ts). The lifetime is
8221
+ // one RUN, not one instance: run() re-news it on entry, so a reused engine
8222
+ // can never replay a previous run's pre-images into a later rollback.
8223
+ journal = new SyncJournal();
8224
+ // B-1 (PR-B2 review): generators that failed-soft this run. Four generators
8225
+ // catch their own exceptions into `result.error` by contract (Wave-2e: skip
8226
+ // the package, do not abort the run) — but a swallowed failure plans zero
8227
+ // ops, so a run that could not even read a target still summarized as
8228
+ // `Total ops : 0` and the CLI exited 0: errors masqueraded as convergence,
8229
+ // silently breaking `--check`'s "exit 0 ⇒ converged" promise. Failures are
8230
+ // recorded at each production site (NOT off the merged rows — mergeResult
8231
+ // keeps only the first error, so row-level counting would under-report
8232
+ // multi-module failures), printed as FAILED rows under the summary, and
8233
+ // surfaced as `SyncRunSummary.errors` for cli.ts to turn into exit ≠ 0.
8234
+ // Per-run lifetime, same reset discipline as the journal.
8235
+ failures = [];
7993
8236
  partialConfig;
7994
8237
  fullConfig = null;
7995
8238
  manifest = {};
8239
+ manifestMissing = false;
7996
8240
  workspaceRoot = "";
7997
8241
  options;
7998
8242
  constructor(flags, options) {
@@ -8011,6 +8255,19 @@ var SyncEngine = class {
8011
8255
  }
8012
8256
  return this.fullConfig;
8013
8257
  }
8258
+ /**
8259
+ * Record a failed-soft generator result (B-1). Called at every site that
8260
+ * receives a GeneratorResult, including the ones that never set `error`
8261
+ * today — the check is one truthy test, and a future generator adopting the
8262
+ * catch-into-result contract is then surfaced without anyone remembering
8263
+ * this seam. `row` matches the summary-table label so the FAILED line and
8264
+ * the table read as one report.
8265
+ */
8266
+ noteFailure(row, result) {
8267
+ if (result.error) {
8268
+ this.failures.push({ row, message: result.error.message });
8269
+ }
8270
+ }
8014
8271
  async ensureDirectories() {
8015
8272
  const config = this.getConfig();
8016
8273
  const result = createEmptyResult();
@@ -8025,20 +8282,12 @@ var SyncEngine = class {
8025
8282
  );
8026
8283
  continue;
8027
8284
  }
8028
- const moduleDir = path6.join(this.workspaceRoot, "packages", mod.name);
8285
+ const moduleDir = path7.join(this.workspaceRoot, "packages", mod.name);
8029
8286
  logger.info(
8030
8287
  `Ensuring directories for module: ${mod.name} at ${moduleDir}`
8031
8288
  );
8032
- const layerResult = await ensureLayerFolders(
8033
- moduleDir,
8034
- layers,
8035
- config,
8036
- this.report
8037
- );
8038
- result.created.push(...layerResult.created);
8039
- result.skipped.push(...layerResult.skipped);
8040
- result.updated.push(...layerResult.updated);
8041
- result.totalOps += layerResult.totalOps;
8289
+ const layerResult = await ensureLayerFolders(moduleDir, layers, config);
8290
+ mergeResult2(result, layerResult);
8042
8291
  }
8043
8292
  return result;
8044
8293
  }
@@ -8053,7 +8302,7 @@ var SyncEngine = class {
8053
8302
  const stubs = createEmptyResult();
8054
8303
  for (const module of modules) {
8055
8304
  const moduleName = module.name;
8056
- const moduleDir = path6.join(this.workspaceRoot, "packages", moduleName);
8305
+ const moduleDir = path7.join(this.workspaceRoot, "packages", moduleName);
8057
8306
  if (moduleName.includes("..") || moduleName.includes("/") || moduleName.startsWith(".")) {
8058
8307
  logger.warn(
8059
8308
  `Skipping invalid module name (potential path traversal): ${moduleName}`
@@ -8090,6 +8339,11 @@ var SyncEngine = class {
8090
8339
  config,
8091
8340
  this.report
8092
8341
  );
8342
+ this.noteFailure("Barrels", barrelResult);
8343
+ this.noteFailure("package.json", pkgResult);
8344
+ this.noteFailure("tsconfig.json", tsResult);
8345
+ this.noteFailure("ESLint", eslintResult);
8346
+ this.noteFailure("Stubs", stubResult);
8093
8347
  if (this.partialConfig.mode === "self-regen") {
8094
8348
  await reapLegacyFolders(moduleDir, config, this.report);
8095
8349
  }
@@ -8115,6 +8369,9 @@ var SyncEngine = class {
8115
8369
  const { logger, dryRun, allowDirty, mode } = this.partialConfig;
8116
8370
  const start = Date.now();
8117
8371
  let lockFile = null;
8372
+ this.journal = new SyncJournal();
8373
+ this.failures = [];
8374
+ this.manifestMissing = false;
8118
8375
  logger.info(
8119
8376
  dryRun ? "[DRY-RUN MODE] Starting sync..." : "Starting sync..."
8120
8377
  );
@@ -8154,16 +8411,19 @@ var SyncEngine = class {
8154
8411
  try {
8155
8412
  const initOptions = this.getInitOptions();
8156
8413
  this.workspaceRoot = await findWorkspaceRoot(initOptions);
8157
- this.manifest = await loadManifest(
8414
+ const loaded = await loadManifest(
8158
8415
  this.workspaceRoot,
8159
8416
  this.partialConfig,
8160
8417
  initOptions
8161
8418
  );
8419
+ this.manifest = loaded.manifest;
8420
+ this.manifestMissing = loaded.manifestMissing;
8162
8421
  validateManifest(this.manifest, this.partialConfig);
8163
8422
  this.fullConfig = {
8164
8423
  ...this.partialConfig,
8165
8424
  workspaceRoot: this.workspaceRoot,
8166
- manifest: this.manifest
8425
+ manifest: this.manifest,
8426
+ journal: this.journal
8167
8427
  };
8168
8428
  if (!dryRun && mode === "self-regen") {
8169
8429
  lockFile = new LockFile(this.workspaceRoot);
@@ -8189,23 +8449,29 @@ var SyncEngine = class {
8189
8449
  this.fullConfig,
8190
8450
  this.report
8191
8451
  );
8452
+ this.noteFailure("RootFiles", rootFilesResult);
8192
8453
  const archFilesResult = await generateArchitectureFiles(
8193
8454
  this.fullConfig,
8194
8455
  this.report
8195
8456
  );
8457
+ this.noteFailure("ArchFiles", archFilesResult);
8196
8458
  const layerResult = await this.ensureDirectories();
8459
+ this.noteFailure("Layers", layerResult);
8197
8460
  const coreResults = await this.generateCoreArtifacts();
8198
8461
  const { pkgs, tsconfigs, eslint, stubs } = coreResults;
8199
8462
  const firstPassBarrels = coreResults.barrels;
8200
8463
  const appsResult = await generateApps(this.fullConfig, this.report);
8464
+ this.noteFailure("Apps", appsResult);
8201
8465
  const crossContextResult = await generateCrossContext(
8202
8466
  this.fullConfig,
8203
8467
  this.report
8204
8468
  );
8469
+ this.noteFailure("CrossContext", crossContextResult);
8205
8470
  const sharedKernelResult = await generateSharedKernel(
8206
8471
  this.fullConfig,
8207
8472
  this.report
8208
8473
  );
8474
+ this.noteFailure("SharedKernel", sharedKernelResult);
8209
8475
  const secondPassBarrels = createEmptyResult();
8210
8476
  const modules = this.fullConfig.manifest.bounded_contexts ?? [];
8211
8477
  for (const module of modules) {
@@ -8213,16 +8479,48 @@ var SyncEngine = class {
8213
8479
  if (!moduleName || moduleName.includes("..") || moduleName.includes("/") || moduleName.startsWith(".")) {
8214
8480
  continue;
8215
8481
  }
8216
- const moduleDir = path6.join(this.workspaceRoot, "packages", moduleName);
8482
+ const moduleDir = path7.join(this.workspaceRoot, "packages", moduleName);
8217
8483
  const pass2 = await generateBarrels(
8218
8484
  moduleDir,
8219
8485
  this.fullConfig,
8220
8486
  this.report
8221
8487
  );
8488
+ this.noteFailure("Barrels", pass2);
8222
8489
  mergeResult2(secondPassBarrels, pass2);
8223
8490
  }
8224
8491
  const barrels = mergeBarrelPasses(firstPassBarrels, secondPassBarrels);
8225
- const totalOps = rootFilesResult.totalOps + archFilesResult.totalOps + layerResult.totalOps + barrels.totalOps + pkgs.totalOps + tsconfigs.totalOps + eslint.totalOps + stubs.totalOps + appsResult.totalOps + crossContextResult.totalOps + sharedKernelResult.totalOps;
8492
+ const rows = [
8493
+ ["RootFiles", rootFilesResult],
8494
+ ["ArchFiles", archFilesResult],
8495
+ ["Layers", layerResult],
8496
+ ["Barrels", barrels],
8497
+ ["CrossContext", crossContextResult],
8498
+ ["SharedKernel", sharedKernelResult],
8499
+ ["package.json", pkgs],
8500
+ ["tsconfig.json", tsconfigs],
8501
+ ["ESLint", eslint],
8502
+ ["Stubs", stubs],
8503
+ ["Apps", appsResult]
8504
+ ];
8505
+ const runSummary = {
8506
+ created: 0,
8507
+ updated: 0,
8508
+ deleted: 0,
8509
+ unchanged: 0,
8510
+ skipped: 0,
8511
+ totalOps: 0,
8512
+ errors: this.failures.length,
8513
+ manifestMissing: this.manifestMissing,
8514
+ durationMs: 0
8515
+ };
8516
+ for (const [, r] of rows) {
8517
+ runSummary.created += r.created.length;
8518
+ runSummary.updated += r.updated.length;
8519
+ runSummary.deleted += r.deleted.length;
8520
+ runSummary.unchanged += r.unchanged.length;
8521
+ runSummary.skipped += r.skipped.length;
8522
+ runSummary.totalOps += r.totalOps;
8523
+ }
8226
8524
  if (mode === "self-regen") {
8227
8525
  await runArchLinter(this.fullConfig);
8228
8526
  await this.report.writeReport(this.fullConfig);
@@ -8230,62 +8528,70 @@ var SyncEngine = class {
8230
8528
  logger.info("Skipping arch-linter and report (external mode)");
8231
8529
  }
8232
8530
  const duration = Date.now() - start;
8233
- logger.info("\nSync completed successfully.");
8531
+ runSummary.durationMs = duration;
8532
+ if (this.failures.length === 0) {
8533
+ logger.info("\nSync completed successfully.");
8534
+ } else {
8535
+ logger.error(
8536
+ `
8537
+ Sync completed with ${this.failures.length} generator failure(s) — see the FAILED row(s) below.`
8538
+ );
8539
+ }
8234
8540
  logger.info(
8235
8541
  `Processed ${this.manifest.bounded_contexts?.length ?? 0} modules in ${duration}ms`
8236
8542
  );
8237
8543
  logger.info(`
8238
8544
  === Generator Summary ===`);
8239
- logger.info(
8240
- `• RootFiles : ${rootFilesResult.created.length} created, ${rootFilesResult.updated.length} updated, ${rootFilesResult.skipped.length} skipped`
8241
- );
8242
- logger.info(
8243
- `• ArchFiles : ${archFilesResult.created.length} created, ${archFilesResult.updated.length} updated, ${archFilesResult.skipped.length} skipped`
8244
- );
8245
- logger.info(
8246
- `• Layers : ${layerResult.created.length} created, ${layerResult.updated.length} updated, ${layerResult.skipped.length} skipped`
8247
- );
8248
- logger.info(
8249
- `• Barrels : ${barrels.created.length} created, ${barrels.updated.length} updated, ${barrels.skipped.length} skipped`
8250
- );
8251
- logger.info(
8252
- `• CrossContext : ${crossContextResult.created.length} created, ${crossContextResult.updated.length} updated, ${crossContextResult.skipped.length} skipped`
8253
- );
8254
- logger.info(
8255
- `• SharedKernel : ${sharedKernelResult.created.length} created, ${sharedKernelResult.updated.length} updated, ${sharedKernelResult.skipped.length} skipped`
8256
- );
8257
- logger.info(
8258
- `• package.json : ${pkgs.created.length} created, ${pkgs.updated.length} updated, ${pkgs.skipped.length} skipped`
8259
- );
8260
- logger.info(
8261
- `• tsconfig.json : ${tsconfigs.created.length} created, ${tsconfigs.updated.length} updated, ${tsconfigs.skipped.length} skipped`
8262
- );
8263
- logger.info(
8264
- `• ESLint : ${eslint.created.length} created, ${eslint.updated.length} updated, ${eslint.skipped.length} skipped`
8265
- );
8266
- logger.info(
8267
- `• Stubs : ${stubs.created.length} created, ${stubs.updated.length} updated, ${stubs.skipped.length} skipped`
8268
- );
8269
- logger.info(
8270
- `• Apps : ${appsResult.created.length} created, ${appsResult.updated.length} updated, ${appsResult.skipped.length} skipped`
8271
- );
8272
- logger.info(`• Total ops : ${totalOps}`);
8545
+ for (const [label, r] of rows) {
8546
+ logger.info(
8547
+ `• ${label} : ${r.created.length} created, ${r.updated.length} updated, ${r.deleted.length} deleted, ${r.unchanged.length} unchanged, ${r.skipped.length} skipped`
8548
+ );
8549
+ }
8550
+ for (const f of this.failures) {
8551
+ logger.error(`• ${f.row} : FAILED — ${f.message}`);
8552
+ }
8553
+ logger.info(`• Total ops : ${runSummary.totalOps}`);
8554
+ return runSummary;
8273
8555
  } catch (err3) {
8274
8556
  const message = err3 instanceof Error ? err3.message : "Unknown sync error";
8275
8557
  logger.error(`Sync failed: ${message}`);
8276
8558
  if (!dryRun) {
8277
- try {
8278
- await execAsync2("git reset --hard HEAD && git clean -fd", {
8279
- cwd: this.workspaceRoot
8280
- });
8281
- logger.info("Rollback completed after failure.");
8282
- } catch (rollbackErr) {
8559
+ if (this.journal.size === 0) {
8560
+ logger.info(
8561
+ "No files were touched before the failure — nothing to roll back."
8562
+ );
8563
+ } else if (allowDirty) {
8283
8564
  logger.warn(
8284
- `Rollback failed: ${rollbackErr instanceof Error ? rollbackErr.message : rollbackErr}`
8565
+ `Sync failed after touching ${this.journal.size} path(s) — NO rollback under --allow-dirty; the tree is left as-is:`
8285
8566
  );
8567
+ for (const line of this.journal.describeEntries(this.workspaceRoot)) {
8568
+ logger.warn(` ${line}`);
8569
+ }
8570
+ } else {
8571
+ logger.info(
8572
+ `Rolling back ${this.journal.size} journaled path(s) (inverse-ops; never git reset/clean)...`
8573
+ );
8574
+ const outcome = await this.journal.rollback(
8575
+ logger,
8576
+ this.workspaceRoot
8577
+ );
8578
+ if (outcome.failures.length === 0) {
8579
+ logger.info(
8580
+ `Rollback completed: ${outcome.restored}/${outcome.attempted} path(s) restored.`
8581
+ );
8582
+ } else {
8583
+ for (const f of outcome.failures) {
8584
+ logger.error(
8585
+ `Rollback failed for ${path7.relative(this.workspaceRoot, f.path)}: intended to ${f.intended} — ${f.error}`
8586
+ );
8587
+ }
8588
+ logger.error(
8589
+ `Rollback incomplete: ${outcome.failures.length} of ${outcome.attempted} path(s) NOT restored — inspect the paths above.`
8590
+ );
8591
+ }
8286
8592
  }
8287
- process.exit(1);
8288
8593
  }
8594
+ throw err3;
8289
8595
  } finally {
8290
8596
  if (lockFile) {
8291
8597
  try {
@@ -8376,6 +8682,19 @@ function parseArgs(rawArgs) {
8376
8682
  case "--allow-dirty":
8377
8683
  flags.allowDirty = true;
8378
8684
  break;
8685
+ // Lenient on a missing value (warn + skip) where the commander front
8686
+ // door hard-errors on `--report <path>` — deliberate divergence:
8687
+ // parseArgs serves programmatic/test callers that shouldn't die on a
8688
+ // malformed optional flag (review #315).
8689
+ case "--report": {
8690
+ const next = args[i + 1];
8691
+ if (next !== void 0 && !next.startsWith("-")) {
8692
+ flags.report = args[++i];
8693
+ } else {
8694
+ flags.logger.warn("--report requires a path argument — ignored");
8695
+ }
8696
+ break;
8697
+ }
8379
8698
  case "--only": {
8380
8699
  const patterns = [];
8381
8700
  while (i + 1 < args.length && !args[i + 1].startsWith("-")) {
@@ -8401,7 +8720,7 @@ function ok2(value) {
8401
8720
  function err2(error) {
8402
8721
  return { success: false, error };
8403
8722
  }
8404
- var CONFIG_FILE = path6.join(
8723
+ var CONFIG_FILE = path7.join(
8405
8724
  process.cwd(),
8406
8725
  ".architecture/generator.config.yaml"
8407
8726
  );
@@ -8412,7 +8731,7 @@ function isFailureMode(v) {
8412
8731
  return v === "abort" || v === "abort-and-cleanup" || v === "warn-and-continue";
8413
8732
  }
8414
8733
  var YamlConfigAdapter = class {
8415
- constructor(configFile = CONFIG_FILE, fsImpl = fs3, logger = console) {
8734
+ constructor(configFile = CONFIG_FILE, fsImpl = fs5, logger = console) {
8416
8735
  this.configFile = configFile;
8417
8736
  this.fsImpl = fsImpl;
8418
8737
  this.logger = logger;
@@ -8568,7 +8887,7 @@ var YamlConfigAdapter = class {
8568
8887
  const updated = { ...current, ...sanitized };
8569
8888
  const yamlDoc = this.toYamlDoc(updated);
8570
8889
  const content = yaml3.dump(yamlDoc, { indent: 2, lineWidth: -1 });
8571
- await this.fsImpl.mkdir(path6.dirname(this.configFile), { recursive: true });
8890
+ await this.fsImpl.mkdir(path7.dirname(this.configFile), { recursive: true });
8572
8891
  const tmpPath = `${this.configFile}.tmp`;
8573
8892
  await this.fsImpl.writeFile(tmpPath, content, {
8574
8893
  encoding: "utf8",
@@ -8778,7 +9097,7 @@ var InMemoryConfigDouble = class _InMemoryConfigDouble {
8778
9097
  var execAsync3 = promisify(exec);
8779
9098
  async function loadManifest2(workspaceRoot) {
8780
9099
  try {
8781
- const manifestPath = path6.join(
9100
+ const manifestPath = path7.join(
8782
9101
  workspaceRoot,
8783
9102
  ".architecture/manifest.yaml"
8784
9103
  );
@@ -8819,18 +9138,18 @@ async function validateManifest2(workspaceRoot) {
8819
9138
  }
8820
9139
  async function saveManifest(workspaceRoot, manifest) {
8821
9140
  try {
8822
- const manifestPath = path6.join(
9141
+ const manifestPath = path7.join(
8823
9142
  workspaceRoot,
8824
9143
  ".architecture/manifest.yaml"
8825
9144
  );
8826
9145
  const content = yaml3.dump(manifest, { indent: 2 });
8827
- await fs3.writeFile(manifestPath, content, "utf-8");
9146
+ await fs5.writeFile(manifestPath, content, "utf-8");
8828
9147
  return ok2(void 0);
8829
9148
  } catch (errObj) {
8830
9149
  return err2(errObj);
8831
9150
  }
8832
9151
  }
8833
9152
 
8834
- export { DEFAULT_NAMING, DEFAULT_TEMPLATES, InMemoryConfigDouble, SyncEngine, YamlConfigAdapter, createEmptyResult, err2 as err, isGeneratedFile, isInScope, isIndexManifest, isProtectedRoot, loadManifest2 as loadManifest, mergeSplitManifest, ok2 as ok, parseArgs, portName, protectedFiles, safeWriteFile, safeWriteFileAtomic, saveManifest, validateManifest2 as validateManifest };
9153
+ export { DEFAULT_NAMING, DEFAULT_TEMPLATES, InMemoryConfigDouble, SyncEngine, YamlConfigAdapter, createEmptyResult, err2 as err, isGeneratedFile, isInScope, isIndexManifest, isProtectedRoot, loadManifest2 as loadManifest, mergeSplitManifest, ok2 as ok, parseArgs, portName, protectedFiles, recordWriteStatus, safeWriteFile, safeWriteFileAtomic, saveManifest, validateManifest2 as validateManifest };
8835
9154
  //# sourceMappingURL=index.js.map
8836
9155
  //# sourceMappingURL=index.js.map