@open-mercato/cli 0.6.7-develop.6685.1.77c0a5591b → 0.6.7-develop.6687.1.46a258e592

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 (215) hide show
  1. package/.turbo/turbo-build.log +2 -3
  2. package/build.mjs +21 -5
  3. package/dist/agentic/claude-code/hooks/entity-migration-check.ts +32 -88
  4. package/dist/agentic/codex/enforcement-rules.md +2 -16
  5. package/dist/agentic/cursor/hooks/entity-migration-check.mjs +19 -50
  6. package/dist/agentic/cursor/rules/entity-guard.mdc +9 -21
  7. package/dist/agentic/cursor/rules/generated-guard.mdc +3 -5
  8. package/dist/agentic/cursor/rules/open-mercato.mdc +3 -29
  9. package/dist/agentic/guides/ai-workflows.md +76 -0
  10. package/dist/agentic/guides/architecture.md +107 -0
  11. package/dist/agentic/guides/backend-ui.md +80 -0
  12. package/dist/agentic/guides/contracts.md +92 -0
  13. package/dist/agentic/guides/extensions.md +104 -0
  14. package/dist/agentic/guides/integrations.md +81 -0
  15. package/dist/agentic/guides/module-facts.json +217 -81
  16. package/dist/agentic/guides/module-system.md +12 -127
  17. package/dist/agentic/guides/modules/ai_assistant.md +1 -1
  18. package/dist/agentic/guides/modules/api_docs.md +1 -1
  19. package/dist/agentic/guides/modules/api_keys.md +1 -1
  20. package/dist/agentic/guides/modules/attachments.md +2 -2
  21. package/dist/agentic/guides/modules/audit_logs.md +2 -2
  22. package/dist/agentic/guides/modules/auth.md +1 -1
  23. package/dist/agentic/guides/modules/business_rules.md +1 -1
  24. package/dist/agentic/guides/modules/catalog.md +5 -5
  25. package/dist/agentic/guides/modules/channel_gmail.md +1 -1
  26. package/dist/agentic/guides/modules/channel_imap.md +1 -1
  27. package/dist/agentic/guides/modules/checkout.md +1 -1
  28. package/dist/agentic/guides/modules/communication_channels.md +1 -1
  29. package/dist/agentic/guides/modules/configs.md +1 -1
  30. package/dist/agentic/guides/modules/content.md +1 -1
  31. package/dist/agentic/guides/modules/currencies.md +1 -1
  32. package/dist/agentic/guides/modules/customer_accounts.md +1 -1
  33. package/dist/agentic/guides/modules/customers.md +2 -2
  34. package/dist/agentic/guides/modules/dashboards.md +1 -1
  35. package/dist/agentic/guides/modules/data_sync.md +1 -1
  36. package/dist/agentic/guides/modules/dictionaries.md +1 -1
  37. package/dist/agentic/guides/modules/directory.md +1 -1
  38. package/dist/agentic/guides/modules/entities.md +2 -2
  39. package/dist/agentic/guides/modules/events.md +1 -1
  40. package/dist/agentic/guides/modules/feature_toggles.md +1 -1
  41. package/dist/agentic/guides/modules/gateway_stripe.md +1 -1
  42. package/dist/agentic/guides/modules/generators.md +1 -1
  43. package/dist/agentic/guides/modules/inbox_ops.md +1 -1
  44. package/dist/agentic/guides/modules/integrations.md +1 -1
  45. package/dist/agentic/guides/modules/messages.md +1 -1
  46. package/dist/agentic/guides/modules/notifications.md +1 -1
  47. package/dist/agentic/guides/modules/onboarding.md +1 -1
  48. package/dist/agentic/guides/modules/payment_gateways.md +1 -1
  49. package/dist/agentic/guides/modules/perspectives.md +1 -1
  50. package/dist/agentic/guides/modules/planner.md +1 -1
  51. package/dist/agentic/guides/modules/portal.md +1 -1
  52. package/dist/agentic/guides/modules/progress.md +1 -1
  53. package/dist/agentic/guides/modules/query_index.md +2 -2
  54. package/dist/agentic/guides/modules/record_locks.md +1 -1
  55. package/dist/agentic/guides/modules/resources.md +1 -1
  56. package/dist/agentic/guides/modules/sales.md +17 -17
  57. package/dist/agentic/guides/modules/scheduler.md +1 -1
  58. package/dist/agentic/guides/modules/search.md +1 -1
  59. package/dist/agentic/guides/modules/security.md +1 -1
  60. package/dist/agentic/guides/modules/shipping_carriers.md +1 -1
  61. package/dist/agentic/guides/modules/sso.md +1 -1
  62. package/dist/agentic/guides/modules/staff.md +2 -2
  63. package/dist/agentic/guides/modules/storage_s3.md +1 -1
  64. package/dist/agentic/guides/modules/sync_akeneo.md +1 -1
  65. package/dist/agentic/guides/modules/sync_excel.md +1 -1
  66. package/dist/agentic/guides/modules/system_status_overlays.md +1 -1
  67. package/dist/agentic/guides/modules/translations.md +1 -1
  68. package/dist/agentic/guides/modules/webhooks.md +2 -2
  69. package/dist/agentic/guides/modules/wms.md +2 -2
  70. package/dist/agentic/guides/modules/workflows.md +1 -1
  71. package/dist/agentic/guides/testing-debugging.md +74 -0
  72. package/dist/agentic/guides/upstream/AGENTS.md +297 -0
  73. package/dist/agentic/guides/upstream/BACKWARD_COMPATIBILITY.md +303 -0
  74. package/dist/agentic/guides/upstream/manifest.json +8 -0
  75. package/dist/agentic/shared/AGENTS.md.template +123 -311
  76. package/dist/agentic/shared/ai/agentic.config.json +1 -0
  77. package/dist/agentic/shared/ai/harness/README.md +48 -0
  78. package/dist/agentic/shared/ai/harness/RELEASE.md +57 -0
  79. package/dist/agentic/shared/ai/harness/cases.json +13487 -0
  80. package/dist/agentic/shared/ai/harness/cases.schema.json +132 -0
  81. package/dist/agentic/shared/ai/harness/fixtures/index.json +49 -0
  82. package/dist/agentic/shared/ai/harness/fixtures/seeds.json +162 -0
  83. package/dist/agentic/shared/ai/harness/generated-code-review-policy.md +20 -0
  84. package/dist/agentic/shared/ai/harness/generated-code-review-response.schema.json +43 -0
  85. package/dist/agentic/shared/ai/harness/generated-code-review-result.schema.json +110 -0
  86. package/dist/agentic/shared/ai/harness/release-matrix.json +133 -0
  87. package/dist/agentic/shared/ai/harness/release-result.schema.json +219 -0
  88. package/dist/agentic/shared/ai/harness/result.schema.json +76 -0
  89. package/dist/agentic/shared/ai/harness/routing-response.schema.json +12 -0
  90. package/dist/agentic/shared/ai/harness/target-validation-result.schema.json +73 -0
  91. package/dist/agentic/shared/ai/harness/validators.json +78 -0
  92. package/dist/agentic/shared/ai/harness/writable-ast-oracles.mjs +1768 -0
  93. package/dist/agentic/shared/ai/harness/writable-behavior-oracles.mjs +1096 -0
  94. package/dist/agentic/shared/ai/review-checklist.md +36 -0
  95. package/dist/agentic/shared/ai/skills/om-auto-review-pr/SKILL.md +4 -0
  96. package/dist/agentic/shared/ai/skills/om-backend-ui-design/SKILL.md +20 -241
  97. package/dist/agentic/shared/ai/skills/om-backend-ui-design/references/crud-surfaces.md +16 -0
  98. package/dist/agentic/shared/ai/skills/om-backend-ui-design/references/frontend-and-design-system.md +53 -0
  99. package/dist/agentic/shared/ai/skills/om-backend-ui-design/references/page-and-navigation.md +13 -0
  100. package/dist/agentic/shared/ai/skills/om-backend-ui-design/references/quality-states.md +11 -0
  101. package/dist/agentic/shared/ai/skills/om-build-workflow/SKILL.md +30 -0
  102. package/dist/agentic/shared/ai/skills/om-build-workflow/references/activity-contracts.md +12 -0
  103. package/dist/agentic/shared/ai/skills/om-build-workflow/references/durability-and-progress.md +13 -0
  104. package/dist/agentic/shared/ai/skills/om-build-workflow/references/workflow-design.md +14 -0
  105. package/dist/agentic/shared/ai/skills/om-create-ai-agent/SKILL.md +28 -0
  106. package/dist/agentic/shared/ai/skills/om-create-ai-agent/references/attachments-and-overrides.md +12 -0
  107. package/dist/agentic/shared/ai/skills/om-create-ai-agent/references/module-agents-and-tools.md +22 -0
  108. package/dist/agentic/shared/ai/skills/om-create-ai-agent/references/orchestrator-agents.md +12 -0
  109. package/dist/agentic/shared/ai/skills/om-create-ai-agent/references/surface-selector.md +19 -0
  110. package/dist/agentic/shared/ai/skills/om-data-model-design/SKILL.md +16 -601
  111. package/dist/agentic/shared/ai/skills/om-data-model-design/references/integrity-and-concurrency.md +19 -0
  112. package/dist/agentic/shared/ai/skills/om-data-model-design/references/migration-workflow.md +13 -0
  113. package/dist/agentic/shared/ai/skills/om-data-model-design/references/schema-design.md +14 -0
  114. package/dist/agentic/shared/ai/skills/om-data-model-design/references/sensitive-data.md +10 -0
  115. package/dist/agentic/shared/ai/skills/om-eject-and-customize/SKILL.md +14 -310
  116. package/dist/agentic/shared/ai/skills/om-eject-and-customize/references/decision-and-procedure.md +17 -0
  117. package/dist/agentic/shared/ai/skills/om-evolve-harness/SKILL.md +28 -0
  118. package/dist/agentic/shared/ai/skills/om-evolve-harness/references/case-template.md +89 -0
  119. package/dist/agentic/shared/ai/skills/om-evolve-harness/references/case-workflow.md +16 -0
  120. package/dist/agentic/shared/ai/skills/om-evolve-harness/references/owner-selection.md +17 -0
  121. package/dist/agentic/shared/ai/skills/om-framework-context/SKILL.md +25 -0
  122. package/dist/agentic/shared/ai/skills/om-framework-context/references/resolver-procedure.md +11 -0
  123. package/dist/agentic/shared/ai/skills/om-framework-context/references/skew-and-escalation.md +13 -0
  124. package/dist/agentic/shared/ai/skills/om-help/SKILL.md +15 -97
  125. package/dist/agentic/shared/ai/skills/om-help/references/delivery-workflows.md +17 -0
  126. package/dist/agentic/shared/ai/skills/om-help/references/task-families.md +20 -0
  127. package/dist/agentic/shared/ai/skills/om-implement-spec/SKILL.md +15 -156
  128. package/dist/agentic/shared/ai/skills/om-implement-spec/references/phases-and-gates.md +12 -0
  129. package/dist/agentic/shared/ai/skills/om-integration-builder/SKILL.md +24 -708
  130. package/dist/agentic/shared/ai/skills/om-integration-builder/references/package-and-activation.md +16 -0
  131. package/dist/agentic/shared/ai/skills/om-integration-builder/references/provider-families.md +14 -0
  132. package/dist/agentic/shared/ai/skills/om-integration-builder/references/security-and-reliability.md +15 -0
  133. package/dist/agentic/shared/ai/skills/om-integration-builder/references/sync-and-files.md +12 -0
  134. package/dist/agentic/shared/ai/skills/om-module-scaffold/SKILL.md +20 -820
  135. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/api-and-domain.md +19 -0
  136. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/business-one-shot-blueprints.md +107 -0
  137. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/data-and-migrations.md +12 -0
  138. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/discovery-surface-catalog.md +83 -0
  139. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/module-surfaces.md +21 -0
  140. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/planning.md +11 -0
  141. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/runtime-cache-and-queues.md +22 -0
  142. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/verification.md +13 -0
  143. package/dist/agentic/shared/ai/skills/om-system-extension/SKILL.md +19 -843
  144. package/dist/agentic/shared/ai/skills/om-system-extension/references/extension-branches.md +18 -0
  145. package/dist/agentic/shared/ai/skills/om-system-extension/references/mechanism-selector.md +25 -0
  146. package/dist/agentic/shared/ai/skills/om-system-extension/references/read-write-roundtrip.md +13 -0
  147. package/dist/agentic/shared/ai/skills/om-system-extension/references/unified-overrides.md +38 -0
  148. package/dist/agentic/shared/ai/skills/om-system-extension/references/verification.md +11 -0
  149. package/dist/agentic/shared/ai/skills/om-trim-unused-modules/SKILL.md +15 -63
  150. package/dist/agentic/shared/ai/skills/om-trim-unused-modules/references/dependency-and-redirect.md +15 -0
  151. package/dist/agentic/shared/ai/skills/om-troubleshooter/SKILL.md +16 -467
  152. package/dist/agentic/shared/ai/skills/om-troubleshooter/references/diagnosis-map.md +16 -0
  153. package/dist/agentic/shared/ai/skills/om-troubleshooter/references/regression-oracles.md +14 -0
  154. package/dist/agentic/shared/ai/skills/tiers.json +137 -20
  155. package/dist/agentic/shared/ai/skills/tiers.schema.json +52 -40
  156. package/dist/agentic/shared/scripts/agent-harness-tool-server.mjs +174 -0
  157. package/dist/agentic/shared/scripts/evaluate-agent-harness.mjs +2783 -0
  158. package/dist/agentic/shared/scripts/execution-sandbox.mjs +329 -0
  159. package/dist/agentic/shared/scripts/framework-context.mjs +894 -0
  160. package/dist/agentic/shared/scripts/install-skills.mjs +1029 -0
  161. package/dist/agentic/shared/scripts/install-skills.sh +4 -694
  162. package/dist/agentic/shared/scripts/prepare-agent-harness-fixture.mjs +222 -0
  163. package/dist/agentic/shared/scripts/run-agent-harness-release.mjs +1761 -0
  164. package/dist/lib/__integration__/TC-INT-008.spec.js +87 -8
  165. package/dist/lib/__integration__/TC-INT-008.spec.js.map +2 -2
  166. package/dist/lib/agentic-init.js +13 -3
  167. package/dist/lib/agentic-init.js.map +2 -2
  168. package/dist/lib/agentic-setup.js +418 -186
  169. package/dist/lib/agentic-setup.js.map +2 -2
  170. package/dist/lib/generators/extensions/injection-widgets.js +20 -0
  171. package/dist/lib/generators/extensions/injection-widgets.js.map +2 -2
  172. package/dist/lib/generators/module-facts-discovery.js +41 -7
  173. package/dist/lib/generators/module-facts-discovery.js.map +2 -2
  174. package/dist/lib/generators/module-facts.js +65 -17
  175. package/dist/lib/generators/module-facts.js.map +2 -2
  176. package/dist/lib/generators/module-registry.js +5 -4
  177. package/dist/lib/generators/module-registry.js.map +2 -2
  178. package/dist/lib/resolver.js +2 -0
  179. package/dist/lib/resolver.js.map +2 -2
  180. package/package.json +5 -5
  181. package/src/lib/__integration__/TC-INT-008.spec.ts +103 -8
  182. package/src/lib/__tests__/agentic-init.test.ts +41 -5
  183. package/src/lib/__tests__/agentic-setup.ownership.test.ts +380 -0
  184. package/src/lib/__tests__/injection-widget-id-validation.test.ts +184 -0
  185. package/src/lib/agentic-init.ts +15 -3
  186. package/src/lib/agentic-setup.ts +526 -224
  187. package/src/lib/generators/__tests__/module-facts.bc-guard.test.ts +6 -0
  188. package/src/lib/generators/__tests__/module-facts.customers.fixture.test.ts +1 -0
  189. package/src/lib/generators/__tests__/module-facts.discovery.test.ts +54 -10
  190. package/src/lib/generators/__tests__/module-facts.extension-hosts.test.ts +108 -0
  191. package/src/lib/generators/__tests__/module-subset.test.ts +18 -0
  192. package/src/lib/generators/extensions/injection-widgets.ts +51 -0
  193. package/src/lib/generators/module-facts-discovery.ts +58 -7
  194. package/src/lib/generators/module-facts.ts +84 -20
  195. package/src/lib/generators/module-registry.ts +8 -4
  196. package/src/lib/resolver.ts +3 -0
  197. package/dist/agentic/guides/cache.md +0 -45
  198. package/dist/agentic/guides/core.md +0 -453
  199. package/dist/agentic/guides/events.md +0 -117
  200. package/dist/agentic/guides/queue.md +0 -53
  201. package/dist/agentic/guides/search.md +0 -115
  202. package/dist/agentic/guides/shared.md +0 -108
  203. package/dist/agentic/guides/ui.md +0 -347
  204. package/dist/agentic/shared/ai/skills/om-auto-continue-pr-loop/SKILL.md +0 -27
  205. package/dist/agentic/shared/ai/skills/om-auto-create-pr-loop/SKILL.md +0 -27
  206. package/dist/agentic/shared/ai/skills/om-backend-ui-design/references/ui-components.md +0 -260
  207. package/dist/agentic/shared/ai/skills/om-data-model-design/references/mikro-orm-cheatsheet.md +0 -146
  208. package/dist/agentic/shared/ai/skills/om-help/references/skills-catalog.md +0 -84
  209. package/dist/agentic/shared/ai/skills/om-help/references/workflow-sequences.md +0 -193
  210. package/dist/agentic/shared/ai/skills/om-integration-builder/STANDALONE.md +0 -34
  211. package/dist/agentic/shared/ai/skills/om-integration-builder/references/adapter-contracts.md +0 -762
  212. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/naming-conventions.md +0 -50
  213. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/navigation-patterns.md +0 -97
  214. package/dist/agentic/shared/ai/skills/om-system-extension/references/extension-contracts.md +0 -271
  215. package/dist/agentic/shared/ai/skills/om-troubleshooter/references/diagnostic-commands.md +0 -101
@@ -0,0 +1,894 @@
1
+ #!/usr/bin/env node
2
+
3
+ import {
4
+ closeSync,
5
+ constants,
6
+ existsSync,
7
+ fstatSync,
8
+ lstatSync,
9
+ mkdirSync,
10
+ openSync,
11
+ readdirSync,
12
+ readFileSync,
13
+ realpathSync,
14
+ rmSync,
15
+ writeFileSync,
16
+ } from 'node:fs'
17
+ import { createRequire } from 'node:module'
18
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
19
+ import { spawnSync } from 'node:child_process'
20
+ import { TextDecoder } from 'node:util'
21
+
22
+ const workingDirectory = process.cwd()
23
+ const workingDirectoryStat = lstatSync(workingDirectory)
24
+ if (workingDirectoryStat.isSymbolicLink() || !workingDirectoryStat.isDirectory()) {
25
+ throw new Error('app root must be a regular directory, not a symbolic link')
26
+ }
27
+ const appRoot = realpathSync(workingDirectory)
28
+ const requireFromApp = createRequire(join(appRoot, 'package.json'))
29
+ const SEARCH_MATCH_LIMIT = 200
30
+ const INSTALLED_PACKAGE_SCAN_LIMIT = 1000
31
+ const FALLBACK_TREE_ENTRY_LIMIT = 50_000
32
+ const FALLBACK_SEARCH_BYTE_LIMIT = 64 * 1024 * 1024
33
+ const MATERIALIZATION_ENTRY_LIMIT = 10_000
34
+ const MATERIALIZATION_FILE_BYTE_LIMIT = 8 * 1024 * 1024
35
+ const MATERIALIZATION_TOTAL_BYTE_LIMIT = 64 * 1024 * 1024
36
+ const MATERIALIZATION_TEXT_EXTENSIONS = new Set([
37
+ '.cjs', '.conf', '.css', '.csv', '.cts', '.graphql', '.html', '.ini', '.js', '.json',
38
+ '.jsx', '.less', '.md', '.mdx', '.mjs', '.mts', '.prisma', '.sass', '.scss', '.sql',
39
+ '.svg', '.toml', '.ts', '.tsx', '.txt', '.xml', '.yaml', '.yml',
40
+ ])
41
+ const MATERIALIZATION_DENIED_DIRECTORIES = new Set([
42
+ '.aws', '.azure', '.git', '.gnupg', '.ssh', 'node_modules',
43
+ ])
44
+ const MATERIALIZATION_DENIED_FILES = new Set([
45
+ '.netrc', '.npmrc', '.pypirc', '.yarnrc', '.yarnrc.yml',
46
+ 'auth.json', 'credentials', 'credentials.json', 'id_dsa', 'id_ecdsa', 'id_ed25519',
47
+ 'id_rsa', 'secret.json', 'secrets.json', 'secrets.yaml', 'secrets.yml',
48
+ 'service-account.json',
49
+ ])
50
+ const MATERIALIZATION_DENIED_EXTENSIONS = new Set([
51
+ '.jks', '.key', '.keystore', '.p12', '.p8', '.pem', '.pfx',
52
+ ])
53
+ const utf8Decoder = new TextDecoder('utf-8', { fatal: true })
54
+
55
+ function fail(message) {
56
+ console.error(`framework-context: ${message}`)
57
+ process.exitCode = 2
58
+ }
59
+
60
+ function parseArgs(argv) {
61
+ const args = { json: false, materialize: true }
62
+ for (let index = 0; index < argv.length; index += 1) {
63
+ const value = argv[index]
64
+ if (value === '--json') args.json = true
65
+ else if (value === '--no-materialize') args.materialize = false
66
+ else if (value === '--root') args.root = true
67
+ else if (value === '--module') args.module = argv[++index]
68
+ else if (value.startsWith('--module=')) args.module = value.slice(9)
69
+ else if (value === '--package') args.package = argv[++index]
70
+ else if (value.startsWith('--package=')) args.package = value.slice(10)
71
+ else if (value === '--query') args.query = argv[++index]
72
+ else if (value.startsWith('--query=')) args.query = value.slice(8)
73
+ else if (value === '--help' || value === '-h') args.help = true
74
+ else throw new Error(`unknown argument: ${value}`)
75
+ }
76
+ return args
77
+ }
78
+
79
+ function assertToken(value, label, pattern) {
80
+ if (typeof value !== 'string' || !pattern.test(value)) {
81
+ throw new Error(`invalid ${label}: ${String(value)}`)
82
+ }
83
+ return value
84
+ }
85
+
86
+ function readJson(path) {
87
+ return JSON.parse(readFileSync(path, 'utf8'))
88
+ }
89
+
90
+ function parseModuleEntries() {
91
+ const modulesPath = join(appRoot, 'src', 'modules.ts')
92
+ if (!existsSync(modulesPath)) return []
93
+ const source = readFileSync(modulesPath, 'utf8')
94
+ const entries = []
95
+ const objectPattern = /\{[\s\S]*?\bid\s*:\s*['"]([^'"]+)['"][\s\S]*?\bfrom\s*:\s*['"]([^'"]+)['"][\s\S]*?\}/g
96
+ for (const match of source.matchAll(objectPattern)) {
97
+ entries.push({ id: match[1], from: match[2] })
98
+ }
99
+ return entries
100
+ }
101
+
102
+ function findPackageRoot(packageName) {
103
+ const attempts = [`${packageName}/package.json`, packageName]
104
+ for (const request of attempts) {
105
+ try {
106
+ let resolvedPath = requireFromApp.resolve(request)
107
+ if (basename(resolvedPath) === 'package.json') return realpathSync(dirname(resolvedPath))
108
+ let cursor = dirname(realpathSync(resolvedPath))
109
+ while (cursor !== dirname(cursor)) {
110
+ const manifestPath = join(cursor, 'package.json')
111
+ if (existsSync(manifestPath)) {
112
+ const manifest = readJson(manifestPath)
113
+ if (manifest.name === packageName) return realpathSync(cursor)
114
+ }
115
+ cursor = dirname(cursor)
116
+ }
117
+ } catch {
118
+ // Package export maps commonly hide package.json; try the entry point next.
119
+ }
120
+ }
121
+ return null
122
+ }
123
+
124
+ function assertInside(root, candidate, label) {
125
+ const delta = relative(root, candidate)
126
+ if (delta === '' || (!delta.startsWith(`..${sep}`) && delta !== '..' && !isAbsolute(delta))) return candidate
127
+ throw new Error(`${label} escapes ${root}`)
128
+ }
129
+
130
+ function assertStrictlyInside(root, candidate, label) {
131
+ const delta = relative(root, candidate)
132
+ if (delta !== '' && !delta.startsWith(`..${sep}`) && delta !== '..' && !isAbsolute(delta)) return candidate
133
+ throw new Error(`${label} escapes ${root}`)
134
+ }
135
+
136
+ function lstatIfPresent(candidate) {
137
+ try {
138
+ return lstatSync(candidate)
139
+ } catch (error) {
140
+ if (error?.code === 'ENOENT') return null
141
+ throw error
142
+ }
143
+ }
144
+
145
+ function assertRegularDirectory(root, candidate, label) {
146
+ const lexical = resolve(candidate)
147
+ assertInside(root, lexical, label)
148
+ const stat = lstatIfPresent(lexical)
149
+ if (!stat) return false
150
+ if (stat.isSymbolicLink()) throw new Error(`${label} must not be a symbolic link`)
151
+ if (!stat.isDirectory()) throw new Error(`${label} must be a directory`)
152
+ assertInside(root, realpathSync(lexical), label)
153
+ return true
154
+ }
155
+
156
+ function ensureDirectoryChain(root, candidate, label) {
157
+ const lexical = resolve(candidate)
158
+ assertInside(root, lexical, label)
159
+ if (!assertRegularDirectory(root, root, 'app root')) throw new Error('app root is unavailable')
160
+ const delta = relative(root, lexical)
161
+ if (!delta) return
162
+
163
+ let cursor = root
164
+ for (const component of delta.split(sep).filter(Boolean)) {
165
+ cursor = join(cursor, component)
166
+ if (assertRegularDirectory(root, cursor, `${label} parent`)) continue
167
+ try {
168
+ mkdirSync(cursor, { mode: 0o755 })
169
+ } catch (error) {
170
+ if (error?.code !== 'EEXIST') throw error
171
+ }
172
+ if (!assertRegularDirectory(root, cursor, `${label} parent`)) {
173
+ throw new Error(`failed to create ${label} parent`)
174
+ }
175
+ }
176
+ }
177
+
178
+ function writeContextFile(destination, content) {
179
+ const parent = dirname(destination)
180
+ ensureDirectoryChain(appRoot, parent, 'context output')
181
+ assertStrictlyInside(appRoot, resolve(destination), 'context output')
182
+ const flags = constants.O_CREAT
183
+ | constants.O_EXCL
184
+ | constants.O_WRONLY
185
+ | (constants.O_NOFOLLOW ?? 0)
186
+ let descriptor
187
+ try {
188
+ descriptor = openSync(destination, flags, 0o644)
189
+ writeFileSync(descriptor, content)
190
+ } catch (error) {
191
+ if (error?.code === 'EEXIST' || error?.code === 'ELOOP') {
192
+ throw new Error(`context output already exists: ${relative(appRoot, destination)}`)
193
+ }
194
+ throw error
195
+ } finally {
196
+ if (descriptor !== undefined) closeSync(descriptor)
197
+ }
198
+ const stat = lstatSync(destination)
199
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error('context output is not a regular file')
200
+ assertInside(appRoot, realpathSync(destination), 'context output')
201
+ }
202
+
203
+ function encodePackageVersion(value) {
204
+ if (
205
+ typeof value !== 'string'
206
+ || value.length === 0
207
+ || value.length > 128
208
+ || !/^[0-9A-Za-z][0-9A-Za-z._+-]*$/.test(value)
209
+ ) {
210
+ throw new Error(`invalid package version: ${String(value)}`)
211
+ }
212
+ return encodeURIComponent(value)
213
+ }
214
+
215
+ function candidatePackages(moduleId) {
216
+ const declared = parseModuleEntries().filter((entry) => entry.id === moduleId)
217
+ if (declared.length > 0) {
218
+ const providers = [...new Set(declared.map((entry) => entry.from))].sort()
219
+ if (declared.length > 1 && providers.length === 1) {
220
+ throw new Error(`module ${moduleId} is declared ${declared.length} times for ${providers[0]}`)
221
+ }
222
+ return providers
223
+ }
224
+
225
+ const appManifest = readJson(join(appRoot, 'package.json'))
226
+ const names = Object.keys({ ...appManifest.dependencies, ...appManifest.devDependencies })
227
+ .filter((name) => name.startsWith('@open-mercato/'))
228
+ return names.filter((name) => {
229
+ const root = findPackageRoot(name)
230
+ return root && (
231
+ existsSync(join(root, 'src', 'modules', moduleId))
232
+ || existsSync(join(root, 'dist', 'modules', moduleId))
233
+ )
234
+ })
235
+ }
236
+
237
+ function nearestAgentsFiles(packageRoot, sourceRoot) {
238
+ const files = []
239
+ const packageAgents = join(packageRoot, 'AGENTS.md')
240
+ if (existsSync(packageAgents)) files.push(packageAgents)
241
+ if (!sourceRoot) return files
242
+
243
+ let cursor = sourceRoot
244
+ const nested = []
245
+ while (cursor.startsWith(packageRoot)) {
246
+ const candidate = join(cursor, 'AGENTS.md')
247
+ if (existsSync(candidate) && candidate !== packageAgents) nested.unshift(candidate)
248
+ if (cursor === packageRoot) break
249
+ cursor = dirname(cursor)
250
+ }
251
+ files.push(...nested)
252
+ return [...new Set(files)]
253
+ }
254
+
255
+ function deniedMaterializationPath(relativePath, directory) {
256
+ const components = relativePath.split(sep).filter(Boolean).map((component) => component.toLowerCase())
257
+ if (components.some((component) => MATERIALIZATION_DENIED_DIRECTORIES.has(component))) return true
258
+ if (directory || components.length === 0) return false
259
+ const filename = components.at(-1)
260
+ if (filename === '.env' || filename.startsWith('.env.')) return true
261
+ if (MATERIALIZATION_DENIED_FILES.has(filename)) return true
262
+ return MATERIALIZATION_DENIED_EXTENSIONS.has(extname(filename))
263
+ }
264
+
265
+ function readMaterializationText(source, relativePath, state) {
266
+ let descriptor
267
+ try {
268
+ descriptor = openSync(source, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
269
+ const stat = fstatSync(descriptor)
270
+ if (!stat.isFile()) throw new Error(`context source contains a non-regular file: ${relativePath}`)
271
+ if (stat.size > MATERIALIZATION_FILE_BYTE_LIMIT) {
272
+ throw new Error(`context source file exceeds ${MATERIALIZATION_FILE_BYTE_LIMIT} byte limit: ${relativePath}`)
273
+ }
274
+ if (state.copiedBytes + stat.size > MATERIALIZATION_TOTAL_BYTE_LIMIT) {
275
+ throw new Error(`context source exceeds ${MATERIALIZATION_TOTAL_BYTE_LIMIT} materialized bytes`)
276
+ }
277
+ const content = readFileSync(descriptor)
278
+ if (content.includes(0)) return null
279
+ try {
280
+ utf8Decoder.decode(content)
281
+ } catch {
282
+ return null
283
+ }
284
+ if (/-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/.test(content.toString('utf8'))) return null
285
+ return content
286
+ } finally {
287
+ if (descriptor !== undefined) closeSync(descriptor)
288
+ }
289
+ }
290
+
291
+ function copyContextFile(source, destination) {
292
+ ensureDirectoryChain(appRoot, dirname(destination), 'context output')
293
+ assertStrictlyInside(appRoot, resolve(destination), 'context output')
294
+ if (lstatIfPresent(destination)) throw new Error(`context output already exists: ${relative(appRoot, destination)}`)
295
+
296
+ const sourceRoot = resolve(source)
297
+ const rootStat = lstatSync(sourceRoot)
298
+ if (rootStat.isSymbolicLink()) throw new Error('context source must not be a symbolic link')
299
+ const state = { entriesVisited: 0, copiedFiles: 0, copiedBytes: 0, omittedEntries: 0 }
300
+
301
+ function copyEntry(candidate, target, relativePath, root = false) {
302
+ state.entriesVisited += 1
303
+ if (state.entriesVisited > MATERIALIZATION_ENTRY_LIMIT) {
304
+ throw new Error(`context source exceeded ${MATERIALIZATION_ENTRY_LIMIT} filesystem entries`)
305
+ }
306
+
307
+ const stat = lstatSync(candidate)
308
+ if (stat.isSymbolicLink()) {
309
+ if (root) throw new Error('context source must not be a symbolic link')
310
+ state.omittedEntries += 1
311
+ return
312
+ }
313
+ if (stat.isDirectory()) {
314
+ if (!root && deniedMaterializationPath(relativePath, true)) {
315
+ state.omittedEntries += 1
316
+ return
317
+ }
318
+ ensureDirectoryChain(appRoot, target, 'context output')
319
+ for (const entry of readdirSync(candidate, { withFileTypes: true })
320
+ .sort((left, right) => comparePaths(left.name, right.name))) {
321
+ copyEntry(join(candidate, entry.name), join(target, entry.name), join(relativePath, entry.name))
322
+ }
323
+ return
324
+ }
325
+ if (!stat.isFile()) throw new Error(`context source contains a special filesystem entry: ${relativePath}`)
326
+ if (deniedMaterializationPath(relativePath, false)
327
+ || !MATERIALIZATION_TEXT_EXTENSIONS.has(extname(relativePath).toLowerCase())) {
328
+ state.omittedEntries += 1
329
+ return
330
+ }
331
+
332
+ const content = readMaterializationText(candidate, relativePath, state)
333
+ if (!content) {
334
+ state.omittedEntries += 1
335
+ return
336
+ }
337
+ writeContextFile(target, content)
338
+ state.copiedFiles += 1
339
+ state.copiedBytes += content.byteLength
340
+ }
341
+
342
+ copyEntry(sourceRoot, destination, basename(sourceRoot), true)
343
+ if (rootStat.isFile() && state.copiedFiles !== 1) {
344
+ throw new Error(`context source is not an allowed regular text file: ${basename(sourceRoot)}`)
345
+ }
346
+ const stat = lstatSync(destination)
347
+ if (stat.isSymbolicLink()) throw new Error('context output must not be a symbolic link')
348
+ assertInside(appRoot, realpathSync(destination), 'context output')
349
+ return state
350
+ }
351
+
352
+ function runRg(args, label, maxBuffer = 4 * 1024 * 1024) {
353
+ const result = spawnSync('rg', args, {
354
+ cwd: appRoot,
355
+ encoding: 'utf8',
356
+ maxBuffer,
357
+ })
358
+ if (result.error?.code === 'ENOENT') return null
359
+ if (result.error) throw new Error(`${label}: ${result.error.message}`)
360
+ if (result.status !== 0 && result.status !== 1) {
361
+ const detail = (result.stderr || result.stdout || '').trim()
362
+ throw new Error(`${label} (exit ${String(result.status)}): ${detail || 'unknown rg error'}`)
363
+ }
364
+ return result
365
+ }
366
+
367
+ function nulDelimitedPaths(output) {
368
+ return output.split('\0').filter(Boolean)
369
+ }
370
+
371
+ function regularFileStrictlyBelow(root, candidate, label) {
372
+ const lexicalRoot = resolve(root)
373
+ const lexical = resolve(candidate)
374
+ const canonicalRoot = realpathSync(lexicalRoot)
375
+ try {
376
+ assertStrictlyInside(lexicalRoot, lexical, label)
377
+ } catch {
378
+ assertStrictlyInside(canonicalRoot, lexical, label)
379
+ }
380
+ const stat = lstatIfPresent(lexical)
381
+ if (!stat || stat.isSymbolicLink() || !stat.isFile()) {
382
+ throw new Error(`${label} must be a regular non-symbolic file below ${lexicalRoot}`)
383
+ }
384
+ const canonical = realpathSync(lexical)
385
+ assertStrictlyInside(canonicalRoot, canonical, label)
386
+ return canonical
387
+ }
388
+
389
+ function comparePaths(left, right) {
390
+ return left < right ? -1 : left > right ? 1 : 0
391
+ }
392
+
393
+ function fallbackRegularFiles(root, label) {
394
+ const scanRoot = realpathSync(root)
395
+ const pending = [scanRoot]
396
+ const files = []
397
+ let entriesVisited = 0
398
+
399
+ while (pending.length > 0) {
400
+ const directory = pending.pop()
401
+ const entries = readdirSync(directory, { withFileTypes: true })
402
+ .sort((left, right) => comparePaths(left.name, right.name))
403
+ for (const entry of entries) {
404
+ entriesVisited += 1
405
+ if (entriesVisited > FALLBACK_TREE_ENTRY_LIMIT) {
406
+ throw new Error(`${label} exceeded ${FALLBACK_TREE_ENTRY_LIMIT} filesystem entries`)
407
+ }
408
+ const candidate = join(directory, entry.name)
409
+ const stat = lstatSync(candidate)
410
+ if (stat.isSymbolicLink()) continue
411
+ if (stat.isDirectory()) {
412
+ assertInside(scanRoot, realpathSync(candidate), label)
413
+ pending.push(candidate)
414
+ } else if (stat.isFile()) {
415
+ assertInside(scanRoot, realpathSync(candidate), label)
416
+ files.push(candidate)
417
+ }
418
+ }
419
+ }
420
+
421
+ return files.sort(comparePaths)
422
+ }
423
+
424
+ function fallbackInstalledPackageManifests(nodeModulesRoot) {
425
+ const scanRoot = realpathSync(nodeModulesRoot)
426
+ const manifests = []
427
+ const pendingNodeModules = [scanRoot]
428
+ const visitedNodeModules = new Set()
429
+ let entriesVisited = 0
430
+
431
+ function boundedDirectories(directory) {
432
+ const directories = []
433
+ for (const entry of readdirSync(directory, { withFileTypes: true })
434
+ .sort((left, right) => comparePaths(left.name, right.name))) {
435
+ entriesVisited += 1
436
+ if (entriesVisited > FALLBACK_TREE_ENTRY_LIMIT) {
437
+ throw new Error(`installed package scan failed exceeded ${FALLBACK_TREE_ENTRY_LIMIT} filesystem entries`)
438
+ }
439
+ const candidate = join(directory, entry.name)
440
+ const stat = lstatSync(candidate)
441
+ if (stat.isSymbolicLink() || !stat.isDirectory()) continue
442
+ assertInside(scanRoot, realpathSync(candidate), 'installed package scan failed')
443
+ directories.push(candidate)
444
+ }
445
+ return directories
446
+ }
447
+
448
+ function enqueueNodeModules(candidate) {
449
+ const stat = lstatIfPresent(candidate)
450
+ if (!stat || stat.isSymbolicLink() || !stat.isDirectory()) return
451
+ const canonical = realpathSync(candidate)
452
+ assertInside(scanRoot, canonical, 'installed package scan failed')
453
+ if (!visitedNodeModules.has(canonical)) pendingNodeModules.push(canonical)
454
+ }
455
+
456
+ function inspectPackageRoot(packageRoot, isOpenMercato) {
457
+ if (isOpenMercato) {
458
+ const manifest = join(packageRoot, 'package.json')
459
+ const stat = lstatIfPresent(manifest)
460
+ if (stat?.isFile() && !stat.isSymbolicLink()) {
461
+ assertInside(scanRoot, realpathSync(manifest), 'installed package scan failed')
462
+ manifests.push(manifest)
463
+ if (manifests.length > INSTALLED_PACKAGE_SCAN_LIMIT) {
464
+ throw new Error(`installed package scan exceeded ${INSTALLED_PACKAGE_SCAN_LIMIT} manifests`)
465
+ }
466
+ }
467
+ }
468
+ enqueueNodeModules(join(packageRoot, 'node_modules'))
469
+ }
470
+
471
+ while (pendingNodeModules.length > 0) {
472
+ pendingNodeModules.sort(comparePaths)
473
+ const directory = pendingNodeModules.shift()
474
+ if (visitedNodeModules.has(directory)) continue
475
+ visitedNodeModules.add(directory)
476
+
477
+ for (const entryPath of boundedDirectories(directory)) {
478
+ const entryName = basename(entryPath)
479
+ if (entryName === '.pnpm') {
480
+ for (const pnpmPackage of boundedDirectories(entryPath)) {
481
+ enqueueNodeModules(join(pnpmPackage, 'node_modules'))
482
+ }
483
+ } else if (entryName.startsWith('@')) {
484
+ for (const packageRoot of boundedDirectories(entryPath)) {
485
+ inspectPackageRoot(packageRoot, entryName === '@open-mercato')
486
+ }
487
+ } else if (!entryName.startsWith('.')) {
488
+ inspectPackageRoot(entryPath, false)
489
+ }
490
+ }
491
+ }
492
+
493
+ return manifests.sort(comparePaths)
494
+ }
495
+
496
+ function fallbackBoundedSearch(query, sourceRoot) {
497
+ let pattern
498
+ try {
499
+ pattern = new RegExp(query)
500
+ } catch (error) {
501
+ throw new Error(`bounded search failed: ${error instanceof Error ? error.message : String(error)}`)
502
+ }
503
+
504
+ const matches = []
505
+ let bytesRead = 0
506
+ for (const file of fallbackRegularFiles(sourceRoot, 'bounded search failed')) {
507
+ const size = lstatSync(file).size
508
+ if (bytesRead + size > FALLBACK_SEARCH_BYTE_LIMIT) {
509
+ throw new Error(`bounded search failed: fallback scan exceeded ${FALLBACK_SEARCH_BYTE_LIMIT} bytes`)
510
+ }
511
+ bytesRead += size
512
+ const content = readFileSync(file)
513
+ if (content.includes(0)) continue
514
+
515
+ const lines = content.toString('utf8').split(/\r?\n/)
516
+ for (let index = 0; index < lines.length; index += 1) {
517
+ const line = lines[index]
518
+ if (!pattern.test(line)) continue
519
+ const preview = line.length > 500 ? `${line.slice(0, 500)}…` : line
520
+ matches.push(`${file}:${index + 1}:${preview}`)
521
+ if (matches.length > SEARCH_MATCH_LIMIT) break
522
+ }
523
+ if (matches.length > SEARCH_MATCH_LIMIT) break
524
+ }
525
+
526
+ const truncated = matches.length > SEARCH_MATCH_LIMIT
527
+ const boundedMatches = matches.slice(0, SEARCH_MATCH_LIMIT)
528
+ return {
529
+ output: boundedMatches.length > 0 ? `${boundedMatches.join('\n')}\n` : '',
530
+ matches: boundedMatches.length,
531
+ truncated,
532
+ status: boundedMatches.length > 0 ? 'matched' : 'no-matches',
533
+ }
534
+ }
535
+
536
+ function packageRecord(packageName, packageRoot) {
537
+ const manifest = readJson(join(packageRoot, 'package.json'))
538
+ if (manifest.name !== packageName) {
539
+ throw new Error(`resolved package ${packageName} has manifest name ${String(manifest.name)}`)
540
+ }
541
+ const version = typeof manifest.version === 'string' ? manifest.version : 'unknown'
542
+ encodePackageVersion(version)
543
+ return {
544
+ name: packageName,
545
+ version,
546
+ root: packageRoot,
547
+ }
548
+ }
549
+
550
+ function relevantPackageNames(selectedPackage) {
551
+ const appManifest = readJson(join(appRoot, 'package.json'))
552
+ return [...new Set([
553
+ selectedPackage,
554
+ ...parseModuleEntries().map((entry) => entry.from),
555
+ ...Object.keys({ ...appManifest.dependencies, ...appManifest.devDependencies }),
556
+ ].filter((name) => typeof name === 'string' && name.startsWith('@open-mercato/')))].sort()
557
+ }
558
+
559
+ function installedPackageDiagnostics(selectedPackage, selectedRoot) {
560
+ const packageNames = relevantPackageNames(selectedPackage)
561
+ const packageNameSet = new Set(packageNames)
562
+ const cohort = []
563
+ for (const packageName of packageNames) {
564
+ const packageRoot = packageName === selectedPackage ? selectedRoot : findPackageRoot(packageName)
565
+ if (packageRoot) cohort.push(packageRecord(packageName, packageRoot))
566
+ }
567
+ cohort.sort((left, right) => left.name.localeCompare(right.name) || left.root.localeCompare(right.root))
568
+
569
+ const installations = new Map()
570
+ for (const record of cohort) installations.set(`${record.name}\0${record.root}`, record)
571
+ const nodeModulesRoot = join(appRoot, 'node_modules')
572
+ if (existsSync(nodeModulesRoot)) {
573
+ const packageScan = runRg(
574
+ [
575
+ '--no-ignore',
576
+ '--hidden',
577
+ '--files',
578
+ '--null',
579
+ '--sort',
580
+ 'path',
581
+ '--glob',
582
+ '**/@open-mercato/*/package.json',
583
+ nodeModulesRoot,
584
+ ],
585
+ 'installed package scan failed',
586
+ )
587
+ const manifests = packageScan
588
+ ? nulDelimitedPaths(packageScan.stdout)
589
+ : fallbackInstalledPackageManifests(nodeModulesRoot)
590
+ if (manifests.length > INSTALLED_PACKAGE_SCAN_LIMIT) {
591
+ throw new Error(`installed package scan exceeded ${INSTALLED_PACKAGE_SCAN_LIMIT} manifests`)
592
+ }
593
+ for (const manifestPath of manifests) {
594
+ const safeManifestPath = regularFileStrictlyBelow(
595
+ nodeModulesRoot,
596
+ manifestPath,
597
+ 'installed package manifest',
598
+ )
599
+ const packageName = `@open-mercato/${basename(dirname(safeManifestPath))}`
600
+ if (!packageNameSet.has(packageName)) continue
601
+ const packageRoot = realpathSync(dirname(safeManifestPath))
602
+ const record = packageRecord(packageName, packageRoot)
603
+ installations.set(`${record.name}\0${record.root}`, record)
604
+ }
605
+ }
606
+
607
+ const allInstallations = [...installations.values()]
608
+ .sort((left, right) => left.name.localeCompare(right.name)
609
+ || left.version.localeCompare(right.version)
610
+ || left.root.localeCompare(right.root))
611
+ const duplicates = []
612
+ for (const packageName of packageNames) {
613
+ const records = allInstallations.filter((record) => record.name === packageName)
614
+ if (records.length > 1) duplicates.push({ name: packageName, installations: records })
615
+ }
616
+ return { cohort, duplicates }
617
+ }
618
+
619
+ function displayPackageRecord(record) {
620
+ const location = relative(appRoot, record.root).split(sep).join('/') || '.'
621
+ return `${record.name}@${record.version} (${location})`
622
+ }
623
+
624
+ function packageDiagnosticWarnings(diagnostics) {
625
+ const warnings = []
626
+ const versions = new Set(diagnostics.cohort.map((record) => record.version))
627
+ if (versions.size > 1) {
628
+ warnings.push(
629
+ `Installed Open Mercato package cohort uses mixed versions: ${diagnostics.cohort.map(displayPackageRecord).join(', ')}. Context remains package-specific; do not combine generated facts or source across versions.`,
630
+ )
631
+ }
632
+ for (const duplicate of diagnostics.duplicates) {
633
+ const selected = diagnostics.cohort.find((record) => record.name === duplicate.name)
634
+ warnings.push(
635
+ `Multiple installed copies of ${duplicate.name} were found: ${duplicate.installations.map(displayPackageRecord).join(', ')}.${selected ? ` App resolution selected ${displayPackageRecord(selected)}; no other copy was read.` : ''}`,
636
+ )
637
+ }
638
+ return warnings
639
+ }
640
+
641
+ function runBoundedSearch(query, sourceRoot) {
642
+ const fileSearch = runRg(
643
+ ['--no-ignore', '--hidden', '--files-with-matches', '--null', '--sort', 'path', '--', query, sourceRoot],
644
+ 'bounded search failed',
645
+ )
646
+ if (!fileSearch) return fallbackBoundedSearch(query, sourceRoot)
647
+ if (fileSearch.status === 1) {
648
+ return { output: '', matches: 0, truncated: false, status: 'no-matches' }
649
+ }
650
+
651
+ const matchingFiles = nulDelimitedPaths(fileSearch.stdout)
652
+ .sort()
653
+ const matches = []
654
+
655
+ for (const file of matchingFiles.slice(0, SEARCH_MATCH_LIMIT + 1)) {
656
+ const remaining = SEARCH_MATCH_LIMIT + 1 - matches.length
657
+ if (remaining <= 0) break
658
+ const safeFile = regularFileStrictlyBelow(sourceRoot, file, 'bounded search candidate')
659
+ const search = runRg(
660
+ [
661
+ '--no-ignore',
662
+ '--hidden',
663
+ '--line-number',
664
+ '--with-filename',
665
+ '--color',
666
+ 'never',
667
+ '--max-columns',
668
+ '500',
669
+ '--max-columns-preview',
670
+ '--max-count',
671
+ String(remaining),
672
+ '--',
673
+ query,
674
+ safeFile,
675
+ ],
676
+ `bounded search failed for ${safeFile}`,
677
+ 512 * 1024,
678
+ )
679
+ if (!search) return fallbackBoundedSearch(query, sourceRoot)
680
+ if (search.status === 0) {
681
+ matches.push(...search.stdout.split(/\r?\n/).filter(Boolean))
682
+ }
683
+ }
684
+
685
+ const truncated = matches.length > SEARCH_MATCH_LIMIT
686
+ const boundedMatches = matches.slice(0, SEARCH_MATCH_LIMIT)
687
+ return {
688
+ output: boundedMatches.length > 0 ? `${boundedMatches.join('\n')}\n` : '',
689
+ matches: boundedMatches.length,
690
+ truncated,
691
+ status: boundedMatches.length > 0 ? 'matched' : 'no-matches',
692
+ }
693
+ }
694
+
695
+ function materialize(result, query) {
696
+ const safePackage = result.package.name.replace(/^@/, '').replaceAll('/', '-')
697
+ const safeVersion = encodePackageVersion(result.package.version)
698
+ const contextRoot = resolve(appRoot, '.ai', 'framework-context')
699
+ const outputRoot = assertStrictlyInside(
700
+ contextRoot,
701
+ resolve(contextRoot, `${safePackage}@${safeVersion}`),
702
+ 'context output',
703
+ )
704
+ ensureDirectoryChain(appRoot, contextRoot, 'framework context root')
705
+ const existingOutput = lstatIfPresent(outputRoot)
706
+ if (existingOutput) {
707
+ assertRegularDirectory(appRoot, outputRoot, 'context output')
708
+ ensureDirectoryChain(appRoot, contextRoot, 'framework context root')
709
+ rmSync(outputRoot, { recursive: true, force: true })
710
+ }
711
+ ensureDirectoryChain(appRoot, outputRoot, 'context output')
712
+
713
+ for (const instruction of result.instructions) {
714
+ if (!instruction.path || !existsSync(instruction.path)) continue
715
+ const target = join(outputRoot, 'instructions', `${instruction.kind}.md`)
716
+ copyContextFile(instruction.path, target)
717
+ instruction.materializedPath = relative(appRoot, target)
718
+ }
719
+
720
+ let materializedSourceRoot
721
+ if (result.sourceRoot && existsSync(result.sourceRoot)) {
722
+ const sourceTarget = join(outputRoot, 'source', result.module ?? 'package')
723
+ const materialization = copyContextFile(result.sourceRoot, sourceTarget)
724
+ materializedSourceRoot = sourceTarget
725
+ result.materializedSource = relative(appRoot, sourceTarget)
726
+ if (materialization.omittedEntries > 0) {
727
+ result.warnings.push(
728
+ `Materialized source omitted ${materialization.omittedEntries} credential, key, symbolic, binary, or unsupported filesystem entries.`,
729
+ )
730
+ }
731
+ }
732
+
733
+ if (query && materializedSourceRoot) {
734
+ const search = runBoundedSearch(query, materializedSourceRoot)
735
+ const searchPath = join(outputRoot, 'search.txt')
736
+ writeContextFile(searchPath, search.output)
737
+ result.searchResult = relative(appRoot, searchPath)
738
+ result.boundedSearch = {
739
+ query,
740
+ maxMatches: SEARCH_MATCH_LIMIT,
741
+ matches: search.matches,
742
+ truncated: search.truncated,
743
+ status: search.status,
744
+ result: result.searchResult,
745
+ }
746
+ }
747
+
748
+ const manifestPath = join(outputRoot, 'manifest.json')
749
+ writeContextFile(manifestPath, `${JSON.stringify({ ...result, generatedAt: new Date().toISOString() }, null, 2)}\n`)
750
+ result.manifest = relative(appRoot, manifestPath)
751
+ }
752
+
753
+ function buildResult(args) {
754
+ const upstreamRoot = join(appRoot, '.ai', 'guides', 'upstream', 'AGENTS.md')
755
+ const upstreamBc = join(appRoot, '.ai', 'guides', 'upstream', 'BACKWARD_COMPATIBILITY.md')
756
+ const standaloneRoot = join(appRoot, 'AGENTS.md')
757
+ const snapshotManifestPath = join(appRoot, '.ai', 'guides', 'upstream', 'manifest.json')
758
+ const snapshot = existsSync(snapshotManifestPath) ? readJson(snapshotManifestPath) : null
759
+
760
+ if (args.root) {
761
+ return {
762
+ mode: 'root',
763
+ snapshot,
764
+ instructions: [
765
+ { kind: 'standalone-root', path: existsSync(standaloneRoot) ? standaloneRoot : null },
766
+ { kind: 'upstream-bc', path: existsSync(upstreamBc) ? upstreamBc : null },
767
+ { kind: 'upstream-root', path: existsSync(upstreamRoot) ? upstreamRoot : null },
768
+ ],
769
+ }
770
+ }
771
+
772
+ const moduleId = args.module
773
+ ? assertToken(args.module, 'module id', /^[a-z0-9][a-z0-9_-]*$/)
774
+ : null
775
+ let packageName = args.package
776
+ ? assertToken(args.package, 'package name', /^@open-mercato\/[a-z0-9][a-z0-9._-]*$/)
777
+ : null
778
+
779
+ if (moduleId && !packageName) {
780
+ const candidates = candidatePackages(moduleId)
781
+ if (candidates.length === 0) throw new Error(`no installed package declares module ${moduleId}`)
782
+ if (candidates.length > 1) {
783
+ throw new Error(`module ${moduleId} is ambiguous; pass --package (${candidates.join(', ')})`)
784
+ }
785
+ packageName = candidates[0]
786
+ }
787
+ if (!packageName) throw new Error('pass --module, --package, or --root')
788
+
789
+ const packageRoot = findPackageRoot(packageName)
790
+ if (!packageRoot) throw new Error(`cannot resolve ${packageName} from ${appRoot}`)
791
+ const packageManifest = readJson(join(packageRoot, 'package.json'))
792
+ const installedPackages = installedPackageDiagnostics(packageName, packageRoot)
793
+ const sourceCandidate = moduleId
794
+ ? join(packageRoot, 'src', 'modules', moduleId)
795
+ : join(packageRoot, 'src')
796
+ const distCandidate = moduleId
797
+ ? join(packageRoot, 'dist', 'modules', moduleId)
798
+ : join(packageRoot, 'dist')
799
+ const sourceKind = existsSync(sourceCandidate) ? 'source' : existsSync(distCandidate) ? 'dist' : 'missing'
800
+ const sourceRoot = sourceKind === 'source'
801
+ ? assertInside(packageRoot, realpathSync(sourceCandidate), 'source root')
802
+ : sourceKind === 'dist'
803
+ ? assertInside(packageRoot, realpathSync(distCandidate), 'dist root')
804
+ : null
805
+ const degraded = sourceKind !== 'source'
806
+ const snapshotVersion = typeof snapshot?.generator === 'string'
807
+ ? snapshot.generator.match(/@(\d+\.\d+\.\d+(?:-[^\s]+)?)/)?.[1] ?? null
808
+ : null
809
+ const factsPath = join(appRoot, '.ai', 'guides', 'module-facts.json')
810
+ const moduleFact = moduleId && existsSync(factsPath) ? readJson(factsPath)?.[moduleId] ?? null : null
811
+ const factSourcePackage = moduleFact?.sourcePackage ?? null
812
+ const factSourceVersion = moduleFact?.sourceVersion ?? moduleFact?.coreVersion ?? null
813
+ const factsCurrent = !moduleFact || (
814
+ (!factSourcePackage || factSourcePackage === packageName)
815
+ && (!factSourceVersion || factSourceVersion === packageManifest.version)
816
+ )
817
+
818
+ return {
819
+ mode: moduleId ? 'module' : 'package',
820
+ module: moduleId,
821
+ package: { name: packageName, version: packageManifest.version ?? 'unknown', root: packageRoot },
822
+ installedPackages,
823
+ sourceRoot,
824
+ sourceKind,
825
+ degraded,
826
+ snapshot,
827
+ generatedFacts: moduleFact ? {
828
+ current: factsCurrent,
829
+ sourcePackage: factSourcePackage,
830
+ sourceVersion: factSourceVersion,
831
+ } : null,
832
+ instructions: [
833
+ { kind: 'standalone-root', path: existsSync(standaloneRoot) ? standaloneRoot : null },
834
+ { kind: 'upstream-bc', path: existsSync(upstreamBc) ? upstreamBc : null },
835
+ ...nearestAgentsFiles(packageRoot, sourceRoot).map((path, index) => ({
836
+ kind: index === 0 ? 'package' : `module-${index}`,
837
+ path,
838
+ })),
839
+ { kind: 'upstream-root', path: existsSync(upstreamRoot) ? upstreamRoot : null },
840
+ ],
841
+ boundedSearch: sourceRoot ? {
842
+ query: args.query ?? null,
843
+ maxMatches: SEARCH_MATCH_LIMIT,
844
+ matches: null,
845
+ truncated: null,
846
+ status: args.query ? 'pending' : 'query-required',
847
+ result: null,
848
+ } : null,
849
+ warnings: [
850
+ ...(degraded ? ['TypeScript package source is unavailable; analysis is limited to dist/types.'] : []),
851
+ ...(!existsSync(join(packageRoot, 'AGENTS.md')) ? ['Package AGENTS.md is unavailable.'] : []),
852
+ ...(snapshotVersion && snapshotVersion !== packageManifest.version
853
+ ? [`Upstream snapshot ${snapshotVersion} differs from installed ${packageName}@${packageManifest.version}.`]
854
+ : []),
855
+ ...(!factsCurrent
856
+ ? [`Generated facts for ${moduleId} are stale. After registry changes run yarn generate, then yarn mercato agentic:init --update-harness; after a dependency-only upgrade run the update-harness command.`]
857
+ : []),
858
+ ...packageDiagnosticWarnings(installedPackages),
859
+ ],
860
+ }
861
+ }
862
+
863
+ function printHelp() {
864
+ console.log(`Usage:
865
+ yarn framework:context --module <id> [--package <name>] [--query <text>] [--json]
866
+ yarn framework:context --package <@open-mercato/name> [--query <text>] [--json]
867
+ yarn framework:context --root [--json]
868
+
869
+ The command reads the installed package selected by this app and materializes the
870
+ smallest read-only instruction/source context under .ai/framework-context/.`)
871
+ }
872
+
873
+ try {
874
+ const args = parseArgs(process.argv.slice(2))
875
+ if (args.help) {
876
+ printHelp()
877
+ } else {
878
+ const result = buildResult(args)
879
+ if (args.materialize && result.package) materialize(result, args.query)
880
+ if (args.json) console.log(JSON.stringify(result, null, 2))
881
+ else {
882
+ if (result.package) console.log(`Package: ${result.package.name}@${result.package.version}`)
883
+ if (result.module) console.log(`Module: ${result.module}`)
884
+ if (result.sourceRoot) console.log(`Source: ${result.sourceRoot}`)
885
+ for (const instruction of result.instructions) {
886
+ if (instruction.path) console.log(`Instruction (${instruction.kind}): ${instruction.path}`)
887
+ }
888
+ if (result.manifest) console.log(`Materialized: ${result.manifest}`)
889
+ for (const warning of result.warnings ?? []) console.warn(`Warning: ${warning}`)
890
+ }
891
+ }
892
+ } catch (error) {
893
+ fail(error instanceof Error ? error.message : String(error))
894
+ }