{"version":3,"file":"upgrade.mjs","names":[],"sources":["../../src/handlers/upgrade.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport process from \"node:process\";\nimport { Effect } from \"effect\";\nimport { generateUiManifest } from \"every-plugin/ui/manifest-generator\";\nimport { upgradeTemplate } from \"../cli/upgrade\";\nimport { findConfigPath, MISSING_CONFIG_MESSAGE, readAuthoredConfigInput } from \"../config\";\nimport { generateCodeArtifacts } from \"../services/codegen/artifacts\";\nimport { checkFederationCompat, checkUiCompositionCompat } from \"../services/federation/service\";\nimport { readInstalledFrameworkVersion } from \"../services/framework-version\";\nimport {\n  type PlatformCompatViolation,\n  PlatformManifestService,\n  type ResolvedPlatformManifest,\n} from \"../services/platform/manifest\";\nimport { resolvePublishedConfig } from \"../services/registry/published\";\nimport { openResolution } from \"../services/resolution/session\";\nimport {\n  applyV1Tree,\n  auditV1Tree,\n  isV2Tree,\n  maintainV1Tree,\n} from \"../services/scaffold/upgrade-audit\";\nimport { selectWorkspaceTargets } from \"../services/workspace/build-train\";\nimport { readWorkspaceCatalog } from \"../services/workspace/catalog\";\nimport { findWorkspaceRoot } from \"../services/workspace/workspace\";\nimport type { BosConfig } from \"../types\";\nimport { colors } from \"../utils/theme\";\nimport type { BosBuilder } from \"./shared\";\n\nexport function registerUpgrade(builder: BosBuilder) {\n  return {\n    upgrade: builder.upgrade.effect(function* (_opts, input) {\n      return yield* Effect.tryPromise({\n        try: async () => {\n          const configPath = findConfigPath();\n          if (!configPath) {\n            return {\n              status: \"error\" as const,\n              packages: [],\n              error: `${MISSING_CONFIG_MESSAGE} in current directory`,\n            };\n          }\n\n          const projectDir = resolve(dirname(configPath));\n\n          if (input.from === \"v1\") {\n            if (isV2Tree(projectDir)) {\n              return {\n                status: \"already-upgraded\" as const,\n                packages: [],\n                notes: [\n                  \"bos.app.ts present — this tree is already on the v2 train; nothing to audit or apply\",\n                ],\n              };\n            }\n            if (input.maintain && input.maintain.length > 0) {\n              const migrated: string[] = [];\n              const notes: string[] = [];\n              for (const step of input.maintain) {\n                const result = await maintainV1Tree(projectDir, step, input.dryRun);\n                for (const path of result.writes) migrated.push(`${step}: wrote ${path}`);\n                for (const path of result.deletes) migrated.push(`${step}: deleted ${path}`);\n                for (const note of result.notes) notes.push(`${step}: ${note}`);\n              }\n              return {\n                status: input.dryRun ? (\"dry-run\" as const) : (\"upgraded\" as const),\n                packages: [],\n                migrated,\n                notes,\n              };\n            }\n            if (input.audit) {\n              const outcome = await auditV1Tree(projectDir);\n              const auditResult = {\n                tier: outcome.tier,\n                findings: outcome.findings,\n                manifest: outcome.manifest,\n              };\n              return outcome.gateBlocked\n                ? {\n                    status: \"gate-blocked\" as const,\n                    packages: [],\n                    audit: auditResult,\n                    blockers: outcome.findings.filter((f) => f.severity === \"blocker\"),\n                  }\n                : { status: \"audit\" as const, packages: [], audit: auditResult };\n            }\n            const outcome = await applyV1Tree(projectDir, input.dryRun);\n            if (!outcome.ok) {\n              return {\n                status: \"gate-blocked\" as const,\n                packages: [],\n                blockers: outcome.blockers,\n              };\n            }\n            return {\n              status: input.dryRun ? (\"dry-run\" as const) : (\"upgraded\" as const),\n              packages: [],\n              migrated: outcome.outcome.migrated,\n              notes: outcome.outcome.notes,\n            };\n          }\n\n          return await upgradeTemplate(projectDir, input);\n        },\n        catch: (error) => ({\n          status: \"error\" as const,\n          packages: [],\n          error: error instanceof Error ? error.message : \"Unknown error\",\n        }),\n      });\n    }),\n\n    typesGen: builder.typesGen.effect(function* (_opts, input) {\n      return yield* Effect.tryPromise({\n        try: async () => {\n          const configPath = findConfigPath();\n          if (!configPath) {\n            return {\n              status: \"error\" as const,\n              generated: [],\n              fetched: [],\n              skipped: [],\n              failed: [],\n              error: `${MISSING_CONFIG_MESSAGE} in current directory`,\n            };\n          }\n\n          const projectDir = resolve(dirname(configPath));\n          const env =\n            input.env ?? (process.env.NODE_ENV === \"production\" ? \"production\" : \"development\");\n\n          const refreshed = await openResolution({\n            cwd: projectDir,\n            env,\n            remotePlugins: input.remotePlugins,\n          });\n          if (!refreshed?.config || !refreshed.runtime) {\n            return {\n              status: \"error\" as const,\n              generated: [],\n              fetched: [],\n              skipped: [],\n              failed: [],\n              error: \"Failed to load the authored config\",\n            };\n          }\n\n          const runtime = refreshed.runtime;\n          const resolvedConfig = refreshed.config;\n\n          if (input.dryRun) {\n            const pluginEntries = Object.entries(runtime.plugins ?? {});\n            const fetched: string[] = [];\n            const skipped: string[] = [];\n            const hasLocalApiWorkspace = existsSync(join(projectDir, \"api\", \"src\"));\n\n            if (runtime.api.source !== \"local\") {\n              fetched.push(`api remote (${runtime.api.url})`);\n            } else {\n              const path = runtime.api.localPath\n                ? ` (${relative(projectDir, runtime.api.localPath)})`\n                : \"\";\n              skipped.push(`api local${path}`);\n            }\n\n            if (runtime.auth) {\n              if (runtime.auth.source !== \"local\") {\n                fetched.push(`auth remote (${runtime.auth.url})`);\n              } else {\n                const path = runtime.auth.localPath\n                  ? ` (${relative(projectDir, runtime.auth.localPath)})`\n                  : \"\";\n                skipped.push(`auth local${path}`);\n              }\n            }\n\n            for (const [key, plugin] of pluginEntries) {\n              if (plugin.url && plugin.source !== \"local\") {\n                fetched.push(`${key} remote (${plugin.url})`);\n              } else if (plugin.localPath) {\n                skipped.push(`${key} local (${relative(projectDir, plugin.localPath)})`);\n              } else {\n                skipped.push(`${key} no URL resolved`);\n              }\n            }\n\n            const generated = [\n              \"ui/src/lib/api-types.gen.ts\",\n              \"ui/src/lib/auth-types.gen.ts\",\n              \".bos/bos.resolved-config.json\",\n            ];\n            if (hasLocalApiWorkspace) {\n              generated.push(\"api/src/lib/plugins-types.gen.ts\", \"api/src/lib/auth-types.gen.ts\");\n            }\n            if (existsSync(join(projectDir, \"host\", \"src\"))) {\n              generated.push(\"host/src/lib/auth-types.gen.ts\");\n            }\n            for (const [_key, plugin] of pluginEntries) {\n              const localPath = plugin.localPath;\n              if (!localPath) continue;\n              const pluginSrc = join(localPath, \"src\", \"lib\", \"plugins-client.gen.ts\");\n              if (existsSync(pluginSrc)) {\n                generated.push(relative(projectDir, pluginSrc));\n              }\n            }\n            if (runtime.auth?.localPath) {\n              const authSrc = join(runtime.auth.localPath, \"src\", \"lib\", \"plugins-client.gen.ts\");\n              if (existsSync(authSrc)) {\n                generated.push(relative(projectDir, authSrc));\n              }\n            }\n\n            return {\n              status: \"success\" as const,\n              generated,\n              fetched,\n              skipped,\n              failed: [],\n            };\n          }\n\n          const artifacts = await generateCodeArtifacts(projectDir, resolvedConfig, {\n            env,\n            extendsChain: [...refreshed.chain],\n            runtimeConfig: runtime,\n            forceRouteTree: true,\n          });\n\n          const hasLocalApiWorkspace = existsSync(join(projectDir, \"api\", \"src\"));\n          const generated = [\"ui/src/lib/api-types.gen.ts\"];\n          if (hasLocalApiWorkspace) {\n            generated.push(\"api/src/lib/plugins-types.gen.ts\", \"api/src/lib/auth-types.gen.ts\");\n          }\n          if (runtime.auth && (runtime.auth.source !== \"local\" || runtime.auth.localPath)) {\n            generated.push(\"ui/src/lib/auth-types.gen.ts\");\n          }\n          if (existsSync(join(projectDir, \"host\", \"src\"))) {\n            generated.push(\"host/src/lib/auth-types.gen.ts\");\n          }\n          for (const [_key, plugin] of Object.entries(runtime.plugins ?? {})) {\n            const localPath = plugin.localPath;\n            if (!localPath) continue;\n            const pluginSrc = join(localPath, \"src\", \"lib\", \"plugins-client.gen.ts\");\n            if (existsSync(pluginSrc)) {\n              generated.push(relative(projectDir, pluginSrc));\n            }\n          }\n          if (runtime.auth?.localPath) {\n            const authSrc = join(runtime.auth.localPath, \"src\", \"lib\", \"plugins-client.gen.ts\");\n            if (existsSync(authSrc)) {\n              generated.push(relative(projectDir, authSrc));\n            }\n          }\n\n          const contractStatus = artifacts?.contractStatus ?? [];\n          const fetched: string[] = [];\n          const skipped: string[] = [];\n          const failed: string[] = [];\n          for (const entry of contractStatus) {\n            if (entry.source === \"remote\") {\n              fetched.push(entry.url ? `${entry.key} remote (${entry.url})` : entry.key);\n            } else if (entry.source === \"local\") {\n              const path = entry.localPath ? ` (${relative(projectDir, entry.localPath)})` : \"\";\n              skipped.push(`${entry.key} local${path}`);\n            } else if (entry.source === \"skipped\") {\n              skipped.push(`${entry.key} no URL resolved`);\n            } else if (entry.source === \"failed\") {\n              const detail = entry.error ? `: ${entry.error}` : \"\";\n              failed.push(`${entry.key}${detail}`);\n            }\n          }\n\n          return {\n            status: \"success\" as const,\n            generated: [...generated, \".bos/bos.resolved-config.json\"],\n            fetched,\n            skipped,\n            failed,\n          };\n        },\n        catch: (error) => ({\n          status: \"error\" as const,\n          generated: [],\n          fetched: [],\n          skipped: [],\n          failed: [],\n          error: error instanceof Error ? error.message : \"Unknown error\",\n        }),\n      });\n    }),\n\n    typecheck: builder.typecheck.effect(function* (_opts, input) {\n      return yield* Effect.tryPromise({\n        try: async () => {\n          const configPath = findConfigPath();\n          if (!configPath) {\n            return {\n              status: \"error\" as const,\n              checked: [],\n              skipped: [],\n              results: [],\n              error: `${MISSING_CONFIG_MESSAGE} in current directory`,\n            };\n          }\n\n          const projectDir = resolve(dirname(configPath));\n          const refreshed = await openResolution({ cwd: projectDir });\n          if (!refreshed?.config || !refreshed.runtime) {\n            return {\n              status: \"error\" as const,\n              checked: [],\n              skipped: [],\n              results: [],\n              error: \"Failed to load the authored config\",\n            };\n          }\n\n          const runtime = refreshed.runtime;\n          const resolvedConfig = refreshed.config;\n\n          await generateCodeArtifacts(projectDir, resolvedConfig, {\n            env: process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n            extendsChain: [...refreshed.chain],\n            runtimeConfig: runtime,\n          });\n          type AppTarget = { source?: string; localPath?: string };\n          const workspaceEntries: Array<{\n            key: string;\n            label: string;\n            dir: string;\n            ui?: boolean;\n          }> = [];\n          const skipped: Array<{ key: string; label: string }> = [];\n\n          const appTargets: Array<{\n            key: string;\n            label: string;\n            target: AppTarget | undefined;\n          }> = [\n            { key: \"host\", label: \"host\", target: runtime.host },\n            { key: \"ui\", label: \"ui\", target: runtime.ui },\n            { key: \"api\", label: \"api\", target: runtime.api },\n          ];\n          if (runtime.auth) {\n            appTargets.push({ key: \"auth\", label: \"auth\", target: runtime.auth });\n          }\n\n          for (const entry of appTargets) {\n            if (\n              entry.target?.source === \"local\" &&\n              entry.target.localPath &&\n              existsSync(join(entry.target.localPath, \"tsconfig.json\"))\n            ) {\n              workspaceEntries.push({\n                key: entry.key,\n                label: entry.label,\n                dir: entry.target.localPath,\n              });\n            } else {\n              skipped.push({ key: entry.key, label: entry.label });\n            }\n          }\n\n          for (const [key, plugin] of Object.entries(runtime.plugins ?? {})) {\n            const label = `plugins/${key}`;\n            const localPath = plugin.source === \"local\" ? plugin.localPath : undefined;\n            if (localPath && existsSync(join(localPath, \"tsconfig.json\"))) {\n              workspaceEntries.push({ key, label, dir: localPath });\n            } else {\n              skipped.push({ key, label });\n            }\n            // Plugin UIs are not in the plugin root tsconfig — they typecheck\n            // through their own ui/tsconfig.json (the typecheck:ui script).\n            if (localPath && existsSync(join(localPath, \"ui\", \"tsconfig.json\"))) {\n              workspaceEntries.push({ key, label: `${label}/ui`, dir: localPath, ui: true });\n            }\n          }\n\n          const selected = selectWorkspaceTargets(input.packages, resolvedConfig);\n          const targets =\n            input.packages === \"all\"\n              ? workspaceEntries\n              : workspaceEntries.filter((entry) => selected.includes(entry.key));\n          const skippedEntries =\n            input.packages === \"all\"\n              ? skipped\n              : skipped.filter((entry) => selected.includes(entry.key));\n\n          const checked: string[] = [];\n          const results: Array<{\n            workspace: string;\n            passed: boolean;\n            error?: string;\n          }> = [];\n\n          for (const entry of targets) {\n            // Builds keep the plugin ui's routeTree write on a scratch path\n            // (the router plugin owns the build-time tree), so typechecking a\n            // plugin ui first materializes ui/src/routeTree.gen.ts on disk —\n            // without it every createFileRoute call types as `undefined`.\n            if (entry.ui && !existsSync(join(entry.dir, \"ui\", \"src\", \"routeTree.gen.ts\"))) {\n              try {\n                await generateUiManifest({\n                  workspaceRoot: join(entry.dir, \"ui\"),\n                  pluginName: entry.key,\n                  emitRouteTree: true,\n                });\n              } catch (error) {\n                checked.push(entry.label);\n                results.push({\n                  workspace: entry.label,\n                  passed: false,\n                  error: `routeTree materialization failed: ${\n                    error instanceof Error ? error.message : String(error)\n                  }`,\n                });\n                continue;\n              }\n            }\n\n            const packageJsonPath = join(entry.dir, \"package.json\");\n            let args: string[] = entry.ui\n              ? [\"exec\", \"tsc\", \"--noEmit\", \"-p\", \"ui/tsconfig.json\"]\n              : [\"exec\", \"tsc\", \"--noEmit\"];\n            if (existsSync(packageJsonPath)) {\n              try {\n                const pkg = JSON.parse(readFileSync(packageJsonPath, \"utf-8\")) as {\n                  scripts?: Record<string, string>;\n                };\n                const scriptName = entry.ui ? \"typecheck:ui\" : \"typecheck\";\n                if (pkg.scripts?.[scriptName]) {\n                  args = [\"run\", scriptName];\n                }\n              } catch {}\n            }\n\n            console.log(`\\n  ${colors.dim(\"Checking\")} ${colors.cyan(entry.label)}`);\n            const child = spawnSync(\"pnpm\", args, {\n              cwd: entry.dir,\n              stdio: \"inherit\",\n            });\n            const passed = child.status === 0;\n            checked.push(entry.label);\n            results.push({\n              workspace: entry.label,\n              passed,\n              error: passed ? undefined : `typecheck failed (exit code ${child.status ?? \"n/a\"})`,\n            });\n          }\n\n          return {\n            status: \"success\" as const,\n            checked,\n            skipped: skippedEntries.map((entry) => entry.label),\n            results,\n          };\n        },\n        catch: (error) => ({\n          status: \"error\" as const,\n          checked: [],\n          skipped: [],\n          results: [],\n          error: error instanceof Error ? error.message : \"Unknown error\",\n        }),\n      });\n    }),\n\n    mfCheck: builder.mfCheck.effect(function* (_opts, input) {\n      const platformManifest = yield* PlatformManifestService;\n      return yield* Effect.promise(async () => {\n        let authored: BosConfig | null = null;\n        try {\n          authored = (await readAuthoredConfigInput()) as BosConfig | null;\n        } catch (e) {\n          return {\n            status: \"fail\" as const,\n            hostVersion: null,\n            hostReachable: false,\n            hostReason: e instanceof Error ? e.message : String(e),\n            remotes: [],\n          };\n        }\n        if (!authored) {\n          // No local authored config (the universal image carries none): fall\n          // back to the registry identity — the same source `bos start` boots\n          // from in a runtime container.\n          const account = process.env.BOS_ACCOUNT;\n          const gateway = process.env.BOS_GATEWAY;\n          if (!account || !gateway) {\n            return {\n              status: \"fail\" as const,\n              hostVersion: null,\n              hostReachable: false,\n              hostReason: MISSING_CONFIG_MESSAGE,\n              remotes: [],\n            };\n          }\n          try {\n            authored = await resolvePublishedConfig(account, gateway);\n          } catch (e) {\n            return {\n              status: \"fail\" as const,\n              hostVersion: null,\n              hostReachable: false,\n              hostReason: e instanceof Error ? e.message : String(e),\n              remotes: [],\n            };\n          }\n          if (!authored) {\n            return {\n              status: \"fail\" as const,\n              hostVersion: null,\n              hostReachable: false,\n              hostReason: `No config found at bos://${account}/${gateway} — verify BOS_ACCOUNT/BOS_GATEWAY and that the config has been published.`,\n              remotes: [],\n            };\n          }\n        }\n\n        const report = await checkFederationCompat(authored, {\n          timeoutMs: input.timeoutMs,\n        });\n\n        // #546: the UI composition compat gate — sibling UI manifests must\n        // agree on named shared singletons (the mf-check mirror of the\n        // host's boot guard). Absent when no UI slots exist.\n        const ui = await checkUiCompositionCompat(authored, { timeoutMs: input.timeoutMs });\n\n        // ADR 0034 pt 5 — the platform compat gate, additive to the federation\n        // check (a sibling, never a relaxation). Absent when no manifest\n        // resolves (in-image hosts self-describe; the smoke gate covers them).\n        let platform: { ok: boolean; violations: PlatformCompatViolation[] } | undefined;\n        try {\n          const configPath = findConfigPath();\n          if (configPath) {\n            const projectDir = resolve(dirname(configPath));\n            const resolved = await platformManifest.resolvePlatformManifest({\n              configDir: projectDir,\n              localConfig: authored as Record<string, unknown>,\n            });\n            if (resolved) {\n              const root = findWorkspaceRoot(projectDir)?.dir ?? projectDir;\n              const violations = platformManifest.checkPlatformCompat(resolved.manifest, {\n                platformVersion: readInstalledFrameworkVersion(projectDir, \"everything-dev\"),\n                catalog: readWorkspaceCatalog(root),\n              });\n              platform = { ok: violations.length === 0, violations };\n            }\n          }\n        } catch (e) {\n          platform = {\n            ok: false,\n            violations: [\n              {\n                kind: \"minChild\",\n                message: `platform manifest resolution failed: ${e instanceof Error ? e.message : String(e)}`,\n              },\n            ],\n          };\n        }\n\n        return {\n          status: report.ok && (platform?.ok ?? true) ? (\"ok\" as const) : (\"fail\" as const),\n          hostVersion: report.hostVersion,\n          hostReachable: report.hostReachable,\n          hostReason: report.hostReason,\n          remotes: report.remotes,\n          ...(ui.slots.length > 0 ? { ui: { ok: ui.ok, slots: ui.slots } } : {}),\n          ...(platform ? { platform } : {}),\n        };\n      });\n    }),\n\n    platformManifest: builder.platformManifest.effect(function* (_opts, input) {\n      const platformManifest = yield* PlatformManifestService;\n      return yield* Effect.promise(async () => {\n        // In-image: the booted host self-describes (ADR 0034 pt 1) — the\n        // staged manifest is the release's own bytes; a compat check of the\n        // image against itself is trivially consistent.\n        const inImage = platformManifest.readInImagePlatformManifest();\n        if (inImage) {\n          return {\n            status: \"ok\" as const,\n            version: inImage.frameworkVersion,\n            source: \"in-image\",\n            ...(input.check ? { compat: { ok: true, violations: [] } } : {}),\n          };\n        }\n\n        const configPath = findConfigPath();\n        if (!configPath) {\n          return {\n            status: \"absent\" as const,\n            version: null,\n            error: `${MISSING_CONFIG_MESSAGE} — and the in-image platform manifest is absent (non-framework image)`,\n          };\n        }\n        const projectDir = resolve(dirname(configPath));\n        try {\n          const authoredConfig =\n            ((await readAuthoredConfigInput()) as Record<string, unknown> | null) ?? {};\n          let resolved: ResolvedPlatformManifest | null;\n          let drift: { pinned: string; published: string } | undefined;\n          try {\n            resolved = await platformManifest.resolvePlatformManifest({\n              configDir: projectDir,\n              localConfig: authoredConfig,\n            });\n          } catch (pinError) {\n            // The pin names a release the chain no longer serves — the root\n            // republished past it (issue #546). Resolve the latest published\n            // manifest so the report names the drift instead of the cryptic\n            // pin-not-found error.\n            const latest = await platformManifest.resolvePlatformManifest({\n              configDir: projectDir,\n              localConfig: { ...authoredConfig, platform: undefined },\n            });\n            if (!latest) throw pinError;\n            resolved = latest;\n            const pinned =\n              typeof authoredConfig.platform === \"string\" ? authoredConfig.platform : undefined;\n            drift = pinned ? { pinned, published: latest.manifest.frameworkVersion } : undefined;\n          }\n          if (!resolved) {\n            return { status: \"absent\" as const, version: null };\n          }\n          if (drift) {\n            return {\n              status: \"fail\" as const,\n              version: drift.published,\n              source: `bos://${resolved.source.account}/${resolved.source.gateway}`,\n              drift,\n              error: `parent platform is ${drift.published} (published at bos://${resolved.source.account}/${resolved.source.gateway}), you pinned ${drift.pinned} — run \\`bos upgrade\\` to realign`,\n            };\n          }\n          const base = {\n            status: \"ok\" as const,\n            version: resolved.manifest.frameworkVersion,\n            source: `bos://${resolved.source.account}/${resolved.source.gateway}`,\n            fromCache: resolved.fromCache,\n          };\n          if (!input.check) {\n            return base;\n          }\n          const root = findWorkspaceRoot(projectDir)?.dir ?? projectDir;\n          const violations = platformManifest.checkPlatformCompat(resolved.manifest, {\n            platformVersion: readInstalledFrameworkVersion(projectDir, \"everything-dev\"),\n            catalog: readWorkspaceCatalog(root),\n          });\n          return { ...base, compat: { ok: violations.length === 0, violations } };\n        } catch (e) {\n          return {\n            status: \"fail\" as const,\n            version: null,\n            error: e instanceof Error ? e.message : String(e),\n          };\n        }\n      });\n    }),\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,gBAAgB,SAAqB;CACnD,OAAO;EACL,SAAS,QAAQ,QAAQ,OAAO,WAAW,OAAO,OAAO;GACvD,OAAO,OAAO,OAAO,WAAW;IAC9B,KAAK,YAAY;KACf,MAAM,aAAa,eAAe;KAClC,IAAI,CAAC,YACH,OAAO;MACL,QAAQ;MACR,UAAU,CAAC;MACX,OAAO,GAAG,uBAAuB;KACnC;KAGF,MAAM,aAAa,QAAQ,QAAQ,UAAU,CAAC;KAE9C,IAAI,MAAM,SAAS,MAAM;MACvB,IAAI,SAAS,UAAU,GACrB,OAAO;OACL,QAAQ;OACR,UAAU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