@open-mercato/cli 0.11.1-develop.8587.1.5952ba9ee6 → 0.11.1-develop.8593.1.50784dae35

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 (133) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/AGENTS.md +1 -0
  3. package/dist/agentic/guides/module-facts.json +164 -164
  4. package/dist/agentic/guides/module-facts.v2.json +164 -164
  5. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  6. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  7. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  8. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  9. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  10. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  11. package/dist/agentic/guides/modules/auth/index.md +1 -1
  12. package/dist/agentic/guides/modules/availability/index.md +1 -1
  13. package/dist/agentic/guides/modules/backups/index.md +1 -1
  14. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  15. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  16. package/dist/agentic/guides/modules/cart/index.md +1 -1
  17. package/dist/agentic/guides/modules/catalog/index.md +1 -1
  18. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  19. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  20. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  21. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  22. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  23. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  24. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  25. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  26. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  27. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  28. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  29. package/dist/agentic/guides/modules/configs/index.md +1 -1
  30. package/dist/agentic/guides/modules/content/index.md +1 -1
  31. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  32. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  33. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  34. package/dist/agentic/guides/modules/customers/index.md +1 -1
  35. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  36. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  37. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  38. package/dist/agentic/guides/modules/devices/index.md +1 -1
  39. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  40. package/dist/agentic/guides/modules/directory/index.md +1 -1
  41. package/dist/agentic/guides/modules/documents/index.md +1 -1
  42. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  43. package/dist/agentic/guides/modules/entities/index.md +1 -1
  44. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  45. package/dist/agentic/guides/modules/events/index.md +1 -1
  46. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  47. package/dist/agentic/guides/modules/forms/index.md +1 -1
  48. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  49. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  50. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  51. package/dist/agentic/guides/modules/generators/index.md +1 -1
  52. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  53. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  54. package/dist/agentic/guides/modules/messages/index.md +1 -1
  55. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  56. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  57. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  58. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  59. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  60. package/dist/agentic/guides/modules/planner/index.md +1 -1
  61. package/dist/agentic/guides/modules/portal/index.md +1 -1
  62. package/dist/agentic/guides/modules/progress/index.md +1 -1
  63. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  64. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  65. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  66. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  67. package/dist/agentic/guides/modules/resources/index.md +1 -1
  68. package/dist/agentic/guides/modules/sales/index.md +1 -1
  69. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  70. package/dist/agentic/guides/modules/search/index.md +1 -1
  71. package/dist/agentic/guides/modules/security/index.md +1 -1
  72. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  73. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  74. package/dist/agentic/guides/modules/sso/index.md +1 -1
  75. package/dist/agentic/guides/modules/staff/index.md +1 -1
  76. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  77. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  78. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  79. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  80. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  81. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  82. package/dist/agentic/guides/modules/translations/index.md +1 -1
  83. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  84. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  85. package/dist/agentic/guides/modules/wms/index.md +1 -1
  86. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  87. package/dist/agentic/guides/reference-module-facts.json +1 -1
  88. package/dist/agentic/guides/upstream/manifest.json +1 -1
  89. package/dist/lib/generate-child-process.js +21 -3
  90. package/dist/lib/generate-child-process.js.map +2 -2
  91. package/dist/lib/generate-watch-events.js +135 -19
  92. package/dist/lib/generate-watch-events.js.map +2 -2
  93. package/dist/lib/generate-watch-plan.js +166 -0
  94. package/dist/lib/generate-watch-plan.js.map +7 -0
  95. package/dist/lib/generate-watch-runner.js +53 -0
  96. package/dist/lib/generate-watch-runner.js.map +7 -0
  97. package/dist/lib/generate-watch-structure.js +576 -203
  98. package/dist/lib/generate-watch-structure.js.map +3 -3
  99. package/dist/lib/generators/extensions/agent-files.js +1 -0
  100. package/dist/lib/generators/extensions/agent-files.js.map +2 -2
  101. package/dist/lib/generators/module-registry.js +148 -191
  102. package/dist/lib/generators/module-registry.js.map +3 -3
  103. package/dist/lib/generators/openapi.js +24 -1
  104. package/dist/lib/generators/openapi.js.map +2 -2
  105. package/dist/lib/generators/web-research-adapters.js +54 -22
  106. package/dist/lib/generators/web-research-adapters.js.map +2 -2
  107. package/dist/lib/in-process-generate-watcher.js +98 -75
  108. package/dist/lib/in-process-generate-watcher.js.map +2 -2
  109. package/dist/mercato.js +74 -46
  110. package/dist/mercato.js.map +2 -2
  111. package/package.json +7 -7
  112. package/src/lib/__tests__/generate-child-process.test.ts +30 -0
  113. package/src/lib/__tests__/generate-watch-events.test.ts +377 -8
  114. package/src/lib/__tests__/generate-watch-plan.test.ts +98 -0
  115. package/src/lib/__tests__/generate-watch-runner.test.ts +126 -0
  116. package/src/lib/__tests__/generate-watch-structure.test.ts +522 -1
  117. package/src/lib/__tests__/in-process-generate-watcher.test.ts +393 -6
  118. package/src/lib/__tests__/module-inspection.test.ts +17 -11
  119. package/src/lib/generate-child-process.ts +26 -3
  120. package/src/lib/generate-watch-events.ts +189 -17
  121. package/src/lib/generate-watch-plan.ts +177 -0
  122. package/src/lib/generate-watch-runner.ts +62 -0
  123. package/src/lib/generate-watch-structure.ts +666 -227
  124. package/src/lib/generators/__tests__/incremental-registry.test.ts +262 -0
  125. package/src/lib/generators/__tests__/openapi.test.ts +91 -1
  126. package/src/lib/generators/__tests__/web-research-adapters.test.ts +298 -87
  127. package/src/lib/generators/extension.ts +2 -0
  128. package/src/lib/generators/extensions/agent-files.ts +1 -0
  129. package/src/lib/generators/module-registry.ts +168 -200
  130. package/src/lib/generators/openapi.ts +34 -0
  131. package/src/lib/generators/web-research-adapters.ts +76 -21
  132. package/src/lib/in-process-generate-watcher.ts +151 -96
  133. package/src/mercato.ts +85 -53
@@ -1,3 +1,4 @@
1
+ import { planGenerateWatchChanges } from "./generate-watch-plan.js";
1
2
  const MIN_POLL_MS = 250;
2
3
  const DEFAULT_POLL_MS = 1e3;
3
4
  function resolvePollMs(value) {
@@ -9,111 +10,137 @@ function startInProcessGenerateWatcher(options) {
9
10
  const logger = options.logger ?? console;
10
11
  const quiet = options.quiet === true;
11
12
  const pollMs = resolvePollMs(options.pollMs);
12
- const skipInitial = options.skipInitial === true;
13
- const { changeSignal, computeStructureChecksum, runGenerators } = options;
13
+ const { changeSignal, computeStructureChecksum, runGenerators, incremental } = options;
14
14
  let stopping = false;
15
15
  let pollTimer = null;
16
- let activeCycle = null;
17
- let running = false;
18
- let pendingReason = null;
19
- let previousChecksum = "";
16
+ let previousChecksum;
17
+ let previousSnapshot;
20
18
  let observedChangeVersion = -1;
21
- let doneResolve = null;
19
+ let attemptedChangeVersion = -1;
20
+ let attemptedChecksum;
21
+ let attemptedUncertaintyKey;
22
+ let hasAttemptedCapture = false;
23
+ let retryReason;
24
+ let doneResolve = () => {
25
+ };
22
26
  const done = new Promise((resolve) => {
23
27
  doneResolve = resolve;
24
28
  });
25
- async function runOnce(reason) {
29
+ async function captureAndGenerate(initial, refreshSubscriptions = true) {
30
+ const changeVersion = changeSignal?.currentVersion() ?? 0;
31
+ const hadPriorAttempt = hasAttemptedCapture;
32
+ const priorAttemptVersion = attemptedChangeVersion;
33
+ const priorAttemptChecksum = attemptedChecksum;
34
+ const priorAttemptUncertaintyKey = attemptedUncertaintyKey;
35
+ hasAttemptedCapture = true;
36
+ attemptedChangeVersion = changeVersion;
37
+ let candidate;
38
+ let checksum;
39
+ try {
40
+ candidate = incremental ? await incremental.capture() : void 0;
41
+ checksum = candidate?.checksum ?? await computeStructureChecksum();
42
+ } catch (error) {
43
+ attemptedChecksum = void 0;
44
+ attemptedUncertaintyKey = "capture failed";
45
+ retryReason = "retry after uncertain structure snapshot";
46
+ throw error;
47
+ }
48
+ if (stopping) return;
49
+ if (refreshSubscriptions) await changeSignal?.refresh();
26
50
  if (stopping) return;
27
- if (running) {
28
- pendingReason = reason;
51
+ const uncertaintyKey = candidate?.fullReasons.join("\0");
52
+ const inputChangedSinceAttempt = !hadPriorAttempt || changeVersion !== priorAttemptVersion || checksum !== priorAttemptChecksum || uncertaintyKey !== priorAttemptUncertaintyKey;
53
+ attemptedChecksum = checksum;
54
+ attemptedUncertaintyKey = uncertaintyKey;
55
+ const skipInitial = initial && options.skipInitial === true;
56
+ const changed = checksum !== previousChecksum;
57
+ const uncertain = Boolean(candidate?.fullReasons.length);
58
+ const eventReason = changeSignal?.fullGenerationReasonSince?.(observedChangeVersion);
59
+ const shouldGenerate = !skipInitial && (retryReason ? inputChangedSinceAttempt : initial || changed || uncertain || Boolean(eventReason));
60
+ if (shouldGenerate) {
61
+ let plan;
62
+ if (incremental && candidate) {
63
+ const fallbackReason = initial ? "initial generation" : retryReason ?? (!previousSnapshot ? "no successful snapshot" : changeSignal?.usesPollingFallback() ? "filesystem watching unavailable; polling fallback" : eventReason);
64
+ const candidatePlan = previousSnapshot ? incremental.plan(previousSnapshot, candidate) : void 0;
65
+ plan = fallbackReason ? planGenerateWatchChanges(candidatePlan?.changes ?? [], [fallbackReason, ...candidate.fullReasons]) : candidatePlan;
66
+ }
67
+ if (plan?.mode !== "none") {
68
+ const reason = initial ? "initial" : retryReason ?? "structure change";
69
+ if (!quiet) {
70
+ const detail = plan ? `; categories=${[...new Set(plan.changes.map((change) => change.category))].join(",") || "all"}; groups=${plan.groups.join(",")}${plan.reasons.length ? `; reasons=${plan.reasons.join("; ")}` : ""}` : "";
71
+ logger.log(`[generate:watch] Regenerating (${reason}${detail})...`);
72
+ }
73
+ try {
74
+ if (plan) await runGenerators(reason, plan);
75
+ else await runGenerators(reason);
76
+ } catch (error) {
77
+ retryReason = "retry after failed generation";
78
+ const message = error instanceof Error ? error.message : String(error);
79
+ logger.error(`[generate:watch] Generation failed: ${message}`);
80
+ return;
81
+ }
82
+ if (incremental && !stopping) await changeSignal?.refresh();
83
+ if (!quiet) logger.log("[generate:watch] Generators completed.");
84
+ }
85
+ } else if (retryReason) {
86
+ return;
87
+ }
88
+ if (uncertain) {
89
+ retryReason = "retry after uncertain structure snapshot";
29
90
  return;
30
91
  }
31
- running = true;
92
+ previousChecksum = checksum;
93
+ previousSnapshot = candidate;
94
+ observedChangeVersion = changeVersion;
95
+ retryReason = void 0;
96
+ }
97
+ async function poll() {
32
98
  try {
33
- if (!quiet) {
34
- logger.log(`[generate:watch] Regenerating (${reason})...`);
35
- }
36
- await runGenerators(reason);
37
- if (!quiet) {
38
- logger.log("[generate:watch] Generators completed.");
99
+ if (stopping) return;
100
+ const eventGatedIdle = hasAttemptedCapture && changeSignal && !changeSignal.usesPollingFallback() && changeSignal.currentVersion() === attemptedChangeVersion;
101
+ if (eventGatedIdle) {
102
+ if (!changeSignal.hasSkippedTargets?.()) return;
103
+ await changeSignal.refresh();
104
+ if (stopping) return;
105
+ const stillAtAttemptedVersion = changeSignal.currentVersion() === attemptedChangeVersion;
106
+ if (stillAtAttemptedVersion && (retryReason || changeSignal.hasSkippedTargets?.())) return;
39
107
  }
108
+ await captureAndGenerate(false, !eventGatedIdle);
40
109
  } catch (error) {
41
110
  const message = error instanceof Error ? error.message : String(error);
42
- logger.error(`[generate:watch] Generation failed: ${message}`);
111
+ logger.error(`[generate:watch] Poll cycle failed: ${message}`);
43
112
  } finally {
44
- running = false;
45
- if (pendingReason && !stopping) {
46
- const queued = pendingReason;
47
- pendingReason = null;
48
- await runOnce(queued);
49
- }
113
+ scheduleNext();
50
114
  }
51
115
  }
52
116
  function scheduleNext() {
53
117
  if (stopping) return;
54
118
  pollTimer = setTimeout(() => {
55
- activeCycle = (async () => {
56
- if (stopping) return;
57
- try {
58
- const changeVersion = changeSignal?.currentVersion() ?? 0;
59
- const eventGatedIdle = Boolean(
60
- changeSignal && !changeSignal.usesPollingFallback() && changeVersion === observedChangeVersion
61
- );
62
- let refreshedSkippedTargets = false;
63
- if (eventGatedIdle) {
64
- if (!changeSignal?.hasSkippedTargets?.()) return;
65
- await changeSignal.refresh();
66
- refreshedSkippedTargets = true;
67
- if (changeSignal.hasSkippedTargets?.()) return;
68
- }
69
- const nextChecksum = await computeStructureChecksum();
70
- observedChangeVersion = changeVersion;
71
- if (!refreshedSkippedTargets) {
72
- await changeSignal?.refresh();
73
- }
74
- if (nextChecksum !== previousChecksum) {
75
- previousChecksum = nextChecksum;
76
- await runOnce("structure change");
77
- }
78
- } catch (error) {
79
- const message = error instanceof Error ? error.message : String(error);
80
- logger.error(`[generate:watch] Poll cycle failed: ${message}`);
81
- } finally {
82
- if (!stopping) scheduleNext();
83
- }
84
- })();
119
+ pollTimer = null;
120
+ activeCycle = poll();
85
121
  }, pollMs);
86
122
  pollTimer.unref?.();
87
123
  }
88
- activeCycle = (async () => {
124
+ let activeCycle = (async () => {
89
125
  try {
90
126
  await changeSignal?.refresh();
91
127
  if (stopping) return;
92
- const initialChangeVersion = changeSignal?.currentVersion() ?? 0;
93
- if (!skipInitial) {
94
- await runOnce("initial");
95
- }
96
- if (stopping) return;
97
- previousChecksum = await computeStructureChecksum();
98
- observedChangeVersion = initialChangeVersion;
99
- if (!quiet) {
100
- if (skipInitial) {
128
+ await captureAndGenerate(true, Boolean(incremental));
129
+ if (!quiet && !stopping) {
130
+ if (options.skipInitial) {
101
131
  logger.log("[generate:watch] Skipping initial regeneration and watching the current generated state.");
102
132
  }
103
133
  logger.log(`[generate:watch] Watching structural module files with a ${pollMs}ms debounce (in-process).`);
104
134
  }
105
- scheduleNext();
106
135
  } catch (error) {
107
136
  const message = error instanceof Error ? error.message : String(error);
108
137
  logger.error(`[generate:watch] Initial setup failed: ${message}`);
138
+ } finally {
109
139
  scheduleNext();
110
140
  }
111
141
  })();
112
142
  async function close() {
113
- if (stopping) {
114
- await done;
115
- return;
116
- }
143
+ if (stopping) return done;
117
144
  stopping = true;
118
145
  if (pollTimer) {
119
146
  clearTimeout(pollTimer);
@@ -123,14 +150,10 @@ function startInProcessGenerateWatcher(options) {
123
150
  await activeCycle;
124
151
  await changeSignal?.close();
125
152
  } finally {
126
- doneResolve?.();
127
- doneResolve = null;
153
+ doneResolve();
128
154
  }
129
155
  }
130
- return {
131
- done,
132
- close
133
- };
156
+ return { done, close };
134
157
  }
135
158
  export {
136
159
  startInProcessGenerateWatcher
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/in-process-generate-watcher.ts"],
4
- "sourcesContent": ["/**\n * In-process generate watcher.\n *\n * Coalesces filesystem events on a configurable interval, then verifies them\n * with the existing structural fingerprint before invoking the generator.\n * If filesystem watching is unavailable, it falls back to fingerprint polling.\n * The polling loop is identical to the legacy standalone watcher; the only\n * difference is that it now runs inside whatever process calls it\n * (typically `mercato server dev`), so the dev runtime no longer needs a\n * sidecar `mercato generate watch` Node process.\n *\n * Contract preserved from the prior standalone watcher:\n * - Default debounce/fallback poll interval 1000 ms (minimum 250 ms).\n * - One initial generator run unless `skipInitial` is true.\n * - Concurrent regeneration requests are coalesced (running + pending).\n * - Generator errors are logged but never crash the watcher.\n * - The polling timer uses `.unref()` so it never blocks process exit.\n */\n\nexport type GenerateWatcherLogger = Pick<Console, 'log' | 'error'>\n\nexport type GenerateWatcherChangeSignal = {\n /** Monotonic event generation. Changes indicate that a checksum may be stale. */\n currentVersion(): number\n /** Refresh filesystem subscriptions after module configuration changes. */\n refresh(): Promise<void> | void\n /** Whether configured roots are missing and should be retried on idle polls. */\n hasSkippedTargets?(): boolean\n /** When true, preserve the legacy full-checksum-on-every-poll behavior. */\n usesPollingFallback(): boolean\n /** Close filesystem subscriptions. Idempotent. */\n close(): Promise<void> | void\n}\n\nexport type GenerateWatcherOptions = {\n /**\n * Function that returns the current structural fingerprint of the module\n * tree. The watcher re-runs `runGenerators` whenever this value changes.\n */\n computeStructureChecksum: () => Promise<string> | string\n /** Optional event signal that avoids full checksum work during idle polls. */\n changeSignal?: GenerateWatcherChangeSignal\n /**\n * Function that performs the actual regeneration work. Called once on\n * startup (unless `skipInitial`) and again whenever the checksum changes.\n * The `reason` argument is suitable for logging (`'initial'`,\n * `'structure change'`, `'queued change'`).\n */\n runGenerators: (reason: string) => Promise<void>\n /** Poll interval in milliseconds. Defaults to 1000. Clamped to >= 250. */\n pollMs?: number\n /** Skip the initial regeneration on startup. Defaults to false. */\n skipInitial?: boolean\n /** Suppress informational logs. Errors are always logged. */\n quiet?: boolean\n /** Logger override. Defaults to `console`. */\n logger?: GenerateWatcherLogger\n}\n\nexport type GenerateWatcherHandle = {\n /** Resolves when the watcher loop has stopped (after `close()`). */\n readonly done: Promise<void>\n /** Stop polling, drain the active cycle, and resolve `done`. Idempotent. */\n close(): Promise<void>\n}\n\nconst MIN_POLL_MS = 250\nconst DEFAULT_POLL_MS = 1000\n\nfunction resolvePollMs(value: number | undefined): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) return DEFAULT_POLL_MS\n const numeric = Math.floor(value)\n return numeric >= MIN_POLL_MS ? numeric : DEFAULT_POLL_MS\n}\n\n/**\n * Start an in-process generate watcher. The returned handle exposes a\n * `close()` to stop polling and a `done` promise that resolves once the\n * watcher loop has finished.\n */\nexport function startInProcessGenerateWatcher(\n options: GenerateWatcherOptions,\n): GenerateWatcherHandle {\n const logger = options.logger ?? console\n const quiet = options.quiet === true\n const pollMs = resolvePollMs(options.pollMs)\n const skipInitial = options.skipInitial === true\n const { changeSignal, computeStructureChecksum, runGenerators } = options\n\n let stopping = false\n let pollTimer: ReturnType<typeof setTimeout> | null = null\n let activeCycle: Promise<void> | null = null\n let running = false\n let pendingReason: string | null = null\n let previousChecksum = ''\n let observedChangeVersion = -1\n let doneResolve: (() => void) | null = null\n const done = new Promise<void>((resolve) => {\n doneResolve = resolve\n })\n\n async function runOnce(reason: string): Promise<void> {\n if (stopping) return\n if (running) {\n pendingReason = reason\n return\n }\n running = true\n try {\n if (!quiet) {\n logger.log(`[generate:watch] Regenerating (${reason})...`)\n }\n await runGenerators(reason)\n if (!quiet) {\n logger.log('[generate:watch] Generators completed.')\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[generate:watch] Generation failed: ${message}`)\n } finally {\n running = false\n if (pendingReason && !stopping) {\n const queued = pendingReason\n pendingReason = null\n await runOnce(queued)\n }\n }\n }\n\n function scheduleNext(): void {\n if (stopping) return\n pollTimer = setTimeout(() => {\n activeCycle = (async () => {\n if (stopping) return\n try {\n const changeVersion = changeSignal?.currentVersion() ?? 0\n const eventGatedIdle = Boolean(\n changeSignal\n && !changeSignal.usesPollingFallback()\n && changeVersion === observedChangeVersion\n )\n let refreshedSkippedTargets = false\n if (eventGatedIdle) {\n if (!changeSignal?.hasSkippedTargets?.()) return\n await changeSignal.refresh()\n refreshedSkippedTargets = true\n if (changeSignal.hasSkippedTargets?.()) return\n }\n const nextChecksum = await computeStructureChecksum()\n observedChangeVersion = changeVersion\n if (!refreshedSkippedTargets) {\n await changeSignal?.refresh()\n }\n if (nextChecksum !== previousChecksum) {\n previousChecksum = nextChecksum\n await runOnce('structure change')\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[generate:watch] Poll cycle failed: ${message}`)\n } finally {\n if (!stopping) scheduleNext()\n }\n })()\n }, pollMs)\n pollTimer.unref?.()\n }\n\n activeCycle = (async () => {\n try {\n await changeSignal?.refresh()\n if (stopping) return\n const initialChangeVersion = changeSignal?.currentVersion() ?? 0\n if (!skipInitial) {\n await runOnce('initial')\n }\n if (stopping) return\n previousChecksum = await computeStructureChecksum()\n observedChangeVersion = initialChangeVersion\n if (!quiet) {\n if (skipInitial) {\n logger.log('[generate:watch] Skipping initial regeneration and watching the current generated state.')\n }\n logger.log(`[generate:watch] Watching structural module files with a ${pollMs}ms debounce (in-process).`)\n }\n scheduleNext()\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[generate:watch] Initial setup failed: ${message}`)\n // Even if the initial bootstrap fails, schedule polling so a later\n // checksum recovery still picks up the next change on disk.\n scheduleNext()\n }\n })()\n\n async function close(): Promise<void> {\n if (stopping) {\n await done\n return\n }\n stopping = true\n if (pollTimer) {\n clearTimeout(pollTimer)\n pollTimer = null\n }\n // Drain before closing subscriptions: an in-flight capture can refresh\n // them, and a generator child must exit before dev restarts its group.\n try {\n await activeCycle\n await changeSignal?.close()\n } finally {\n doneResolve?.()\n doneResolve = null\n }\n }\n\n return {\n done,\n close,\n }\n}\n"],
5
- "mappings": "AAkEA,MAAM,cAAc;AACpB,MAAM,kBAAkB;AAExB,SAAS,cAAc,OAAmC;AACxD,MAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACjE,QAAM,UAAU,KAAK,MAAM,KAAK;AAChC,SAAO,WAAW,cAAc,UAAU;AAC5C;AAOO,SAAS,8BACd,SACuB;AACvB,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,QAAQ,QAAQ,UAAU;AAChC,QAAM,SAAS,cAAc,QAAQ,MAAM;AAC3C,QAAM,cAAc,QAAQ,gBAAgB;AAC5C,QAAM,EAAE,cAAc,0BAA0B,cAAc,IAAI;AAElE,MAAI,WAAW;AACf,MAAI,YAAkD;AACtD,MAAI,cAAoC;AACxC,MAAI,UAAU;AACd,MAAI,gBAA+B;AACnC,MAAI,mBAAmB;AACvB,MAAI,wBAAwB;AAC5B,MAAI,cAAmC;AACvC,QAAM,OAAO,IAAI,QAAc,CAAC,YAAY;AAC1C,kBAAc;AAAA,EAChB,CAAC;AAED,iBAAe,QAAQ,QAA+B;AACpD,QAAI,SAAU;AACd,QAAI,SAAS;AACX,sBAAgB;AAChB;AAAA,IACF;AACA,cAAU;AACV,QAAI;AACF,UAAI,CAAC,OAAO;AACV,eAAO,IAAI,kCAAkC,MAAM,MAAM;AAAA,MAC3D;AACA,YAAM,cAAc,MAAM;AAC1B,UAAI,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;AAC5B,UAAI,SAAU;AACd,YAAM,uBAAuB,cAAc,eAAe,KAAK;AAC/D,UAAI,CAAC,aAAa;AAChB,cAAM,QAAQ,SAAS;AAAA,MACzB;AACA,UAAI,SAAU;AACd,yBAAmB,MAAM,yBAAyB;AAClD,8BAAwB;AACxB,UAAI,CAAC,OAAO;AACV,YAAI,aAAa;AACf,iBAAO,IAAI,0FAA0F;AAAA,QACvG;AACA,eAAO,IAAI,4DAA4D,MAAM,2BAA2B;AAAA,MAC1G;AACA,mBAAa;AAAA,IACf,SAAS,OAAO;AACd,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,aAAO,MAAM,0CAA0C,OAAO,EAAE;AAGhE,mBAAa;AAAA,IACf;AAAA,EACF,GAAG;AAEH,iBAAe,QAAuB;AACpC,QAAI,UAAU;AACZ,YAAM;AACN;AAAA,IACF;AACA,eAAW;AACX,QAAI,WAAW;AACb,mBAAa,SAAS;AACtB,kBAAY;AAAA,IACd;AAGA,QAAI;AACF,YAAM;AACN,YAAM,cAAc,MAAM;AAAA,IAC5B,UAAE;AACA,oBAAc;AACd,oBAAc;AAAA,IAChB;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["/**\n * In-process generate watcher.\n *\n * Coalesces filesystem events before comparing the current module structure\n * with the last successfully generated snapshot. Failed or uncertain\n * candidates remain unacknowledged, but are retried only after a new input\n * event (or a newly observed polling-fallback snapshot). Capturing before\n * generation leaves edits made during a run dirty for the next serial poll.\n *\n * Contract preserved from the prior standalone watcher:\n * - Default debounce/fallback poll interval 1000 ms (minimum 250 ms).\n * - One initial generator run unless `skipInitial` is true.\n * - Concurrent regeneration requests are coalesced (running + pending).\n * - Generator errors are logged but never crash the watcher.\n * - The polling timer uses `.unref()` so it never blocks process exit.\n */\nimport { planGenerateWatchChanges } from './generate-watch-plan'\nimport type { GenerateWatchPlan, GenerateWatchSnapshot } from './generate-watch-plan'\n\nexport type GenerateWatcherLogger = Pick<Console, 'log' | 'error'>\n\nexport type GenerateWatcherChangeSignal = {\n /** Monotonic event generation. Changes indicate that a checksum may be stale. */\n currentVersion(): number\n /** Explain events without a usable filename since a captured event version. */\n fullGenerationReasonSince?(version: number): string | undefined\n /** Refresh filesystem subscriptions after module configuration changes. */\n refresh(): Promise<void> | void\n /** Whether configured roots are missing and should be retried on idle polls. */\n hasSkippedTargets?(): boolean\n /** When true, preserve the legacy full-checksum-on-every-poll behavior. */\n usesPollingFallback(): boolean\n /** Close filesystem subscriptions. Idempotent. */\n close(): Promise<void> | void\n}\n\nexport type GenerateWatcherOptions = {\n /**\n * Function that returns the current structural fingerprint of the module\n * tree. The watcher re-runs `runGenerators` whenever this value changes.\n */\n computeStructureChecksum: () => Promise<string> | string\n /** Optional event signal that avoids full checksum work during idle polls. */\n changeSignal?: GenerateWatcherChangeSignal\n /** Opt in to category-aware planning; legacy checksum-only callers stay valid. */\n incremental?: {\n capture(): Promise<GenerateWatchSnapshot> | GenerateWatchSnapshot\n plan(previous: GenerateWatchSnapshot, next: GenerateWatchSnapshot): GenerateWatchPlan\n }\n /**\n * Function that performs the actual regeneration work. Called once on\n * startup (unless `skipInitial`) and again whenever the input changes.\n * After a failed or uncertain candidate, the next changed input is repaired\n * with a full generation. The `reason` argument is suitable for logging\n * (`'initial'`, `'structure change'`, `'retry after failed generation'`,\n * or `'retry after uncertain structure snapshot'`).\n */\n runGenerators: (reason: string, plan?: GenerateWatchPlan) => Promise<void>\n /** Poll interval in milliseconds. Defaults to 1000. Clamped to >= 250. */\n pollMs?: number\n /** Skip the initial regeneration on startup. Defaults to false. */\n skipInitial?: boolean\n /** Suppress informational logs. Errors are always logged. */\n quiet?: boolean\n /** Logger override. Defaults to `console`. */\n logger?: GenerateWatcherLogger\n}\n\nexport type GenerateWatcherHandle = {\n /** Resolves when the watcher loop has stopped (after `close()`). */\n readonly done: Promise<void>\n /** Stop polling, drain the active cycle, and resolve `done`. Idempotent. */\n close(): Promise<void>\n}\n\nconst MIN_POLL_MS = 250\nconst DEFAULT_POLL_MS = 1000\n\nfunction resolvePollMs(value: number | undefined): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) return DEFAULT_POLL_MS\n const numeric = Math.floor(value)\n return numeric >= MIN_POLL_MS ? numeric : DEFAULT_POLL_MS\n}\n\n/**\n * Start an in-process generate watcher. The returned handle exposes a\n * `close()` to stop polling and a `done` promise that resolves once the\n * watcher loop has finished.\n */\nexport function startInProcessGenerateWatcher(\n options: GenerateWatcherOptions,\n): GenerateWatcherHandle {\n const logger = options.logger ?? console\n const quiet = options.quiet === true\n const pollMs = resolvePollMs(options.pollMs)\n const { changeSignal, computeStructureChecksum, runGenerators, incremental } = options\n let stopping = false\n let pollTimer: ReturnType<typeof setTimeout> | null = null\n let previousChecksum: string | undefined\n let previousSnapshot: GenerateWatchSnapshot | undefined\n let observedChangeVersion = -1\n let attemptedChangeVersion = -1\n let attemptedChecksum: string | undefined\n let attemptedUncertaintyKey: string | undefined\n let hasAttemptedCapture = false\n let retryReason: string | undefined\n let doneResolve: () => void = () => {}\n const done = new Promise<void>((resolve) => { doneResolve = resolve })\n\n async function captureAndGenerate(initial: boolean, refreshSubscriptions = true): Promise<void> {\n // This version belongs to the candidate, not to the state after generation.\n const changeVersion = changeSignal?.currentVersion() ?? 0\n const hadPriorAttempt = hasAttemptedCapture\n const priorAttemptVersion = attemptedChangeVersion\n const priorAttemptChecksum = attemptedChecksum\n const priorAttemptUncertaintyKey = attemptedUncertaintyKey\n hasAttemptedCapture = true\n attemptedChangeVersion = changeVersion\n\n let candidate: GenerateWatchSnapshot | undefined\n let checksum: string\n try {\n candidate = incremental ? await incremental.capture() : undefined\n checksum = candidate?.checksum ?? await computeStructureChecksum()\n } catch (error) {\n // A later authoritative capture must be treated as a new candidate even\n // when it has the same checksum as the snapshot preceding this failure.\n attemptedChecksum = undefined\n attemptedUncertaintyKey = 'capture failed'\n retryReason = 'retry after uncertain structure snapshot'\n throw error\n }\n if (stopping) return\n if (refreshSubscriptions) await changeSignal?.refresh()\n if (stopping) return\n\n const uncertaintyKey = candidate?.fullReasons.join('\\u0000')\n const inputChangedSinceAttempt = !hadPriorAttempt\n || changeVersion !== priorAttemptVersion\n || checksum !== priorAttemptChecksum\n || uncertaintyKey !== priorAttemptUncertaintyKey\n attemptedChecksum = checksum\n attemptedUncertaintyKey = uncertaintyKey\n\n const skipInitial = initial && options.skipInitial === true\n const changed = checksum !== previousChecksum\n const uncertain = Boolean(candidate?.fullReasons.length)\n const eventReason = changeSignal?.fullGenerationReasonSince?.(observedChangeVersion)\n const shouldGenerate = !skipInitial && (retryReason\n ? inputChangedSinceAttempt\n : initial || changed || uncertain || Boolean(eventReason))\n if (shouldGenerate) {\n let plan: GenerateWatchPlan | undefined\n if (incremental && candidate) {\n const fallbackReason = initial\n ? 'initial generation'\n : retryReason\n ?? (!previousSnapshot\n ? 'no successful snapshot'\n : changeSignal?.usesPollingFallback()\n ? 'filesystem watching unavailable; polling fallback'\n : eventReason)\n const candidatePlan = previousSnapshot ? incremental.plan(previousSnapshot, candidate) : undefined\n plan = fallbackReason\n ? planGenerateWatchChanges(candidatePlan?.changes ?? [], [fallbackReason, ...candidate.fullReasons])\n : candidatePlan\n }\n if (plan?.mode !== 'none') {\n const reason = initial ? 'initial' : retryReason ?? 'structure change'\n if (!quiet) {\n const detail = plan\n ? `; categories=${[...new Set(plan.changes.map((change) => change.category))].join(',') || 'all'}; groups=${plan.groups.join(',')}${plan.reasons.length ? `; reasons=${plan.reasons.join('; ')}` : ''}`\n : ''\n logger.log(`[generate:watch] Regenerating (${reason}${detail})...`)\n }\n try {\n // Do not add an undefined argument to the legacy callback contract.\n if (plan) await runGenerators(reason, plan)\n else await runGenerators(reason)\n } catch (error) {\n retryReason = 'retry after failed generation'\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[generate:watch] Generation failed: ${message}`)\n return\n }\n // A successful bundle can discover new external dependencies to watch.\n if (incremental && !stopping) await changeSignal?.refresh()\n if (!quiet) logger.log('[generate:watch] Generators completed.')\n }\n } else if (retryReason) {\n // Keep the failed/uncertain candidate unacknowledged without retrying it.\n return\n }\n // Only successful generation (or a verified no-op) acknowledges this input.\n if (uncertain) {\n retryReason = 'retry after uncertain structure snapshot'\n return\n }\n previousChecksum = checksum\n previousSnapshot = candidate\n observedChangeVersion = changeVersion\n retryReason = undefined\n }\n\n async function poll(): Promise<void> {\n try {\n if (stopping) return\n const eventGatedIdle = hasAttemptedCapture\n && changeSignal\n && !changeSignal.usesPollingFallback()\n && changeSignal.currentVersion() === attemptedChangeVersion\n if (eventGatedIdle) {\n if (!changeSignal.hasSkippedTargets?.()) return\n await changeSignal.refresh()\n if (stopping) return\n const stillAtAttemptedVersion = changeSignal.currentVersion() === attemptedChangeVersion\n // A pending repair is strictly event-gated. Normal idle polling may\n // still discover a formerly missing root even if the signal provider\n // cannot attribute that discovery to a filesystem event.\n if (stillAtAttemptedVersion\n && (retryReason || changeSignal.hasSkippedTargets?.())) return\n }\n await captureAndGenerate(false, !eventGatedIdle)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[generate:watch] Poll cycle failed: ${message}`)\n } finally {\n scheduleNext()\n }\n }\n\n function scheduleNext(): void {\n if (stopping) return\n pollTimer = setTimeout(() => {\n pollTimer = null\n activeCycle = poll()\n }, pollMs)\n pollTimer.unref?.()\n }\n\n let activeCycle = (async () => {\n try {\n await changeSignal?.refresh()\n if (stopping) return\n await captureAndGenerate(true, Boolean(incremental))\n if (!quiet && !stopping) {\n if (options.skipInitial) {\n logger.log('[generate:watch] Skipping initial regeneration and watching the current generated state.')\n }\n logger.log(`[generate:watch] Watching structural module files with a ${pollMs}ms debounce (in-process).`)\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[generate:watch] Initial setup failed: ${message}`)\n } finally {\n scheduleNext()\n }\n })()\n\n async function close(): Promise<void> {\n if (stopping) return done\n stopping = true\n if (pollTimer) {\n clearTimeout(pollTimer)\n pollTimer = null\n }\n try {\n await activeCycle\n await changeSignal?.close()\n } finally {\n doneResolve()\n }\n }\n\n return { done, close }\n}\n"],
5
+ "mappings": "AAgBA,SAAS,gCAAgC;AA2DzC,MAAM,cAAc;AACpB,MAAM,kBAAkB;AAExB,SAAS,cAAc,OAAmC;AACxD,MAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACjE,QAAM,UAAU,KAAK,MAAM,KAAK;AAChC,SAAO,WAAW,cAAc,UAAU;AAC5C;AAOO,SAAS,8BACd,SACuB;AACvB,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,QAAQ,QAAQ,UAAU;AAChC,QAAM,SAAS,cAAc,QAAQ,MAAM;AAC3C,QAAM,EAAE,cAAc,0BAA0B,eAAe,YAAY,IAAI;AAC/E,MAAI,WAAW;AACf,MAAI,YAAkD;AACtD,MAAI;AACJ,MAAI;AACJ,MAAI,wBAAwB;AAC5B,MAAI,yBAAyB;AAC7B,MAAI;AACJ,MAAI;AACJ,MAAI,sBAAsB;AAC1B,MAAI;AACJ,MAAI,cAA0B,MAAM;AAAA,EAAC;AACrC,QAAM,OAAO,IAAI,QAAc,CAAC,YAAY;AAAE,kBAAc;AAAA,EAAQ,CAAC;AAErE,iBAAe,mBAAmB,SAAkB,uBAAuB,MAAqB;AAE9F,UAAM,gBAAgB,cAAc,eAAe,KAAK;AACxD,UAAM,kBAAkB;AACxB,UAAM,sBAAsB;AAC5B,UAAM,uBAAuB;AAC7B,UAAM,6BAA6B;AACnC,0BAAsB;AACtB,6BAAyB;AAEzB,QAAI;AACJ,QAAI;AACJ,QAAI;AACF,kBAAY,cAAc,MAAM,YAAY,QAAQ,IAAI;AACxD,iBAAW,WAAW,YAAY,MAAM,yBAAyB;AAAA,IACnE,SAAS,OAAO;AAGd,0BAAoB;AACpB,gCAA0B;AAC1B,oBAAc;AACd,YAAM;AAAA,IACR;AACA,QAAI,SAAU;AACd,QAAI,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AC,SAAS,CAAC,UAAU;AACvB,YAAI,QAAQ,aAAa;AACvB,iBAAO,IAAI,0FAA0F;AAAA,QACvG;AACA,eAAO,IAAI,4DAA4D,MAAM,2BAA2B;AAAA,MAC1G;AAAA,IACF,SAAS,OAAO;AACd,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,aAAO,MAAM,0CAA0C,OAAO,EAAE;AAAA,IAClE,UAAE;AACA,mBAAa;AAAA,IACf;AAAA,EACF,GAAG;AAEH,iBAAe,QAAuB;AACpC,QAAI,SAAU,QAAO;AACrB,eAAW;AACX,QAAI,WAAW;AACb,mBAAa,SAAS;AACtB,kBAAY;AAAA,IACd;AACA,QAAI;AACF,YAAM;AACN,YAAM,cAAc,MAAM;AAAA,IAC5B,UAAE;AACA,kBAAY;AAAA,IACd;AAAA,EACF;AAEA,SAAO,EAAE,MAAM,MAAM;AACvB;",
6
6
  "names": []
7
7
  }
package/dist/mercato.js CHANGED
@@ -29,7 +29,7 @@ import { probeEnabledSchedules, startLazySchedulerSupervisor } from "./lib/sched
29
29
  import {
30
30
  startInProcessGenerateWatcher
31
31
  } from "./lib/in-process-generate-watcher.js";
32
- import { runGenerateChildProcess } from "./lib/generate-child-process.js";
32
+ import { readGenerateWatchRequest, runGenerateChildProcess } from "./lib/generate-child-process.js";
33
33
  import {
34
34
  resolveGenerateWatcherMode
35
35
  } from "./lib/in-process-generate-watcher-mode.js";
@@ -625,31 +625,9 @@ async function runPostGenerateStructuralInvalidation(quiet) {
625
625
  }
626
626
  }
627
627
  }
628
- async function runGeneratorSuite(quiet) {
629
- const { createResolver } = await import("./lib/resolver.js");
630
- const {
631
- generateEntityIds,
632
- generateModuleRegistries,
633
- generateModuleEntities,
634
- generateModuleDi,
635
- generateModulePackageSources,
636
- generateOpenApi,
637
- generateWebResearchAdapters
638
- } = await import("./lib/generators/index.js");
639
- const resolver = createResolver();
640
- const results = [
641
- await generateEntityIds({ resolver, quiet }),
642
- ...await generateModuleRegistries({ resolver, quiet }),
643
- await generateModuleEntities({ resolver, quiet }),
644
- await generateModuleDi({ resolver, quiet }),
645
- await generateModulePackageSources({ resolver, quiet }),
646
- await generateWebResearchAdapters({ resolver, quiet }),
647
- await generateOpenApi({ resolver, quiet })
648
- ];
649
- return results.some((result) => (result?.filesWritten.length ?? 0) > 0);
650
- }
651
- async function runGeneratorSuiteWithStructuralInvalidation(quiet) {
652
- const generatedFilesChanged = await runGeneratorSuite(quiet);
628
+ async function runGeneratorSuiteWithStructuralInvalidation(quiet, plan, onOpenApiCascade) {
629
+ const { runGenerateWatchSuite } = await import("./lib/generate-watch-runner.js");
630
+ const generatedFilesChanged = await runGenerateWatchSuite(quiet, plan, void 0, onOpenApiCascade);
653
631
  if (!generatedFilesChanged) {
654
632
  if (!quiet) {
655
633
  console.log("[generate] Generated outputs unchanged; skipping structural invalidation.");
@@ -658,57 +636,98 @@ async function runGeneratorSuiteWithStructuralInvalidation(quiet) {
658
636
  }
659
637
  await runPostGenerateStructuralInvalidation(quiet);
660
638
  }
661
- async function runWatchGeneratorSuite() {
639
+ async function runWatchGeneratorSuite(plan, logCascade) {
662
640
  const { resolveEnvironment } = await import("./lib/resolver.js");
663
641
  const { rootDir, appDir } = resolveEnvironment();
664
642
  await runGenerateChildProcess({
665
643
  mercatoBin: resolveInstalledBinary([rootDir, appDir], "@open-mercato/cli/bin/mercato"),
666
644
  cwd: process.cwd(),
667
- quiet: true
645
+ quiet: true,
646
+ watchRequest: { plan, logCascade }
668
647
  });
669
648
  }
670
649
  async function createGenerateWatchRuntime(quiet = false) {
671
650
  const [
672
651
  { createResolver },
673
- { calculateGenerateWatchStructureChecksum },
652
+ {
653
+ collectGenerateWatchStructureSnapshot,
654
+ createGenerateWatchStructureCache,
655
+ diffGenerateWatchStructureSnapshots
656
+ },
657
+ { planGenerateWatchChanges },
674
658
  { createGenerateWatchChangeSignal, resolveGenerateWatchTargets },
675
- { resolveStandaloneSourceMirrorBase }
659
+ { resolveStandaloneSourceMirrorBase },
660
+ { getOpenApiWatchInputs },
661
+ { getWebResearchAdapterWatchInputs }
676
662
  ] = await Promise.all([
677
663
  import("./lib/resolver.js"),
678
664
  import("./lib/generate-watch-structure.js"),
665
+ import("./lib/generate-watch-plan.js"),
679
666
  import("./lib/generate-watch-events.js"),
680
- import("./lib/generators/scanner.js")
667
+ import("./lib/generators/scanner.js"),
668
+ import("./lib/generators/openapi.js"),
669
+ import("./lib/generators/web-research-adapters.js")
681
670
  ]);
671
+ let latestSnapshot;
672
+ const structureCache = createGenerateWatchStructureCache();
682
673
  const collectWatchState = () => {
683
674
  const resolver = createResolver();
684
675
  const moduleRoots = [];
676
+ const additionalInputs = /* @__PURE__ */ new Set();
677
+ const outputDirectories = /* @__PURE__ */ new Set([resolver.getOutputDir()]);
678
+ for (const directory of [resolver.getRootDir(), resolver.getAppDir()]) {
679
+ for (const fileName of ["package.json", "tsconfig.json", "tsconfig.base.json", "yarn.lock", "package-lock.json", "pnpm-lock.yaml"]) {
680
+ additionalInputs.add(path.join(directory, fileName));
681
+ }
682
+ }
683
+ const adapterInputs = getWebResearchAdapterWatchInputs(resolver);
684
+ const openapiInputs = getOpenApiWatchInputs(resolver);
685
685
  const watchAppPackageFallbacks = resolver.isMonorepo();
686
686
  for (const entry of resolver.loadEnabledModules()) {
687
+ if (watchAppPackageFallbacks) {
688
+ outputDirectories.add(resolver.getPackageOutputDir(entry.from ?? "@open-mercato/core"));
689
+ }
687
690
  const roots = resolver.getModulePaths(entry);
691
+ const watchPackageBase = entry.from !== "@app" || watchAppPackageFallbacks;
692
+ const compiledBase = watchAppPackageFallbacks && !roots.pkgBase.includes(`${path.sep}dist${path.sep}`) ? [] : ["dist"];
693
+ const additionalModuleBases = watchPackageBase ? ["src", ...compiledBase].map((folder) => path.join(resolver.getPackageRoot(entry.from), folder, "modules", entry.id)) : [];
688
694
  moduleRoots.push({
689
695
  ...roots,
690
- watchPackageBase: entry.from !== "@app" || watchAppPackageFallbacks
696
+ moduleId: entry.id,
697
+ from: entry.from,
698
+ watchPackageBase,
699
+ additionalModuleBases
691
700
  });
692
701
  }
693
702
  return {
694
703
  modulesFile: resolver.getModulesConfigPath(),
695
- moduleRoots
704
+ moduleRoots,
705
+ additionalInputs: [...additionalInputs],
706
+ openapiInputs,
707
+ webResearchAdapterInputs: adapterInputs.manifestPaths,
708
+ webResearchAdapterFullReasons: adapterInputs.fullReasons,
709
+ shallowDirectories: adapterInputs.directoryPaths,
710
+ appSourceDir: path.join(resolver.getAppDir(), "src"),
711
+ outputDir: resolver.getOutputDir(),
712
+ outputDirectories: [...outputDirectories].sort((left, right) => left.localeCompare(right))
696
713
  };
697
714
  };
698
715
  return {
699
- computeStructureChecksum: async () => {
700
- return calculateGenerateWatchStructureChecksum(collectWatchState());
716
+ computeStructureChecksum: () => collectGenerateWatchStructureSnapshot(collectWatchState(), structureCache).checksum,
717
+ incremental: {
718
+ capture: () => {
719
+ latestSnapshot = collectGenerateWatchStructureSnapshot(collectWatchState(), structureCache);
720
+ return latestSnapshot;
721
+ },
722
+ plan: (previous, next) => planGenerateWatchChanges(diffGenerateWatchStructureSnapshots(previous, next), next.fullReasons)
701
723
  },
702
724
  changeSignal: createGenerateWatchChangeSignal({
703
725
  onSkippedDirectory: quiet ? void 0 : (directory) => console.log(`[generate:watch] Skipping missing watch directory: ${directory}`),
704
- getWatchTargets: () => {
705
- const state = collectWatchState();
706
- return resolveGenerateWatchTargets({
707
- modulesFile: state.modulesFile,
708
- moduleRoots: state.moduleRoots,
709
- resolveSourceMirrorBase: resolveStandaloneSourceMirrorBase
710
- });
711
- }
726
+ getWatchTargets: () => resolveGenerateWatchTargets({
727
+ ...collectWatchState(),
728
+ snapshot: latestSnapshot,
729
+ resolveSourceMirrorBase: resolveStandaloneSourceMirrorBase
730
+ })
712
731
  })
713
732
  };
714
733
  }
@@ -1625,7 +1644,12 @@ async function run(argv = process.argv) {
1625
1644
  run: async (args) => {
1626
1645
  const quiet = args.includes("--quiet") || args.includes("-q");
1627
1646
  if (!quiet) console.log("Running all generators...");
1628
- await runGeneratorSuiteWithStructuralInvalidation(quiet);
1647
+ const watchRequest = readGenerateWatchRequest();
1648
+ await runGeneratorSuiteWithStructuralInvalidation(
1649
+ quiet,
1650
+ watchRequest?.plan,
1651
+ watchRequest?.logCascade ? (reason) => console.log(`[generate:watch] Cascading; groups=openapi; reason=${reason}`) : void 0
1652
+ );
1629
1653
  if (!quiet) console.log("All generators completed.");
1630
1654
  }
1631
1655
  },
@@ -1643,7 +1667,9 @@ async function run(argv = process.argv) {
1643
1667
  skipInitial,
1644
1668
  quiet,
1645
1669
  ...generateWatchRuntime,
1646
- runGenerators: runWatchGeneratorSuite
1670
+ runGenerators: async (_reason, plan) => {
1671
+ await runWatchGeneratorSuite(plan, !quiet);
1672
+ }
1647
1673
  });
1648
1674
  const shutdownSignals = ["SIGINT", "SIGTERM"];
1649
1675
  let shuttingDown = false;
@@ -2038,7 +2064,9 @@ async function run(argv = process.argv) {
2038
2064
  skipInitial: true,
2039
2065
  quiet: false,
2040
2066
  ...generateWatchRuntime,
2041
- runGenerators: runWatchGeneratorSuite
2067
+ runGenerators: async (_reason, plan) => {
2068
+ await runWatchGeneratorSuite(plan, true);
2069
+ }
2042
2070
  });
2043
2071
  } else {
2044
2072
  console.log("[server] Legacy out-of-process generate watcher selected via OM_DEV_GENERATE_WATCH_MODE=legacy \u2014 expect the dev orchestrator to spawn `mercato generate watch --skip-initial`.");