@open-mercato/cli 0.11.1-develop.8589.1.db1a76ea60 → 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,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
  }