@open-mercato/cli 0.11.1-develop.8589.1.db1a76ea60 → 0.11.1-develop.8665.1.2455b2503c

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 (285) hide show
  1. package/.turbo/turbo-build.log +4 -2
  2. package/AGENTS.md +3 -0
  3. package/dist/agentic/guides/architecture.md +2 -2
  4. package/dist/agentic/guides/extensions.md +7 -2
  5. package/dist/agentic/guides/framework-extension-points.md +1 -0
  6. package/dist/agentic/guides/infrastructure-providers.md +20 -0
  7. package/dist/agentic/guides/integrations.md +2 -2
  8. package/dist/agentic/guides/module-facts.json +2564 -265
  9. package/dist/agentic/guides/module-facts.v2.json +2580 -265
  10. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  11. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  12. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  13. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  14. package/dist/agentic/guides/modules/assisted_selling/acl-features.md +16 -0
  15. package/dist/agentic/guides/modules/assisted_selling/contribution-resolutions.md +21 -0
  16. package/dist/agentic/guides/modules/assisted_selling/domain-commands.md +11 -0
  17. package/dist/agentic/guides/modules/assisted_selling/entities.md +11 -0
  18. package/dist/agentic/guides/modules/assisted_selling/events.md +22 -0
  19. package/dist/agentic/guides/modules/assisted_selling/exact-override-targets.md +17 -0
  20. package/dist/agentic/guides/modules/assisted_selling/index.md +21 -0
  21. package/dist/agentic/guides/modules/assisted_selling/owned-contract-module-metadata.md +11 -0
  22. package/dist/agentic/guides/modules/assisted_selling/setup.md +11 -0
  23. package/dist/agentic/guides/modules/assisted_selling/umes-contributions.md +21 -0
  24. package/dist/agentic/guides/modules/assisted_selling/umes-hosts.md +23 -0
  25. package/dist/agentic/guides/modules/attachments/exact-override-targets.md +1 -1
  26. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  27. package/dist/agentic/guides/modules/attachments/workers.md +1 -1
  28. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  29. package/dist/agentic/guides/modules/auth/index.md +1 -1
  30. package/dist/agentic/guides/modules/availability/index.md +1 -1
  31. package/dist/agentic/guides/modules/backups/di-registrations-rich.md +11 -0
  32. package/dist/agentic/guides/modules/backups/di-service-tokens.md +11 -0
  33. package/dist/agentic/guides/modules/backups/exact-override-targets.md +11 -0
  34. package/dist/agentic/guides/modules/backups/index.md +5 -2
  35. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  36. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  37. package/dist/agentic/guides/modules/cart/index.md +1 -1
  38. package/dist/agentic/guides/modules/catalog/acl-features.md +2 -1
  39. package/dist/agentic/guides/modules/catalog/active-extension-bindings.md +2 -0
  40. package/dist/agentic/guides/modules/catalog/backend-pages.md +1 -0
  41. package/dist/agentic/guides/modules/catalog/contribution-resolutions.md +5 -0
  42. package/dist/agentic/guides/modules/catalog/di-registrations-rich.md +8 -7
  43. package/dist/agentic/guides/modules/catalog/di-service-tokens.md +5 -4
  44. package/dist/agentic/guides/modules/catalog/domain-commands.md +2 -0
  45. package/dist/agentic/guides/modules/catalog/entities.md +1 -0
  46. package/dist/agentic/guides/modules/catalog/events.md +4 -1
  47. package/dist/agentic/guides/modules/catalog/exact-override-targets.md +13 -7
  48. package/dist/agentic/guides/modules/catalog/index.md +9 -9
  49. package/dist/agentic/guides/modules/catalog/umes-contributions.md +5 -0
  50. package/dist/agentic/guides/modules/catalog/umes-hosts.md +4 -0
  51. package/dist/agentic/guides/modules/catalog/workers.md +1 -0
  52. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  53. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  54. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  55. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  56. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  57. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  58. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  59. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  60. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  61. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  62. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  63. package/dist/agentic/guides/modules/configs/index.md +1 -1
  64. package/dist/agentic/guides/modules/content/index.md +1 -1
  65. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  66. package/dist/agentic/guides/modules/customer_accounts/active-extension-bindings.md +1 -1
  67. package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +2 -0
  68. package/dist/agentic/guides/modules/customer_accounts/index.md +2 -2
  69. package/dist/agentic/guides/modules/customer_accounts/workers.md +2 -0
  70. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  71. package/dist/agentic/guides/modules/customers/active-extension-bindings.md +2 -1
  72. package/dist/agentic/guides/modules/customers/incoming-installed-contributions.md +1 -0
  73. package/dist/agentic/guides/modules/customers/index.md +3 -3
  74. package/dist/agentic/guides/modules/customers/umes-hosts.md +1 -0
  75. package/dist/agentic/guides/modules/dashboards/active-extension-bindings.md +0 -1
  76. package/dist/agentic/guides/modules/dashboards/cli-commands.md +1 -0
  77. package/dist/agentic/guides/modules/dashboards/exact-override-targets.md +1 -0
  78. package/dist/agentic/guides/modules/dashboards/index.md +2 -3
  79. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  80. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  81. package/dist/agentic/guides/modules/devices/index.md +1 -1
  82. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  83. package/dist/agentic/guides/modules/directory/index.md +1 -1
  84. package/dist/agentic/guides/modules/documents/index.md +1 -1
  85. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  86. package/dist/agentic/guides/modules/entities/index.md +1 -1
  87. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  88. package/dist/agentic/guides/modules/events/index.md +1 -1
  89. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  90. package/dist/agentic/guides/modules/forms/index.md +1 -1
  91. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  92. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  93. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  94. package/dist/agentic/guides/modules/generators/index.md +1 -1
  95. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  96. package/dist/agentic/guides/modules/integrations/di-registrations-rich.md +8 -8
  97. package/dist/agentic/guides/modules/integrations/di-service-tokens.md +4 -4
  98. package/dist/agentic/guides/modules/integrations/exact-override-targets.md +14 -12
  99. package/dist/agentic/guides/modules/integrations/index.md +2 -2
  100. package/dist/agentic/guides/modules/integrations/setup.md +1 -1
  101. package/dist/agentic/guides/modules/integrations/workers.md +3 -1
  102. package/dist/agentic/guides/modules/messages/index.md +1 -1
  103. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  104. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  105. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  106. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  107. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  108. package/dist/agentic/guides/modules/planner/index.md +1 -1
  109. package/dist/agentic/guides/modules/portal/index.md +1 -1
  110. package/dist/agentic/guides/modules/progress/index.md +1 -1
  111. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  112. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  113. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  114. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  115. package/dist/agentic/guides/modules/resources/exact-override-targets.md +3 -3
  116. package/dist/agentic/guides/modules/resources/index.md +1 -1
  117. package/dist/agentic/guides/modules/resources/owned-contract-module-metadata.md +1 -1
  118. package/dist/agentic/guides/modules/resources/setup.md +1 -1
  119. package/dist/agentic/guides/modules/sales/contribution-resolutions.md +1 -0
  120. package/dist/agentic/guides/modules/sales/exact-override-targets.md +1 -0
  121. package/dist/agentic/guides/modules/sales/index.md +3 -3
  122. package/dist/agentic/guides/modules/sales/umes-contributions.md +1 -0
  123. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  124. package/dist/agentic/guides/modules/search/index.md +1 -1
  125. package/dist/agentic/guides/modules/security/index.md +1 -1
  126. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  127. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  128. package/dist/agentic/guides/modules/sso/index.md +1 -1
  129. package/dist/agentic/guides/modules/staff/contribution-resolutions.md +1 -1
  130. package/dist/agentic/guides/modules/staff/exact-override-targets.md +1 -1
  131. package/dist/agentic/guides/modules/staff/index.md +1 -1
  132. package/dist/agentic/guides/modules/staff/workers.md +1 -1
  133. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  134. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  135. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  136. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  137. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  138. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  139. package/dist/agentic/guides/modules/translations/index.md +1 -1
  140. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  141. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  142. package/dist/agentic/guides/modules/wms/index.md +1 -1
  143. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  144. package/dist/agentic/guides/reference-module-facts.json +811 -21
  145. package/dist/agentic/guides/reference-modules/example/active-extension-bindings.md +1 -0
  146. package/dist/agentic/guides/reference-modules/example/backend-pages.md +2 -0
  147. package/dist/agentic/guides/reference-modules/example/contribution-resolutions.md +3 -1
  148. package/dist/agentic/guides/reference-modules/example/di-registrations-rich.md +3 -3
  149. package/dist/agentic/guides/reference-modules/example/di-service-tokens.md +1 -1
  150. package/dist/agentic/guides/reference-modules/example/entities.md +2 -0
  151. package/dist/agentic/guides/reference-modules/example/events.md +2 -1
  152. package/dist/agentic/guides/reference-modules/example/exact-override-targets.md +25 -8
  153. package/dist/agentic/guides/reference-modules/example/index.md +7 -7
  154. package/dist/agentic/guides/reference-modules/example/notifications.md +1 -0
  155. package/dist/agentic/guides/reference-modules/example/setup.md +1 -1
  156. package/dist/agentic/guides/reference-modules/example/umes-contributions.md +3 -1
  157. package/dist/agentic/guides/reference-modules/example/umes-hosts.md +4 -0
  158. package/dist/agentic/guides/upstream/AGENTS.md +5 -4
  159. package/dist/agentic/guides/upstream/BACKWARD_COMPATIBILITY.md +37 -20
  160. package/dist/agentic/guides/upstream/manifest.json +3 -3
  161. package/dist/agentic/shared/AGENTS.md.template +11 -15
  162. package/dist/agentic/shared/ai/harness/README.md +4 -2
  163. package/dist/agentic/shared/ai/harness/RELEASE.md +4 -4
  164. package/dist/agentic/shared/ai/harness/cases.json +1420 -41
  165. package/dist/agentic/shared/ai/harness/cases.schema.json +4 -4
  166. package/dist/agentic/shared/ai/harness/design-system-inventory.json +640 -142
  167. package/dist/agentic/shared/ai/harness/source-link-inventory.json +223 -16
  168. package/dist/agentic/shared/ai/harness/validators.json +1 -1
  169. package/dist/agentic/shared/ai/skills/om-system-extension/SKILL.md +1 -1
  170. package/dist/agentic/shared/ai/skills/om-system-extension/references/extension-branches.md +25 -0
  171. package/dist/agentic/shared/ai/skills/om-system-extension/references/mechanism-selector.md +1 -0
  172. package/dist/agentic/shared/ai/skills/om-system-extension/references/unified-overrides.md +2 -0
  173. package/dist/agentic/shared/scripts/run-agent-harness-release.mjs +21 -1
  174. package/dist/lib/cache-provider-manifest.js +9 -0
  175. package/dist/lib/cache-provider-manifest.js.map +7 -0
  176. package/dist/lib/generate-child-process.js +21 -3
  177. package/dist/lib/generate-child-process.js.map +2 -2
  178. package/dist/lib/generate-watch-events.js +135 -19
  179. package/dist/lib/generate-watch-events.js.map +2 -2
  180. package/dist/lib/generate-watch-plan.js +170 -0
  181. package/dist/lib/generate-watch-plan.js.map +7 -0
  182. package/dist/lib/generate-watch-runner.js +54 -0
  183. package/dist/lib/generate-watch-runner.js.map +7 -0
  184. package/dist/lib/generate-watch-structure.js +578 -203
  185. package/dist/lib/generate-watch-structure.js.map +3 -3
  186. package/dist/lib/generators/ast/writers.js +5 -1
  187. package/dist/lib/generators/ast/writers.js.map +2 -2
  188. package/dist/lib/generators/cache-providers.js +80 -0
  189. package/dist/lib/generators/cache-providers.js.map +7 -0
  190. package/dist/lib/generators/extensions/agent-files.js +1 -0
  191. package/dist/lib/generators/extensions/agent-files.js.map +2 -2
  192. package/dist/lib/generators/form-section-ast.js +156 -0
  193. package/dist/lib/generators/form-section-ast.js.map +7 -0
  194. package/dist/lib/generators/form-section-extension-compiler.js +568 -0
  195. package/dist/lib/generators/form-section-extension-compiler.js.map +7 -0
  196. package/dist/lib/generators/form-section-extension-source.js +245 -0
  197. package/dist/lib/generators/form-section-extension-source.js.map +7 -0
  198. package/dist/lib/generators/form-section-runtime-revisions.js +184 -0
  199. package/dist/lib/generators/form-section-runtime-revisions.js.map +7 -0
  200. package/dist/lib/generators/form-sections.js +773 -0
  201. package/dist/lib/generators/form-sections.js.map +7 -0
  202. package/dist/lib/generators/index.js +2 -0
  203. package/dist/lib/generators/index.js.map +2 -2
  204. package/dist/lib/generators/module-entities.js +21 -2
  205. package/dist/lib/generators/module-entities.js.map +2 -2
  206. package/dist/lib/generators/module-extension-facts.js +2 -1
  207. package/dist/lib/generators/module-extension-facts.js.map +2 -2
  208. package/dist/lib/generators/module-facts.js +30 -1
  209. package/dist/lib/generators/module-facts.js.map +2 -2
  210. package/dist/lib/generators/module-override-targets.js +24 -2
  211. package/dist/lib/generators/module-override-targets.js.map +2 -2
  212. package/dist/lib/generators/module-registry.js +223 -194
  213. package/dist/lib/generators/module-registry.js.map +3 -3
  214. package/dist/lib/generators/openapi.js +51 -18
  215. package/dist/lib/generators/openapi.js.map +2 -2
  216. package/dist/lib/generators/web-research-adapters.js +54 -22
  217. package/dist/lib/generators/web-research-adapters.js.map +2 -2
  218. package/dist/lib/in-process-generate-watcher.js +98 -75
  219. package/dist/lib/in-process-generate-watcher.js.map +2 -2
  220. package/dist/lib/post-generate-invalidation.js +20 -1
  221. package/dist/lib/post-generate-invalidation.js.map +2 -2
  222. package/dist/lib/resolver.js +195 -1
  223. package/dist/lib/resolver.js.map +3 -3
  224. package/dist/lib/single-instance-strategy-guard.js +26 -3
  225. package/dist/lib/single-instance-strategy-guard.js.map +2 -2
  226. package/dist/mercato.js +106 -50
  227. package/dist/mercato.js.map +2 -2
  228. package/jest.config.cjs +2 -0
  229. package/package.json +7 -7
  230. package/src/__tests__/mercato.test.ts +18 -0
  231. package/src/__tests__/rotation-json-output.test.ts +52 -0
  232. package/src/lib/__tests__/cache-provider-manifest.test.ts +76 -0
  233. package/src/lib/__tests__/generate-child-process.test.ts +30 -0
  234. package/src/lib/__tests__/generate-watch-events.test.ts +377 -8
  235. package/src/lib/__tests__/generate-watch-plan.test.ts +99 -0
  236. package/src/lib/__tests__/generate-watch-runner.test.ts +138 -0
  237. package/src/lib/__tests__/generate-watch-structure.test.ts +556 -1
  238. package/src/lib/__tests__/in-process-generate-watcher.test.ts +393 -6
  239. package/src/lib/__tests__/module-inspection.test.ts +17 -11
  240. package/src/lib/__tests__/post-generate-invalidation.test.ts +108 -0
  241. package/src/lib/__tests__/resolver.form-section-gates.test.ts +82 -0
  242. package/src/lib/__tests__/single-instance-strategy-guard.test.ts +129 -0
  243. package/src/lib/cache-provider-manifest.ts +8 -0
  244. package/src/lib/generate-child-process.ts +26 -3
  245. package/src/lib/generate-watch-events.ts +189 -17
  246. package/src/lib/generate-watch-plan.ts +180 -0
  247. package/src/lib/generate-watch-runner.ts +63 -0
  248. package/src/lib/generate-watch-structure.ts +670 -227
  249. package/src/lib/generators/__tests__/cache-providers.test.ts +102 -0
  250. package/src/lib/generators/__tests__/derived-crud-route-collisions.test.ts +85 -0
  251. package/src/lib/generators/__tests__/form-section-outbox.test.ts +53 -0
  252. package/src/lib/generators/__tests__/form-sections.test.ts +896 -0
  253. package/src/lib/generators/__tests__/incremental-registry.test.ts +262 -0
  254. package/src/lib/generators/__tests__/module-extension-facts.test.ts +1 -0
  255. package/src/lib/generators/__tests__/module-facts.bc-guard.test.ts +8 -6
  256. package/src/lib/generators/__tests__/module-facts.example-fact-coverage.test.ts +37 -13
  257. package/src/lib/generators/__tests__/module-facts.local-reference.test.ts +13 -0
  258. package/src/lib/generators/__tests__/module-override-targets.test.ts +2 -3
  259. package/src/lib/generators/__tests__/module-subset.test.ts +1 -1
  260. package/src/lib/generators/__tests__/openapi.test.ts +147 -10
  261. package/src/lib/generators/__tests__/structural-contracts.test.ts +2 -2
  262. package/src/lib/generators/__tests__/web-research-adapters.test.ts +298 -87
  263. package/src/lib/generators/ast/writers.ts +6 -1
  264. package/src/lib/generators/cache-providers.ts +111 -0
  265. package/src/lib/generators/extension.ts +2 -0
  266. package/src/lib/generators/extensions/agent-files.ts +1 -0
  267. package/src/lib/generators/form-section-ast.ts +166 -0
  268. package/src/lib/generators/form-section-extension-compiler.ts +632 -0
  269. package/src/lib/generators/form-section-extension-source.ts +308 -0
  270. package/src/lib/generators/form-section-runtime-revisions.ts +211 -0
  271. package/src/lib/generators/form-sections.ts +896 -0
  272. package/src/lib/generators/index.ts +1 -0
  273. package/src/lib/generators/module-entities.ts +22 -4
  274. package/src/lib/generators/module-extension-facts.ts +1 -0
  275. package/src/lib/generators/module-facts.ts +40 -0
  276. package/src/lib/generators/module-override-targets.ts +19 -0
  277. package/src/lib/generators/module-registry.ts +246 -202
  278. package/src/lib/generators/openapi.ts +65 -20
  279. package/src/lib/generators/web-research-adapters.ts +76 -21
  280. package/src/lib/in-process-generate-watcher.ts +151 -96
  281. package/src/lib/post-generate-invalidation.ts +28 -1
  282. package/src/lib/resolver.ts +218 -0
  283. package/src/lib/single-instance-strategy-guard.ts +51 -1
  284. package/src/mercato.ts +117 -57
  285. package/dist/agentic/guides/modules/dashboards/incoming-installed-contributions.md +0 -11
@@ -7,11 +7,12 @@
7
7
  */
8
8
 
9
9
  import * as fs from 'node:fs'
10
- import { randomBytes } from 'node:crypto'
11
10
  import * as path from 'node:path'
12
11
  import type { ModuleEntry, PackageResolver } from '../resolver'
13
12
  import { getEnabledModuleIdentities } from '../module-identity'
14
13
  import { isModuleRouteFile } from './scanner'
14
+ import { resolveNamedObjectExport } from './module-registry'
15
+ import { generatedDerivedCrudRouteIndex, readDerivedCrudFormSectionRouteIndex } from './form-sections'
15
16
  import {
16
17
  calculateChecksum,
17
18
  calculateStructureChecksum,
@@ -31,12 +32,13 @@ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
31
32
 
32
33
  interface ApiRouteInfo {
33
34
  path: string
35
+ moduleId: string
34
36
  methods: HttpMethod[]
35
37
  openApiPath: string
36
38
  }
37
39
 
38
40
  interface OpenApiInputManifest {
39
- version: 1
41
+ version: 2
40
42
  inputPaths: string[]
41
43
  }
42
44
 
@@ -54,9 +56,10 @@ interface OpenApiInputContext {
54
56
  interface OpenApiBundleResult {
55
57
  doc: Record<string, any> | null
56
58
  inputPaths: string[]
59
+ qualifierFailure?: string
57
60
  }
58
61
 
59
- const OPENAPI_INPUT_MANIFEST_VERSION = 1
62
+ const OPENAPI_INPUT_MANIFEST_VERSION = 2
60
63
 
61
64
  function createOpenApiInputContext(resolver: PackageResolver): OpenApiInputContext {
62
65
  const enabled = resolver.loadEnabledModules()
@@ -94,6 +97,40 @@ function readOpenApiInputManifest(filePath: string): OpenApiInputManifest | null
94
97
  }
95
98
  }
96
99
 
100
+ /** All successful bundle inputs, including generated producers; null means unknown. */
101
+ export function getOpenApiGeneratorDependencies(resolver: PackageResolver): readonly string[] | null {
102
+ return readOpenApiInputManifest(
103
+ path.join(resolver.getOutputDir(), 'openapi.generated.inputs.json'),
104
+ )?.inputPaths ?? null
105
+ }
106
+
107
+ /**
108
+ * Returns source inputs from the last successful bundle, including paths since
109
+ * deleted. An empty result does not prove that no dependencies exist: missing or
110
+ * invalid manifests require the watcher's conservative unknown-change fallback.
111
+ */
112
+ export function getOpenApiWatchInputs(resolver: PackageResolver): string[] {
113
+ const inputPaths = getOpenApiGeneratorDependencies(resolver)
114
+ if (!inputPaths) return []
115
+
116
+ const packageNames = new Set([
117
+ '@open-mercato/core',
118
+ ...resolver.loadEnabledModules().map((entry) => entry.from ?? '@open-mercato/core'),
119
+ ])
120
+ const generatedRoots = Array.from(new Set([
121
+ path.resolve(resolver.getOutputDir()),
122
+ ...Array.from(packageNames, (name) => path.resolve(resolver.getPackageOutputDir(name))),
123
+ ]))
124
+ return inputPaths.filter((inputPath) => !generatedRoots.some((root) => {
125
+ const relative = path.relative(root, inputPath)
126
+ return relative === '' || (
127
+ relative !== '..'
128
+ && !relative.startsWith(`..${path.sep}`)
129
+ && !path.isAbsolute(relative)
130
+ )
131
+ }))
132
+ }
133
+
97
134
  function trackedPathRecord(filePath: string): string {
98
135
  try {
99
136
  const stat = fs.statSync(filePath)
@@ -115,6 +152,7 @@ function calculateOpenApiInputFingerprint(
115
152
  const appDir = resolver.getAppDir()
116
153
  const configPaths = [
117
154
  resolver.getModulesConfigPath(),
155
+ path.join(resolver.getOutputDir(), generatedDerivedCrudRouteIndex),
118
156
  path.join(rootDir, 'package.json'),
119
157
  path.join(rootDir, 'yarn.lock'),
120
158
  path.join(rootDir, 'package-lock.json'),
@@ -195,18 +233,30 @@ async function findApiRoutes(
195
233
 
196
234
  // Build API path
197
235
  const routeSegs = relativePath ? relativePath.split('/') : []
198
- const apiPath = `/api/${modId}${routeSegs.length ? '/' + routeSegs.join('/') : ''}`
236
+ const metadataPath = resolveNamedObjectExport(fullPath, 'metadata')?.path
237
+ const routePath = typeof metadataPath === 'string' && metadataPath
238
+ ? metadataPath
239
+ : `/${modId}${routeSegs.length ? '/' + routeSegs.join('/') : ''}`
240
+ const apiPath = `/api/${routePath.replace(/^\/+/, '')}`
199
241
  // Convert [param] to {param} for OpenAPI format
200
242
  .replace(/\[([^\]]+)\]/g, '{$1}')
201
243
 
202
244
  routes.push({
203
245
  path: fullPath,
246
+ moduleId: modId,
204
247
  methods: await detectMethods(fullPath),
205
248
  openApiPath: apiPath,
206
249
  })
207
250
  }
208
251
  }
209
252
 
253
+ const enabledIds = new Set(enabled.map(({ id }) => id))
254
+ const derived = readDerivedCrudFormSectionRouteIndex(resolver.getOutputDir())
255
+ routes.push(...derived.filter(({ moduleId }) => enabledIds.has(moduleId)).map(({ moduleId, routePath, methods, fileName }) => ({
256
+ moduleId, methods,
257
+ path: path.join(resolver.getOutputDir(), fileName),
258
+ openApiPath: `/api${routePath}`.replace(/\[([^\]]+)\]/g, '{$1}'),
259
+ })))
210
260
  return routes
211
261
  }
212
262
 
@@ -338,13 +388,6 @@ async function generateOpenApiViaBundle(
338
388
  return { doc: null, inputPaths: [] }
339
389
  }
340
390
 
341
- const cacheDir = path.join(rootDir, 'node_modules', '.cache')
342
- if (!fs.existsSync(cacheDir)) fs.mkdirSync(cacheDir, { recursive: true })
343
-
344
- // Per-run file: `yarn dev`'s watcher and a CLI `generate` (e.g. after
345
- // create-mercato-module init) can bundle concurrently, and a shared path let
346
- // one process execute the other's half-written bundle ("Unexpected end of input").
347
- const bundlePath = path.join(cacheDir, `_openapi-bundle-${process.pid}-${randomBytes(6).toString('hex')}.mjs`)
348
391
  let inputPaths: string[] = []
349
392
 
350
393
  // Build the entry script that imports all routes and calls buildOpenApiDocument
@@ -358,7 +401,7 @@ async function generateOpenApiViaBundle(
358
401
  importLines.push(`import * as R${i} from ${JSON.stringify(route.path)};`)
359
402
  // Use [param] format so normalizePath in buildOpenApiDocument extracts path params
360
403
  const bracketPath = route.openApiPath.replace(/\{([^}]+)\}/g, '[$1]')
361
- routeMapLines.push(` [${JSON.stringify(bracketPath)}, R${i}],`)
404
+ routeMapLines.push(` [${JSON.stringify(bracketPath)}, ${JSON.stringify(route.moduleId)}, R${i}],`)
362
405
  }
363
406
 
364
407
  const entryScript = `${importLines.join('\n')}
@@ -368,8 +411,7 @@ ${routeMapLines.join('\n')}
368
411
  ];
369
412
 
370
413
  const modules = new Map();
371
- for (const [apiPath, mod] of routeEntries) {
372
- const moduleId = apiPath.replace(/^\\/api\\//, '').split('/')[0];
414
+ for (const [apiPath, moduleId, mod] of routeEntries) {
373
415
  if (!modules.has(moduleId)) modules.set(moduleId, { id: moduleId, apis: [] });
374
416
  modules.get(moduleId).apis.push({
375
417
  path: apiPath,
@@ -531,6 +573,8 @@ process.stdout.write(JSON.stringify(deepClone(doc), (_, v) =>
531
573
  },
532
574
  }
533
575
 
576
+ const bundleDir = fs.mkdtempSync(path.join(resolver.getOutputDir(), '.openapi-'))
577
+ const bundlePath = path.join(bundleDir, 'bundle.mjs')
534
578
  try {
535
579
  const buildResult = await esbuild.build({
536
580
  stdin: {
@@ -605,16 +649,13 @@ process.stdout.write(JSON.stringify(deepClone(doc), (_, v) =>
605
649
  }
606
650
  }
607
651
  }
608
- return { doc: null, inputPaths }
652
+ const qualifierFailure = /Cannot derive CrudForm section host: [^\r\n]+/.exec(`${errMsg}\n${String(stderr ?? '')}`)?.[0]
653
+ return { doc: null, inputPaths, qualifierFailure }
609
654
  } finally {
610
655
  // Shut down esbuild's persistent Go service so it does not deadlock at
611
656
  // process exit when a plugin request is still in flight.
612
657
  try { await esbuild.stop() } catch {}
613
- // Clean up old files from previous tsx-based approach
614
- try { fs.unlinkSync(bundlePath) } catch {}
615
- for (const file of ['_openapi-bundle.mjs', '_openapi-register.mjs', '_openapi-loader.mjs', '_next-stub.cjs']) {
616
- try { fs.unlinkSync(path.join(cacheDir, file)) } catch {}
617
- }
658
+ try { fs.rmSync(bundleDir, { recursive: true, force: true }) } catch {}
618
659
  }
619
660
  }
620
661
 
@@ -714,6 +755,10 @@ export async function generateOpenApi(options: GenerateOpenApiOptions): Promise<
714
755
  const bundleResult = await generateOpenApiViaBundle(routes, resolver, quiet)
715
756
  let doc: Record<string, any> | null = bundleResult.doc
716
757
 
758
+ if (!doc && readDerivedCrudFormSectionRouteIndex(outputDir).length) {
759
+ throw new Error(bundleResult.qualifierFailure ?? '[generate] Could not validate generated CrudForm section-policy OpenAPI schemas')
760
+ }
761
+
717
762
  // Fallback to static regex approach (extracts operationId/summary/tags but no schemas)
718
763
  if (!doc) {
719
764
  if (!quiet) {
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import type { PackageResolver } from '../resolver'
4
- import { calculateStructureChecksum, createGeneratorResult, type GeneratorResult, writeGeneratedFile } from '../utils'
4
+ import { calculateChecksum, createGeneratorResult, type GeneratorResult, writeGeneratedFile } from '../utils'
5
5
 
6
6
  export interface WebResearchAdaptersOptions {
7
7
  resolver: PackageResolver
@@ -22,16 +22,28 @@ type DiscoveredAdapter = {
22
22
  sourceRoot: string
23
23
  }
24
24
 
25
- function readJson(file: string): unknown {
25
+ function isMissing(error: unknown): boolean {
26
+ return typeof error === 'object' && error !== null && 'code' in error
27
+ && (error.code === 'ENOENT' || error.code === 'ENOTDIR')
28
+ }
29
+
30
+ function readJson(file: string, fullReasons: Set<string>): unknown {
31
+ let source: string
32
+ try {
33
+ source = fs.readFileSync(file, 'utf8')
34
+ } catch (error) {
35
+ if (!isMissing(error)) fullReasons.add(`Cannot read web-research adapter manifest: ${file}`)
36
+ return null
37
+ }
26
38
  try {
27
- return JSON.parse(fs.readFileSync(file, 'utf8'))
39
+ return JSON.parse(source)
28
40
  } catch {
29
41
  return null
30
42
  }
31
43
  }
32
44
 
33
- function readManifest(packageJsonPath: string): DiscoveredAdapter | null {
34
- const parsed = readJson(packageJsonPath)
45
+ function readManifest(packageJsonPath: string, fullReasons: Set<string>): DiscoveredAdapter | null {
46
+ const parsed = readJson(packageJsonPath, fullReasons)
35
47
  if (typeof parsed !== 'object' || parsed === null) return null
36
48
  const pkg = parsed as Record<string, unknown>
37
49
  const namespace = pkg[MANIFEST_NAMESPACE]
@@ -45,25 +57,65 @@ function readManifest(packageJsonPath: string): DiscoveredAdapter | null {
45
57
  return { packageName, adapterId, sourceRoot: path.dirname(packageJsonPath) }
46
58
  }
47
59
 
48
- function scanDirectory(root: string, results: Map<string, DiscoveredAdapter>): void {
49
- if (!fs.existsSync(root)) return
60
+ function scanDirectory(
61
+ root: string,
62
+ manifestPaths: string[],
63
+ scopeDirectories: string[],
64
+ fullReasons: Set<string>,
65
+ ): void {
50
66
  let entries: fs.Dirent[]
51
67
  try {
52
68
  entries = fs.readdirSync(root, { withFileTypes: true })
53
- } catch {
69
+ } catch (error) {
70
+ if (!isMissing(error)) fullReasons.add(`Cannot scan web-research adapter packages: ${root}`)
54
71
  return
55
72
  }
56
- for (const entry of entries) {
73
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
57
74
  if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
58
75
  if (entry.name === '.bin' || entry.name === '.cache') continue
59
76
  const child = path.join(root, entry.name)
60
77
  // Scoped packages nest one level deeper (`@scope/name`).
61
78
  if (entry.name.startsWith('@')) {
62
- scanDirectory(child, results)
79
+ scopeDirectories.push(child)
80
+ scanDirectory(child, manifestPaths, scopeDirectories, fullReasons)
63
81
  continue
64
82
  }
65
- const discovered = readManifest(path.join(child, 'package.json'))
66
- if (discovered && !results.has(discovered.packageName)) results.set(discovered.packageName, discovered)
83
+ manifestPaths.push(path.join(child, 'package.json'))
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Shares candidate discovery with generation. Directory paths are the scan roots
89
+ * and their `@scope` folders, watched without recursion: a package appearing or
90
+ * disappearing adds or removes an entry there, and installs also change the
91
+ * watched lockfiles. Package implementations are not registry inputs. Missing
92
+ * manifests are retained so declaring an adapter in an existing package is seen
93
+ * by the next capture.
94
+ */
95
+ export type WebResearchAdapterWatchInputs = {
96
+ manifestPaths: string[]
97
+ directoryPaths: string[]
98
+ fullReasons: string[]
99
+ }
100
+
101
+ export function getWebResearchAdapterWatchInputs(
102
+ resolver: PackageResolver,
103
+ ): WebResearchAdapterWatchInputs {
104
+ const rootDir = resolver.getRootDir()
105
+ const appDir = resolver.getAppDir()
106
+ const manifestPaths: string[] = []
107
+ const scopeDirectories: string[] = []
108
+ const fullReasons = new Set<string>()
109
+ const scanRoots = [...new Set([
110
+ path.join(rootDir, 'packages'),
111
+ path.join(rootDir, 'node_modules'),
112
+ path.join(appDir, 'node_modules'),
113
+ ].map((directory) => path.resolve(directory)))]
114
+ for (const root of scanRoots) scanDirectory(root, manifestPaths, scopeDirectories, fullReasons)
115
+ return {
116
+ manifestPaths: [...new Set(manifestPaths)],
117
+ directoryPaths: [...new Set([...scanRoots, ...scopeDirectories])],
118
+ fullReasons: [...fullReasons].sort((left, right) => left.localeCompare(right)),
67
119
  }
68
120
  }
69
121
 
@@ -119,15 +171,16 @@ export async function generateWebResearchAdapters(
119
171
  const outFile = path.join(outputDir, 'web-research-adapters.generated.ts')
120
172
  const checksumFile = path.join(outputDir, 'web-research-adapters.checksum')
121
173
 
122
- const appDir = resolver.getAppDir()
123
- const repoRoot = path.resolve(appDir, '..', '..')
174
+ const { manifestPaths, fullReasons: scanFullReasons } = getWebResearchAdapterWatchInputs(resolver)
175
+ const fullReasons = new Set(scanFullReasons)
124
176
  const discovered = new Map<string, DiscoveredAdapter>()
125
- const scanRoots = [
126
- path.join(repoRoot, 'packages'),
127
- path.join(repoRoot, 'node_modules'),
128
- path.join(appDir, 'node_modules'),
129
- ]
130
- for (const root of scanRoots) scanDirectory(root, discovered)
177
+ for (const manifestPath of manifestPaths) {
178
+ const adapter = readManifest(manifestPath, fullReasons)
179
+ if (adapter && !discovered.has(adapter.packageName)) discovered.set(adapter.packageName, adapter)
180
+ }
181
+ if (fullReasons.size > 0) {
182
+ throw new Error([...fullReasons].sort((left, right) => left.localeCompare(right)).join('\n'))
183
+ }
131
184
 
132
185
  const adapters = [...discovered.values()].sort((left, right) =>
133
186
  left.packageName.localeCompare(right.packageName),
@@ -150,7 +203,9 @@ ${renderEntries(adapters)}`
150
203
  outFile,
151
204
  checksumFile,
152
205
  content,
153
- structureChecksum: calculateStructureChecksum(adapters.map((adapter) => adapter.sourceRoot)),
206
+ // Discovery rereads candidate manifests on every run; adapter implementations
207
+ // cannot affect these static imports, so do not walk their package trees.
208
+ structureChecksum: calculateChecksum(JSON.stringify(adapters)),
154
209
  result,
155
210
  quiet,
156
211
  })
@@ -1,13 +1,11 @@
1
1
  /**
2
2
  * In-process generate watcher.
3
3
  *
4
- * Coalesces filesystem events on a configurable interval, then verifies them
5
- * with the existing structural fingerprint before invoking the generator.
6
- * If filesystem watching is unavailable, it falls back to fingerprint polling.
7
- * The polling loop is identical to the legacy standalone watcher; the only
8
- * difference is that it now runs inside whatever process calls it
9
- * (typically `mercato server dev`), so the dev runtime no longer needs a
10
- * sidecar `mercato generate watch` Node process.
4
+ * Coalesces filesystem events before comparing the current module structure
5
+ * with the last successfully generated snapshot. Failed or uncertain
6
+ * candidates remain unacknowledged, but are retried only after a new input
7
+ * event (or a newly observed polling-fallback snapshot). Capturing before
8
+ * generation leaves edits made during a run dirty for the next serial poll.
11
9
  *
12
10
  * Contract preserved from the prior standalone watcher:
13
11
  * - Default debounce/fallback poll interval 1000 ms (minimum 250 ms).
@@ -16,12 +14,16 @@
16
14
  * - Generator errors are logged but never crash the watcher.
17
15
  * - The polling timer uses `.unref()` so it never blocks process exit.
18
16
  */
17
+ import { planGenerateWatchChanges } from './generate-watch-plan'
18
+ import type { GenerateWatchPlan, GenerateWatchSnapshot } from './generate-watch-plan'
19
19
 
20
20
  export type GenerateWatcherLogger = Pick<Console, 'log' | 'error'>
21
21
 
22
22
  export type GenerateWatcherChangeSignal = {
23
23
  /** Monotonic event generation. Changes indicate that a checksum may be stale. */
24
24
  currentVersion(): number
25
+ /** Explain events without a usable filename since a captured event version. */
26
+ fullGenerationReasonSince?(version: number): string | undefined
25
27
  /** Refresh filesystem subscriptions after module configuration changes. */
26
28
  refresh(): Promise<void> | void
27
29
  /** Whether configured roots are missing and should be retried on idle polls. */
@@ -40,13 +42,20 @@ export type GenerateWatcherOptions = {
40
42
  computeStructureChecksum: () => Promise<string> | string
41
43
  /** Optional event signal that avoids full checksum work during idle polls. */
42
44
  changeSignal?: GenerateWatcherChangeSignal
45
+ /** Opt in to category-aware planning; legacy checksum-only callers stay valid. */
46
+ incremental?: {
47
+ capture(): Promise<GenerateWatchSnapshot> | GenerateWatchSnapshot
48
+ plan(previous: GenerateWatchSnapshot, next: GenerateWatchSnapshot): GenerateWatchPlan
49
+ }
43
50
  /**
44
51
  * Function that performs the actual regeneration work. Called once on
45
- * startup (unless `skipInitial`) and again whenever the checksum changes.
46
- * The `reason` argument is suitable for logging (`'initial'`,
47
- * `'structure change'`, `'queued change'`).
52
+ * startup (unless `skipInitial`) and again whenever the input changes.
53
+ * After a failed or uncertain candidate, the next changed input is repaired
54
+ * with a full generation. The `reason` argument is suitable for logging
55
+ * (`'initial'`, `'structure change'`, `'retry after failed generation'`,
56
+ * or `'retry after uncertain structure snapshot'`).
48
57
  */
49
- runGenerators: (reason: string) => Promise<void>
58
+ runGenerators: (reason: string, plan?: GenerateWatchPlan) => Promise<void>
50
59
  /** Poll interval in milliseconds. Defaults to 1000. Clamped to >= 250. */
51
60
  pollMs?: number
52
61
  /** Skip the initial regeneration on startup. Defaults to false. */
@@ -84,138 +93,184 @@ export function startInProcessGenerateWatcher(
84
93
  const logger = options.logger ?? console
85
94
  const quiet = options.quiet === true
86
95
  const pollMs = resolvePollMs(options.pollMs)
87
- const skipInitial = options.skipInitial === true
88
- const { changeSignal, computeStructureChecksum, runGenerators } = options
89
-
96
+ const { changeSignal, computeStructureChecksum, runGenerators, incremental } = options
90
97
  let stopping = false
91
98
  let pollTimer: ReturnType<typeof setTimeout> | null = null
92
- let activeCycle: Promise<void> | null = null
93
- let running = false
94
- let pendingReason: string | null = null
95
- let previousChecksum = ''
99
+ let previousChecksum: string | undefined
100
+ let previousSnapshot: GenerateWatchSnapshot | undefined
96
101
  let observedChangeVersion = -1
97
- let doneResolve: (() => void) | null = null
98
- const done = new Promise<void>((resolve) => {
99
- doneResolve = resolve
100
- })
102
+ let attemptedChangeVersion = -1
103
+ let attemptedChecksum: string | undefined
104
+ let attemptedUncertaintyKey: string | undefined
105
+ let hasAttemptedCapture = false
106
+ let retryReason: string | undefined
107
+ let doneResolve: () => void = () => {}
108
+ const done = new Promise<void>((resolve) => { doneResolve = resolve })
109
+
110
+ async function captureAndGenerate(initial: boolean, refreshSubscriptions = true): Promise<void> {
111
+ // This version belongs to the candidate, not to the state after generation.
112
+ const changeVersion = changeSignal?.currentVersion() ?? 0
113
+ const hadPriorAttempt = hasAttemptedCapture
114
+ const priorAttemptVersion = attemptedChangeVersion
115
+ const priorAttemptChecksum = attemptedChecksum
116
+ const priorAttemptUncertaintyKey = attemptedUncertaintyKey
117
+ hasAttemptedCapture = true
118
+ attemptedChangeVersion = changeVersion
101
119
 
102
- async function runOnce(reason: string): Promise<void> {
120
+ let candidate: GenerateWatchSnapshot | undefined
121
+ let checksum: string
122
+ try {
123
+ candidate = incremental ? await incremental.capture() : undefined
124
+ checksum = candidate?.checksum ?? await computeStructureChecksum()
125
+ } catch (error) {
126
+ // A later authoritative capture must be treated as a new candidate even
127
+ // when it has the same checksum as the snapshot preceding this failure.
128
+ attemptedChecksum = undefined
129
+ attemptedUncertaintyKey = 'capture failed'
130
+ retryReason = 'retry after uncertain structure snapshot'
131
+ throw error
132
+ }
133
+ if (stopping) return
134
+ if (refreshSubscriptions) await changeSignal?.refresh()
103
135
  if (stopping) return
104
- if (running) {
105
- pendingReason = reason
136
+
137
+ const uncertaintyKey = candidate?.fullReasons.join('\u0000')
138
+ const inputChangedSinceAttempt = !hadPriorAttempt
139
+ || changeVersion !== priorAttemptVersion
140
+ || checksum !== priorAttemptChecksum
141
+ || uncertaintyKey !== priorAttemptUncertaintyKey
142
+ attemptedChecksum = checksum
143
+ attemptedUncertaintyKey = uncertaintyKey
144
+
145
+ const skipInitial = initial && options.skipInitial === true
146
+ const changed = checksum !== previousChecksum
147
+ const uncertain = Boolean(candidate?.fullReasons.length)
148
+ const eventReason = changeSignal?.fullGenerationReasonSince?.(observedChangeVersion)
149
+ const shouldGenerate = !skipInitial && (retryReason
150
+ ? inputChangedSinceAttempt
151
+ : initial || changed || uncertain || Boolean(eventReason))
152
+ if (shouldGenerate) {
153
+ let plan: GenerateWatchPlan | undefined
154
+ if (incremental && candidate) {
155
+ const fallbackReason = initial
156
+ ? 'initial generation'
157
+ : retryReason
158
+ ?? (!previousSnapshot
159
+ ? 'no successful snapshot'
160
+ : changeSignal?.usesPollingFallback()
161
+ ? 'filesystem watching unavailable; polling fallback'
162
+ : eventReason)
163
+ const candidatePlan = previousSnapshot ? incremental.plan(previousSnapshot, candidate) : undefined
164
+ plan = fallbackReason
165
+ ? planGenerateWatchChanges(candidatePlan?.changes ?? [], [fallbackReason, ...candidate.fullReasons])
166
+ : candidatePlan
167
+ }
168
+ if (plan?.mode !== 'none') {
169
+ const reason = initial ? 'initial' : retryReason ?? 'structure change'
170
+ if (!quiet) {
171
+ const detail = plan
172
+ ? `; categories=${[...new Set(plan.changes.map((change) => change.category))].join(',') || 'all'}; groups=${plan.groups.join(',')}${plan.reasons.length ? `; reasons=${plan.reasons.join('; ')}` : ''}`
173
+ : ''
174
+ logger.log(`[generate:watch] Regenerating (${reason}${detail})...`)
175
+ }
176
+ try {
177
+ // Do not add an undefined argument to the legacy callback contract.
178
+ if (plan) await runGenerators(reason, plan)
179
+ else await runGenerators(reason)
180
+ } catch (error) {
181
+ retryReason = 'retry after failed generation'
182
+ const message = error instanceof Error ? error.message : String(error)
183
+ logger.error(`[generate:watch] Generation failed: ${message}`)
184
+ return
185
+ }
186
+ // A successful bundle can discover new external dependencies to watch.
187
+ if (incremental && !stopping) await changeSignal?.refresh()
188
+ if (!quiet) logger.log('[generate:watch] Generators completed.')
189
+ }
190
+ } else if (retryReason) {
191
+ // Keep the failed/uncertain candidate unacknowledged without retrying it.
192
+ return
193
+ }
194
+ // Only successful generation (or a verified no-op) acknowledges this input.
195
+ if (uncertain) {
196
+ retryReason = 'retry after uncertain structure snapshot'
106
197
  return
107
198
  }
108
- running = true
199
+ previousChecksum = checksum
200
+ previousSnapshot = candidate
201
+ observedChangeVersion = changeVersion
202
+ retryReason = undefined
203
+ }
204
+
205
+ async function poll(): Promise<void> {
109
206
  try {
110
- if (!quiet) {
111
- logger.log(`[generate:watch] Regenerating (${reason})...`)
112
- }
113
- await runGenerators(reason)
114
- if (!quiet) {
115
- logger.log('[generate:watch] Generators completed.')
207
+ if (stopping) return
208
+ const eventGatedIdle = hasAttemptedCapture
209
+ && changeSignal
210
+ && !changeSignal.usesPollingFallback()
211
+ && changeSignal.currentVersion() === attemptedChangeVersion
212
+ if (eventGatedIdle) {
213
+ if (!changeSignal.hasSkippedTargets?.()) return
214
+ await changeSignal.refresh()
215
+ if (stopping) return
216
+ const stillAtAttemptedVersion = changeSignal.currentVersion() === attemptedChangeVersion
217
+ // A pending repair is strictly event-gated. Normal idle polling may
218
+ // still discover a formerly missing root even if the signal provider
219
+ // cannot attribute that discovery to a filesystem event.
220
+ if (stillAtAttemptedVersion
221
+ && (retryReason || changeSignal.hasSkippedTargets?.())) return
116
222
  }
223
+ await captureAndGenerate(false, !eventGatedIdle)
117
224
  } catch (error) {
118
225
  const message = error instanceof Error ? error.message : String(error)
119
- logger.error(`[generate:watch] Generation failed: ${message}`)
226
+ logger.error(`[generate:watch] Poll cycle failed: ${message}`)
120
227
  } finally {
121
- running = false
122
- if (pendingReason && !stopping) {
123
- const queued = pendingReason
124
- pendingReason = null
125
- await runOnce(queued)
126
- }
228
+ scheduleNext()
127
229
  }
128
230
  }
129
231
 
130
232
  function scheduleNext(): void {
131
233
  if (stopping) return
132
234
  pollTimer = setTimeout(() => {
133
- activeCycle = (async () => {
134
- if (stopping) return
135
- try {
136
- const changeVersion = changeSignal?.currentVersion() ?? 0
137
- const eventGatedIdle = Boolean(
138
- changeSignal
139
- && !changeSignal.usesPollingFallback()
140
- && changeVersion === observedChangeVersion
141
- )
142
- let refreshedSkippedTargets = false
143
- if (eventGatedIdle) {
144
- if (!changeSignal?.hasSkippedTargets?.()) return
145
- await changeSignal.refresh()
146
- refreshedSkippedTargets = true
147
- if (changeSignal.hasSkippedTargets?.()) return
148
- }
149
- const nextChecksum = await computeStructureChecksum()
150
- observedChangeVersion = changeVersion
151
- if (!refreshedSkippedTargets) {
152
- await changeSignal?.refresh()
153
- }
154
- if (nextChecksum !== previousChecksum) {
155
- previousChecksum = nextChecksum
156
- await runOnce('structure change')
157
- }
158
- } catch (error) {
159
- const message = error instanceof Error ? error.message : String(error)
160
- logger.error(`[generate:watch] Poll cycle failed: ${message}`)
161
- } finally {
162
- if (!stopping) scheduleNext()
163
- }
164
- })()
235
+ pollTimer = null
236
+ activeCycle = poll()
165
237
  }, pollMs)
166
238
  pollTimer.unref?.()
167
239
  }
168
240
 
169
- activeCycle = (async () => {
241
+ let activeCycle = (async () => {
170
242
  try {
171
243
  await changeSignal?.refresh()
172
244
  if (stopping) return
173
- const initialChangeVersion = changeSignal?.currentVersion() ?? 0
174
- if (!skipInitial) {
175
- await runOnce('initial')
176
- }
177
- if (stopping) return
178
- previousChecksum = await computeStructureChecksum()
179
- observedChangeVersion = initialChangeVersion
180
- if (!quiet) {
181
- if (skipInitial) {
245
+ await captureAndGenerate(true, Boolean(incremental))
246
+ if (!quiet && !stopping) {
247
+ if (options.skipInitial) {
182
248
  logger.log('[generate:watch] Skipping initial regeneration and watching the current generated state.')
183
249
  }
184
250
  logger.log(`[generate:watch] Watching structural module files with a ${pollMs}ms debounce (in-process).`)
185
251
  }
186
- scheduleNext()
187
252
  } catch (error) {
188
253
  const message = error instanceof Error ? error.message : String(error)
189
254
  logger.error(`[generate:watch] Initial setup failed: ${message}`)
190
- // Even if the initial bootstrap fails, schedule polling so a later
191
- // checksum recovery still picks up the next change on disk.
255
+ } finally {
192
256
  scheduleNext()
193
257
  }
194
258
  })()
195
259
 
196
260
  async function close(): Promise<void> {
197
- if (stopping) {
198
- await done
199
- return
200
- }
261
+ if (stopping) return done
201
262
  stopping = true
202
263
  if (pollTimer) {
203
264
  clearTimeout(pollTimer)
204
265
  pollTimer = null
205
266
  }
206
- // Drain before closing subscriptions: an in-flight capture can refresh
207
- // them, and a generator child must exit before dev restarts its group.
208
267
  try {
209
268
  await activeCycle
210
269
  await changeSignal?.close()
211
270
  } finally {
212
- doneResolve?.()
213
- doneResolve = null
271
+ doneResolve()
214
272
  }
215
273
  }
216
274
 
217
- return {
218
- done,
219
- close,
220
- }
275
+ return { done, close }
221
276
  }