@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,6 +1,7 @@
1
1
  import crypto from 'node:crypto'
2
2
  import fs from 'node:fs'
3
3
  import path from 'node:path'
4
+ import ts from 'typescript-js'
4
5
  import {
5
6
  MODULE_CODE_EXTENSIONS,
6
7
  SCAN_CONFIGS,
@@ -8,279 +9,717 @@ import {
8
9
  scanModuleDir,
9
10
  stripModuleCodeExtension,
10
11
  type ModuleRoots,
12
+ type ScanConfig,
13
+ type ScannedFile,
11
14
  } from './generators/scanner'
15
+ import type {
16
+ GenerateWatchCategory, GenerateWatchChange, GenerateWatchRecord, GenerateWatchSnapshot,
17
+ } from './generate-watch-plan'
12
18
 
13
- const STRUCTURAL_CONVENTION_FILES = [
14
- 'index.ts',
15
- 'cli.ts',
16
- 'di.ts',
17
- 'acl.ts',
18
- 'setup.ts',
19
- 'runtime.ts',
20
- 'encryption.ts',
21
- 'ce.ts',
22
- 'search.ts',
23
- 'events.ts',
24
- 'notifications.ts',
25
- 'notifications.client.ts',
26
- 'notifications.handlers.ts',
27
- 'translations.ts',
28
- 'generators.ts',
29
- 'ai-tools.ts',
30
- 'ai-agents.ts',
31
- 'analytics.ts',
32
- 'workflows.ts',
33
- 'inbox-actions.ts',
34
- 'message-types.ts',
35
- 'message-objects.ts',
36
- 'integration.ts',
37
- 'security.mfa-providers.ts',
38
- 'security.sudo.ts',
39
- 'data/entities.ts',
40
- 'data/extensions.ts',
41
- 'data/fields.ts',
42
- 'data/enrichers.ts',
43
- 'data/guards.ts',
44
- 'api/interceptors.ts',
45
- 'commands/interceptors.ts',
46
- 'widgets/components.ts',
47
- 'widgets/injection-table.ts',
48
- 'frontend/middleware.ts',
49
- 'backend/middleware.ts',
50
- ] as const
51
-
52
- const CONTENT_SENSITIVE_SCAN_CONFIGS = [
53
- SCAN_CONFIGS.apiRoutes,
54
- SCAN_CONFIGS.apiPlainFiles,
55
- SCAN_CONFIGS.subscribers,
56
- SCAN_CONFIGS.workers,
57
- SCAN_CONFIGS.dashboardWidgets,
58
- SCAN_CONFIGS.injectionWidgets,
59
- ] as const
60
-
61
- const ROUTE_SHAPE_SCAN_CONFIGS = [
62
- SCAN_CONFIGS.frontendPages,
63
- SCAN_CONFIGS.backendPages,
64
- ] as const
19
+ type InputKind = { category: GenerateWatchCategory; extensionId?: string }
20
+ type WatchRoots = ModuleRoots & { moduleId?: string; from?: string }
21
+ export type GenerateWatchStructureOptions = {
22
+ modulesFile: string
23
+ moduleRoots: WatchRoots[]
24
+ /** Dependency/configuration inputs whose changes require a conservative full generation. */
25
+ additionalInputs?: string[]
26
+ /** Inputs consumed specifically by OpenAPI generation. */
27
+ openapiInputs?: string[]
28
+ /** Candidate package manifests consumed specifically by web-research adapter discovery. */
29
+ webResearchAdapterInputs?: string[]
30
+ /** Adapter discovery failures that make this capture non-authoritative. */
31
+ webResearchAdapterFullReasons?: readonly string[]
32
+ }
33
+
34
+ /**
35
+ * Facts derived from one stat identity of a tracked file. Source text and parsed
36
+ * ASTs are capture-local; only these small extracted values outlive a capture.
37
+ */
38
+ type CachedStructureFile = {
39
+ identity: string
40
+ fingerprint: string
41
+ parseFailed?: true
42
+ pageFingerprint?: string | null
43
+ imports?: { specifiers: string[]; uncertain: boolean }
44
+ pluginConventions?: string[] | null
45
+ supervisorOverride?: boolean
46
+ }
47
+
48
+ type GenerateWatchStructureCacheState = {
49
+ files: Map<string, CachedStructureFile>
50
+ }
51
+
52
+ declare const generateWatchStructureCacheBrand: unique symbol
53
+ export type GenerateWatchStructureCache = {
54
+ readonly [generateWatchStructureCacheBrand]: true
55
+ }
56
+
57
+ const cacheStates = new WeakMap<GenerateWatchStructureCache, GenerateWatchStructureCacheState>()
58
+
59
+ export function createGenerateWatchStructureCache(): GenerateWatchStructureCache {
60
+ const cache = {} as GenerateWatchStructureCache
61
+ cacheStates.set(cache, { files: new Map() })
62
+ return cache
63
+ }
64
+
65
+ const REGISTRY_CONVENTIONS = [
66
+ 'index', 'acl', 'setup', 'runtime', 'encryption', 'ce', 'integration', 'vector',
67
+ 'data/extensions', 'data/fields',
68
+ ]
69
+ const EXTENSION_CONVENTIONS: Readonly<Record<string, string>> = {
70
+ notifications: 'registry.notifications',
71
+ 'notifications.client': 'registry.notifications',
72
+ 'notifications.handlers': 'registry.notifications',
73
+ 'message-types': 'registry.messages',
74
+ 'message-objects': 'registry.messages',
75
+ 'ai-tools': 'registry.ai-tools',
76
+ 'ai-agents': 'registry.ai-agents',
77
+ analytics: 'registry.analytics',
78
+ translations: 'registry.translatable-fields',
79
+ workflows: 'registry.workflows',
80
+ 'inbox-actions': 'registry.inbox-actions',
81
+ 'data/enrichers': 'registry.enrichers',
82
+ 'data/guards': 'registry.guards',
83
+ 'api/interceptors': 'registry.interceptors',
84
+ 'commands/interceptors': 'registry.command-interceptors',
85
+ 'widgets/components': 'registry.component-overrides',
86
+ 'frontend/middleware': 'registry.page-middleware',
87
+ 'backend/middleware': 'registry.page-middleware',
88
+ }
89
+
90
+ // These two policies mirror the registry's command/legacy-API scans; all other
91
+ // directory discovery is shared with the generator through SCAN_CONFIGS.
92
+ const COMMAND_SCAN_CONFIG: ScanConfig = {
93
+ folder: 'commands',
94
+ include: (name) => MODULE_CODE_EXTENSIONS.some((extension) => name.endsWith(extension))
95
+ && !name.endsWith('.d.ts') && !/\.(test|spec)\.[jt]sx?$/.test(name)
96
+ && !['index', 'shared', 'factory'].includes(stripModuleCodeExtension(name)),
97
+ }
98
+ const LEGACY_API_SCAN_CONFIGS: ScanConfig[] = ['get', 'post', 'put', 'patch', 'delete'].map((method) => ({
99
+ folder: `api/${method}`,
100
+ include: (name) => /\.[jt]s$/.test(name) && !/\.(test|spec)\.[jt]s$/.test(name),
101
+ }))
65
102
 
66
103
  function checksum(value: string): string {
67
104
  return crypto.createHash('md5').update(value).digest('hex')
68
105
  }
69
106
 
70
- function moduleRootIdentity(roots: ModuleRoots): string {
71
- return JSON.stringify([
72
- roots.pkgBase.replace(/\\/g, '/'),
73
- roots.appBase.replace(/\\/g, '/'),
74
- ])
107
+ function isMissing(error: unknown): boolean {
108
+ return typeof error === 'object' && error !== null && 'code' in error
109
+ && (error.code === 'ENOENT' || error.code === 'ENOTDIR')
75
110
  }
76
111
 
77
- function fileRecord(filePath: string, base: string, mode: 'content' | 'shape'): string | null {
78
- if (!fs.existsSync(filePath)) return null
79
- let stat: fs.Stats
80
- try {
81
- stat = fs.statSync(filePath)
82
- } catch {
83
- return null
112
+ function unwrap(node: ts.Expression): ts.Expression {
113
+ while (ts.isParenthesizedExpression(node) || ts.isAsExpression(node)
114
+ || ts.isTypeAssertionExpression(node) || ts.isSatisfiesExpression(node)) node = node.expression
115
+ return node
116
+ }
117
+
118
+ /** Read only static declaration data; never execute a plugin to watch it. */
119
+ function pluginConventions(file: ts.SourceFile): string[] | null {
120
+ const declarations = new Map<string, ts.Expression>()
121
+ let exported: ts.Expression | undefined
122
+ for (const statement of file.statements) {
123
+ if (ts.isVariableStatement(statement)) {
124
+ for (const declaration of statement.declarationList.declarations) {
125
+ if (ts.isIdentifier(declaration.name) && declaration.initializer) {
126
+ declarations.set(declaration.name.text, declaration.initializer)
127
+ if (declaration.name.text === 'generatorPlugins'
128
+ && statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
129
+ exported = declaration.initializer
130
+ }
131
+ }
132
+ }
133
+ } else if (ts.isExportAssignment(statement)) {
134
+ exported ??= statement.expression
135
+ } else if (ts.isImportDeclaration(statement)) {
136
+ if (!statement.importClause?.isTypeOnly) return null
137
+ } else if (!ts.isFunctionDeclaration(statement) && !ts.isInterfaceDeclaration(statement)
138
+ && !ts.isTypeAliasDeclaration(statement) && !ts.isEmptyStatement(statement)) return null
84
139
  }
85
- if (!stat.isFile()) return null
86
- const rel = path.relative(base, filePath).replace(/\\/g, '/')
87
- if (mode === 'shape') {
88
- return `file:${rel}`
140
+ if (!exported) return null
141
+ const resolve = (expression: ts.Expression, seen = new Set<string>()): ts.Expression | null => {
142
+ const node = unwrap(expression)
143
+ if (!ts.isIdentifier(node)) return node
144
+ if (seen.has(node.text)) return null
145
+ seen.add(node.text)
146
+ const value = declarations.get(node.text)
147
+ return value ? resolve(value, seen) : null
89
148
  }
90
- try {
91
- return `file:${rel}:${stat.size}:${checksum(fs.readFileSync(filePath, 'utf8'))}`
92
- } catch {
93
- return `file:${rel}:unreadable`
149
+ const plugins = resolve(exported)
150
+ if (!plugins || !ts.isArrayLiteralExpression(plugins)) return null
151
+ const conventions: string[] = []
152
+ for (const element of plugins.elements) {
153
+ const plugin = resolve(element)
154
+ if (!plugin || !ts.isObjectLiteralExpression(plugin)) return null
155
+ let convention: string | undefined
156
+ for (const property of plugin.properties) {
157
+ if (ts.isSpreadAssignment(property) || ts.isComputedPropertyName(property.name)) return null
158
+ if (property.name.getText(file).replace(/^['"]|['"]$/g, '') !== 'conventionFile') continue
159
+ const value = ts.isPropertyAssignment(property) ? resolve(property.initializer) : null
160
+ if (!value || !ts.isStringLiteralLike(value)) return null
161
+ convention = value.text
162
+ }
163
+ if (!convention) return null
164
+ conventions.push(convention)
94
165
  }
166
+ return conventions
95
167
  }
96
168
 
97
- function addFileRecord(
98
- records: string[],
99
- prefix: string,
100
- filePath: string,
101
- base: string,
102
- mode: 'content' | 'shape',
103
- ): void {
104
- const record = fileRecord(filePath, base, mode)
105
- if (record) records.push(`${prefix}:${record}`)
169
+ /** `null` when the page exports metadata (content fingerprint applies); otherwise its default-export marker. */
170
+ function pageFingerprint(parsed: ts.SourceFile): string | null {
171
+ const metadata = parsed.statements.some((statement) => {
172
+ if (ts.isExportDeclaration(statement)) {
173
+ return !statement.exportClause || (ts.isNamedExports(statement.exportClause)
174
+ && statement.exportClause.elements.some((element) => element.name.text === 'metadata'))
175
+ }
176
+ if (!ts.canHaveModifiers(statement)
177
+ || !ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) return false
178
+ if (ts.isVariableStatement(statement)) {
179
+ return statement.declarationList.declarations.some((declaration) => /\bmetadata\b/.test(declaration.name.getText(parsed)))
180
+ }
181
+ return (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name?.text === 'metadata'
182
+ })
183
+ if (metadata) return null
184
+ const hasDefault = parsed.statements.some((statement) =>
185
+ (ts.isExportAssignment(statement) && !statement.isExportEquals)
186
+ || (ts.canHaveModifiers(statement) && ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword))
187
+ || (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)
188
+ && statement.exportClause.elements.some((element) => element.name.text === 'default')),
189
+ )
190
+ return `page:default:${hasDefault}`
106
191
  }
107
192
 
108
- function resolveCodeFile(base: string, relativePath: string): string | null {
109
- const stripped = stripModuleCodeExtension(relativePath)
110
- const candidates = MODULE_CODE_EXTENSIONS.map((extension) => `${stripped}${extension}`)
111
- for (const candidate of candidates) {
112
- const filePath = path.join(base, ...candidate.split('/'))
113
- if (fs.existsSync(filePath)) return filePath
193
+ const SUPERVISOR_OVERRIDE_CALLS = ['applyWorkerOverrides', 'applyCliOverrides']
194
+
195
+ function declaresSupervisorOverride(parsed: ts.SourceFile): boolean {
196
+ const direct = new Set<string>()
197
+ const namespaces = new Set<string>()
198
+ for (const statement of parsed.statements) {
199
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteralLike(statement.moduleSpecifier)
200
+ || statement.moduleSpecifier.text !== '@open-mercato/shared/modules/overrides') continue
201
+ const bindings = statement.importClause?.namedBindings
202
+ if (bindings && ts.isNamespaceImport(bindings)) namespaces.add(bindings.name.text)
203
+ if (bindings && ts.isNamedImports(bindings)) {
204
+ for (const element of bindings.elements) {
205
+ if (SUPERVISOR_OVERRIDE_CALLS.includes(element.propertyName?.text ?? element.name.text)) direct.add(element.name.text)
206
+ }
207
+ }
208
+ }
209
+ let found = false
210
+ const visit = (node: ts.Node): void => {
211
+ if (ts.isCallExpression(node)) {
212
+ const expression = node.expression
213
+ if (ts.isIdentifier(expression) && direct.has(expression.text)) found = true
214
+ if (ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression)
215
+ && namespaces.has(expression.expression.text)
216
+ && SUPERVISOR_OVERRIDE_CALLS.includes(expression.name.text)) found = true
217
+ }
218
+ if (!found) ts.forEachChild(node, visit)
114
219
  }
115
- return null
220
+ visit(parsed)
221
+ return found
116
222
  }
117
223
 
118
- function resolveRuntimeCounterpart(
119
- pkgBase: string,
120
- sourceBase: string,
121
- sourceFile: string,
122
- ): string | null {
123
- if (sourceBase === pkgBase) return null
124
- const relativePath = path.relative(sourceBase, sourceFile).replace(/\\/g, '/')
125
- return resolveCodeFile(pkgBase, relativePath)
224
+ /** Module specifiers evaluated at load time; `uncertain` marks a non-literal import()/require(). */
225
+ function staticImports(parsed: ts.SourceFile): { specifiers: string[]; uncertain: boolean } {
226
+ const specifiers: string[] = []
227
+ let uncertain = false
228
+ const visit = (node: ts.Node): void => {
229
+ // Handler/component bodies are not evaluated to discover registrations.
230
+ // Static imports are still tracked, including imports used by metadata.
231
+ if (ts.isFunctionLike(node)) return
232
+ if (ts.isImportDeclaration(node)) {
233
+ if (node.importClause?.isTypeOnly) return
234
+ const bindings = node.importClause?.namedBindings
235
+ if (!node.importClause?.name && bindings && ts.isNamedImports(bindings)
236
+ && bindings.elements.length > 0 && bindings.elements.every((element) => element.isTypeOnly)) return
237
+ if (ts.isStringLiteralLike(node.moduleSpecifier)) specifiers.push(node.moduleSpecifier.text)
238
+ return
239
+ }
240
+ if (ts.isExportDeclaration(node) && !node.isTypeOnly && node.moduleSpecifier
241
+ && ts.isStringLiteralLike(node.moduleSpecifier)) specifiers.push(node.moduleSpecifier.text)
242
+ if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword
243
+ || (ts.isIdentifier(node.expression) && node.expression.text === 'require'))) {
244
+ const argument = node.arguments[0]
245
+ if (argument && ts.isStringLiteralLike(argument)) specifiers.push(argument.text)
246
+ else uncertain = true
247
+ }
248
+ ts.forEachChild(node, visit)
249
+ }
250
+ visit(parsed)
251
+ return { specifiers, uncertain }
126
252
  }
127
253
 
128
- function hasInlinePageMetadata(filePath: string): boolean {
129
- try {
130
- const source = fs.readFileSync(filePath, 'utf8')
131
- return /\bexport\s+(?:const|let|var|function|class)\s+metadata\b/.test(source)
132
- || /\bexport\s+\{[^}]*\bmetadata\b[^}]*\}/.test(source)
133
- } catch {
134
- return false
254
+ class SnapshotCollector {
255
+ readonly records = new Map<string, GenerateWatchRecord>()
256
+ readonly fullReasons = new Set<string>()
257
+ private readonly stats = new Map<string, fs.Stats | null>()
258
+ private readonly identities = new Map<string, string | null>()
259
+ readonly uncertainDependencies = new Set<string>()
260
+ readonly uncertainPluginDescriptors = new Set<string>()
261
+ private readonly dependencySeeds = new Map<string, Map<string, InputKind>>()
262
+ readonly inspectedCachePaths = new Set<string>()
263
+ private readonly sources = new Map<string, string>()
264
+ private readonly parsedFiles = new Map<string, ts.SourceFile>()
265
+
266
+ constructor(private readonly cache: GenerateWatchStructureCacheState) {}
267
+
268
+ private identity(file: string): string | null {
269
+ if (!this.identities.has(file)) this.stat(file)
270
+ return this.identities.get(file) ?? null
135
271
  }
136
- }
137
272
 
138
- function addConventionRecords(records: string[], roots: ModuleRoots): void {
139
- const packageSourceBase = resolveStandaloneSourceMirrorBase(roots.pkgBase) ?? roots.pkgBase
140
- for (const base of [roots.pkgBase, roots.appBase]) {
141
- records.push(`module-root:${base}:${fs.existsSync(base) ? 'present' : 'missing'}`)
142
- }
143
- if (packageSourceBase !== roots.pkgBase) {
144
- records.push(
145
- `module-root:${packageSourceBase}:${fs.existsSync(packageSourceBase) ? 'present' : 'missing'}`,
146
- )
147
- }
148
-
149
- for (const relativePath of STRUCTURAL_CONVENTION_FILES) {
150
- const appFile = resolveCodeFile(roots.appBase, relativePath)
151
- if (appFile) {
152
- addFileRecord(records, 'convention:app', appFile, roots.appBase, 'content')
153
- continue
154
- }
155
-
156
- const sourceFile = resolveCodeFile(packageSourceBase, relativePath)
157
- if (!sourceFile) {
158
- const runtimeFile = packageSourceBase === roots.pkgBase
159
- ? null
160
- : resolveCodeFile(roots.pkgBase, relativePath)
161
- if (runtimeFile) {
162
- addFileRecord(records, 'convention:package-runtime', runtimeFile, roots.pkgBase, 'content')
163
- } else {
164
- records.push(`convention:missing:${relativePath}`)
165
- }
166
- continue
273
+ private seedDependency(file: string, kind: InputKind): void {
274
+ const identity = `${kind.category}:${kind.extensionId ?? ''}`
275
+ const kinds = this.dependencySeeds.get(file) ?? new Map<string, InputKind>()
276
+ kinds.set(identity, kind)
277
+ this.dependencySeeds.set(file, kinds)
278
+ }
279
+
280
+ stat(file: string): fs.Stats | null {
281
+ if (this.stats.has(file)) return this.stats.get(file) ?? null
282
+ try {
283
+ const stat = fs.statSync(file)
284
+ const identity = [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(':')
285
+ this.stats.set(file, stat)
286
+ this.identities.set(file, identity)
287
+ return stat
288
+ } catch (error) {
289
+ if (!isMissing(error)) this.fullReasons.add(`Cannot inspect generator input: ${file}`)
290
+ this.stats.set(file, null)
291
+ this.identities.set(file, null)
292
+ return null
167
293
  }
294
+ }
168
295
 
169
- const packagePrefix = packageSourceBase === roots.pkgBase ? 'package' : 'package-source'
170
- addFileRecord(records, `convention:${packagePrefix}`, sourceFile, packageSourceBase, 'content')
171
- const runtimeFile = resolveRuntimeCounterpart(roots.pkgBase, packageSourceBase, sourceFile)
172
- if (runtimeFile) {
173
- addFileRecord(records, 'convention:package-runtime', runtimeFile, roots.pkgBase, 'content')
174
- } else if (packageSourceBase !== roots.pkgBase) {
175
- records.push(`convention:package-runtime:missing:${relativePath}`)
296
+ /** Stat-keyed cache entry for a readable file; unchanged identities are never re-read. */
297
+ entry(file: string): CachedStructureFile | null {
298
+ const stat = this.stat(file)
299
+ const identity = this.identity(file)
300
+ if (!stat?.isFile() || !identity) {
301
+ this.fullReasons.add(`Cannot read generator input: ${file}`)
302
+ return null
176
303
  }
304
+ this.inspectedCachePaths.add(file)
305
+ const cached = this.cache.files.get(file)
306
+ if (cached?.identity === identity) return cached
307
+ const source = this.readSource(file)
308
+ if (source === null) return null
309
+ const entry: CachedStructureFile = { identity, fingerprint: checksum(source) }
310
+ this.cache.files.set(file, entry)
311
+ return entry
177
312
  }
178
- }
179
313
 
180
- function addScannedRecords(records: string[], roots: ModuleRoots): void {
181
- const packageSourceBase = resolveStandaloneSourceMirrorBase(roots.pkgBase) ?? roots.pkgBase
182
- for (const config of CONTENT_SENSITIVE_SCAN_CONFIGS) {
183
- for (const scanned of scanModuleDir(roots, config)) {
184
- const base = scanned.fromApp ? roots.appBase : packageSourceBase
185
- const filePath = path.join(base, ...config.folder.split('/'), ...scanned.relPath.split('/'))
186
- let sourceOrigin = 'app'
187
- if (!scanned.fromApp) {
188
- sourceOrigin = packageSourceBase === roots.pkgBase ? 'package' : 'package-source'
314
+ private readSource(file: string): string | null {
315
+ const known = this.sources.get(file)
316
+ if (known !== undefined) return known
317
+ try {
318
+ const source = fs.readFileSync(file, 'utf8')
319
+ this.sources.set(file, source)
320
+ return source
321
+ } catch {
322
+ this.fullReasons.add(`Cannot read generator input: ${file}`)
323
+ return null
324
+ }
325
+ }
326
+
327
+ /** Capture-local AST for a file whose cached facts are missing; parse failures are cached per identity. */
328
+ parsed(file: string, entry: CachedStructureFile): ts.SourceFile | null {
329
+ if (entry.parseFailed) {
330
+ this.fullReasons.add(`Cannot parse generator input: ${file}`)
331
+ return null
332
+ }
333
+ const known = this.parsedFiles.get(file)
334
+ if (known) return known
335
+ const source = this.readSource(file)
336
+ if (source === null) return null
337
+ let parsed: ts.SourceFile
338
+ try {
339
+ parsed = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true)
340
+ } catch {
341
+ this.fullReasons.add(`Cannot parse generator input: ${file}`)
342
+ return null
343
+ }
344
+ const diagnostics = (parsed as ts.SourceFile & { parseDiagnostics?: readonly ts.Diagnostic[] }).parseDiagnostics
345
+ if (diagnostics?.length) {
346
+ entry.parseFailed = true
347
+ this.fullReasons.add(`Cannot parse generator input: ${file}`)
348
+ return null
349
+ }
350
+ this.parsedFiles.set(file, parsed)
351
+ return parsed
352
+ }
353
+
354
+ record(key: string, file: string, kind: InputKind, fingerprint: string): void {
355
+ this.records.set(key, { key, path: file, ...kind, fingerprint })
356
+ }
357
+
358
+ file(key: string, file: string, kind: InputKind, mode: 'content' | 'page' | 'membership' | 'stat' = 'content'): void {
359
+ if (!this.stat(file)?.isFile()) return
360
+ if (mode === 'membership') {
361
+ this.record(key, file, kind, 'present')
362
+ return
363
+ }
364
+ if (mode === 'stat') {
365
+ this.record(key, file, kind, this.identity(file) ?? 'present')
366
+ return
367
+ }
368
+ const entry = this.entry(file)
369
+ if (!entry) {
370
+ this.record(key, file, kind, 'unreadable')
371
+ return
372
+ }
373
+ if (mode === 'page') {
374
+ if (entry.pageFingerprint === undefined) {
375
+ const parsed = this.parsed(file, entry)
376
+ if (!parsed) {
377
+ this.record(key, file, kind, 'unparseable')
378
+ return
379
+ }
380
+ entry.pageFingerprint = pageFingerprint(parsed)
381
+ }
382
+ if (entry.pageFingerprint !== null) {
383
+ this.record(key, file, kind, entry.pageFingerprint)
384
+ return
189
385
  }
190
- addFileRecord(records, `${config.folder}:${sourceOrigin}`, filePath, base, 'content')
191
-
192
- if (!scanned.fromApp && packageSourceBase !== roots.pkgBase) {
193
- const runtimeFile = resolveRuntimeCounterpart(roots.pkgBase, packageSourceBase, filePath)
194
- if (runtimeFile) {
195
- addFileRecord(
196
- records,
197
- `${config.folder}:package-runtime`,
198
- runtimeFile,
199
- roots.pkgBase,
200
- 'content',
201
- )
202
- } else {
203
- records.push(`${config.folder}:package-runtime:missing:${scanned.relPath}`)
386
+ }
387
+ this.record(key, file, kind, entry.fingerprint)
388
+ if (/\.[cm]?[jt]sx?$/.test(file)) this.seedDependency(file, kind)
389
+ }
390
+
391
+ codeFile(base: string, relativePath: string): string | null {
392
+ const stripped = stripModuleCodeExtension(relativePath)
393
+ const candidates = [relativePath, ...MODULE_CODE_EXTENSIONS.map((extension) => `${stripped}${extension}`)]
394
+ for (const candidate of candidates) {
395
+ const file = path.join(base, candidate)
396
+ if (this.stat(file)?.isFile()) return file
397
+ }
398
+ return null
399
+ }
400
+
401
+ scan(roots: ModuleRoots, config: ScanConfig): ScannedFile[] {
402
+ try {
403
+ return scanModuleDir(roots, config)
404
+ } catch {
405
+ this.fullReasons.add(`Cannot scan generator inputs: ${roots.appBase}, ${roots.pkgBase}/${config.folder}`)
406
+ return []
407
+ }
408
+ }
409
+
410
+ entries(directory: string): fs.Dirent[] {
411
+ if (!this.stat(directory)?.isDirectory()) return []
412
+ try {
413
+ return fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))
414
+ } catch {
415
+ this.fullReasons.add(`Cannot scan generator inputs: ${directory}`)
416
+ return []
417
+ }
418
+ }
419
+
420
+ pair(identity: string, roots: ModuleRoots, relativePath: string, kind: InputKind, mode: 'content' | 'page' = 'content'): string[] {
421
+ const sourceBase = resolveStandaloneSourceMirrorBase(roots.pkgBase) ?? roots.pkgBase
422
+ const app = this.codeFile(roots.appBase, relativePath)
423
+ const source = app ?? this.codeFile(sourceBase, relativePath)
424
+ // Conventions retain stale compiled inputs after source deletion. Directory
425
+ // scans still enumerate only the authoritative source mirror before pairing.
426
+ const runtime = !app && sourceBase !== roots.pkgBase
427
+ ? this.codeFile(roots.pkgBase, stripModuleCodeExtension(relativePath))
428
+ : source
429
+ const primary = source ?? runtime
430
+ if (!primary) return []
431
+ const logical = stripModuleCodeExtension(relativePath).replace(/\\/g, '/')
432
+ const key = `${identity}:${kind.category}:${kind.extensionId ?? ''}:${logical}`
433
+ if (source) this.file(`${key}:source`, source, kind, mode)
434
+ if (runtime && runtime !== source) this.file(`${key}:runtime`, runtime, kind, mode)
435
+ // Physical ownership is part of the fingerprint even for identical bytes.
436
+ this.record(`${key}:authority`, primary, kind, JSON.stringify([source, runtime]))
437
+ return source && runtime && runtime !== source ? [source, runtime] : [primary]
438
+ }
439
+
440
+ tree(identity: string, directory: string, kind: InputKind, skipTests = true): void {
441
+ for (const entry of this.entries(directory)) {
442
+ if (skipTests && (entry.name === '__tests__' || entry.name === '__mocks__')) continue
443
+ const file = path.join(directory, entry.name)
444
+ if (entry.isDirectory()) this.tree(identity, file, kind, skipTests)
445
+ else if (entry.isFile()) this.file(`${identity}:${file}`, file, kind)
446
+ }
447
+ }
448
+
449
+ supervisor(appSource: string): void {
450
+ const pending = [appSource]
451
+ let found = false
452
+ while (pending.length > 0 && !found) {
453
+ const directory = pending.pop()!
454
+ for (const entry of this.entries(directory)) {
455
+ const file = path.join(directory, entry.name)
456
+ if (entry.isDirectory()) {
457
+ if (entry.name !== '__tests__' && entry.name !== 'node_modules') pending.push(file)
458
+ continue
459
+ }
460
+ if (!/\.[cm]?tsx?$/.test(entry.name) || /(?:^|\.)test\.[cm]?tsx?$/.test(entry.name)) continue
461
+ const cached = this.entry(file)
462
+ if (!cached) continue
463
+ if (cached.supervisorOverride === undefined) {
464
+ if (!this.readSource(file)?.includes('@open-mercato/shared/modules/overrides')) {
465
+ cached.supervisorOverride = false
466
+ continue
467
+ }
468
+ const parsed = this.parsed(file, cached)
469
+ if (!parsed) continue
470
+ cached.supervisorOverride = declaresSupervisorOverride(parsed)
471
+ }
472
+ if (cached.supervisorOverride) {
473
+ found = true
474
+ break
204
475
  }
205
476
  }
206
477
  }
478
+ this.record('supervisor-overrides', appSource, { category: 'registry-convention', extensionId: 'supervisor' }, String(found))
207
479
  }
208
480
 
209
- for (const config of ROUTE_SHAPE_SCAN_CONFIGS) {
210
- for (const scanned of scanModuleDir(roots, config)) {
211
- const base = scanned.fromApp ? roots.appBase : packageSourceBase
212
- const folderPath = path.join(base, ...config.folder.split('/'))
213
- const filePath = path.join(folderPath, ...scanned.relPath.split('/'))
214
- let sourceOrigin = 'app'
215
- if (!scanned.fromApp) {
216
- sourceOrigin = packageSourceBase === roots.pkgBase ? 'package' : 'package-source'
481
+ dependencies(appSource: string): void {
482
+ const visited = new Set<string>()
483
+ const pending = [...this.dependencySeeds]
484
+ .flatMap(([file, kinds]) => [...kinds.entries()].map(([identity, kind]) => ({ file, identity, kind })))
485
+ .sort((left, right) => right.file.localeCompare(left.file) || right.identity.localeCompare(left.identity))
486
+ while (pending.length > 0) {
487
+ const { file, identity, kind } = pending.pop()!
488
+ const visitKey = `${identity}:${file}`
489
+ if (visited.has(visitKey)) continue
490
+ visited.add(visitKey)
491
+ const cached = this.entry(file)
492
+ if (!cached) continue
493
+ if (!cached.imports) {
494
+ const parsed = this.parsed(file, cached)
495
+ if (!parsed) continue
496
+ cached.imports = staticImports(parsed)
217
497
  }
218
- addFileRecord(
219
- records,
220
- `${config.folder}:${sourceOrigin}`,
221
- filePath,
222
- base,
223
- hasInlinePageMetadata(filePath) ? 'content' : 'shape',
224
- )
225
-
226
- let runtimeFile: string | null = null
227
- if (!scanned.fromApp && packageSourceBase !== roots.pkgBase) {
228
- runtimeFile = resolveRuntimeCounterpart(roots.pkgBase, packageSourceBase, filePath)
229
- if (runtimeFile) {
230
- addFileRecord(
231
- records,
232
- `${config.folder}:package-runtime`,
233
- runtimeFile,
234
- roots.pkgBase,
235
- hasInlinePageMetadata(runtimeFile) ? 'content' : 'shape',
236
- )
237
- } else {
238
- records.push(`${config.folder}:package-runtime:missing:${scanned.relPath}`)
498
+ if (cached.imports.uncertain) this.uncertainDependencies.add(file)
499
+ const imports = cached.imports.specifiers
500
+ for (const specifier of imports) {
501
+ if (!specifier.startsWith('.') && !specifier.startsWith('@/')) continue
502
+ const target = specifier.startsWith('@/')
503
+ ? path.join(appSource, specifier.slice(2)) : path.resolve(path.dirname(file), specifier)
504
+ const resolved = this.codeFile(path.dirname(target), path.basename(target))
505
+ ?? this.codeFile(target, 'index')
506
+ const dependencyKey = `dependency:${identity}:${file}:${target}`
507
+ if (!resolved) {
508
+ // Keep an absence record so a newly supplied helper invalidates the plan.
509
+ this.record(dependencyKey, target, kind, 'missing')
510
+ continue
239
511
  }
512
+ // A generator's own outputs must not feed back into its watcher baseline.
513
+ if (resolved.includes(`${path.sep}.mercato${path.sep}`) || resolved.includes(`${path.sep}generated${path.sep}`)) continue
514
+ const fingerprint = this.entry(resolved)?.fingerprint ?? 'unreadable'
515
+ this.record(dependencyKey, resolved, kind, `${resolved}:${fingerprint}`)
516
+ if (/\.[cm]?[jt]sx?$/.test(resolved)) pending.push({ file: resolved, identity, kind })
240
517
  }
518
+ }
519
+ }
520
+ }
241
521
 
242
- const stem = stripModuleCodeExtension(path.basename(filePath))
243
- const metaCandidates = stem === 'page'
244
- ? ['page.meta', 'meta']
245
- : [`${stem}.meta`, 'meta']
246
- for (const candidate of metaCandidates) {
247
- const metaPath = resolveCodeFile(path.dirname(filePath), candidate)
248
- if (!metaPath) continue
249
- addFileRecord(records, `${config.folder}:meta:${sourceOrigin}`, metaPath, base, 'content')
250
- }
522
+ function addModule(collector: SnapshotCollector, roots: WatchRoots, index: number, plugins: Set<string>): void {
523
+ const distMarker = `${path.sep}dist${path.sep}modules${path.sep}`
524
+ const distIndex = roots.pkgBase.lastIndexOf(distMarker)
525
+ if (distIndex >= 0) {
526
+ const packageRoot = roots.pkgBase.slice(0, distIndex)
527
+ collector.stat(path.join(packageRoot, 'src', 'modules', roots.pkgBase.slice(distIndex + distMarker.length)))
528
+ }
529
+ const sourceBase = resolveStandaloneSourceMirrorBase(roots.pkgBase) ?? roots.pkgBase
530
+ const identity = `module:${index}:${roots.moduleId ?? path.basename(roots.appBase)}:${roots.appBase}:${roots.pkgBase}`
531
+ collector.record(`${identity}:roots`, roots.appBase, { category: 'configuration' }, JSON.stringify([
532
+ Object.entries(roots).sort(([left], [right]) => left.localeCompare(right)), sourceBase,
533
+ collector.stat(roots.appBase)?.isDirectory() ?? false, collector.stat(roots.pkgBase)?.isDirectory() ?? false,
534
+ ]))
535
+ const convention = (relativePath: string, kind: InputKind) => collector.pair(identity, roots, `${relativePath}.ts`, kind)
536
+ for (const relativePath of REGISTRY_CONVENTIONS) convention(relativePath, { category: 'registry-convention' })
537
+ for (const [relativePath, extensionId] of Object.entries(EXTENSION_CONVENTIONS)) {
538
+ convention(relativePath, { category: 'extension', extensionId })
539
+ }
540
+ collector.pair(identity, roots, 'widgets/payments/client.tsx', { category: 'extension', extensionId: 'registry.notifications' })
541
+ for (const category of ['cli', 'di', 'search', 'events'] as const) convention(category, { category })
542
+ convention('widgets/injection-table', { category: 'injection-widgets' })
543
+ for (const descriptor of convention('generators', { category: 'generator-plugin' })) {
544
+ const cached = collector.entry(descriptor)
545
+ if (cached && cached.pluginConventions === undefined) {
546
+ const parsed = collector.parsed(descriptor, cached)
547
+ if (parsed) cached.pluginConventions = pluginConventions(parsed)
548
+ }
549
+ const discovered = cached?.pluginConventions ?? null
550
+ if (discovered === null) collector.uncertainPluginDescriptors.add(descriptor)
551
+ else for (const file of discovered) plugins.add(file)
552
+ }
251
553
 
252
- if (runtimeFile) {
253
- for (const candidate of metaCandidates) {
254
- const runtimeMetaPath = resolveCodeFile(path.dirname(runtimeFile), candidate)
255
- if (!runtimeMetaPath) continue
256
- addFileRecord(
257
- records,
258
- `${config.folder}:meta:package-runtime`,
259
- runtimeMetaPath,
260
- roots.pkgBase,
261
- 'content',
262
- )
554
+ // Entity generators use direct app/package candidates, including legacy db and
555
+ // override/schema fallbacks, rather than resolveModuleFile's source authority.
556
+ for (const base of new Set([roots.appBase, roots.pkgBase, sourceBase])) {
557
+ for (const directory of ['data', 'db']) {
558
+ for (const stem of ['entities.override', 'entities', 'schema']) {
559
+ for (const extension of MODULE_CODE_EXTENSIONS) {
560
+ const file = path.join(base, directory, `${stem}${extension}`)
561
+ collector.file(`${identity}:entities:${file}`, file, { category: 'entities' })
263
562
  }
264
563
  }
265
564
  }
266
565
  }
566
+ if (distIndex >= 0) {
567
+ const packageRoot = roots.pkgBase.slice(0, distIndex)
568
+ const direct = path.join(packageRoot, 'generated')
569
+ collector.record(`${identity}:package-entities-direct-root`, direct, { category: 'entities' },
570
+ collector.stat(direct)?.isDirectory() ? 'directory' : 'missing')
571
+ const generated = collector.stat(direct)?.isDirectory() ? direct : path.join(packageRoot, 'dist', 'generated')
572
+ collector.record(`${identity}:package-entities-root`, generated, { category: 'entities' }, generated)
573
+ for (const extension of ['.ts', '.js']) {
574
+ const ids = path.join(generated, `entities.ids.generated${extension}`)
575
+ collector.file(`${identity}:package-entities:${ids}`, ids, { category: 'entities' })
576
+ for (const entry of collector.entries(path.join(generated, 'entities'))) {
577
+ if (!entry.isDirectory()) continue
578
+ const fields = path.join(generated, 'entities', entry.name, `index${extension}`)
579
+ collector.file(`${identity}:package-entities:${fields}`, fields, { category: 'entities' })
580
+ }
581
+ }
582
+ }
583
+ const scans: Array<[ScanConfig, GenerateWatchCategory]> = [
584
+ [SCAN_CONFIGS.apiRoutes, 'api-route'], [SCAN_CONFIGS.apiPlainFiles, 'api-route'],
585
+ ...LEGACY_API_SCAN_CONFIGS.map((config): [ScanConfig, GenerateWatchCategory] => [config, 'api-route']),
586
+ [COMMAND_SCAN_CONFIG, 'commands'], [SCAN_CONFIGS.subscribers, 'subscribers'],
587
+ [SCAN_CONFIGS.workers, 'workers'], [SCAN_CONFIGS.dashboardWidgets, 'dashboard-widgets'],
588
+ [SCAN_CONFIGS.injectionWidgets, 'injection-widgets'],
589
+ [SCAN_CONFIGS.frontendPages, 'frontend-page'], [SCAN_CONFIGS.backendPages, 'backend-page'],
590
+ ]
591
+ for (const [config, category] of scans) {
592
+ for (const scanned of collector.scan(roots, config)) {
593
+ const relativePath = `${config.folder}/${scanned.relPath}`
594
+ // Exact conventions in route/page directories are not route registrations.
595
+ if (EXTENSION_CONVENTIONS[stripModuleCodeExtension(relativePath)]) continue
596
+ const page = category === 'frontend-page' || category === 'backend-page'
597
+ const files = collector.pair(identity, roots, relativePath, { category }, page ? 'page' : 'content')
598
+ if (!page) continue
599
+ for (const file of files) {
600
+ const stem = stripModuleCodeExtension(path.basename(file))
601
+ for (const candidate of [stem === 'page' ? 'page.meta' : `${stem}.meta`, 'meta']) {
602
+ const metadata = collector.codeFile(path.dirname(file), candidate)
603
+ if (metadata) collector.file(`${identity}:${category}:metadata:${metadata}`, metadata, { category })
604
+ }
605
+ }
606
+ }
607
+ }
608
+ for (const base of new Set([sourceBase, roots.appBase])) {
609
+ const directory = path.join(base, 'i18n')
610
+ for (const entry of collector.entries(directory)) {
611
+ if (!entry.isFile() || !/^[a-zA-Z0-9][a-zA-Z0-9_-]*\.json$/.test(entry.name)) continue
612
+ const file = path.join(directory, entry.name)
613
+ collector.file(`${identity}:i18n:${file}`, file, { category: 'i18n' }, 'membership')
614
+ if (base === sourceBase && sourceBase !== roots.pkgBase) {
615
+ const runtime = path.join(roots.pkgBase, 'i18n', entry.name)
616
+ collector.file(`${identity}:i18n:runtime:${runtime}`, runtime, { category: 'i18n' }, 'membership')
617
+ }
618
+ }
619
+ collector.tree(`${identity}:agents`, path.join(base, 'agents'), { category: 'extension', extensionId: 'registry.agent-files' })
620
+ }
267
621
  }
268
622
 
269
- export function calculateGenerateWatchStructureChecksum(options: {
270
- modulesFile: string
271
- moduleRoots: ModuleRoots[]
272
- }): string {
273
- const records: string[] = []
274
- const modulesRecord = fileRecord(options.modulesFile, path.dirname(options.modulesFile), 'content')
275
- records.push(modulesRecord ?? `missing:${options.modulesFile}`)
623
+ export function collectGenerateWatchStructureSnapshot(
624
+ options: GenerateWatchStructureOptions,
625
+ cache?: GenerateWatchStructureCache,
626
+ ): GenerateWatchSnapshot {
627
+ const cacheState = cache ? cacheStates.get(cache) : { files: new Map<string, CachedStructureFile>() }
628
+ if (!cacheState) throw new TypeError('Invalid generate watch structure cache')
629
+ const collector = new SnapshotCollector(cacheState)
630
+ for (const reason of options.webResearchAdapterFullReasons ?? []) collector.fullReasons.add(reason)
631
+ collector.file(`configuration:${options.modulesFile}`, options.modulesFile, { category: 'configuration' })
632
+ const plugins = new Set<string>()
633
+ options.moduleRoots.forEach((roots, index) => addModule(collector, roots, index, plugins))
634
+ options.moduleRoots.forEach((roots, index) => {
635
+ const identity = `module:${index}:${roots.moduleId ?? path.basename(roots.appBase)}:${roots.appBase}:${roots.pkgBase}`
636
+ for (const relativePath of plugins) collector.pair(identity, roots, relativePath, { category: 'generator-plugin' })
637
+ })
638
+ const knownInputs = new Map<string, GenerateWatchRecord>()
639
+ for (const record of collector.records.values()) {
640
+ if (record.category !== 'configuration') knownInputs.set(record.path, record)
641
+ }
642
+ const ordered = (inputs: readonly string[] | undefined) =>
643
+ [...new Set(inputs ?? [])].sort((left, right) => left < right ? -1 : left > right ? 1 : 0)
644
+ for (const input of ordered(options.additionalInputs)) {
645
+ if (knownInputs.has(input)) continue
646
+ const stat = collector.stat(input)
647
+ if (stat?.isFile()) collector.file(`configuration:${input}`, input, { category: 'configuration' })
648
+ else collector.record(`configuration:${input}`, input, { category: 'configuration' }, stat?.isDirectory() ? 'directory' : 'missing')
649
+ }
650
+ const addSpecializedInputs = (
651
+ inputs: readonly string[] | undefined,
652
+ kind: InputKind,
653
+ keyPrefix: string,
654
+ mode: 'content' | 'stat' = 'content',
655
+ ) => {
656
+ for (const input of ordered(inputs)) {
657
+ const stat = collector.stat(input)
658
+ if (stat?.isFile()) collector.file(`${keyPrefix}:${input}`, input, kind, mode)
659
+ else collector.record(`${keyPrefix}:${input}`, input, kind, stat?.isDirectory() ? 'directory' : 'missing')
660
+ }
661
+ }
662
+ addSpecializedInputs(options.openapiInputs, { category: 'openapi' }, 'openapi-input')
663
+ addSpecializedInputs(
664
+ options.webResearchAdapterInputs,
665
+ { category: 'web-research-adapters' },
666
+ 'web-research-adapter-input',
667
+ 'stat',
668
+ )
669
+ collector.supervisor(path.dirname(options.modulesFile))
670
+ collector.dependencies(path.dirname(options.modulesFile))
671
+ // A dynamic descriptor is valid source, not a transient failed capture. Until
672
+ // its dependencies can be proven, watch all potential module contributions.
673
+ // Changes require a full suite, but an unchanged successful baseline is clean.
674
+ if (collector.uncertainPluginDescriptors.size > 0 || collector.uncertainDependencies.size > 0) {
675
+ const category = collector.uncertainPluginDescriptors.size > 0 ? 'generator-plugin' : 'unknown'
676
+ for (const roots of options.moduleRoots) {
677
+ for (const base of new Set([roots.appBase, roots.pkgBase, resolveStandaloneSourceMirrorBase(roots.pkgBase)])) {
678
+ if (base) collector.tree(`uncertain-dependencies:${base}`, base, { category }, false)
679
+ }
680
+ }
681
+ for (const descriptor of collector.uncertainPluginDescriptors) {
682
+ collector.record(`uncertain-plugin:${descriptor}`, descriptor, { category: 'generator-plugin' }, 'unresolved-conventions')
683
+ }
684
+ for (const dependency of collector.uncertainDependencies) {
685
+ collector.record(`uncertain-dependency:${dependency}`, dependency, { category: 'unknown' }, 'unresolved-import')
686
+ }
687
+ }
688
+ const records = new Map([...collector.records].sort(([left], [right]) => left.localeCompare(right)))
689
+ const fullReasons = [...collector.fullReasons].sort((left, right) => left < right ? -1 : left > right ? 1 : 0)
690
+ if (fullReasons.length === 0) {
691
+ for (const cachedPath of cacheState.files.keys()) {
692
+ if (!collector.inspectedCachePaths.has(cachedPath)) cacheState.files.delete(cachedPath)
693
+ }
694
+ }
695
+ return {
696
+ checksum: checksum(JSON.stringify([[...records.values()], fullReasons])),
697
+ records,
698
+ fullReasons,
699
+ }
700
+ }
276
701
 
277
- for (const roots of options.moduleRoots) {
278
- const moduleRecords: string[] = []
279
- addConventionRecords(moduleRecords, roots)
280
- addScannedRecords(moduleRecords, roots)
281
- const rootIdentity = moduleRootIdentity(roots)
282
- records.push(...moduleRecords.map((record) => `${rootIdentity}:${record}`))
702
+ export function diffGenerateWatchStructureSnapshots(
703
+ previous: GenerateWatchSnapshot,
704
+ next: GenerateWatchSnapshot,
705
+ ): GenerateWatchChange[] {
706
+ const changes: GenerateWatchChange[] = []
707
+ for (const key of [...new Set([...previous.records.keys(), ...next.records.keys()])].sort((left, right) => left < right ? -1 : left > right ? 1 : 0)) {
708
+ const before = previous.records.get(key)
709
+ const after = next.records.get(key)
710
+ if (before && after && before.fingerprint === after.fingerprint && before.path === after.path
711
+ && before.category === after.category && before.extensionId === after.extensionId) continue
712
+ const record = after ?? before!
713
+ changes.push({
714
+ key, kind: !before ? 'add' : !after ? 'delete' : 'change',
715
+ category: record.category, path: record.path,
716
+ ...(record.extensionId ? { extensionId: record.extensionId } : {}),
717
+ })
283
718
  }
719
+ return changes
720
+ }
284
721
 
285
- return checksum(records.sort((a, b) => a.localeCompare(b)).join('\n'))
722
+ /** Legacy callers intentionally receive only the opaque snapshot checksum. */
723
+ export function calculateGenerateWatchStructureChecksum(options: GenerateWatchStructureOptions): string {
724
+ return collectGenerateWatchStructureSnapshot(options).checksum
286
725
  }