@useorgx/wizard 0.1.32 → 0.1.36

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.
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/banner.ts","../src/constants.ts","../src/lib/browser-auth.ts","../src/lib/fs.ts","../src/surfaces/openclaw-config.ts","../src/lib/auth-store.ts","../src/lib/auth.ts","../src/lib/local-auth-server.ts","../src/lib/pkce.ts","../src/lib/oauth-client.ts","../src/lib/wizard-state.ts","../src/surfaces/names.ts","../src/lib/agent-roster.ts","../src/lib/openclaw-health.ts","../src/lib/hosted-mcp-health.ts","../src/lib/hosted-mcp-tool-check.ts","../src/lib/npm-registry-health.ts","../src/lib/workspaces.ts","../src/lib/workspace-connectivity.ts","../src/lib/plugins.ts","../src/surfaces/mcp-config.ts","../src/surfaces/detection.ts","../src/lib/skills.ts","../src/surfaces/registry.ts","../src/lib/continuity.ts","../src/lib/initiatives.ts","../src/lib/setup-workspace.ts","../src/lib/founder-preset.ts","../src/lib/mutation-output.ts","../src/lib/setup-verification.ts","../src/lib/telemetry-events.ts","../src/lib/telemetry.ts","../src/lib/intents.ts","../src/lib/intent-render.ts","../src/lib/daily-brief-onboarding.ts","../src/lib/ai-session-import.ts","../src/lib/self-audit.ts","../src/lib/work-graph.ts","../src/lib/runtime-hooks.ts","../src/spinner.ts"],"sourcesContent":["import * as clack from \"@clack/prompts\";\nimport { spawnSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { hostname } from \"node:os\";\nimport { resolve } from \"node:path\";\nimport { Command } from \"commander\";\nimport pc from \"picocolors\";\n\ndeclare const __PKG_VERSION__: string;\n\nimport { renderBanner } from \"./banner.js\";\nimport { DEFAULT_ORGX_BASE_URL, ORGX_WIZARD_AUTH_PATH } from \"./constants.js\";\nimport {\n acknowledgeBrowserPairing,\n openBrowser,\n startBrowserPairing,\n waitForBrowserPairing,\n} from \"./lib/browser-auth.js\";\nimport {\n checkOrgxAuth,\n normalizeOrgxBaseUrl,\n resolveOrgxAuth,\n verifyOrgxAuth,\n type OrgxAuthCheckResult,\n} from \"./lib/auth.js\";\nimport { clearWizardAuth, writeWizardAuth } from \"./lib/auth-store.js\";\nimport { startPkceLogin } from \"./lib/oauth-client.js\";\nimport {\n AGENT_ROSTER_DOMAINS,\n configureAgentRoster,\n ensureDefaultAgentRoster,\n listAgentRosterProfiles,\n type AgentRosterAssignment,\n} from \"./lib/agent-roster.js\";\nimport { persistContinuityDefaults } from \"./lib/continuity.js\";\nimport { runFounderPreset, type FounderPresetResult } from \"./lib/founder-preset.js\";\nimport {\n FIRST_VALUE_INITIATIVE_TITLE,\n ensureFirstValueInitiative,\n ensureOnboardingTask,\n type FirstValueInitiativeResult,\n} from \"./lib/initiatives.js\";\nimport {\n countPluginReportChanges,\n installOrgxPlugins,\n listOrgxPluginStatuses,\n uninstallOrgxPlugins,\n type OrgxPluginMutationReport,\n type OrgxPluginStatus,\n} from \"./lib/plugins.js\";\nimport {\n addSkillExtension,\n getSkillStatus,\n installOrgxSkills,\n listSkillExtensions,\n setSkillExtensionEnabled,\n type SkillsInstallReport,\n type SkillExtension,\n type SkillExtensionWrite,\n} from \"./lib/skills.js\";\nimport { summarizeMutationResults } from \"./lib/mutation-output.js\";\nimport {\n HOSTED_MCP_OUTAGE_TITLE,\n getSetupVerificationHeadline,\n summarizeSetupVerification,\n} from \"./lib/setup-verification.js\";\nimport {\n buildAgentRosterTelemetryProperties,\n buildDoctorTelemetryProperties,\n buildFirstValueInitiativeTelemetryProperties,\n buildFounderDemoTelemetryProperties,\n buildOnboardingTaskTelemetryProperties,\n buildWorkspaceSetupTelemetryProperties,\n} from \"./lib/telemetry-events.js\";\nimport { trackWizardTelemetry } from \"./lib/telemetry.js\";\nimport {\n clearWizardState,\n getOrCreateWizardInstallationId,\n hasSetupPromptSkip,\n readWizardState,\n recordSetupPromptSkip,\n type WizardAgentRosterRecord,\n type WizardFirstValueInitiativeRecord,\n} from \"./lib/wizard-state.js\";\nimport {\n createWorkspace,\n getCurrentWorkspace,\n listWorkspaces,\n setDefaultWorkspace,\n type OrgxWorkspace,\n} from \"./lib/workspaces.js\";\nimport {\n buildIntentHandoffUrl,\n createIntent,\n updateIntent,\n type AgentSlug,\n type Intent,\n} from \"./lib/intents.js\";\nimport {\n DEFAULT_HOTKEYS,\n detectRenderCapabilities,\n dim as renderDim,\n isInteractive,\n normalizeHotkey,\n renderHotkeyBar,\n renderPlanPreview,\n renderRoutingLine,\n resolveConfidenceDecimal,\n type IntentAction,\n} from \"./lib/intent-render.js\";\nimport { runWorkspaceSetup, type WorkspaceSetupResult } from \"./lib/setup-workspace.js\";\nimport { runDailyBriefOnboarding } from \"./lib/daily-brief-onboarding.js\";\nimport {\n loadAiSessionImports,\n parseAiSessionSources,\n} from \"./lib/ai-session-import.js\";\nimport {\n buildSelfAuditPlan,\n createAuditArtifact,\n createAuditFollowUpTask,\n createInitiativeFromAuditPlan,\n renderSelfAuditMarkdown,\n type AuditScores,\n type FounderLoopImport,\n} from \"./lib/self-audit.js\";\nimport {\n buildWorkGraphExtractionProtocol,\n buildSessionReconciliationReport,\n renderWorkGraphExtractionProtocolMarkdown,\n renderWorkGraphMarkdown,\n type WorkGraphClientExtraction,\n type WorkGraphOpportunityScore,\n} from \"./lib/work-graph.js\";\nimport {\n inspectRuntimeHooks,\n installRuntimeHooks,\n parseRuntimeHookTargets,\n type RuntimeHookInspection,\n} from \"./lib/runtime-hooks.js\";\nimport { createOrgxSpinner } from \"./spinner.js\";\nimport { detectSurface } from \"./surfaces/detection.js\";\nimport {\n assessDoctorReport,\n addMcpSurface,\n addSurface,\n listSurfaceStatuses,\n removeMcpSurface,\n removeSurface,\n runDoctor,\n setupDetectedSurfaces,\n type SurfaceMutationResult,\n type SurfaceStatus,\n} from \"./surfaces/registry.js\";\nimport { isRecord, writeJsonFile, writeTextFile } from \"./lib/fs.js\";\n\nconst ICON = {\n ok: pc.green(\"✓\"),\n err: pc.red(\"✗\"),\n warn: pc.yellow(\"!\"),\n skip: pc.dim(\"·\"),\n} as const;\n\n/**\n * Returns the right command prefix based on how the wizard was invoked.\n * When run via `npx @useorgx/wizard`, `orgx-wizard` won't be in PATH — hints\n * should use the npx form so users can copy-paste them directly.\n */\nfunction getCmd(): string {\n const argv1 = process.argv[1] ?? \"\";\n return argv1.includes(\"_npx\") || argv1.includes(\"/.npm/\") || argv1.includes(\"/npm/_npx\")\n ? \"npx @useorgx/wizard\"\n : \"orgx-wizard\";\n}\n\nfunction formatAuthSource(source: OrgxAuthCheckResult[\"source\"]): string {\n switch (source) {\n case \"environment\":\n return \"env ORGX_API_KEY\";\n case \"wizard-store\":\n return \"wizard auth store\";\n case \"openclaw-config-file\":\n return \"openclaw config\";\n default:\n return \"not configured\";\n }\n}\n\nfunction formatPluginTargetLabel(target: OrgxPluginStatus[\"target\"]): string {\n switch (target) {\n case \"cursor\":\n return \"Cursor plugin\";\n case \"claude\":\n return \"Claude Code\";\n case \"codex\":\n return \"Codex\";\n case \"openclaw\":\n return \"OpenClaw\";\n }\n}\n\nfunction printSurfaceTable(statuses: SurfaceStatus[]): void {\n for (const status of statuses) {\n const icon = status.configured ? ICON.ok : status.detected ? ICON.warn : ICON.skip;\n const state = status.configured\n ? pc.green(\"configured\")\n : status.detected\n ? pc.yellow(\"detected\")\n : pc.dim(\"not found\");\n const mode = pc.dim(status.mode === \"automated\" ? \"auto \" : \"manual\");\n console.log(` ${icon} ${pc.bold(status.name.padEnd(10))} ${mode} ${state}`);\n if (status.mode === \"manual\") {\n console.log(` ${pc.dim(status.summary)}`);\n }\n }\n}\n\nfunction printPluginStatusReport(statuses: OrgxPluginStatus[]): void {\n for (const status of statuses) {\n const icon = status.installed ? ICON.ok : status.available ? ICON.warn : ICON.skip;\n const state = status.installed\n ? pc.green(\"installed\")\n : status.available\n ? pc.yellow(\"available\")\n : pc.dim(\"not found\");\n console.log(\n ` ${icon} ${pc.bold(formatPluginTargetLabel(status.target).padEnd(12))} ${state} ${pc.dim(status.message)}`,\n );\n }\n}\n\nfunction printMutationResults(results: SurfaceMutationResult[]): void {\n for (const result of summarizeMutationResults(results)) {\n const icon = result.state === \"updated\" ? ICON.ok : ICON.skip;\n const state = result.state === \"updated\" ? pc.green(\"updated \") : pc.dim(\"unchanged\");\n console.log(` ${icon} ${pc.bold(result.name.padEnd(10))} ${state} ${pc.dim(result.message)}`);\n }\n}\n\nfunction printSurfaceSummary(results: SurfaceMutationResult[]): void {\n const summarized = summarizeMutationResults(results);\n const updated = summarized.filter((r) => r.state === \"updated\");\n if (updated.length === 0) {\n console.log(\n ` ${ICON.skip} ${pc.dim(`${summarized.length} surface${summarized.length === 1 ? \"\" : \"s\"} already configured`)}`,\n );\n return;\n }\n for (const result of summarized) {\n const icon = result.state === \"updated\" ? ICON.ok : ICON.skip;\n const state = result.state === \"updated\" ? pc.green(\"updated \") : pc.dim(\"unchanged\");\n console.log(` ${icon} ${pc.bold(result.name.padEnd(10))} ${state} ${pc.dim(result.message)}`);\n }\n}\n\nfunction printPluginMutationReport(report: OrgxPluginMutationReport): void {\n for (const result of report.results) {\n const icon = result.changed ? ICON.ok : ICON.skip;\n const state = result.changed ? pc.green(\"updated \") : pc.dim(\"unchanged\");\n console.log(\n ` ${icon} ${pc.bold(formatPluginTargetLabel(result.target).padEnd(12))} ${state} ${pc.dim(result.message)}`,\n );\n }\n}\n\ninterface AuditCommandOptions {\n attachToInitiative?: string;\n claudeProjectsDir?: string;\n codexSessionsDir?: string;\n createInitiative?: boolean;\n dryRun?: boolean;\n extraction?: string[];\n from?: string;\n input?: string;\n json?: boolean;\n milestoneId?: string;\n outputDir?: string;\n sourceLabel?: string;\n sessionDays?: string;\n sessionLimit?: string;\n workspaceId?: string;\n workspaceName?: string;\n workstreamId?: string;\n writeFollowUp?: boolean;\n yes?: boolean;\n}\n\ntype WorkGraphCommandOptions = AuditCommandOptions;\n\ninterface HooksCommandOptions {\n json?: boolean;\n targets?: string;\n}\n\ninterface WorkGraphExtractionSchemaCommandOptions {\n json?: boolean;\n output?: string;\n}\n\nfunction formatScoreLine(scores: AuditScores): string {\n return Object.entries(scores)\n .map(([dimension, score]) => `${dimension}=${score}`)\n .join(\" \");\n}\n\nfunction formatWorkGraphScoreLine(score: WorkGraphOpportunityScore): string {\n return [\n `overall=${score.overall}`,\n `value=${score.value_potential}`,\n `evidence=${score.evidence_quality}`,\n `urgency=${score.urgency}`,\n `owner=${score.owner_clarity}`,\n `automation=${score.automation_potential}`,\n `orgx_fit=${score.orgx_fit}`,\n ].join(\" \");\n}\n\nfunction printRuntimeHookInspection(report: RuntimeHookInspection): void {\n console.log(` ${report.installed.hookScript ? ICON.ok : ICON.warn} ${pc.bold(\"hook script \")} ${report.installed.hookScript ? pc.green(\"installed\") : pc.yellow(\"missing\")} ${pc.dim(report.paths.hookScriptPath)}`);\n console.log(` ${report.installed.codex ? ICON.ok : ICON.warn} ${pc.bold(\"Codex \")} ${report.installed.codex ? pc.green(\"installed\") : pc.yellow(\"missing\")} ${pc.dim(report.paths.codexHooksPath)}`);\n console.log(` ${report.codex.hooksEnabled ? ICON.ok : ICON.warn} ${pc.bold(\"Codex flag \")} ${report.codex.hooksEnabled ? pc.green(\"enabled\") : pc.yellow(\"not enabled\")} ${pc.dim(report.paths.codexConfigPath)}`);\n console.log(` ${report.codex.notifyPreserved ? ICON.ok : ICON.warn} ${pc.bold(\"notify \")} ${report.codex.notifyPreserved ? pc.green(\"preserved\") : pc.yellow(\"check config\")} ${pc.dim(report.codex.hasNotify ? \"existing notify detected\" : \"no notify entry\")}`);\n console.log(` ${report.installed.claudeCode ? ICON.ok : ICON.warn} ${pc.bold(\"Claude Code \")} ${report.installed.claudeCode ? pc.green(\"installed\") : pc.yellow(\"missing\")} ${pc.dim(report.paths.claudeSettingsPath)}`);\n console.log(` ${ICON.skip} ${pc.bold(\"outbox \")} ${pc.dim(`${report.outboxEvents} event${report.outboxEvents === 1 ? \"\" : \"s\"} at ${report.paths.outboxPath}`)}`);\n}\n\nfunction readAuditInput(options: AuditCommandOptions, interactive: boolean): Promise<string> | string {\n if (options.input?.trim()) {\n return readFileSync(resolve(options.input.trim()), \"utf8\");\n }\n\n if (!process.stdin.isTTY) {\n return readFileSync(0, \"utf8\");\n }\n\n if (!interactive) {\n throw new Error(\"Audit input is required. Pass --input <file> or pipe text into wizard audit.\");\n }\n\n return textPrompt({\n message: \"Paste a short AI-session summary, decision log, or founder context excerpt\",\n placeholder: \"Decision: Founder Loop first. Artifact: proof ledger attached. Next action: ...\",\n validate: (value) => value?.trim().length ? undefined : \"Audit context is required.\",\n }).then((value) => {\n if (clack.isCancel(value) || typeof value !== \"string\") {\n clack.cancel(\"Audit cancelled.\");\n return \"\";\n }\n return value;\n });\n}\n\nfunction parsePositiveInteger(value: string | undefined, fallback: number, label: string): number {\n if (!value?.trim()) return fallback;\n\n const parsed = Number.parseInt(value.trim(), 10);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(`${label} must be a positive integer.`);\n }\n\n return parsed;\n}\n\nfunction collectPathOption(value: string, previous: string[] = []): string[] {\n return [\n ...previous,\n ...value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean),\n ];\n}\n\nfunction parseClientExtractionFile(path: string): WorkGraphClientExtraction {\n const resolvedPath = resolve(path);\n const parsed = JSON.parse(readFileSync(resolvedPath, \"utf8\")) as unknown;\n if (!isRecord(parsed)) {\n throw new Error(`AI-client extraction must be a JSON object: ${resolvedPath}`);\n }\n if (!Array.isArray(parsed.findings)) {\n throw new Error(`AI-client extraction must include findings[]: ${resolvedPath}`);\n }\n if (typeof parsed.source_client !== \"string\" || !parsed.source_client.trim()) {\n throw new Error(`AI-client extraction must include source_client: ${resolvedPath}`);\n }\n\n return parsed as unknown as WorkGraphClientExtraction;\n}\n\nfunction readClientExtractions(options: WorkGraphCommandOptions): WorkGraphClientExtraction[] {\n return (options.extraction ?? []).map(parseClientExtractionFile);\n}\n\nasync function readAuditImports(\n options: AuditCommandOptions,\n interactive: boolean,\n): Promise<{\n connectedSources: string[];\n imports: FounderLoopImport[];\n missingSources: string[];\n}> {\n const sources = parseAiSessionSources(options.from);\n const imports: FounderLoopImport[] = [];\n const connectedSources: string[] = [];\n const missingSources: string[] = [];\n\n if (sources.length > 0) {\n const imported = loadAiSessionImports({\n ...(options.claudeProjectsDir?.trim() ? { claudeProjectsDir: resolve(options.claudeProjectsDir.trim()) } : {}),\n ...(options.codexSessionsDir?.trim() ? { codexSessionsDir: resolve(options.codexSessionsDir.trim()) } : {}),\n limitPerSource: parsePositiveInteger(options.sessionLimit, 3, \"--session-limit\"),\n sinceDays: parsePositiveInteger(options.sessionDays, 30, \"--session-days\"),\n sources,\n });\n imports.push(...imported.imports);\n connectedSources.push(...imported.connectedSources);\n missingSources.push(...imported.missingSources);\n }\n\n const shouldReadManualInput = Boolean(options.input?.trim()) || sources.length === 0 || !process.stdin.isTTY;\n if (shouldReadManualInput) {\n const text = (await readAuditInput(options, interactive)).trim();\n if (text) {\n imports.push({\n sourceId: \"wizard-audit-input\",\n sourceLabel: options.sourceLabel?.trim() || \"Wizard audit input\",\n text,\n });\n connectedSources.push(options.sourceLabel?.trim() || \"Manual AI-session import\");\n }\n }\n\n if (imports.length === 0) {\n const sourceHint = sources.length > 0\n ? ` No audit-relevant lines were found in ${sources.join(\", \")} sessions.`\n : \"\";\n throw new Error(`Audit input is required.${sourceHint} Pass --input <file>, pipe text, or use --from codex|claude|all.`);\n }\n\n return {\n connectedSources,\n imports,\n missingSources,\n };\n}\n\nasync function readWorkGraphInputs(\n options: WorkGraphCommandOptions,\n interactive: boolean,\n): Promise<{\n clientExtractions: WorkGraphClientExtraction[];\n connectedSources: string[];\n imports: FounderLoopImport[];\n missingSources: string[];\n}> {\n const clientExtractions = readClientExtractions(options);\n const shouldReadSessionImports = Boolean(\n options.from?.trim() ||\n options.input?.trim() ||\n clientExtractions.length === 0 ||\n (!process.stdin.isTTY && clientExtractions.length === 0),\n );\n\n if (!shouldReadSessionImports) {\n return {\n clientExtractions,\n connectedSources: [],\n imports: [],\n missingSources: [],\n };\n }\n\n let auditImports: Awaited<ReturnType<typeof readAuditImports>>;\n try {\n auditImports = await readAuditImports(options, interactive);\n } catch (error) {\n if (clientExtractions.length === 0) throw error;\n const message = error instanceof Error ? error.message : String(error);\n auditImports = {\n connectedSources: [],\n imports: [],\n missingSources: [`fallback session import: ${message}`],\n };\n }\n return {\n clientExtractions,\n connectedSources: auditImports.connectedSources,\n imports: auditImports.imports,\n missingSources: auditImports.missingSources,\n };\n}\n\nfunction requireWriteApproval(options: AuditCommandOptions, interactive: boolean): Promise<boolean> | boolean {\n const wantsWrite = Boolean(options.createInitiative || options.attachToInitiative || options.writeFollowUp);\n if (!wantsWrite || options.yes || options.dryRun) return true;\n\n if (!interactive) {\n throw new Error(\"Write flags require --yes in non-interactive mode.\");\n }\n\n return clack.confirm({\n message: \"Approve OrgX writes for this audit run?\",\n }).then((value) => {\n if (clack.isCancel(value) || value !== true) {\n clack.cancel(\"Audit writeback cancelled.\");\n return false;\n }\n return true;\n });\n}\n\nasync function resolveAuditWorkspace(\n options: AuditCommandOptions,\n): Promise<{ id: string; name: string }> {\n const explicitId = options.workspaceId?.trim();\n const explicitName = options.workspaceName?.trim();\n if (explicitId || explicitName) {\n return {\n id: explicitId || \"manual-workspace\",\n name: explicitName || explicitId || \"Manual workspace\",\n };\n }\n\n try {\n const workspace = await getCurrentWorkspace();\n if (workspace) {\n return {\n id: workspace.id,\n name: workspace.name,\n };\n }\n } catch {\n // Local-only audits should still work without OrgX auth. The failed current\n // workspace lookup becomes visible through the missing source finding.\n }\n\n return {\n id: \"local-workspace\",\n name: \"Local workspace\",\n };\n}\n\nasync function runAuditCommand(options: AuditCommandOptions): Promise<void> {\n const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);\n const auditImports = await readAuditImports(options, interactive);\n\n const workspace = await resolveAuditWorkspace(options);\n const plan = buildSelfAuditPlan({\n connectedSources: [\n ...auditImports.connectedSources,\n ...(workspace.id === \"local-workspace\" ? [] : [\"OrgX workspace\"]),\n ],\n generatedAt: new Date().toISOString(),\n imports: auditImports.imports,\n missingSources: [\n ...(workspace.id === \"local-workspace\" ? [\"OrgX workspace auth\"] : []),\n ...auditImports.missingSources,\n ],\n workspace,\n });\n const markdown = renderSelfAuditMarkdown(plan);\n const outputDir = resolve(options.outputDir?.trim() || \".orgx/audits\");\n const timestamp = plan.generated_at.replace(/[:.]/g, \"-\");\n const jsonPath = resolve(outputDir, `ai-native-self-audit-${timestamp}.json`);\n const markdownPath = resolve(outputDir, `ai-native-self-audit-${timestamp}.md`);\n\n writeJsonFile(jsonPath, plan);\n writeTextFile(markdownPath, markdown);\n\n if (options.json) {\n console.log(JSON.stringify({ jsonPath, markdownPath, scores: plan.scores }, null, 2));\n } else {\n console.log(` ${ICON.ok} ${pc.green(\"audit generated\")} ${pc.dim(markdownPath)}`);\n console.log(` ${ICON.ok} ${pc.green(\"scores \")} ${pc.dim(formatScoreLine(plan.scores))}`);\n const belowTarget = plan.self_critique.filter((item) => !item.passed);\n if (belowTarget.length === 0) {\n console.log(` ${ICON.ok} ${pc.green(\"score gate \")} ${pc.dim(\"all dimensions at 95+\")}`);\n } else {\n console.log(` ${ICON.warn} ${pc.yellow(\"score gate \")} ${pc.dim(`${belowTarget.length} dimension${belowTarget.length === 1 ? \"\" : \"s\"} below 95`)}`);\n }\n }\n\n const approved = await requireWriteApproval(options, interactive);\n if (!approved) return;\n\n let targetInitiativeId = options.attachToInitiative?.trim() || \"\";\n if (options.createInitiative) {\n const initiative = await createInitiativeFromAuditPlan({\n dryRun: Boolean(options.dryRun),\n plan,\n });\n targetInitiativeId = initiative.id;\n console.log(` ${ICON.ok} ${pc.green(\"initiative \")} ${pc.bold(initiative.title)} ${pc.dim(initiative.id)}`);\n }\n\n if (targetInitiativeId && (options.attachToInitiative || options.createInitiative)) {\n const artifact = await createAuditArtifact({\n dryRun: Boolean(options.dryRun),\n initiativeId: targetInitiativeId,\n markdown,\n plan,\n });\n console.log(` ${ICON.ok} ${pc.green(\"artifact \")} ${pc.bold(artifact.title)} ${pc.dim(artifact.id)}`);\n }\n\n if (options.writeFollowUp) {\n if (!targetInitiativeId) {\n throw new Error(\"--write-follow-up requires --attach-to-initiative <id> or --create-initiative.\");\n }\n const followUp = await createAuditFollowUpTask({\n dryRun: Boolean(options.dryRun),\n initiativeId: targetInitiativeId,\n ...(options.milestoneId?.trim() ? { milestoneId: options.milestoneId.trim() } : {}),\n plan,\n ...(options.workstreamId?.trim() ? { workstreamId: options.workstreamId.trim() } : {}),\n });\n console.log(` ${ICON.ok} ${pc.green(\"follow-up \")} ${pc.bold(followUp.title)} ${pc.dim(followUp.id)}`);\n }\n}\n\nfunction runWorkGraphExtractionSchemaCommand(options: WorkGraphExtractionSchemaCommandOptions): void {\n const protocol = buildWorkGraphExtractionProtocol();\n const outputPath = options.output?.trim() ? resolve(options.output.trim()) : \"\";\n if (outputPath) {\n if (options.json) {\n writeJsonFile(outputPath, protocol);\n } else {\n writeTextFile(outputPath, renderWorkGraphExtractionProtocolMarkdown(protocol));\n }\n }\n\n if (options.json) {\n console.log(JSON.stringify(protocol, null, 2));\n return;\n }\n\n const markdown = renderWorkGraphExtractionProtocolMarkdown(protocol);\n console.log(markdown);\n}\n\nasync function runWorkGraphCommand(\n options: WorkGraphCommandOptions,\n defaults: { from?: string } = {},\n): Promise<void> {\n const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);\n const commandOptions = {\n ...options,\n ...(options.from?.trim() ? {} : defaults.from ? { from: defaults.from } : {}),\n };\n const auditInputs = await readWorkGraphInputs(commandOptions, interactive);\n const workspace = await resolveAuditWorkspace(commandOptions);\n const report = buildSessionReconciliationReport({\n clientExtractions: auditInputs.clientExtractions,\n connectedSources: [\n ...auditInputs.connectedSources,\n ...(workspace.id === \"local-workspace\" ? [] : [\"OrgX workspace\"]),\n ],\n generatedAt: new Date().toISOString(),\n imports: auditInputs.imports,\n missingSources: [\n ...(workspace.id === \"local-workspace\" ? [\"OrgX workspace auth\"] : []),\n ...auditInputs.missingSources,\n ],\n workspace,\n });\n const markdown = renderWorkGraphMarkdown(report);\n const outputDir = resolve(commandOptions.outputDir?.trim() || \".orgx/work-graph\");\n const timestamp = report.generated_at.replace(/[:.]/g, \"-\");\n const jsonPath = resolve(outputDir, `work-graph-report-${timestamp}.json`);\n const markdownPath = resolve(outputDir, `work-graph-report-${timestamp}.md`);\n\n writeJsonFile(jsonPath, report);\n writeTextFile(markdownPath, markdown);\n\n if (commandOptions.json) {\n console.log(JSON.stringify({\n jsonPath,\n markdownPath,\n reportId: report.report_id,\n workGraphFingerprint: report.work_graph_fingerprint,\n hydrationKey: report.signup_hydration.hydration_key,\n finalState: report.final_state,\n opportunityScore: report.opportunity_score,\n missedOrchestration: report.missed_orchestration_opportunities.length,\n clientExtractionCount: report.client_extractions.length,\n kickoffCount: report.initiative_kickoffs.length,\n trailCount: report.trails.length,\n recurringPatternCount: report.recurring_patterns.length,\n topTrail: report.mirror.primary_trail_id ?? null,\n mirrorHeadline: report.mirror.headline,\n }, null, 2));\n return;\n }\n\n console.log(` ${ICON.ok} ${pc.green(\"work graph \")} ${pc.dim(markdownPath)}`);\n console.log(` ${ICON.ok} ${pc.green(\"report id \")} ${pc.dim(report.report_id)}`);\n console.log(` ${ICON.ok} ${pc.green(\"fingerprint \")} ${pc.dim(report.work_graph_fingerprint)}`);\n console.log(` ${ICON.ok} ${pc.green(\"state \")} ${pc.dim(report.final_state)}`);\n console.log(` ${ICON.ok} ${pc.green(\"extractions \")} ${pc.dim(String(report.client_extractions.length))}`);\n console.log(` ${ICON.ok} ${pc.green(\"score \")} ${pc.dim(formatWorkGraphScoreLine(report.opportunity_score))}`);\n const missed = report.missed_orchestration_opportunities.length;\n const missedColor = missed > 0 ? pc.yellow : pc.green;\n console.log(` ${missed > 0 ? ICON.warn : ICON.ok} ${missedColor(\"missed \")} ${pc.dim(`${missed} orchestration opportunit${missed === 1 ? \"y\" : \"ies\"}`)}`);\n console.log(` ${ICON.ok} ${pc.green(\"trails \")} ${pc.dim(`${report.trails.length} trail${report.trails.length === 1 ? \"\" : \"s\"} · ${report.recurring_patterns.length} recurring pattern${report.recurring_patterns.length === 1 ? \"\" : \"s\"}`)}`);\n console.log(` ${ICON.skip} ${pc.bold(\"mirror \")} ${report.mirror.headline}`);\n for (const metric of report.tension_metrics.slice(0, 4)) {\n const tone = metric.tone === \"danger\" ? pc.red : metric.tone === \"warning\" ? pc.yellow : metric.tone === \"good\" ? pc.green : pc.dim;\n console.log(` ${ICON.skip} ${tone(`${metric.value} ${metric.label}`)} ${pc.dim(metric.explanation)}`);\n }\n for (const kickoff of report.initiative_kickoffs) {\n console.log(` ${ICON.skip} ${pc.bold(kickoff.priority.padEnd(3))} ${kickoff.title}`);\n }\n}\n\nasync function printPluginStatusSection(): Promise<OrgxPluginStatus[]> {\n const spinner = createOrgxSpinner(\"Checking OrgX companion plugin status\");\n spinner.start();\n const statuses = await listOrgxPluginStatuses();\n spinner.succeed(\"OrgX companion plugin status checked\");\n console.log(\"\");\n console.log(pc.dim(\" plugins\"));\n printPluginStatusReport(statuses);\n return statuses;\n}\n\nasync function checkPluginStatusesCompact(): Promise<OrgxPluginStatus[]> {\n const spinner = createOrgxSpinner(\"Checking OrgX companion plugin status\");\n spinner.start();\n const statuses = await listOrgxPluginStatuses();\n const installable = statuses.filter((s) => s.available && !s.installed);\n const installed = statuses.filter((s) => s.installed).length;\n if (installable.length === 0) {\n spinner.succeed(`Plugins ready (${installed} installed)`);\n return statuses;\n }\n spinner.succeed(\"OrgX companion plugin status checked\");\n console.log(\"\");\n console.log(pc.dim(\" plugins\"));\n printPluginStatusReport(statuses);\n return statuses;\n}\n\nfunction printSkillInstallReport(report: SkillsInstallReport): void {\n for (const write of report.writes) {\n const icon = write.skipped ? ICON.warn : write.changed ? ICON.ok : ICON.skip;\n const state = write.skipped ? pc.yellow(\"skipped \") : write.changed ? pc.green(\"updated \") : pc.dim(\"unchanged\");\n console.log(` ${icon} ${pc.bold(write.label.padEnd(10))} ${state}`);\n if (write.reason) {\n console.log(` ${pc.dim(write.reason)}`);\n }\n }\n\n for (const pack of report.packs) {\n const changedCount = pack.files.filter((f) => f.changed).length;\n const skippedCount = pack.files.filter((f) => f.skipped).length;\n const icon = skippedCount > 0 ? ICON.warn : changedCount > 0 ? ICON.ok : ICON.skip;\n const state = skippedCount > 0\n ? pc.yellow(`${skippedCount} skipped `)\n : changedCount > 0\n ? pc.green(`${changedCount} updated `)\n : pc.dim(\"unchanged\");\n console.log(` ${icon} ${pc.bold(pack.name.padEnd(10))} ${state} ${pc.dim(`${pack.files.length} files`)}`);\n for (const file of pack.files.filter((entry) => entry.skipped && entry.reason)) {\n console.log(` ${pc.dim(`${file.label}: ${file.reason}`)}`);\n }\n }\n\n for (const note of report.notes) {\n console.log(` ${ICON.skip} ${pc.dim(note)}`);\n }\n}\n\nfunction countSkillReportChanges(report: SkillsInstallReport): number {\n const writeChanges = report.writes.filter((write) => write.changed && !write.skipped).length;\n const packChanges = report.packs.reduce(\n (count, pack) => count + pack.files.filter((file) => file.changed && !file.skipped).length,\n 0,\n );\n return writeChanges + packChanges;\n}\n\nfunction printSkillExtensions(extensions: readonly SkillExtension[]): void {\n if (extensions.length === 0) {\n console.log(` ${ICON.skip} ${pc.dim(\"no skill extensions yet\")}`);\n return;\n }\n\n for (const extension of extensions) {\n const icon = extension.enabled ? ICON.ok : ICON.skip;\n const state = extension.enabled ? pc.green(\"enabled \") : pc.dim(\"disabled \");\n console.log(\n ` ${icon} ${pc.bold(extension.id.padEnd(24))} ${state} ${pc.dim(extension.path)}`,\n );\n }\n}\n\nfunction printSkillExtensionWrite(result: SkillExtensionWrite): void {\n const action = result.created ? \"created\" : result.changed ? \"updated\" : \"unchanged\";\n const color = result.created || result.changed ? pc.green : pc.dim;\n console.log(\n ` ${result.created || result.changed ? ICON.ok : ICON.skip} ${pc.bold(result.extension.id.padEnd(24))} ${color(action)}`,\n );\n console.log(` ${pc.dim(result.path)}`);\n}\n\nfunction openPathInEditor(path: string): boolean {\n const editor = process.env.EDITOR || process.env.VISUAL;\n if (!editor) {\n return false;\n }\n\n const result = spawnSync(editor, [path], {\n shell: true,\n stdio: \"inherit\",\n });\n return result.status === 0;\n}\n\nasync function safeTrackWizardTelemetry(\n event: string,\n properties: Record<string, unknown> = {},\n): Promise<void> {\n try {\n await trackWizardTelemetry(event, properties);\n } catch {\n // Telemetry should never block setup/auth flows.\n }\n}\n\nfunction printWorkspace(workspace: OrgxWorkspace): void {\n console.log(\n `${pc.bold(workspace.name)}${workspace.isDefault ? ` ${pc.green(\"(default)\")}` : \"\"}`,\n );\n console.log(` id: ${workspace.id}`);\n if (workspace.description) {\n console.log(` description: ${workspace.description}`);\n }\n if (workspace.createdAt) {\n console.log(` created: ${workspace.createdAt}`);\n }\n if (workspace.updatedAt) {\n console.log(` updated: ${workspace.updatedAt}`);\n }\n}\n\nfunction printWorkspaceList(workspaces: OrgxWorkspace[]): void {\n if (workspaces.length === 0) {\n console.log(pc.yellow(\"No workspaces found for this OrgX user.\"));\n return;\n }\n\n for (const workspace of workspaces) {\n printWorkspace(workspace);\n }\n}\n\nfunction printWorkspaceSetupResult(result: WorkspaceSetupResult): void {\n if (result.workspace) {\n const icon = result.status === \"updated\" ? ICON.ok : ICON.skip;\n console.log(` ${icon} ${pc.green(\"workspace \")} ${pc.bold(result.workspace.name)}`);\n } else {\n console.log(` ${ICON.skip} ${pc.dim(result.message)}`);\n }\n}\n\nfunction printSetupScopeNote(): void {\n console.log(pc.dim(\" setup updates your AI tools with:\"));\n console.log(` ${ICON.skip} ${pc.dim(\"MCP configs for local and cloud OrgX access\")}`);\n console.log(` ${ICON.skip} ${pc.dim(\"OrgX agent skills, rules, prompts, commands, and hooks\")}`);\n console.log(` ${ICON.skip} ${pc.dim(\"companion plugins where your editor supports them\")}`);\n}\n\nfunction printFirstValueHandoff(input: {\n initiative: FirstValueInitiativeResult;\n workspace: Pick<OrgxWorkspace, \"name\">;\n}): void {\n const cmd = getCmd();\n console.log(\"\");\n console.log(pc.bold(\"first OrgX handoff\"));\n console.log(\n ` ${input.initiative.created ? pc.green(\"created\") : pc.yellow(\"ready\")} ${pc.bold(input.initiative.initiative.title)}`,\n );\n console.log(` live: ${input.initiative.liveUrl}`);\n console.log(\n ` ${pc.dim(\"ask your AI tool:\")} ${pc.cyan(\n `Use OrgX to continue \"${input.initiative.initiative.title}\" in ${input.workspace.name}. Show the next action, then start with the onboarding task.`,\n )}`,\n );\n console.log(` ${pc.dim(\"later:\")} ${pc.cyan(`${cmd} doctor`)} ${pc.dim(\"checks tool wiring\")}`);\n}\n\nfunction firstValueRecordToResult(\n record: WizardFirstValueInitiativeRecord | undefined,\n): FirstValueInitiativeResult | null {\n if (!record) {\n return null;\n }\n\n return {\n created: false,\n initiative: {\n id: record.id,\n title: record.title,\n ...(record.summary ? { summary: record.summary } : {}),\n },\n liveUrl: record.liveUrl,\n };\n}\n\nfunction printFounderPresetResult(result: FounderPresetResult): void {\n printMutationResults(result.surfaceResults);\n console.log(\"\");\n printSkillInstallReport(result.skillReport);\n\n if (result.workspaceSetup) {\n console.log(\"\");\n printWorkspaceSetupResult(result.workspaceSetup);\n }\n\n if (result.demoInitiative) {\n console.log(\"\");\n console.log(pc.bold(\"demo initiative\"));\n console.log(\n ` ${result.demoInitiative.created ? pc.green(\"created\") : pc.yellow(\"unchanged\")} ${result.demoInitiative.initiative.title}`,\n );\n console.log(` live: ${result.demoInitiative.liveUrl}`);\n console.log(\n ` decision: ${result.demoInitiative.decision.title} ${pc.dim(`(${result.demoInitiative.decision.status ?? \"pending\"})`)}`,\n );\n console.log(\n ` artifact: ${result.demoInitiative.artifact.name}${result.demoInitiative.artifact.url ? ` ${pc.dim(result.demoInitiative.artifact.url)}` : \"\"}`,\n );\n }\n}\n\nfunction normalizePromptResult<T>(value: T | symbol): T | symbol {\n return value;\n}\n\nasync function secretPrompt(message: string): Promise<string | null> {\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n return null;\n }\n\n process.stdout.write(`${message}: `);\n\n const stdin = process.stdin;\n const stdout = process.stdout;\n const previousRawMode = stdin.isRaw === true;\n\n return await new Promise<string | null>((resolve) => {\n let value = \"\";\n\n const cleanup = (result: string | null) => {\n stdin.off(\"data\", onData);\n if (stdin.isTTY) {\n stdin.setRawMode(previousRawMode);\n }\n stdin.pause();\n stdout.write(\"\\n\");\n resolve(result);\n };\n\n const onData = (chunk: Buffer | string) => {\n const text = chunk.toString(\"utf8\");\n\n for (const char of text) {\n if (char === \"\\u0003\") {\n cleanup(null);\n return;\n }\n\n if (char === \"\\r\" || char === \"\\n\") {\n cleanup(value.trim());\n return;\n }\n\n if (char === \"\\u007f\" || char === \"\\b\") {\n value = value.slice(0, -1);\n continue;\n }\n\n if (char >= \" \") {\n value += char;\n }\n }\n };\n\n if (stdin.isTTY) {\n stdin.setRawMode(true);\n }\n stdin.resume();\n stdin.on(\"data\", onData);\n });\n}\n\nasync function selectPrompt(input: {\n initialValue?: string | undefined;\n message: string;\n options: { hint?: string; label: string; value: string }[];\n}): Promise<string | symbol> {\n const promptInput = input.initialValue\n ? { ...input, initialValue: input.initialValue }\n : { message: input.message, options: input.options };\n\n return normalizePromptResult(await clack.select<string>(promptInput));\n}\n\nasync function textPrompt(input: {\n initialValue?: string | undefined;\n message: string;\n placeholder?: string;\n validate?: (value: string | undefined) => Error | string | undefined;\n}): Promise<string | symbol> {\n const promptInput = input.initialValue\n ? { ...input, initialValue: input.initialValue }\n : {\n message: input.message,\n ...(input.placeholder ? { placeholder: input.placeholder } : {}),\n ...(input.validate ? { validate: input.validate } : {}),\n };\n\n return normalizePromptResult(await clack.text(promptInput));\n}\n\nasync function multiselectPrompt(input: {\n initialValues?: string[] | undefined;\n message: string;\n options: { disabled?: boolean; hint?: string; label: string; value: string }[];\n required?: boolean;\n}): Promise<string[] | symbol> {\n const promptInput = {\n message: `${input.message} ${pc.dim(\"Space to select, Enter to continue. Defaults are preselected.\")}`,\n options: input.options,\n ...(input.initialValues ? { initialValues: input.initialValues } : {}),\n ...(input.required !== undefined ? { required: input.required } : {}),\n };\n\n return normalizePromptResult(await clack.multiselect<string>(promptInput));\n}\n\nfunction printAgentRoster(roster: WizardAgentRosterRecord): void {\n console.log(` ${ICON.ok} ${pc.green(\"agent roster\")} ${pc.bold(`${roster.agents.length} agents`)}`);\n for (const agent of roster.agents) {\n console.log(\n ` ${pc.dim(agent.domain.padEnd(12))} ${pc.bold(agent.name)} ${pc.dim(agent.agentType)}`,\n );\n }\n}\n\nasync function promptForGuidedAgentRoster(\n workspace: OrgxWorkspace,\n): Promise<\"cancelled\" | WizardAgentRosterRecord | null> {\n const remainingAgents = listAgentRosterProfiles();\n const assignments: AgentRosterAssignment[] = [];\n\n for (const domain of AGENT_ROSTER_DOMAINS) {\n if (remainingAgents.length === 0) {\n break;\n }\n\n const defaultAgent = remainingAgents.find((agent) => agent.defaultDomain === domain);\n const choice = await selectPrompt({\n initialValue: defaultAgent?.name ?? \"skip\",\n message: `Assign an OrgX agent to the ${domain} domain`,\n options: [\n ...remainingAgents.map((agent) => ({\n value: agent.name,\n label: agent.name,\n hint: `${agent.agentType} · default ${agent.defaultDomain}`,\n })),\n { value: \"skip\", label: `Leave ${domain} unassigned`, hint: \"optional\" },\n ],\n });\n\n if (clack.isCancel(choice)) {\n clack.cancel(\"Setup cancelled.\");\n return \"cancelled\";\n }\n\n if (choice === \"skip\") {\n continue;\n }\n\n const index = remainingAgents.findIndex((agent) => agent.name === choice);\n if (index === -1) {\n continue;\n }\n\n const [selectedAgent] = remainingAgents.splice(index, 1);\n if (!selectedAgent) {\n continue;\n }\n\n assignments.push({ domain, name: selectedAgent.name });\n }\n\n if (assignments.length === 0) {\n return null;\n }\n\n return configureAgentRoster(workspace, assignments);\n}\n\nasync function verifyAndPersistAuth(\n apiKey: string,\n options: { baseUrl?: string; telemetrySource?: string },\n): Promise<{\n verification: OrgxAuthCheckResult;\n} | {\n openclawResults: SurfaceMutationResult[];\n stored: Awaited<ReturnType<typeof writeWizardAuth>>;\n verification: OrgxAuthCheckResult;\n}> {\n const trimmedKey = apiKey.trim();\n if (!trimmedKey.toLowerCase().startsWith(\"oxk_\")) {\n throw new Error(\"Expected a per-user OrgX API key that starts with oxk_.\");\n }\n\n const baseUrl = normalizeOrgxBaseUrl(options.baseUrl);\n const verification = await verifyOrgxAuth({\n apiKey: trimmedKey,\n keyPrefix: trimmedKey.slice(0, 12),\n baseUrl,\n source: \"wizard-store\",\n });\n\n if (!verification.ok) {\n return { verification };\n }\n\n const stored = await writeWizardAuth({\n apiKey: trimmedKey,\n baseUrl,\n verifiedAt: new Date().toISOString(),\n });\n await safeTrackWizardTelemetry(\"auth_completed\", {\n auth_source: options.telemetrySource ?? \"manual_api_key\",\n has_base_url: Boolean(baseUrl),\n });\n const openclawResults = detectSurface(\"openclaw\").detected\n ? await addSurface(\"openclaw\")\n : [];\n\n return { openclawResults, stored, verification };\n}\n\nasync function syncContinuityAfterAuth(seed: {\n executionMode?: \"cloud\" | \"local\" | null;\n workspaceName?: string | null;\n} = {}): Promise<void> {\n try {\n const workspace = await getCurrentWorkspace().catch(() => null);\n persistContinuityDefaults({\n ...(seed.executionMode !== undefined ? { executionMode: seed.executionMode } : {}),\n workspace,\n workspaceName: seed.workspaceName ?? workspace?.name ?? null,\n });\n } catch {\n // Auth success should not depend on workspace or continuity writes.\n }\n}\n\nfunction parseTimeoutSeconds(value: string): number {\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\"--timeout must be a positive number of seconds.\");\n }\n return parsed;\n}\n\n/**\n * Read a single keystroke from stdin in raw mode. Returns the lowercased\n * character, or null on EOF / Ctrl-C / non-TTY. Mirrors the `secretPrompt`\n * pattern used elsewhere in this file so we do not pull in an extra dep\n * for the M-P5 intent flow.\n */\nasync function readSingleKey(): Promise<string | null> {\n const stdin = process.stdin;\n if (!stdin.isTTY) return null;\n\n const previousRawMode = stdin.isRaw === true;\n return await new Promise<string | null>((resolve) => {\n const cleanup = (result: string | null) => {\n stdin.off(\"data\", onData);\n if (stdin.isTTY) {\n stdin.setRawMode(previousRawMode);\n }\n stdin.pause();\n resolve(result);\n };\n\n const onData = (chunk: Buffer | string) => {\n const text = chunk.toString(\"utf8\");\n const first = text.charAt(0);\n if (first === \"\\u0003\" || first === \"\\u0004\") {\n cleanup(null);\n return;\n }\n cleanup(first.toLowerCase());\n };\n\n if (stdin.isTTY) {\n stdin.setRawMode(true);\n }\n stdin.resume();\n stdin.on(\"data\", onData);\n });\n}\n\n/**\n * Pretty-print the classified intent: routing line, plan preview, hotkey bar.\n * Stays pure on the render side (all strings built in `intent-render.ts`); the\n * only side effects are `console.log` calls.\n */\nfunction printIntentPreview(intent: Intent, baseUrl: string): void {\n const render = detectRenderCapabilities();\n const agent: AgentSlug = intent.suggested_agent_slug ?? \"xandy\";\n const confidence = resolveConfidenceDecimal(intent.plan_preview);\n\n console.log(\"\");\n console.log(renderRoutingLine(agent, confidence, render));\n console.log(\"\");\n console.log(renderPlanPreview(intent.plan_preview, render));\n console.log(\"\");\n console.log(\n renderDim(\n ` slug ${intent.slug} handoff ${buildIntentHandoffUrl(intent.slug, { baseUrl })}`,\n render,\n ),\n );\n console.log(\"\");\n console.log(renderHotkeyBar(DEFAULT_HOTKEYS, render));\n}\n\n/**\n * Capture a first OrgX intent during `setup`. Replaces the old people-first\n * capture: instead of asking for one contact by hand, we ask the user what\n * they want OrgX to move, hand that to the classifier, and let the agent\n * draft the ICP + source the people downstream. Mirrors the Fon fixture\n * pattern in the main orgx repo (lib/execution/fixtures/fonScenario.ts).\n *\n * Contract:\n * - Requires an interactive TTY and a resolved workspace, otherwise skipped.\n * - One prompt. Blank answer = skip. Non-blank = create intent + preview.\n * - Optionally approves the intent so the /command view opens in \"ready\"\n * state instead of \"pending\".\n * - Never throws; network/auth failures return \"failed\" and print a hint.\n */\nasync function maybeCaptureSetupIntent(input: {\n interactive: boolean;\n workspace: OrgxWorkspace | null;\n}): Promise<\"skipped\" | \"captured\" | \"approved\" | \"failed\" | \"cancelled\"> {\n if (!input.interactive || !input.workspace) {\n return \"skipped\";\n }\n if (hasSetupPromptSkip(input.workspace.id, \"setup_intent\")) {\n return \"skipped\";\n }\n\n const prompt = await textPrompt({\n message: \"In one line, what do you want OrgX to move first? (blank to skip — you can start from the dashboard)\",\n placeholder: \"e.g. open a warm-intro loop to 50 design-led SaaS founders\",\n validate: (value) => {\n const trimmed = (value ?? \"\").trim();\n if (!trimmed) return undefined;\n if (trimmed.length > 4_000) return \"Keep it under 4,000 characters.\";\n return undefined;\n },\n });\n if (clack.isCancel(prompt)) {\n return \"cancelled\";\n }\n const intentText = typeof prompt === \"string\" ? prompt.trim() : \"\";\n if (!intentText) {\n recordSetupPromptSkip({\n promptKey: \"setup_intent\",\n workspaceId: input.workspace.id,\n workspaceName: input.workspace.name,\n });\n return \"skipped\";\n }\n\n const spinner = createOrgxSpinner(\"Routing\");\n spinner.start();\n\n let intent: Intent;\n try {\n intent = await createIntent({\n workspace_id: input.workspace.id,\n text: intentText,\n });\n spinner.stop();\n } catch (error) {\n spinner.fail(\"Could not classify intent.\");\n const message = error instanceof Error ? error.message : String(error);\n console.log(` ${ICON.warn} ${pc.yellow(\"intent\")} ${pc.dim(message)}`);\n return \"failed\";\n }\n\n const auth = await resolveOrgxAuth().catch(() => null);\n const baseUrl = auth?.baseUrl ?? DEFAULT_ORGX_BASE_URL;\n\n printIntentPreview(intent, baseUrl);\n\n const approveChoice = await clack.confirm({\n message: \"Approve this plan and hand off to OrgX?\",\n initialValue: true,\n });\n if (clack.isCancel(approveChoice)) {\n return \"cancelled\";\n }\n\n if (approveChoice) {\n const approveSpinner = createOrgxSpinner(\"Approving\");\n approveSpinner.start();\n try {\n await updateIntent(intent.id, { status: \"approved\" });\n approveSpinner.stop();\n } catch (error) {\n approveSpinner.fail(\"Approve failed.\");\n const message = error instanceof Error ? error.message : String(error);\n console.log(` ${ICON.warn} ${pc.yellow(\"intent\")} ${pc.dim(message)}`);\n return \"failed\";\n }\n const handoff = buildIntentHandoffUrl(intent.slug, { baseUrl });\n console.log(` ${ICON.ok} ${pc.green(\"intent\")} ${pc.dim(`approved · ${handoff}`)}`);\n return \"approved\";\n }\n\n const handoff = buildIntentHandoffUrl(intent.slug, { baseUrl });\n console.log(` ${ICON.skip} ${pc.dim(`intent pending · ${handoff}`)}`);\n return \"captured\";\n}\n\nasync function runIntentCommand(options: {\n initialText?: string;\n workspaceId?: string;\n jsonOutput?: boolean;\n}): Promise<void> {\n const interactive = isInteractive();\n\n // Step 1 — collect the intent text. In an interactive TTY we use clack's\n // text prompt (same styling as the rest of the wizard); non-TTY invocations\n // must pass the intent as arguments so the command stays pipeable.\n let intentText = options.initialText?.trim() ?? \"\";\n if (!intentText) {\n if (!interactive) {\n console.error(\n pc.red(\"Intent text is required when running non-interactively.\"),\n );\n console.error(\n pc.dim(\" Example: orgx-wizard intent \\\"launch partner outreach campaign\\\"\"),\n );\n process.exitCode = 1;\n return;\n }\n const prompt = await textPrompt({\n message: \"What do you want to move?\",\n placeholder: \"e.g. launch partner outreach campaign\",\n validate: (value) => {\n const trimmed = (value ?? \"\").trim();\n if (!trimmed) return \"Intent text cannot be empty.\";\n if (trimmed.length > 4_000) return \"Intent text exceeds 4,000 characters.\";\n return undefined;\n },\n });\n if (clack.isCancel(prompt) || typeof prompt !== \"string\") {\n console.log(pc.dim(\"Cancelled.\"));\n return;\n }\n intentText = prompt.trim();\n }\n\n // Step 2 — resolve the workspace. The intent API insists on a workspace id;\n // we default to the current workspace so the happy path is `orgx-wizard\n // intent \"...\"` with no extra flags.\n let workspaceId = options.workspaceId ?? \"\";\n let workspaceName: string | null = null;\n let workspaceBaseUrl: string | null = null;\n if (!workspaceId) {\n const loadLabel = \"Loading current OrgX workspace\";\n const spinner = interactive ? createOrgxSpinner(loadLabel) : null;\n if (spinner) spinner.start();\n else console.log(pc.dim(`${loadLabel}...`));\n try {\n const current = await getCurrentWorkspace();\n if (!current) {\n if (spinner) spinner.fail(\"No OrgX workspace is configured.\");\n else console.error(pc.red(\"No OrgX workspace is configured.\"));\n console.log(\n pc.dim(\" Run `orgx-wizard workspace create <name>` or pass --workspace <id>.\"),\n );\n process.exitCode = 1;\n return;\n }\n workspaceId = current.id;\n workspaceName = current.name;\n if (spinner) spinner.stop();\n } catch (error) {\n if (spinner) spinner.fail(\"Failed to load current workspace.\");\n console.error(\n pc.red(error instanceof Error ? error.message : String(error)),\n );\n process.exitCode = 1;\n return;\n }\n }\n\n // Step 3 — classify. The spinner in interactive mode shows the spec's\n // \"⠋ Classifying intent…\" affordance; non-interactive runs print a single\n // status line so CI logs stay readable.\n const classifyLabel = \"Routing\";\n const classifySpinner = interactive\n ? createOrgxSpinner(classifyLabel)\n : null;\n if (classifySpinner) classifySpinner.start();\n else console.log(pc.dim(`${classifyLabel}...`));\n\n let intent: Intent;\n try {\n intent = await createIntent({ workspace_id: workspaceId, text: intentText });\n if (classifySpinner) classifySpinner.stop();\n } catch (error) {\n if (classifySpinner) classifySpinner.fail(\"Classification failed.\");\n console.error(\n pc.red(error instanceof Error ? error.message : String(error)),\n );\n process.exitCode = 1;\n return;\n }\n\n // Resolve the OrgX base URL for handoff links. We prefer the auth-resolved\n // URL so environment overrides (ORGX_BASE_URL, wizard auth store) take\n // precedence over the public default.\n const auth = await resolveOrgxAuth().catch(() => null);\n const baseUrl = auth?.baseUrl ?? DEFAULT_ORGX_BASE_URL;\n workspaceBaseUrl = baseUrl;\n\n if (options.jsonOutput) {\n const payload = {\n intent,\n handoff_url: buildIntentHandoffUrl(intent.slug, { baseUrl }),\n workspace: workspaceName ? { id: workspaceId, name: workspaceName } : { id: workspaceId },\n };\n console.log(JSON.stringify(payload, null, 2));\n return;\n }\n\n // Step 4 — render the preview block.\n printIntentPreview(intent, baseUrl);\n console.log(\"\");\n\n // Step 5 — hotkey bar. In non-interactive mode we exit after rendering so\n // scripts can parse stdout; interactive mode waits for a single keypress.\n if (!interactive) {\n console.log(\n pc.dim(\n `Run \\`orgx-wizard intent --workspace ${workspaceId}\\` interactively to approve, edit, or archive.`,\n ),\n );\n return;\n }\n\n let action: IntentAction | null = null;\n while (action === null) {\n const key = await readSingleKey();\n if (!key) {\n action = \"quit\";\n break;\n }\n action = normalizeHotkey(key);\n if (action === null) {\n console.log(\n pc.dim(` Unrecognized key. Press a, e, x, or q.`),\n );\n }\n }\n\n switch (action) {\n case \"approve\": {\n const approveLabel = \"Approving\";\n const spinner = interactive ? createOrgxSpinner(approveLabel) : null;\n if (spinner) spinner.start();\n try {\n await updateIntent(intent.id, { status: \"approved\" });\n if (spinner) spinner.stop();\n } catch (error) {\n if (spinner) spinner.fail(\"Approve failed.\");\n console.error(\n pc.red(error instanceof Error ? error.message : String(error)),\n );\n process.exitCode = 1;\n return;\n }\n const handoff = buildIntentHandoffUrl(intent.slug, { baseUrl: workspaceBaseUrl ?? baseUrl });\n console.log(\"\");\n console.log(`${pc.green(\"✓\")} Approved · ${handoff}`);\n return;\n }\n case \"edit\": {\n const handoff = buildIntentHandoffUrl(intent.slug, { baseUrl: workspaceBaseUrl ?? baseUrl });\n console.log(\"\");\n console.log(`${pc.yellow(\"✎\")} Opening ${handoff}`);\n const result = openBrowser(handoff);\n if (!result.ok) {\n console.log(pc.dim(` Could not launch browser: ${result.error}`));\n console.log(pc.dim(` Visit ${handoff} to finish editing.`));\n }\n return;\n }\n case \"archive\": {\n const archiveLabel = \"Archiving\";\n const spinner = interactive ? createOrgxSpinner(archiveLabel) : null;\n if (spinner) spinner.start();\n try {\n await updateIntent(intent.id, { status: \"archived\" });\n if (spinner) spinner.stop();\n } catch (error) {\n if (spinner) spinner.fail(\"Archive failed.\");\n console.error(\n pc.red(error instanceof Error ? error.message : String(error)),\n );\n process.exitCode = 1;\n return;\n }\n console.log(\"\");\n console.log(`${pc.red(\"✕\")} Archived · intent will not be executed.`);\n return;\n }\n case \"quit\":\n default: {\n console.log(\"\");\n console.log(pc.dim(\" Exited without saving. Intent remains pending.\"));\n console.log(\n pc.dim(\n ` Resume at ${buildIntentHandoffUrl(intent.slug, { baseUrl: workspaceBaseUrl ?? baseUrl })}`,\n ),\n );\n return;\n }\n }\n}\n\nasync function maybeConfigureOptionalWorkspaceAddOns(input: {\n initiativeId?: string;\n interactive: boolean;\n telemetry?: {\n command: string;\n preset?: string;\n };\n workspace: OrgxWorkspace | null;\n}): Promise<\"cancelled\" | \"configured\" | \"skipped\"> {\n if (!input.interactive || !input.workspace) {\n return \"skipped\";\n }\n\n const existingState = readWizardState();\n const providedInitiativeId = input.initiativeId?.trim();\n const storedDemoInitiative = existingState?.demoInitiative?.workspaceId === input.workspace.id\n ? existingState.demoInitiative\n : undefined;\n const storedFirstValueInitiative =\n existingState?.firstValueInitiative?.workspaceId === input.workspace.id\n ? existingState.firstValueInitiative\n : undefined;\n let effectiveInitiativeId = providedInitiativeId\n || storedDemoInitiative?.id\n || storedFirstValueInitiative?.id;\n let firstValueInitiative = providedInitiativeId || storedDemoInitiative\n ? null\n : firstValueRecordToResult(storedFirstValueInitiative);\n const firstInitiativeSkipped = hasSetupPromptSkip(\n input.workspace.id,\n \"first_initiative\",\n );\n\n if (!effectiveInitiativeId && !firstInitiativeSkipped) {\n const firstInitiativeChoice = await selectPrompt({\n initialValue: \"yes\",\n message: `Create your first OrgX initiative in ${input.workspace.name}?`,\n options: [\n {\n value: \"yes\",\n label: \"Create first initiative\",\n hint: \"recommended; gives setup a live next step\",\n },\n { value: \"no\", label: \"Skip initiative creation\" },\n ],\n });\n if (clack.isCancel(firstInitiativeChoice)) {\n clack.cancel(\"Setup cancelled.\");\n return \"cancelled\";\n }\n\n if (firstInitiativeChoice === \"yes\") {\n const title = await textPrompt({\n initialValue: FIRST_VALUE_INITIATIVE_TITLE,\n message: \"What should OrgX help you move forward first?\",\n validate: (value) => {\n if (!value || value.trim().length === 0) {\n return \"Enter an initiative title.\";\n }\n return undefined;\n },\n });\n if (clack.isCancel(title)) {\n clack.cancel(\"Setup cancelled.\");\n return \"cancelled\";\n }\n\n const spinner = createOrgxSpinner(\"Creating your first OrgX initiative and live handoff\");\n spinner.start();\n try {\n firstValueInitiative = await ensureFirstValueInitiative(input.workspace, {\n title: String(title),\n });\n spinner.succeed(\n firstValueInitiative.created\n ? \"First OrgX initiative created\"\n : \"First OrgX initiative ready\",\n );\n effectiveInitiativeId = firstValueInitiative.initiative.id;\n await safeTrackWizardTelemetry(\n \"first_value_initiative_ready\",\n buildFirstValueInitiativeTelemetryProperties(\n firstValueInitiative,\n {\n command: input.telemetry?.command ?? \"setup\",\n ...(input.telemetry?.preset ? { preset: input.telemetry.preset } : {}),\n },\n ),\n );\n } catch (error) {\n spinner.fail(\"First OrgX initiative was not created\");\n const message = error instanceof Error ? error.message : String(error);\n console.log(` ${ICON.warn} ${pc.yellow(\"initiative\")} ${pc.dim(message)}`);\n }\n } else if (firstInitiativeChoice === \"no\") {\n recordSetupPromptSkip({\n promptKey: \"first_initiative\",\n workspaceId: input.workspace.id,\n workspaceName: input.workspace.name,\n });\n }\n }\n\n const hasOnboardingTask = existingState?.onboardingTask?.workspaceId === input.workspace.id;\n const onboardingTaskSkipped = hasSetupPromptSkip(\n input.workspace.id,\n \"onboarding_task\",\n );\n if (!hasOnboardingTask && effectiveInitiativeId && !onboardingTaskSkipped) {\n let shouldCreateOnboardingTask = firstValueInitiative !== null;\n if (!shouldCreateOnboardingTask) {\n const onboardingChoice = await selectPrompt({\n initialValue: \"yes\",\n message: `Create a starter onboarding task for ${input.workspace.name}?`,\n options: [\n { value: \"yes\", label: \"Create onboarding task\", hint: \"recommended\" },\n { value: \"no\", label: \"Skip task creation\" },\n ],\n });\n if (clack.isCancel(onboardingChoice)) {\n clack.cancel(\"Setup cancelled.\");\n return \"cancelled\";\n }\n shouldCreateOnboardingTask = onboardingChoice === \"yes\";\n if (onboardingChoice === \"no\") {\n recordSetupPromptSkip({\n promptKey: \"onboarding_task\",\n workspaceId: input.workspace.id,\n workspaceName: input.workspace.name,\n });\n }\n }\n\n if (shouldCreateOnboardingTask) {\n const spinner = createOrgxSpinner(\"Creating onboarding workstream and starter task\");\n spinner.start();\n try {\n const task = await ensureOnboardingTask(input.workspace, {\n initiativeId: effectiveInitiativeId,\n });\n spinner.succeed(\"Onboarding workstream and starter task ready\");\n console.log(` ${ICON.ok} ${pc.green(\"onboarding\")} ${pc.bold(task.title)}`);\n await safeTrackWizardTelemetry(\n \"onboarding_task_created\",\n buildOnboardingTaskTelemetryProperties(\n {\n created: true,\n hasInitiative: true,\n task,\n },\n {\n command: input.telemetry?.command ?? \"setup\",\n ...(input.telemetry?.preset ? { preset: input.telemetry.preset } : {}),\n },\n ),\n );\n } catch (error) {\n spinner.fail(\"Onboarding task was not created\");\n const message = error instanceof Error ? error.message : String(error);\n console.log(` ${ICON.warn} ${pc.yellow(\"onboarding\")} ${pc.dim(message)}`);\n }\n }\n }\n\n if (firstValueInitiative) {\n printFirstValueHandoff({\n initiative: firstValueInitiative,\n workspace: input.workspace,\n });\n }\n\n const refreshedState = readWizardState();\n const hasAgentRoster = refreshedState?.agentRoster?.workspaceId === input.workspace.id;\n const agentRosterSkipped = hasSetupPromptSkip(input.workspace.id, \"agent_roster\");\n if (!hasAgentRoster && !agentRosterSkipped) {\n const rosterChoice = await selectPrompt({\n initialValue: \"default\",\n message: `Set up an OrgX agent roster for ${input.workspace.name}?`,\n options: [\n { value: \"default\", label: \"Install the full default roster\", hint: \"recommended\" },\n { value: \"guided\", label: \"Choose agents and domains\" },\n { value: \"no\", label: \"Skip roster setup\" },\n ],\n });\n if (clack.isCancel(rosterChoice)) {\n clack.cancel(\"Setup cancelled.\");\n return \"cancelled\";\n }\n if (rosterChoice === \"guided\") {\n const roster = await promptForGuidedAgentRoster(input.workspace);\n if (roster === \"cancelled\") {\n return \"cancelled\";\n }\n if (roster) {\n printAgentRoster(roster);\n await safeTrackWizardTelemetry(\n \"agent_roster_configured\",\n buildAgentRosterTelemetryProperties(\n {\n roster,\n strategy: \"guided\",\n },\n {\n command: input.telemetry?.command ?? \"setup\",\n ...(input.telemetry?.preset ? { preset: input.telemetry.preset } : {}),\n },\n ),\n );\n } else {\n console.log(` ${ICON.skip} ${pc.dim(\"agent roster skipped\")} ${pc.dim(\"(no agents selected)\")}`);\n recordSetupPromptSkip({\n promptKey: \"agent_roster\",\n workspaceId: input.workspace.id,\n workspaceName: input.workspace.name,\n });\n }\n } else if (rosterChoice === \"default\") {\n const roster = ensureDefaultAgentRoster(input.workspace);\n printAgentRoster(roster);\n await safeTrackWizardTelemetry(\n \"agent_roster_configured\",\n buildAgentRosterTelemetryProperties(\n {\n roster,\n strategy: \"default\",\n },\n {\n command: input.telemetry?.command ?? \"setup\",\n ...(input.telemetry?.preset ? { preset: input.telemetry.preset } : {}),\n },\n ),\n );\n } else if (rosterChoice === \"no\") {\n recordSetupPromptSkip({\n promptKey: \"agent_roster\",\n workspaceId: input.workspace.id,\n workspaceName: input.workspace.name,\n });\n }\n }\n\n return \"configured\";\n}\n\nasync function promptOptionalCompanionPluginTargets(input: {\n interactive: boolean;\n statuses?: OrgxPluginStatus[];\n}): Promise<\"cancelled\" | OrgxPluginStatus[\"target\"][]> {\n if (!input.interactive) {\n return [];\n }\n\n let statuses = input.statuses;\n if (!statuses) {\n const spinner = createOrgxSpinner(\"Checking optional OrgX companion plugin status\");\n spinner.start();\n statuses = await listOrgxPluginStatuses();\n spinner.succeed(\"Optional OrgX companion plugin status checked\");\n }\n const installable = statuses.filter((status) => status.available && !status.installed);\n if (installable.length === 0) {\n return [];\n }\n\n const selection = await multiselectPrompt({\n initialValues: installable.map((status) => status.target),\n message: \"Install OrgX companion plugins into your detected AI tools?\",\n options: installable.map((status) => ({\n value: status.target,\n label: `Install ${formatPluginTargetLabel(status.target)}`,\n hint: status.message,\n })),\n required: false,\n });\n\n if (clack.isCancel(selection)) {\n clack.cancel(\"Setup cancelled.\");\n return \"cancelled\";\n }\n\n return selection as OrgxPluginStatus[\"target\"][];\n}\n\nfunction printPluginSkillOwnershipNote(targets: readonly OrgxPluginStatus[\"target\"][]): void {\n if (!targets.some((target) => target === \"cursor\" || target === \"claude\" || target === \"codex\")) {\n return;\n }\n\n console.log(\n ` ${ICON.skip} ${pc.dim(\n \"Cursor, Claude Code, and Codex companion plugins carry their own OrgX skills, rules, MCP config, commands, hooks, and agent prompts. Use 'wizard skills add' only for standalone rules or skills when those plugins are not in play.\",\n )}`,\n );\n}\n\nasync function installSelectedCompanionPlugins(input: {\n targets: readonly OrgxPluginStatus[\"target\"][];\n telemetry?: {\n command: string;\n preset?: string;\n };\n}): Promise<\"configured\" | \"skipped\"> {\n if (input.targets.length === 0) {\n return \"skipped\";\n }\n\n const spinner = createOrgxSpinner(\"Installing OrgX companion plugins\");\n spinner.start();\n const report = await installOrgxPlugins({ targets: input.targets });\n spinner.succeed(\"OrgX companion plugins processed\");\n printPluginMutationReport(report);\n printPluginSkillOwnershipNote(input.targets);\n\n await safeTrackWizardTelemetry(\"plugins_installed\", {\n changed_count: countPluginReportChanges(report),\n command: input.telemetry?.command ?? \"setup\",\n ...(input.telemetry?.preset ? { preset: input.telemetry.preset } : {}),\n requested_target_count: input.targets.length,\n target_count: report.results.length,\n });\n\n return countPluginReportChanges(report) > 0 ? \"configured\" : \"skipped\";\n}\n\nasync function maybeInstallOptionalCompanionPlugins(input: {\n interactive: boolean;\n statuses?: OrgxPluginStatus[];\n telemetry?: {\n command: string;\n preset?: string;\n };\n}): Promise<\"cancelled\" | \"configured\" | \"skipped\"> {\n const selection = await promptOptionalCompanionPluginTargets({\n interactive: input.interactive,\n ...(input.statuses ? { statuses: input.statuses } : {}),\n });\n if (selection === \"cancelled\") {\n return \"cancelled\";\n }\n\n return await installSelectedCompanionPlugins({\n targets: selection,\n ...(input.telemetry ? { telemetry: input.telemetry } : {}),\n });\n}\n\n\nfunction printAuthStatus(status: OrgxAuthCheckResult): void {\n if (!status.configured) {\n console.log(` ${ICON.warn} ${pc.yellow(\"not paired\")} run ${pc.cyan(`${getCmd()} auth login`)} to pair this terminal`);\n return;\n }\n\n const icon = status.ok ? ICON.ok : ICON.err;\n const state = status.ok ? pc.green(\"paired \") : status.skipped ? pc.yellow(\"skipped \") : pc.red(\"invalid \");\n const via = pc.dim(formatAuthSource(status.source));\n console.log(` ${icon} ${state} ${pc.bold(status.keyPrefix ?? \"unknown\")} ${via}`);\n if (!status.ok && status.error) {\n console.log(` ${pc.red(status.error)}`);\n }\n}\n\nfunction printDoctorReport(\n report: Awaited<ReturnType<typeof runDoctor>>,\n assessment: ReturnType<typeof assessDoctorReport>,\n): void {\n const verification = summarizeSetupVerification(assessment);\n // — Surfaces —\n console.log(pc.dim(\" surfaces\"));\n printSurfaceTable(report.surfaces);\n\n // — Account —\n console.log(\"\");\n console.log(pc.dim(\" account\"));\n printAuthStatus(report.auth);\n\n // — Services —\n console.log(\"\");\n console.log(pc.dim(\" services\"));\n\n // Hosted MCP\n const mcp = report.hostedMcp;\n {\n const icon = mcp.skipped ? ICON.skip : mcp.ok ? ICON.ok : ICON.err;\n const label = pc.dim(\"cloud mcp \".padEnd(14));\n const state = mcp.skipped ? pc.dim(\"skipped\") : mcp.ok ? pc.green(\"reachable\") : pc.red(\"unreachable\");\n const tail = !mcp.ok && !mcp.skipped && mcp.error ? ` ${pc.dim(mcp.error)}` : \"\";\n console.log(` ${icon} ${label} ${state}${tail}`);\n }\n\n // Tool call\n const tool = report.hostedMcpTool;\n {\n const icon = tool.skipped ? ICON.skip : tool.ok ? ICON.ok : ICON.err;\n const label = pc.dim(\"tool call \".padEnd(14));\n const state = tool.skipped ? pc.dim(\"skipped\") : tool.ok ? pc.green(\"authenticated\") : pc.red(\"failed\");\n const tail = !tool.ok && !tool.skipped && tool.error ? ` ${pc.dim(tool.error)}` : \"\";\n console.log(` ${icon} ${label} ${state}${tail}`);\n }\n\n // Workspace\n const ws = report.workspace;\n {\n const icon = !ws.configured ? ICON.skip : ws.ok ? ICON.ok : ICON.err;\n const label = pc.dim(\"workspace \".padEnd(14));\n const state = !ws.configured\n ? pc.dim(\"not configured\")\n : ws.ok && ws.workspace\n ? pc.green(ws.workspace.name)\n : pc.red(`unreachable${ws.error ? `: ${ws.error}` : \"\"}`);\n console.log(` ${icon} ${label} ${state}`);\n }\n\n // OpenClaw\n const openclaw = report.openclaw;\n {\n const icon = openclaw.skipped ? ICON.skip : openclaw.ok ? ICON.ok : ICON.err;\n const label = pc.dim(\"openclaw \".padEnd(14));\n const state = openclaw.skipped\n ? pc.dim(\"not installed\")\n : openclaw.ok\n ? pc.green(`healthy${openclaw.method && openclaw.method !== \"none\" ? ` (${openclaw.method})` : \"\"}`)\n : pc.red(`unhealthy${openclaw.error ? `: ${openclaw.error}` : \"\"}`);\n console.log(` ${icon} ${label} ${state}`);\n }\n\n // — Summary —\n console.log(\"\");\n const configuredCount = report.surfaces.filter((s) => s.configured).length;\n if (assessment.issues.length === 0) {\n console.log(` ${ICON.ok} ${pc.green(\"All systems ready.\")}`);\n if (!report.auth.configured) {\n console.log(`\\n ${pc.dim(\"→\")} ${pc.cyan(`${getCmd()} auth login`)} ${pc.dim(\"to connect your account\")}`);\n } else {\n console.log(` ${pc.dim(\"→\")} ${pc.dim(`OrgX is active across ${configuredCount} editor${configuredCount !== 1 ? \"s\" : \"\"}`)}`);\n }\n } else {\n const headlineText = getSetupVerificationHeadline(verification);\n const headline = verification.status === \"error\"\n ? `${ICON.err} ${pc.red(headlineText)}`\n : `${ICON.warn} ${pc.yellow(headlineText)}`;\n console.log(` ${headline}`);\n for (const issue of assessment.issues) {\n const degradedHostedMcpIssue =\n verification.hostedMcpDegraded && issue.title === HOSTED_MCP_OUTAGE_TITLE;\n const label = degradedHostedMcpIssue\n ? pc.yellow(\"degr \")\n : issue.level === \"error\"\n ? pc.red(\"error\")\n : pc.yellow(\"warn \");\n console.log(`\\n ${label} ${issue.title}`);\n console.log(` ${pc.dim(\"→\")} ${issue.suggestion}`);\n }\n }\n}\n\nasync function main(): Promise<void> {\n const program = new Command();\n program\n .name(\"orgx-wizard\")\n .description(\"Add OrgX MCP configs, skills/rules, and companion plugins to your local AI tools.\")\n .showHelpAfterError();\n\n const pkgVersion = typeof __PKG_VERSION__ !== \"undefined\" ? __PKG_VERSION__ : undefined;\n program.version(pkgVersion ?? \"unknown\", \"-V, --version\");\n\n program.hook(\"preAction\", (_thisCommand, actionCommand) => {\n if (Boolean(actionCommand.optsWithGlobals().json)) return;\n console.log(renderBanner(pkgVersion));\n });\n\n program\n .command(\"setup\")\n .description(\"Add OrgX MCP configs, skills/rules, and companion plugins to detected tools.\")\n .option(\"--preset <name>\", \"run a setup bundle (currently: founder)\")\n .option(\"--workspace\", \"choose or change the default workspace during setup\")\n .option(\"--daily-brief\", \"configure Daily Brief even if setup already handled it\")\n .option(\"--skip-daily-brief\", \"skip Daily Brief prompts and remember the skip\")\n .action(async (options: {\n dailyBrief?: boolean;\n preset?: string;\n skipDailyBrief?: boolean;\n workspace?: boolean;\n }) => {\n const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);\n if (options.dailyBrief && options.skipDailyBrief) {\n throw new Error(\"Use either --daily-brief or --skip-daily-brief, not both.\");\n }\n await safeTrackWizardTelemetry(\"wizard_started\", {\n command: \"setup\",\n interactive,\n preset: options.preset ?? \"standard\",\n });\n printSetupScopeNote();\n console.log(\"\");\n\n if (options.preset) {\n if (options.preset !== \"founder\") {\n throw new Error(`Unknown setup preset '${options.preset}'. Supported presets: founder.`);\n }\n\n const founderPluginTargets = await promptOptionalCompanionPluginTargets({\n interactive,\n });\n if (founderPluginTargets === \"cancelled\") {\n return;\n }\n\n const spinner = createOrgxSpinner(\"Running founder setup preset\");\n spinner.start();\n const presetResult = await runFounderPreset(\n {\n cancel: clack.cancel,\n isCancel: clack.isCancel,\n select: selectPrompt,\n text: textPrompt,\n },\n {\n interactive,\n pluginTargets: founderPluginTargets,\n },\n );\n\n if (\"status\" in presetResult) {\n spinner.stop();\n if (presetResult.status === \"cancelled\") {\n return;\n }\n printWorkspaceSetupResult(presetResult);\n return;\n }\n\n spinner.succeed(\"Founder setup preset complete\");\n printFounderPresetResult(presetResult);\n await safeTrackWizardTelemetry(\"mcp_injected\", {\n changed_count: presetResult.surfaceResults.filter((result) => result.changed).length,\n preset: \"founder\",\n surface_count: presetResult.surfaceResults.length,\n });\n await safeTrackWizardTelemetry(\"skills_installed\", {\n changed_count: countSkillReportChanges(presetResult.skillReport),\n pack_count: presetResult.skillReport.packs.length,\n preset: \"founder\",\n write_count: presetResult.skillReport.writes.length,\n });\n if (presetResult.workspaceSetup) {\n await safeTrackWizardTelemetry(\n \"workspace_bootstrapped\",\n buildWorkspaceSetupTelemetryProperties(presetResult.workspaceSetup, {\n command: \"setup\",\n interactive,\n preset: \"founder\",\n }),\n );\n }\n if (presetResult.demoInitiative) {\n await safeTrackWizardTelemetry(\n \"founder_demo_ready\",\n buildFounderDemoTelemetryProperties(presetResult.demoInitiative, {\n command: \"setup\",\n preset: \"founder\",\n }),\n );\n }\n\n const addOnResult = await maybeConfigureOptionalWorkspaceAddOns({\n interactive,\n telemetry: { command: \"setup\", preset: \"founder\" },\n workspace: presetResult.workspace,\n ...(presetResult.demoInitiative\n ? { initiativeId: presetResult.demoInitiative.initiative.id }\n : {}),\n });\n if (addOnResult === \"cancelled\") {\n return;\n }\n\n await installSelectedCompanionPlugins({\n telemetry: { command: \"setup\", preset: \"founder\" },\n targets: founderPluginTargets,\n });\n\n console.log(\"\");\n const doctor = await runDoctor();\n const assessment = assessDoctorReport(doctor);\n const verification = summarizeSetupVerification(assessment);\n await safeTrackWizardTelemetry(\n \"setup_verified\",\n buildDoctorTelemetryProperties(doctor, assessment, verification, {\n command: \"setup\",\n preset: \"founder\",\n }),\n );\n printDoctorReport(doctor, assessment);\n if (verification.status === \"error\") {\n process.exitCode = 1;\n }\n return;\n }\n\n const spinner = createOrgxSpinner(\"Configuring detected OrgX surfaces\");\n spinner.start();\n const results = await setupDetectedSurfaces();\n spinner.succeed(\"Detected surfaces configured\");\n printSurfaceSummary(results);\n const pluginStatuses = await checkPluginStatusesCompact();\n await safeTrackWizardTelemetry(\"mcp_injected\", {\n changed_count: results.filter((result) => result.changed).length,\n preset: \"standard\",\n surface_count: results.length,\n });\n\n const wasAlreadyPaired = (await resolveOrgxAuth()) !== null;\n let resolvedAuth = await resolveOrgxAuth();\n if (!resolvedAuth) {\n console.log(\"\");\n if (interactive) {\n const choice = await selectPrompt({\n message: \"Pair this terminal with your OrgX account to finish setup\",\n options: [\n { value: \"login\", label: \"Open browser to pair\", hint: \"recommended\" },\n { value: \"skip\", label: \"Skip for now\", hint: `run \\`${getCmd()} auth login\\` later` },\n ],\n });\n if (clack.isCancel(choice)) {\n clack.cancel(\"Setup cancelled.\");\n return;\n }\n if (choice === \"login\") {\n const loginOk = await runBrowserLogin({ telemetrySource: \"browser_pairing\" });\n if (!loginOk) {\n // Pairing failed — show clean next steps, don't dump the full doctor\n console.log(`\\n ${pc.dim(\"→\")} ${pc.cyan(`${getCmd()} auth login`)} ${pc.dim(\"to start a fresh browser pairing\")}`);\n console.log(` ${pc.dim(\"→\")} ${pc.cyan(`${getCmd()} auth login --api-key`)} ${pc.dim(\"to paste a key directly\")}`);\n return;\n }\n resolvedAuth = await resolveOrgxAuth();\n } else {\n // User skipped\n console.log(`\\n ${pc.dim(\"→\")} ${pc.cyan(`${getCmd()} auth login`)} ${pc.dim(\"to pair when ready\")}`);\n return;\n }\n } else {\n console.log(\n ` ${ICON.warn} ${pc.yellow(\"Terminal not paired.\")} Run ${pc.cyan(`${getCmd()} auth login`)} to pair it.`,\n );\n return;\n }\n }\n\n if (resolvedAuth) {\n console.log(\"\");\n const workspaceSetup = await runWorkspaceSetup(\n {\n createWorkspace,\n getCurrentWorkspace,\n listWorkspaces,\n setDefaultWorkspace,\n },\n {\n cancel: clack.cancel,\n isCancel: clack.isCancel,\n select: selectPrompt,\n text: textPrompt,\n },\n {\n interactive,\n skipIfConfigured: !options.workspace,\n },\n );\n if (workspaceSetup.status === \"cancelled\") {\n return;\n }\n if (workspaceSetup.status === \"reauth_requested\") {\n console.log(\"\");\n console.log(\n ` ${ICON.warn} ${pc.yellow(\"workspace\")} ${pc.dim(\"API key authenticated but returned 0 workspaces — likely an identity mismatch.\")}`,\n );\n console.log(` ${pc.cyan(`${getCmd()} auth login`)} ${pc.dim(\"→ re-link via OAuth, then rerun\")} ${pc.cyan(`${getCmd()} setup`)}`);\n await safeTrackWizardTelemetry(\n \"workspace_bootstrapped\",\n buildWorkspaceSetupTelemetryProperties(workspaceSetup, {\n command: \"setup\",\n interactive,\n preset: \"standard\",\n }),\n );\n return;\n }\n await safeTrackWizardTelemetry(\n \"workspace_bootstrapped\",\n buildWorkspaceSetupTelemetryProperties(workspaceSetup, {\n command: \"setup\",\n interactive,\n preset: \"standard\",\n }),\n );\n const resolvedWorkspace = workspaceSetup.workspace ?? await getCurrentWorkspace().catch(() => null);\n if (resolvedWorkspace) {\n persistContinuityDefaults({ workspace: resolvedWorkspace });\n }\n if (workspaceSetup.workspace) {\n console.log(` ${ICON.ok} ${pc.green(\"workspace \")} ${pc.bold(workspaceSetup.workspace.name)}`);\n }\n\n // Daily Brief + Trust Loop onboarding. Idempotent locally and\n // server-side: repeat setup runs do not re-ask unless --daily-brief is\n // passed.\n const briefResult = await runDailyBriefOnboarding({\n force: Boolean(options.dailyBrief),\n interactive,\n skip: Boolean(options.skipDailyBrief),\n workspace: resolvedWorkspace,\n prompts: {\n cancel: clack.cancel,\n isCancel: clack.isCancel,\n text: textPrompt,\n select: selectPrompt,\n confirm: clack.confirm,\n },\n });\n if (briefResult.status === \"cancelled\") {\n console.log(` ${ICON.skip} ${pc.dim(briefResult.message)}`);\n } else if (briefResult.status === \"skipped_user\") {\n console.log(` ${ICON.skip} ${pc.dim(briefResult.message)}`);\n } else if (briefResult.status === \"completed\") {\n console.log(` ${ICON.ok} ${pc.green(\"daily brief\")} ${pc.dim(briefResult.message)}`);\n } else if (briefResult.status === \"failed\") {\n console.log(` ${ICON.warn} ${pc.yellow(\"daily brief\")} ${pc.dim(briefResult.message)}`);\n }\n\n // Intent capture — the orgx canonical entry point. One free-text line\n // gets classified into an agent + plan (ICP draft, first-wave, etc).\n // The agent sources people from the ICP downstream; we do not ask the\n // user to type contacts by hand.\n const intentResult = await maybeCaptureSetupIntent({\n interactive,\n workspace: resolvedWorkspace,\n });\n if (intentResult === \"cancelled\") {\n return;\n }\n\n const addOnResult = await maybeConfigureOptionalWorkspaceAddOns({\n interactive,\n telemetry: { command: \"setup\", preset: \"standard\" },\n workspace: resolvedWorkspace,\n });\n if (addOnResult === \"cancelled\") {\n return;\n }\n\n const pluginInstallResult = await maybeInstallOptionalCompanionPlugins({\n interactive,\n statuses: pluginStatuses,\n telemetry: { command: \"setup\", preset: \"standard\" },\n });\n if (pluginInstallResult === \"cancelled\") {\n return;\n }\n }\n\n // Compact final status — surfaces already shown above, just give the bottom line\n const doctor = await runDoctor();\n const assessment = assessDoctorReport(doctor);\n const verification = summarizeSetupVerification(assessment);\n await safeTrackWizardTelemetry(\n \"setup_verified\",\n buildDoctorTelemetryProperties(doctor, assessment, verification, {\n command: \"setup\",\n preset: \"standard\",\n }),\n );\n const configuredCount = doctor.surfaces.filter((s) => s.configured).length;\n console.log(\"\");\n if (assessment.issues.length === 0) {\n console.log(` ${ICON.ok} ${pc.green(\"You're all set.\")} ${pc.dim(`OrgX is active across ${configuredCount} editor${configuredCount !== 1 ? \"s\" : \"\"}`)}`);\n if (wasAlreadyPaired) {\n console.log(\n ` ${pc.dim(\"→\")} ${pc.dim(\"If you opened the browser onboarding, click\")} ${pc.cyan(\"I've already paired\")} ${pc.dim(\"to continue.\")}`,\n );\n }\n } else {\n // Something needs attention — show full report\n printDoctorReport(doctor, assessment);\n if (verification.status === \"error\") {\n process.exitCode = 1;\n }\n }\n });\n\n async function runPkceLogin(opts: {\n open?: boolean;\n telemetrySource?: string;\n timeout?: number;\n } = {}): Promise<boolean> {\n const spinner = createOrgxSpinner(\"Starting OrgX OAuth login\");\n spinner.start();\n\n try {\n const pkceResult = await startPkceLogin({\n timeoutMs: (opts.timeout ?? 600) * 1_000,\n onAuthorizeUrl: (url) => {\n spinner.succeed(\"Authorization ready\");\n console.log(`\\n ${pc.dim(\"Open this URL to authorize:\")}`);\n console.log(` ${pc.cyan(url)}\\n`);\n if (opts.open !== false) {\n const openResult = openBrowser(url);\n if (!openResult.ok && openResult.error) {\n console.log(pc.yellow(`Browser open failed: ${openResult.error}`));\n }\n }\n spinner.start();\n spinner.text = \"Waiting for browser authorization...\";\n },\n });\n\n spinner.text = \"Verifying token...\";\n const baseUrl = normalizeOrgxBaseUrl(DEFAULT_ORGX_BASE_URL);\n const verification = await verifyOrgxAuth({\n apiKey: pkceResult.accessToken,\n keyPrefix: pkceResult.accessToken.slice(0, 12),\n baseUrl,\n source: \"wizard-store\",\n });\n\n if (!verification.ok) {\n spinner.fail(\"OAuth token verification failed\");\n console.log(` ${pc.red(verification.error ?? `HTTP ${verification.status ?? \"error\"}`)}`);\n console.log(` ${pc.dim(\"If this persists, try: wizard auth set-key <oxk_...>\")}`);\n return false;\n }\n\n const stored = await writeWizardAuth({\n apiKey: pkceResult.accessToken,\n baseUrl,\n verifiedAt: new Date().toISOString(),\n source: \"pkce\",\n ...(pkceResult.refreshToken !== undefined ? { refreshToken: pkceResult.refreshToken } : {}),\n oauthClientId: pkceResult.clientId,\n });\n\n await safeTrackWizardTelemetry(\"auth_completed\", {\n auth_source: opts.telemetrySource ?? \"pkce\",\n has_base_url: false,\n });\n\n const openclawResults = detectSurface(\"openclaw\").detected\n ? await addSurface(\"openclaw\")\n : [];\n\n spinner.succeed(\"OrgX account paired\");\n await syncContinuityAfterAuth();\n console.log(` ${ICON.ok} ${pc.green(\"paired \")} ${pc.bold(stored.keyPrefix)} ${pc.dim(\"browser sign-in\")}`);\n\n if (openclawResults.length > 0) {\n console.log(\"\");\n printMutationResults(openclawResults);\n }\n\n return true;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n spinner.fail(\"OAuth login failed\");\n console.log(` ${pc.red(message)}`);\n return false;\n }\n }\n\n function shortPairingId(pairingId: string): string {\n return pairingId.length > 13\n ? `${pairingId.slice(0, 8)}...${pairingId.slice(-4)}`\n : pairingId;\n }\n\n function formatPairingExpiry(expiresAt: string): string {\n const remainingMs = Date.parse(expiresAt) - Date.now();\n if (!Number.isFinite(remainingMs) || remainingMs <= 0) return \"expired\";\n const minutes = Math.ceil(remainingMs / 60_000);\n return minutes <= 1 ? \"<1m\" : `${minutes}m`;\n }\n\n async function runBrowserLogin(opts: {\n baseUrl?: string;\n deviceName?: string;\n open?: boolean;\n telemetrySource?: string;\n timeout?: number;\n } = {}): Promise<boolean> {\n const installationId = getOrCreateWizardInstallationId();\n const deviceName = opts.deviceName ?? hostname();\n const spinner = createOrgxSpinner(\"Starting OrgX browser pairing\");\n spinner.start();\n\n try {\n const pairing = await startBrowserPairing({\n installationId,\n baseUrl: opts.baseUrl,\n deviceName,\n platform: process.platform,\n });\n spinner.succeed(\"Browser pairing ready\");\n\n console.log(`\\n ${pc.dim(\"Open this URL to approve terminal pairing:\")}`);\n console.log(` ${pc.cyan(pairing.connectUrl)}\\n`);\n console.log(\n ` ${pc.dim(\"session \")} ${pc.bold(shortPairingId(pairing.pairingId))} ${pc.dim(\"device\")} ${pc.bold(deviceName)} ${pc.dim(\"expires\")} ${pc.bold(formatPairingExpiry(pairing.expiresAt))}\\n`\n );\n if (opts.open !== false) {\n const openResult = openBrowser(pairing.connectUrl);\n if (!openResult.ok && openResult.error) {\n console.log(pc.yellow(`Browser open failed: ${openResult.error}`));\n }\n }\n\n spinner.start();\n spinner.text = \"Waiting for browser approval...\";\n const ready = await waitForBrowserPairing({\n baseUrl: opts.baseUrl,\n pairingId: pairing.pairingId,\n pollIntervalMs: pairing.pollIntervalMs,\n pollToken: pairing.pollToken,\n timeoutMs: (opts.timeout ?? 600) * 1000,\n });\n\n spinner.text = \"Verifying paired account...\";\n const result = await verifyAndPersistAuth(ready.key!, {\n ...(opts.baseUrl !== undefined ? { baseUrl: opts.baseUrl } : {}),\n ...(opts.telemetrySource ? { telemetrySource: opts.telemetrySource } : {}),\n });\n\n if (!(\"stored\" in result)) {\n spinner.fail(\"Pairing completed but OrgX rejected the key\");\n console.log(` ${pc.red(result.verification.error ?? `HTTP ${result.verification.status ?? \"error\"}`)}`);\n console.log(` ${pc.dim(\"The browser flow finished, but OrgX rejected the key. Try again or check your account at useorgx.com.\")}`);\n return false;\n }\n\n let ackConfirmed = false;\n try {\n await acknowledgeBrowserPairing({\n baseUrl: opts.baseUrl,\n pairingId: pairing.pairingId,\n pollToken: pairing.pollToken,\n });\n ackConfirmed = true;\n } catch (error: unknown) {\n console.log(pc.dim(`Pairing ack failed: ${error instanceof Error ? error.message : String(error)}`));\n }\n\n spinner.succeed(\"OrgX account paired\");\n await syncContinuityAfterAuth({\n executionMode: ready.executionMode,\n workspaceName: ready.workspaceName,\n });\n\n console.log(` ${ICON.ok} ${pc.green(\"paired \")} ${pc.bold(result.stored.keyPrefix ?? result.verification.keyPrefix ?? \"unknown\")} ${pc.dim(\"wizard auth store\")}`);\n if (ready.workspaceName) {\n console.log(` ${ICON.ok} ${pc.green(\"workspace \")} ${pc.bold(ready.workspaceName)}`);\n }\n console.log(` ${ackConfirmed ? ICON.ok : ICON.warn} ${ackConfirmed ? pc.green(\"ack \") : pc.yellow(\"ack \")} ${pc.bold(ackConfirmed ? \"terminal confirmed\" : \"browser delivery pending\")} ${pc.dim(shortPairingId(pairing.pairingId))}`);\n\n if (result.openclawResults.length > 0) {\n console.log(\"\");\n printMutationResults(result.openclawResults);\n }\n\n return true;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n spinner.fail(\"Browser pairing failed\");\n console.log(` ${pc.red(message)}`);\n return false;\n }\n }\n\n const auth = program.command(\"auth\").description(\"Pair this terminal with an OrgX account.\");\n\n auth\n .command(\"status\")\n .description(\"Show which OrgX account this terminal is paired with.\")\n .action(async () => {\n const spinner = createOrgxSpinner(\"Checking OrgX auth\");\n spinner.start();\n const status = await checkOrgxAuth();\n spinner.stop();\n console.log(pc.dim(\" account\"));\n printAuthStatus(status);\n });\n\n auth\n .command(\"login\")\n .description(\"Open the browser pairing flow and store a scoped OrgX key for this terminal.\")\n .option(\"--api-key <key>\", \"Bypass browser auth and verify this OrgX API key directly.\")\n .option(\"--base-url <url>\", \"OrgX base URL (for OpenClaw pairing fallback).\")\n .option(\"--device-name <name>\", \"Device name shown during OpenClaw pairing.\")\n .option(\"--no-open\", \"Do not automatically open the browser auth URL.\")\n .option(\"--pairing\", \"Force the terminal pairing fallback instead of browser sign-in.\")\n .option(\"--timeout <seconds>\", \"How long to wait for browser auth before giving up.\", parseTimeoutSeconds, 600)\n .action(async (options: { apiKey?: string; baseUrl?: string; deviceName?: string; open?: boolean; pairing?: boolean; timeout: number }) => {\n // Direct key path — CI / blocked browser fallback\n if (options.apiKey) {\n const spinner = createOrgxSpinner(\"Verifying OrgX API key\");\n spinner.start();\n const result = await verifyAndPersistAuth(options.apiKey, {\n ...options,\n telemetrySource: \"manual_api_key\",\n });\n\n if (!(\"stored\" in result)) {\n spinner.fail(\"OrgX API key verification failed\");\n printAuthStatus(result.verification);\n return;\n }\n\n spinner.succeed(\"OrgX account paired\");\n await syncContinuityAfterAuth();\n console.log(` ${ICON.ok} ${pc.green(\"paired \")} ${pc.bold(result.stored.keyPrefix ?? result.verification.keyPrefix ?? \"unknown\")} ${pc.dim(\"wizard auth store\")}`);\n\n if (result.openclawResults.length > 0) {\n console.log(\"\");\n printMutationResults(result.openclawResults);\n }\n return;\n }\n\n // Force OpenClaw pairing when explicitly requested\n if (options.pairing) {\n await runBrowserLogin({\n ...(options.baseUrl !== undefined ? { baseUrl: options.baseUrl } : {}),\n ...(options.deviceName !== undefined ? { deviceName: options.deviceName } : {}),\n ...(options.open !== undefined ? { open: options.open } : {}),\n telemetrySource: \"browser_pairing\",\n timeout: options.timeout,\n });\n return;\n }\n\n // Default: OAuth PKCE (works without OpenClaw), fall back to OpenClaw pairing\n const pkceOk = await runPkceLogin({\n ...(options.open !== undefined ? { open: options.open } : {}),\n telemetrySource: \"pkce\",\n timeout: options.timeout,\n });\n\n if (!pkceOk) {\n console.log(pc.dim(\"\\n Browser sign-in did not finish. Opening the terminal pairing fallback...\"));\n await runBrowserLogin({\n ...(options.baseUrl !== undefined ? { baseUrl: options.baseUrl } : {}),\n ...(options.deviceName !== undefined ? { deviceName: options.deviceName } : {}),\n ...(options.open !== undefined ? { open: options.open } : {}),\n telemetrySource: \"browser_pairing_fallback\",\n timeout: options.timeout,\n });\n }\n });\n\n auth\n .command(\"set-key\")\n .description(\"Verify and persist a per-user OrgX API key for the wizard.\")\n .argument(\"<apiKey>\", \"per-user OrgX API key (oxk_...)\")\n .option(\"--base-url <url>\", \"OrgX base URL\")\n .action(async (apiKey: string, options: { baseUrl?: string }) => {\n const spinner = createOrgxSpinner(\"Verifying OrgX API key\");\n spinner.start();\n const result = await verifyAndPersistAuth(apiKey, {\n ...options,\n telemetrySource: \"manual_api_key\",\n });\n\n if (!(\"stored\" in result)) {\n spinner.fail(\"OrgX API key verification failed\");\n printAuthStatus(result.verification);\n return;\n }\n\n spinner.succeed(\"OrgX account paired\");\n await syncContinuityAfterAuth();\n console.log(` ${ICON.ok} ${pc.green(\"paired \")} ${pc.bold(result.stored.keyPrefix ?? result.verification.keyPrefix ?? \"unknown\")} ${pc.dim(\"wizard auth store\")}`);\n\n if (result.openclawResults.length > 0) {\n console.log(\"\");\n printMutationResults(result.openclawResults);\n }\n });\n\n auth\n .command(\"clear\")\n .description(\"Remove the wizard-local saved OrgX API key.\")\n .action(async () => {\n const removed = await clearWizardAuth();\n if (removed) {\n console.log(pc.green(\"Removed the wizard-local OrgX API key.\"));\n } else {\n console.log(pc.yellow(\"No wizard-local OrgX API key was stored.\"));\n }\n\n const resolved = await resolveOrgxAuth();\n if (resolved) {\n console.log(\n `Effective OrgX auth still resolves from ${formatAuthSource(resolved.source)} (${resolved.keyPrefix}).`,\n );\n }\n });\n\n program\n .command(\"uninstall\")\n .description(\"Remove OrgX-managed MCP tool configs, companion plugins, auth, and wizard state from this machine.\")\n .option(\"--keep-auth\", \"Keep the wizard-local saved OrgX API key.\")\n .option(\"--keep-state\", \"Keep wizard-local setup state.\")\n .option(\"--skip-plugins\", \"Skip companion plugin and legacy Cursor rules removal.\")\n .option(\"--skip-surfaces\", \"Skip MCP tool config removal.\")\n .action(async (options: {\n keepAuth?: boolean;\n keepState?: boolean;\n skipPlugins?: boolean;\n skipSurfaces?: boolean;\n }) => {\n await safeTrackWizardTelemetry(\"wizard_uninstalled\", {\n keep_auth: Boolean(options.keepAuth),\n keep_state: Boolean(options.keepState),\n skip_plugins: Boolean(options.skipPlugins),\n skip_surfaces: Boolean(options.skipSurfaces),\n });\n\n console.log(pc.bold(\"Removing OrgX wizard-managed configuration\"));\n\n if (options.skipSurfaces) {\n console.log(` ${ICON.skip} ${pc.bold(\"surfaces\".padEnd(10))} ${pc.dim(\"skipped\")}`);\n } else {\n console.log(\"\");\n console.log(pc.dim(\" surfaces\"));\n const surfaceResults = removeSurface([\"all\"]);\n printMutationResults(surfaceResults);\n }\n\n if (options.skipPlugins) {\n console.log(` ${ICON.skip} ${pc.bold(\"plugins\".padEnd(12))} ${pc.dim(\"skipped\")}`);\n } else {\n console.log(\"\");\n console.log(pc.dim(\" plugins\"));\n const spinner = createOrgxSpinner(\"Removing OrgX companion plugins and legacy Cursor rules\");\n spinner.start();\n const pluginReport = await uninstallOrgxPlugins({ targets: [\"all\"] });\n spinner.succeed(\"OrgX companion plugins and legacy Cursor rules processed\");\n printPluginMutationReport(pluginReport);\n }\n\n console.log(\"\");\n if (options.keepAuth) {\n console.log(` ${ICON.skip} ${pc.bold(\"auth\".padEnd(12))} ${pc.dim(\"kept\")}`);\n } else {\n const removedAuth = await clearWizardAuth();\n const state = removedAuth ? pc.green(\"updated \") : pc.dim(\"unchanged\");\n const message = removedAuth\n ? \"Removed the wizard-local OrgX API key.\"\n : \"No wizard-local OrgX API key was stored.\";\n console.log(` ${removedAuth ? ICON.ok : ICON.skip} ${pc.bold(\"auth\".padEnd(12))} ${state} ${pc.dim(message)}`);\n }\n\n if (options.keepState) {\n console.log(` ${ICON.skip} ${pc.bold(\"state\".padEnd(12))} ${pc.dim(\"kept\")}`);\n } else {\n const removedState = clearWizardState();\n const state = removedState ? pc.green(\"updated \") : pc.dim(\"unchanged\");\n const message = removedState\n ? \"Removed wizard-local setup state.\"\n : \"No wizard-local setup state was stored.\";\n console.log(` ${removedState ? ICON.ok : ICON.skip} ${pc.bold(\"state\".padEnd(12))} ${state} ${pc.dim(message)}`);\n }\n });\n\n const surface = program.command(\"surface\").description(\"Manage supported OrgX surfaces.\");\n\n surface\n .command(\"list\")\n .description(\"Show supported surfaces and their current status.\")\n .action(() => {\n printSurfaceTable(listSurfaceStatuses());\n });\n\n surface\n .command(\"add\")\n .description(\"Patch one surface or all automated surfaces.\")\n .argument(\"<names...>\", \"surface names or 'all'\")\n .action(async (names: string[]) => {\n const results = await addSurface(names as Parameters<typeof addSurface>[0]);\n printMutationResults(results);\n });\n\n surface\n .command(\"remove\")\n .description(\"Remove OrgX-managed config from one surface or all automated surfaces.\")\n .argument(\"<names...>\", \"surface names or 'all'\")\n .action((names: string[]) => {\n const results = removeSurface(names as Parameters<typeof removeSurface>[0]);\n printMutationResults(results);\n });\n\n const mcp = program\n .command(\"mcp\")\n .description(\"Add or remove OrgX MCP config entries in Claude, Cursor, Codex, VS Code, Windsurf, and Zed.\");\n\n mcp\n .command(\"add\")\n .description(\"Add OrgX MCP entries to one tool config or all supported MCP tool configs.\")\n .argument(\"[surfaces...]\", \"claude, cursor, codex, vscode, windsurf, zed, or all\", [\"all\"])\n .action(async (names: string[]) => {\n const results = await addMcpSurface(names as Parameters<typeof addMcpSurface>[0]);\n printMutationResults(results);\n });\n\n mcp\n .command(\"remove\")\n .description(\"Remove OrgX MCP entries from one tool config or all supported MCP tool configs.\")\n .argument(\"[surfaces...]\", \"claude, cursor, codex, vscode, windsurf, zed, or all\", [\"all\"])\n .action((names: string[]) => {\n const results = removeMcpSurface(names as Parameters<typeof removeMcpSurface>[0]);\n printMutationResults(results);\n });\n\n const plugins = program\n .command(\"plugins\")\n .description(\"Install or remove OrgX companion plugins in Cursor, Claude Code, Codex, and OpenClaw.\");\n\n plugins\n .command(\"list\")\n .description(\"Show companion plugin availability and install status in your tools.\")\n .action(async () => {\n const spinner = createOrgxSpinner(\"Checking OrgX companion plugin status\");\n spinner.start();\n const statuses = await listOrgxPluginStatuses();\n spinner.succeed(\"OrgX companion plugin status checked\");\n printPluginStatusReport(statuses);\n });\n\n plugins\n .command(\"add\")\n .description(\"Install OrgX companion plugins into Cursor, Claude Code, Codex, and OpenClaw.\")\n .argument(\"[targets...]\", \"cursor, claude, codex, openclaw, or all\", [\"all\"])\n .action(async (targets: string[]) => {\n const spinner = createOrgxSpinner(\"Installing OrgX companion plugins\");\n spinner.start();\n const report = await installOrgxPlugins({ targets });\n spinner.succeed(\"OrgX companion plugins processed\");\n printPluginMutationReport(report);\n printPluginSkillOwnershipNote(report.results.map((result) => result.target));\n await safeTrackWizardTelemetry(\"plugins_installed\", {\n changed_count: countPluginReportChanges(report),\n command: \"plugins:add\",\n requested_target_count: targets.length,\n target_count: report.results.length,\n });\n });\n\n plugins\n .command(\"remove\")\n .description(\"Uninstall managed OrgX companion plugins and legacy managed Cursor rules from Cursor, Claude Code, Codex, and OpenClaw.\")\n .argument(\"[targets...]\", \"cursor, claude, codex, openclaw, or all\", [\"all\"])\n .action(async (targets: string[]) => {\n const spinner = createOrgxSpinner(\"Removing OrgX companion plugins and legacy Cursor rules\");\n spinner.start();\n const report = await uninstallOrgxPlugins({ targets });\n spinner.succeed(\"OrgX companion plugins and legacy Cursor rules processed\");\n printPluginMutationReport(report);\n await safeTrackWizardTelemetry(\"plugins_removed\", {\n changed_count: countPluginReportChanges(report),\n command: \"plugins:remove\",\n requested_target_count: targets.length,\n target_count: report.results.length,\n });\n });\n\n const workspace = program\n .command(\"workspace\")\n .description(\"Inspect and create OrgX workspaces.\");\n\n workspace\n .command(\"current\")\n .description(\"Show the current OrgX workspace.\")\n .action(async () => {\n const spinner = createOrgxSpinner(\"Loading current OrgX workspace\");\n spinner.start();\n const current = await getCurrentWorkspace();\n spinner.stop();\n\n if (!current) {\n console.log(pc.yellow(\"No OrgX workspaces found for the current user.\"));\n return;\n }\n\n printWorkspace(current);\n });\n\n workspace\n .command(\"list\")\n .description(\"List OrgX workspaces accessible with the current API key.\")\n .action(async () => {\n const spinner = createOrgxSpinner(\"Loading OrgX workspaces\");\n spinner.start();\n const workspaces = await listWorkspaces();\n spinner.stop();\n printWorkspaceList(workspaces);\n });\n\n workspace\n .command(\"create\")\n .description(\"Create a new OrgX workspace.\")\n .argument(\"<name>\", \"workspace name\")\n .option(\"--description <text>\", \"workspace description\")\n .action(async (name: string, options: { description?: string }) => {\n const spinner = createOrgxSpinner(\"Creating OrgX workspace\");\n spinner.start();\n const created = await createWorkspace(\n {\n name,\n ...(options.description ? { description: options.description } : {}),\n },\n );\n spinner.succeed(\"OrgX workspace created\");\n if (created.isDefault) {\n persistContinuityDefaults({ workspace: created });\n }\n printWorkspace(created);\n if (!created.isDefault) {\n console.log(\"\");\n console.log(pc.dim(`Run \\`wizard workspace set-default ${created.id}\\` to promote it.`));\n }\n });\n\n workspace\n .command(\"set-default\")\n .description(\"Set the default OrgX workspace.\")\n .argument(\"<id>\", \"workspace id\")\n .action(async (id: string) => {\n const spinner = createOrgxSpinner(\"Updating default OrgX workspace\");\n spinner.start();\n const result = await setDefaultWorkspace({ id });\n spinner.succeed(\n result.changed ? \"Default OrgX workspace updated\" : \"OrgX workspace already set as default\",\n );\n persistContinuityDefaults({ workspace: result.workspace });\n printWorkspace(result.workspace);\n });\n\n program\n .command(\"intent\")\n .description(\n \"Capture an intent, preview the classified agent + plan, and approve or hand off to the browser.\",\n )\n .argument(\"[text...]\", \"intent text (quotes optional)\")\n .option(\"--workspace <id>\", \"workspace id override; defaults to the current workspace\")\n .option(\"--json\", \"emit a JSON summary instead of the box-drawn preview\")\n .action(async (textParts: string[], options: { workspace?: string; json?: boolean }) => {\n const initialText = textParts.join(\" \").trim();\n const workspaceId = options.workspace?.trim() ?? \"\";\n await runIntentCommand({\n ...(initialText ? { initialText } : {}),\n ...(workspaceId ? { workspaceId } : {}),\n jsonOutput: Boolean(options.json),\n });\n });\n\n program\n .command(\"audit\")\n .description(\"Run the AI-native Founder Loop self-audit from pasted or file-based AI-session context.\")\n .option(\"--input <path>\", \"AI-session transcript or summary file; stdin is used when piped\")\n .option(\"--from <sources>\", \"auto-import recent local AI sessions: codex, claude, or all\")\n .option(\"--session-limit <count>\", \"max recent sessions to import per selected source\", \"3\")\n .option(\"--session-days <days>\", \"lookback window for local AI-session imports\", \"30\")\n .option(\"--codex-sessions-dir <path>\", \"override Codex sessions directory for audit import\")\n .option(\"--claude-projects-dir <path>\", \"override Claude projects directory for audit import\")\n .option(\"--source-label <label>\", \"label for the imported AI-session source\")\n .option(\"--workspace-id <id>\", \"workspace id override; defaults to the current OrgX workspace when authenticated\")\n .option(\"--workspace-name <name>\", \"workspace name override for local-only audits\")\n .option(\"--output-dir <path>\", \"directory for generated audit JSON and Markdown\", \".orgx/audits\")\n .option(\"--attach-to-initiative <id>\", \"attach the generated audit artifact to an existing OrgX initiative\")\n .option(\"--create-initiative\", \"create an OrgX initiative from the generated audit plan\")\n .option(\"--write-follow-up\", \"create one approval-gated OrgX follow-up task from the audit recommendation\")\n .option(\"--workstream-id <id>\", \"optional workstream id for the generated follow-up task\")\n .option(\"--milestone-id <id>\", \"optional milestone id for the generated follow-up task\")\n .option(\"--dry-run\", \"exercise OrgX write paths without sending writes\")\n .option(\"--yes\", \"approve OrgX write flags in non-interactive mode\")\n .option(\"--json\", \"emit a JSON command summary\")\n .action(async (options: AuditCommandOptions) => {\n await safeTrackWizardTelemetry(\"audit_started\", {\n attach_to_initiative: Boolean(options.attachToInitiative),\n command: \"audit\",\n create_initiative: Boolean(options.createInitiative),\n dry_run: Boolean(options.dryRun),\n write_follow_up: Boolean(options.writeFollowUp),\n });\n await runAuditCommand(options);\n });\n\n const workGraph = program\n .command(\"work-graph\")\n .description(\"Build a redacted OrgX Work Graph report from AI-client, Slack, MCP, or manual context.\");\n\n workGraph\n .command(\"extraction-schema\")\n .description(\"Print the AI-client search schema used to extract Work Graph Trails from sessions and logs.\")\n .option(\"--output <path>\", \"write the schema prompt to a file\")\n .option(\"--json\", \"emit the protocol as JSON instead of Markdown\")\n .action(async (options: WorkGraphExtractionSchemaCommandOptions) => {\n await safeTrackWizardTelemetry(\"work_graph_extraction_schema_started\", {\n command: \"work-graph extraction-schema\",\n json: Boolean(options.json),\n });\n runWorkGraphExtractionSchemaCommand(options);\n });\n\n workGraph\n .command(\"preview\")\n .description(\"Preview the live Work Graph opportunity map without writing to OrgX.\")\n .option(\"--input <path>\", \"source transcript or summary file; stdin is used when piped\")\n .option(\"--extraction <path>\", \"structured AI-client extraction JSON; repeat or comma-separate for multiple clients\", collectPathOption, [])\n .option(\"--from <sources>\", \"auto-import recent local AI sessions: codex, claude, or all\")\n .option(\"--session-limit <count>\", \"max recent sessions to import per selected source\", \"3\")\n .option(\"--session-days <days>\", \"lookback window for local AI-session imports\", \"30\")\n .option(\"--codex-sessions-dir <path>\", \"override Codex sessions directory for import\")\n .option(\"--claude-projects-dir <path>\", \"override Claude projects directory for import\")\n .option(\"--source-label <label>\", \"label for the imported manual source\")\n .option(\"--workspace-id <id>\", \"workspace id override; defaults to the current OrgX workspace when authenticated\")\n .option(\"--workspace-name <name>\", \"workspace name override for local-only previews\")\n .option(\"--output-dir <path>\", \"directory for generated Work Graph JSON and Markdown\", \".orgx/work-graph\")\n .option(\"--json\", \"emit a JSON command summary\")\n .action(async (options: WorkGraphCommandOptions) => {\n await safeTrackWizardTelemetry(\"work_graph_preview_started\", {\n command: \"work-graph preview\",\n from: options.from ?? \"manual\",\n });\n await runWorkGraphCommand(options);\n });\n\n workGraph\n .command(\"profile\")\n .description(\"Build a local OrgX Profile with Work Graph Trails, Mirror, tensions, and launch recommendations.\")\n .option(\"--input <path>\", \"source transcript or summary file; stdin is used when piped\")\n .option(\"--extraction <path>\", \"structured AI-client extraction JSON; repeat or comma-separate for multiple clients\", collectPathOption, [])\n .option(\"--from <sources>\", \"auto-import recent local AI sessions: codex, claude, or all\")\n .option(\"--session-limit <count>\", \"max recent sessions to import per selected source\", \"5\")\n .option(\"--session-days <days>\", \"lookback window for local AI-session imports\", \"30\")\n .option(\"--codex-sessions-dir <path>\", \"override Codex sessions directory for import\")\n .option(\"--claude-projects-dir <path>\", \"override Claude projects directory for import\")\n .option(\"--source-label <label>\", \"label for the imported manual source\")\n .option(\"--workspace-id <id>\", \"workspace id override; defaults to the current OrgX workspace when authenticated\")\n .option(\"--workspace-name <name>\", \"workspace name override for local-only profiles\")\n .option(\"--output-dir <path>\", \"directory for generated Work Graph JSON and Markdown\", \".orgx/work-graph\")\n .option(\"--json\", \"emit a JSON command summary\")\n .action(async (options: WorkGraphCommandOptions) => {\n await safeTrackWizardTelemetry(\"work_graph_profile_started\", {\n command: \"work-graph profile\",\n from: options.from ?? \"manual\",\n });\n await runWorkGraphCommand(options);\n });\n\n const sessions = program\n .command(\"sessions\")\n .description(\"Inspect and reconcile local AI sessions into OrgX-ready Work Graph reports.\");\n\n sessions\n .command(\"reconcile\")\n .description(\"Backfill recent Codex and Claude sessions into a redacted Work Graph report.\")\n .option(\"--extraction <path>\", \"structured AI-client extraction JSON; repeat or comma-separate for multiple clients\", collectPathOption, [])\n .option(\"--from <sources>\", \"auto-import recent local AI sessions: codex, claude, or all\", \"all\")\n .option(\"--session-limit <count>\", \"max recent sessions to import per selected source\", \"5\")\n .option(\"--session-days <days>\", \"lookback window for local AI-session imports\", \"7\")\n .option(\"--codex-sessions-dir <path>\", \"override Codex sessions directory for import\")\n .option(\"--claude-projects-dir <path>\", \"override Claude projects directory for import\")\n .option(\"--workspace-id <id>\", \"workspace id override; defaults to the current OrgX workspace when authenticated\")\n .option(\"--workspace-name <name>\", \"workspace name override for local-only reconciliation\")\n .option(\"--output-dir <path>\", \"directory for generated Work Graph JSON and Markdown\", \".orgx/work-graph\")\n .option(\"--json\", \"emit a JSON command summary\")\n .action(async (options: WorkGraphCommandOptions) => {\n await safeTrackWizardTelemetry(\"sessions_reconcile_started\", {\n command: \"sessions reconcile\",\n from: options.from ?? \"all\",\n });\n await runWorkGraphCommand(options, { from: \"all\" });\n });\n\n const hooks = program\n .command(\"hooks\")\n .description(\"Inspect or install passive OrgX runtime hooks for local agent clients.\");\n\n hooks\n .command(\"doctor\")\n .description(\"Show Codex and Claude Code runtime hook wiring status.\")\n .option(\"--json\", \"emit a JSON command summary\")\n .action(async (options: HooksCommandOptions) => {\n const report = inspectRuntimeHooks();\n await safeTrackWizardTelemetry(\"hooks_doctor_ran\", {\n command: \"hooks doctor\",\n codex_installed: report.installed.codex,\n claude_code_installed: report.installed.claudeCode,\n hook_script_installed: report.installed.hookScript,\n });\n if (options.json) {\n console.log(JSON.stringify(report, null, 2));\n return;\n }\n printRuntimeHookInspection(report);\n });\n\n hooks\n .command(\"install\")\n .description(\"Install passive OrgX runtime hooks for Codex and/or Claude Code.\")\n .option(\"--targets <targets>\", \"comma-separated targets: codex, claude-code, or all\", \"all\")\n .option(\"--json\", \"emit a JSON command summary\")\n .action(async (options: HooksCommandOptions) => {\n const targets = parseRuntimeHookTargets(options.targets);\n const result = installRuntimeHooks(targets);\n await safeTrackWizardTelemetry(\"hooks_install_ran\", {\n command: \"hooks install\",\n targets: targets.join(\",\"),\n codex_changed: result.changed.codex,\n claude_code_changed: result.changed.claudeCode,\n });\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n printRuntimeHookInspection(result);\n if (result.backups.length > 0) {\n console.log(\"\");\n console.log(pc.dim(\" backups\"));\n for (const backup of result.backups) {\n console.log(` ${ICON.skip} ${pc.dim(backup)}`);\n }\n }\n });\n\n program\n .command(\"doctor\")\n .description(\"Verify local OrgX surface config and optional remote setup status.\")\n .action(async () => {\n const spinner = createOrgxSpinner(\"Running OrgX health check\");\n spinner.start();\n const report = await runDoctor();\n spinner.stop();\n const assessment = assessDoctorReport(report);\n const verification = summarizeSetupVerification(assessment);\n await safeTrackWizardTelemetry(\n \"doctor_ran\",\n buildDoctorTelemetryProperties(report, assessment, verification, {\n command: \"doctor\",\n }),\n );\n printDoctorReport(report, assessment);\n if (verification.status === \"error\") {\n process.exitCode = 1;\n }\n });\n\n const skills = program\n .command(\"skills\")\n .description(\"Install OrgX skills and rules into supported local tools.\");\n\n skills\n .command(\"add\")\n .description(\"Write standalone OrgX Cursor rules and Claude skills, skipping tool surfaces already owned by companion plugins.\")\n .argument(\"[packs...]\", \"skill pack names or 'all'\", [\"all\"])\n .option(\"--force\", \"Overwrite generated skill files even when manual edits are detected.\")\n .action(async (packs: string[], options: { force?: boolean }) => {\n const pluginTargets = (await listOrgxPluginStatuses())\n .filter((status) => status.installed)\n .map((status) => status.target);\n const spinner = createOrgxSpinner(\"Installing OrgX skills/rules into tools\");\n spinner.start();\n const report = await installOrgxSkills({\n force: options.force === true,\n pluginTargets,\n skillNames: packs,\n });\n spinner.succeed(\"OrgX skills/rules installed into tools\");\n printSkillInstallReport(report);\n await safeTrackWizardTelemetry(\"skills_installed\", {\n changed_count: countSkillReportChanges(report),\n command: \"skills:add\",\n pack_count: report.packs.length,\n plugin_managed_target_count: pluginTargets.length,\n requested_pack_count: packs.length,\n skill_extension_count: report.extensions.length,\n write_count: report.writes.length,\n });\n });\n\n skills\n .command(\"sync\")\n .description(\"Recompose installed OrgX skills/rules from core skills plus local extensions.\")\n .argument(\"[packs...]\", \"skill pack names or 'all'\", [\"all\"])\n .option(\"--force\", \"Overwrite generated skill files even when manual edits are detected.\")\n .action(async (packs: string[], options: { force?: boolean }) => {\n const pluginTargets = (await listOrgxPluginStatuses())\n .filter((status) => status.installed)\n .map((status) => status.target);\n const spinner = createOrgxSpinner(\"Syncing OrgX skills/rules and extensions into tools\");\n spinner.start();\n const report = await installOrgxSkills({\n force: options.force === true,\n pluginTargets,\n skillNames: packs,\n });\n spinner.succeed(\"OrgX skills/rules synced into tools\");\n printSkillInstallReport(report);\n await safeTrackWizardTelemetry(\"skills_synced\", {\n changed_count: countSkillReportChanges(report),\n command: \"skills:sync\",\n pack_count: report.packs.length,\n plugin_managed_target_count: pluginTargets.length,\n requested_pack_count: packs.length,\n skill_extension_count: report.extensions.length,\n write_count: report.writes.length,\n });\n });\n\n skills\n .command(\"status\")\n .description(\"Show installed skill/rule tracking and local skill extensions.\")\n .action(async () => {\n const report = getSkillStatus();\n console.log(pc.dim(\" extensions\"));\n printSkillExtensions(report.extensions);\n console.log(\"\");\n console.log(pc.dim(\" generated files\"));\n if (report.trackedFiles.length === 0) {\n console.log(` ${ICON.skip} ${pc.dim(\"no generated skill files tracked yet\")}`);\n } else {\n for (const file of report.trackedFiles) {\n console.log(` ${ICON.ok} ${pc.bold(file.skillId.padEnd(24))} ${pc.dim(file.path)}`);\n }\n }\n });\n\n const skillExtensions = skills\n .command(\"extensions\")\n .description(\"Create, edit, and sync user extensions appended after OrgX core skills.\");\n\n skillExtensions\n .command(\"list\")\n .description(\"List local OrgX skill extensions.\")\n .action(() => {\n printSkillExtensions(listSkillExtensions());\n });\n\n skillExtensions\n .command(\"add\")\n .description(\"Create a local extension file for an OrgX skill.\")\n .argument(\"<skill>\", \"Skill id, for example orgx, cursor-rules, or morning-briefing\")\n .option(\"--scope <scope>\", \"Extension scope: user, workspace, or project.\", \"user\")\n .option(\"--title <title>\", \"Extension title.\")\n .option(\"--content <content>\", \"Initial extension body content.\")\n .option(\"--overwrite\", \"Overwrite an existing extension file.\")\n .action((skill: string, options: {\n content?: string;\n overwrite?: boolean;\n scope?: \"user\" | \"workspace\" | \"project\";\n title?: string;\n }) => {\n const result = addSkillExtension({\n overwrite: options.overwrite === true,\n skillId: skill,\n ...(options.content !== undefined ? { content: options.content } : {}),\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n ...(options.title !== undefined ? { title: options.title } : {}),\n });\n printSkillExtensionWrite(result);\n console.log(\n ` ${ICON.skip} ${pc.dim(`Run ${getCmd()} skills sync to apply it to configured tools.`)}`,\n );\n });\n\n skillExtensions\n .command(\"edit\")\n .description(\"Create if needed, then open a local OrgX skill extension in $EDITOR.\")\n .argument(\"<skill>\", \"Skill id, for example orgx, cursor-rules, or morning-briefing\")\n .option(\"--scope <scope>\", \"Extension scope: user, workspace, or project.\", \"user\")\n .action((skill: string, options: { scope?: \"user\" | \"workspace\" | \"project\" }) => {\n const result = addSkillExtension({\n skillId: skill,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n });\n printSkillExtensionWrite(result);\n if (!openPathInEditor(result.path)) {\n console.log(\n ` ${ICON.warn} ${pc.yellow(\"editor not opened\")} ${pc.dim(`Set EDITOR or edit ${result.path}`)}`,\n );\n }\n console.log(\n ` ${ICON.skip} ${pc.dim(`Run ${getCmd()} skills sync to apply it to configured tools.`)}`,\n );\n });\n\n skillExtensions\n .command(\"enable\")\n .description(\"Enable a local OrgX skill extension.\")\n .argument(\"<skill>\", \"Skill id, for example orgx, cursor-rules, or morning-briefing\")\n .option(\"--scope <scope>\", \"Extension scope: user, workspace, or project.\", \"user\")\n .action((skill: string, options: { scope?: \"user\" | \"workspace\" | \"project\" }) => {\n const result = setSkillExtensionEnabled({\n enabled: true,\n skillId: skill,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n });\n printSkillExtensionWrite(result);\n console.log(\n ` ${ICON.skip} ${pc.dim(`Run ${getCmd()} skills sync to apply it to configured tools.`)}`,\n );\n });\n\n skillExtensions\n .command(\"disable\")\n .description(\"Disable a local OrgX skill extension without deleting it.\")\n .argument(\"<skill>\", \"Skill id, for example orgx, cursor-rules, or morning-briefing\")\n .option(\"--scope <scope>\", \"Extension scope: user, workspace, or project.\", \"user\")\n .action((skill: string, options: { scope?: \"user\" | \"workspace\" | \"project\" }) => {\n const result = setSkillExtensionEnabled({\n enabled: false,\n skillId: skill,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n });\n printSkillExtensionWrite(result);\n console.log(\n ` ${ICON.skip} ${pc.dim(`Run ${getCmd()} skills sync to apply it to configured tools.`)}`,\n );\n });\n\n await program.parseAsync(process.argv);\n}\n\nmain().catch((error) => {\n console.error(pc.red(error instanceof Error ? error.message : String(error)));\n process.exitCode = 1;\n});\n","import pc from \"picocolors\";\n\nexport function renderBanner(version?: string): string {\n const lines = [\n \" ____ ____ _______ __\",\n \" / __ \\\\/ __ \\\\ / ____/ |/ /\",\n \"/ / / / /_/ // / __ | / \",\n \"/ /_/ / _, _// /_/ // | \",\n \"\\\\____/_/ |_| \\\\____//_/|_| \",\n ];\n\n const art = lines.map((line) => pc.cyan(line)).join(\"\\n\");\n const tag = version ? ` ${pc.dim(`v${version}`)}` : \"\";\n return `${art}${tag}`;\n}\n\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const ORGX_HOSTED_MCP_KEY = \"orgx\";\nexport const ORGX_LOCAL_MCP_KEY = \"orgx-openclaw\";\nexport const ORGX_HOSTED_MCP_URL = \"https://mcp.useorgx.com/mcp\";\nexport const ORGX_HOSTED_MCP_HEALTH_URL = \"https://mcp.useorgx.com/health\";\nexport const ORGX_HOSTED_OAUTH_BASE_URL = \"https://mcp.useorgx.com\";\nexport const ORGX_HOSTED_OAUTH_AUTHORIZE_URL = `${ORGX_HOSTED_OAUTH_BASE_URL}/authorize`;\nexport const ORGX_HOSTED_OAUTH_TOKEN_URL = `${ORGX_HOSTED_OAUTH_BASE_URL}/token`;\nexport const ORGX_HOSTED_OAUTH_REGISTER_URL = `${ORGX_HOSTED_OAUTH_BASE_URL}/register`;\nexport const ORGX_WIZARD_NPM_PACKAGE_NAME = \"@useorgx/wizard\";\nexport const NPM_REGISTRY_BASE_URL = \"https://registry.npmjs.org\";\nexport const DEFAULT_OPENCLAW_GATEWAY_PORT = 18_789;\nexport const DEFAULT_ORGX_BASE_URL =\n process.env.ORGX_BASE_URL?.trim() || \"https://useorgx.com\";\nexport const ORGX_WIZARD_OAUTH_CALLBACK_HOST = \"127.0.0.1\";\nexport const ORGX_WIZARD_OAUTH_CALLBACK_PATH = \"/oauth/callback\";\nexport const ORGX_WIZARD_OAUTH_PREFERRED_PORT = 6_274;\nexport const ORGX_WIZARD_OAUTH_SCOPES = [\n \"decisions:read\",\n \"decisions:write\",\n \"agents:read\",\n \"agents:write\",\n \"initiatives:read\",\n \"initiatives:write\",\n \"memory:read\",\n \"offline_access\",\n] as const;\nexport const ORGX_WIZARD_OAUTH_SCOPE = ORGX_WIZARD_OAUTH_SCOPES.join(\" \");\n\nconst HOME = homedir();\nconst APPDATA = process.env.APPDATA?.trim();\nconst LOCAL_APPDATA = process.env.LOCALAPPDATA?.trim();\nconst XDG_CONFIG_HOME =\n process.env.XDG_CONFIG_HOME?.trim() || join(HOME, \".config\");\nexport const ORGX_WIZARD_CONFIG_HOME =\n process.env.ORGX_WIZARD_CONFIG_HOME?.trim() ||\n join(XDG_CONFIG_HOME, \"useorgx\", \"wizard\");\nexport const ORGX_WIZARD_AUTH_PATH = join(ORGX_WIZARD_CONFIG_HOME, \"auth.json\");\nexport const ORGX_WIZARD_STATE_PATH = join(ORGX_WIZARD_CONFIG_HOME, \"state.json\");\nexport const ORGX_SKILL_EXTENSIONS_DIR = join(ORGX_WIZARD_CONFIG_HOME, \"skill-extensions\");\nexport const ORGX_WIZARD_KEYTAR_SERVICE = \"@useorgx/wizard\";\nexport const ORGX_WIZARD_KEYTAR_ACCOUNT = \"orgx-api-key\";\n\nfunction normalizeOrgxApiBaseUrl(baseUrl: string): string {\n const normalized = baseUrl.replace(/\\/+$/, \"\");\n if (/\\/api(\\/|$)/.test(normalized)) {\n return normalized;\n }\n return `${normalized}/api`;\n}\n\nconst ORGX_API_BASE_URL = normalizeOrgxApiBaseUrl(DEFAULT_ORGX_BASE_URL);\nexport const ORGX_SETUP_STATUS_URL = `${ORGX_API_BASE_URL}/setup/status`;\nexport const ORGX_AUTH_VERIFY_URL = `${ORGX_API_BASE_URL}/auth/verify`;\nexport const ORGX_CLIENT_SYNC_URL = `${ORGX_API_BASE_URL}/client/sync`;\n\nfunction uniquePaths(paths: Array<string | undefined>): string[] {\n return [...new Set(paths.filter((path): path is string => Boolean(path)))];\n}\n\nexport const CLAUDE_DIR = join(HOME, \".claude\");\nexport const CURSOR_DIR = join(HOME, \".cursor\");\nexport const CODEX_DIR = join(HOME, \".codex\");\nexport const OPENCLAW_DIR = join(HOME, \".openclaw\");\nexport const AGENTS_DIR = join(HOME, \".agents\");\nexport const CLAUDE_PROJECTS_DIR = join(CLAUDE_DIR, \"projects\");\nexport const CODEX_SESSIONS_DIR = join(CODEX_DIR, \"sessions\");\nexport const CLAUDE_SKILLS_DIR = join(CLAUDE_DIR, \"skills\");\nexport const CLAUDE_ORGX_SKILL_DIR = join(CLAUDE_SKILLS_DIR, \"orgx\");\nexport const CLAUDE_ORGX_SKILL_PATH = join(CLAUDE_ORGX_SKILL_DIR, \"SKILL.md\");\nexport const CURSOR_RULES_DIR = join(CURSOR_DIR, \"rules\");\nexport const CURSOR_ORGX_RULE_PATH = join(CURSOR_RULES_DIR, \"orgx.md\");\nexport const CURSOR_PLUGINS_DIR = join(CURSOR_DIR, \"plugins\", \"local\");\nexport const CURSOR_ORGX_PLUGIN_DIR = join(CURSOR_PLUGINS_DIR, \"cursor-plugin\");\nexport const CODEX_PLUGINS_DIR = join(CODEX_DIR, \"plugins\");\nexport const CODEX_ORGX_PLUGIN_DIR = join(CODEX_PLUGINS_DIR, \"orgx-codex-plugin\");\nexport const CODEX_MARKETPLACE_DIR = join(AGENTS_DIR, \"plugins\");\nexport const CODEX_MARKETPLACE_PATH = join(CODEX_MARKETPLACE_DIR, \"marketplace.json\");\nexport const CLAUDE_MANAGED_MARKETPLACE_DIR = join(\n ORGX_WIZARD_CONFIG_HOME,\n \"plugins\",\n \"claude-marketplace\",\n);\nexport const CLAUDE_MANAGED_MARKETPLACE_MANIFEST_PATH = join(\n CLAUDE_MANAGED_MARKETPLACE_DIR,\n \".claude-plugin\",\n \"marketplace.json\",\n);\nexport const CLAUDE_MANAGED_PLUGIN_DIR = join(\n CLAUDE_MANAGED_MARKETPLACE_DIR,\n \"plugins\",\n \"orgx-claude-code-plugin\",\n);\n\nexport const CLAUDE_MCP_PATHS = uniquePaths([join(CLAUDE_DIR, \"mcp.json\")]);\nexport const CURSOR_MCP_PATHS = uniquePaths([join(CURSOR_DIR, \"mcp.json\")]);\nexport const CODEX_CONFIG_PATHS = uniquePaths([join(CODEX_DIR, \"config.toml\")]);\nexport const OPENCLAW_CONFIG_PATHS = uniquePaths([\n join(OPENCLAW_DIR, \"openclaw.json\"),\n]);\n\nexport const CLAUDE_MCP_PATH = CLAUDE_MCP_PATHS[0];\nexport const CURSOR_MCP_PATH = CURSOR_MCP_PATHS[0];\nexport const CODEX_CONFIG_PATH = CODEX_CONFIG_PATHS[0];\nexport const OPENCLAW_CONFIG_PATH = OPENCLAW_CONFIG_PATHS[0];\n\nexport const CLAUDE_INSTALL_PATHS = uniquePaths([CLAUDE_DIR]);\nexport const CURSOR_INSTALL_PATHS = uniquePaths([CURSOR_DIR]);\nexport const CODEX_INSTALL_PATHS = uniquePaths([CODEX_DIR]);\nexport const OPENCLAW_INSTALL_PATHS = uniquePaths([OPENCLAW_DIR]);\n\nexport const VSCODE_MCP_PATHS = uniquePaths([\n join(HOME, \"Library\", \"Application Support\", \"Code\", \"User\", \"mcp.json\"),\n join(XDG_CONFIG_HOME, \"Code\", \"User\", \"mcp.json\"),\n APPDATA ? join(APPDATA, \"Code\", \"User\", \"mcp.json\") : undefined,\n]);\nexport const VSCODE_INSTALL_PATHS = uniquePaths([\n join(HOME, \"Library\", \"Application Support\", \"Code\", \"User\"),\n join(XDG_CONFIG_HOME, \"Code\", \"User\"),\n APPDATA ? join(APPDATA, \"Code\", \"User\") : undefined,\n LOCAL_APPDATA ? join(LOCAL_APPDATA, \"Programs\", \"Microsoft VS Code\") : undefined,\n]);\n\nexport const WINDSURF_MCP_PATHS = uniquePaths([\n join(HOME, \".codeium\", \"windsurf\", \"mcp_config.json\"),\n]);\nexport const WINDSURF_INSTALL_PATHS = uniquePaths([\n join(HOME, \".codeium\", \"windsurf\"),\n LOCAL_APPDATA ? join(LOCAL_APPDATA, \"Programs\", \"Windsurf\") : undefined,\n]);\n\nexport const ZED_SETTINGS_PATHS = uniquePaths([\n join(HOME, \"Library\", \"Application Support\", \"Zed\", \"settings.json\"),\n join(XDG_CONFIG_HOME, \"zed\", \"settings.json\"),\n APPDATA ? join(APPDATA, \"Zed\", \"settings.json\") : undefined,\n]);\nexport const ZED_INSTALL_PATHS = uniquePaths([\n join(HOME, \"Library\", \"Application Support\", \"Zed\"),\n join(XDG_CONFIG_HOME, \"zed\"),\n APPDATA ? join(APPDATA, \"Zed\") : undefined,\n LOCAL_APPDATA ? join(LOCAL_APPDATA, \"Programs\", \"Zed\") : undefined,\n]);\n\nexport const CHATGPT_APP_PATHS = uniquePaths([\n join(HOME, \"Library\", \"Application Support\", \"OpenAI\"),\n join(HOME, \"Library\", \"Application Support\", \"com.openai.chat\"),\n join(XDG_CONFIG_HOME, \"OpenAI\"),\n join(XDG_CONFIG_HOME, \"openai\"),\n APPDATA ? join(APPDATA, \"OpenAI\") : undefined,\n LOCAL_APPDATA ? join(LOCAL_APPDATA, \"OpenAI\") : undefined,\n]);\n","import { spawnSync } from \"node:child_process\";\n\nimport { buildOrgxApiUrl, normalizeOrgxBaseUrl } from \"./auth.js\";\nimport { isRecord } from \"./fs.js\";\n\nexport type PairingStatus =\n | \"pending\"\n | \"authorized\"\n | \"ready\"\n | \"consumed\"\n | \"expired\"\n | \"cancelled\"\n | \"failed\";\n\nexport interface BrowserPairingStartResult {\n pairingId: string;\n pollToken: string;\n connectUrl: string;\n expiresAt: string;\n pollIntervalMs: number;\n}\n\nexport interface BrowserPairingPollResult {\n pairingId: string;\n status: PairingStatus;\n expiresAt: string;\n workspaceName: string | null;\n keyPrefix: string | null;\n executionMode: \"cloud\" | \"local\" | null;\n errorCode: string | null;\n errorMessage: string | null;\n key?: string;\n}\n\nexport interface BrowserPairingOpenResult {\n ok: boolean;\n error?: string;\n}\n\ninterface FetchJsonOptions {\n body?: string | undefined;\n fetchImpl?: typeof fetch | undefined;\n method: string;\n url: string;\n}\n\nfunction asString(value: unknown): string | null {\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : null;\n}\n\nfunction parseJsonBody(text: string): unknown {\n if (!text) return null;\n\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nasync function fetchJson<T>({\n url,\n method,\n body,\n fetchImpl = fetch,\n}: FetchJsonOptions): Promise<T> {\n const response = await fetchImpl(url, {\n method,\n headers: {\n Accept: \"application/json\",\n ...(body ? { \"Content-Type\": \"application/json\" } : {}),\n },\n ...(body ? { body } : {}),\n signal: AbortSignal.timeout(7_000),\n });\n\n const payload = parseJsonBody(await response.text());\n\n if (!response.ok) {\n const errorMessage = isRecord(payload)\n ? asString(payload.error) ?? asString(payload.message)\n : typeof payload === \"string\"\n ? payload\n : null;\n throw new Error(errorMessage ?? `HTTP ${response.status}`);\n }\n\n if (isRecord(payload) && payload.ok === true && \"data\" in payload) {\n return payload.data as T;\n }\n\n return payload as T;\n}\n\nconst UNROUTABLE_HOSTNAMES = new Set([\"0.0.0.0\", \"::\", \"[::]\"]);\n\nexport function sanitizeConnectUrl(connectUrl: string, baseUrl?: string): string {\n try {\n const parsed = new URL(connectUrl);\n if (UNROUTABLE_HOSTNAMES.has(parsed.hostname)) {\n const base = new URL(normalizeOrgxBaseUrl(baseUrl));\n parsed.protocol = base.protocol;\n parsed.hostname = base.hostname;\n parsed.port = base.port;\n }\n return parsed.toString();\n } catch {\n return connectUrl;\n }\n}\n\nfunction parsePairingStartResult(value: unknown): BrowserPairingStartResult {\n if (!isRecord(value)) {\n throw new Error(\"OrgX pairing start returned an invalid response.\");\n }\n\n const pairingId = asString(value.pairingId);\n const pollToken = asString(value.pollToken);\n const connectUrl = asString(value.connectUrl);\n const expiresAt = asString(value.expiresAt);\n const pollIntervalMs = typeof value.pollIntervalMs === \"number\"\n ? value.pollIntervalMs\n : Number.NaN;\n\n if (!pairingId || !pollToken || !connectUrl || !expiresAt || !Number.isFinite(pollIntervalMs)) {\n throw new Error(\"OrgX pairing start returned an incomplete response.\");\n }\n\n return { pairingId, pollToken, connectUrl, expiresAt, pollIntervalMs };\n}\n\nfunction parsePairingPollResult(value: unknown): BrowserPairingPollResult {\n if (!isRecord(value)) {\n throw new Error(\"OrgX pairing poll returned an invalid response.\");\n }\n\n const pairingId = asString(value.pairingId);\n const status = asString(value.status) as PairingStatus | null;\n const expiresAt = asString(value.expiresAt);\n\n if (!pairingId || !status || !expiresAt) {\n throw new Error(\"OrgX pairing poll returned an incomplete response.\");\n }\n\n return {\n pairingId,\n status,\n expiresAt,\n workspaceName: asString(value.workspaceName),\n keyPrefix: asString(value.keyPrefix),\n executionMode: value.executionMode === \"cloud\" || value.executionMode === \"local\"\n ? value.executionMode\n : null,\n errorCode: asString(value.errorCode),\n errorMessage: asString(value.errorMessage),\n ...(asString(value.key) ? { key: asString(value.key)! } : {}),\n };\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport async function startBrowserPairing(\n options: {\n baseUrl?: string | undefined;\n deviceName?: string | undefined;\n installationId: string;\n platform?: string | undefined;\n },\n fetchImpl?: typeof fetch,\n): Promise<BrowserPairingStartResult> {\n const data = await fetchJson<unknown>({\n url: buildOrgxApiUrl(\"/plugin/openclaw/pairings\", options.baseUrl),\n method: \"POST\",\n body: JSON.stringify({\n installationId: options.installationId,\n clientType: 'orgx-wizard',\n ...(options.deviceName ? { deviceName: options.deviceName } : {}),\n ...(options.platform ? { platform: options.platform } : {}),\n }),\n fetchImpl,\n });\n\n const result = parsePairingStartResult(data);\n return {\n ...result,\n connectUrl: sanitizeConnectUrl(result.connectUrl, options.baseUrl),\n };\n}\n\nexport async function pollBrowserPairing(\n options: {\n baseUrl?: string | undefined;\n pairingId: string;\n pollToken: string;\n },\n fetchImpl?: typeof fetch,\n): Promise<BrowserPairingPollResult> {\n const baseUrl = normalizeOrgxBaseUrl(options.baseUrl);\n const url = new URL(buildOrgxApiUrl(`/plugin/openclaw/pairings/${options.pairingId}`, baseUrl));\n url.searchParams.set(\"pollToken\", options.pollToken);\n\n const data = await fetchJson<unknown>({\n url: url.toString(),\n method: \"GET\",\n fetchImpl,\n });\n\n return parsePairingPollResult(data);\n}\n\nexport async function waitForBrowserPairing(\n options: {\n baseUrl?: string | undefined;\n pairingId: string;\n pollIntervalMs?: number | undefined;\n pollToken: string;\n timeoutMs?: number | undefined;\n },\n fetchImpl?: typeof fetch,\n): Promise<BrowserPairingPollResult> {\n const timeoutMs = options.timeoutMs ?? 10 * 60_000;\n const pollIntervalMs = options.pollIntervalMs ?? 1_500;\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() <= deadline) {\n const result = await pollBrowserPairing(\n {\n baseUrl: options.baseUrl,\n pairingId: options.pairingId,\n pollToken: options.pollToken,\n },\n fetchImpl,\n );\n\n if (result.status === \"ready\") {\n if (!result.key) {\n throw new Error(\"OrgX pairing completed without returning an API key.\");\n }\n return result;\n }\n\n if (result.status === \"failed\") {\n throw new Error(result.errorMessage ?? \"OrgX pairing failed.\");\n }\n\n if (result.status === \"expired\") {\n throw new Error(\"OrgX pairing expired before it was approved.\");\n }\n\n if (result.status === \"cancelled\") {\n throw new Error(\"OrgX pairing was cancelled in the browser.\");\n }\n\n if (result.status === \"consumed\") {\n throw new Error(\"OrgX pairing was already consumed by another client.\");\n }\n\n await sleep(Math.min(5_000, Math.max(350, pollIntervalMs)));\n }\n\n throw new Error(\n `Timed out waiting for OrgX pairing after ${Math.round(timeoutMs / 1000)} seconds.`,\n );\n}\n\nexport async function acknowledgeBrowserPairing(\n options: {\n baseUrl?: string | undefined;\n pairingId: string;\n pollToken: string;\n },\n fetchImpl?: typeof fetch,\n): Promise<void> {\n await fetchJson<unknown>({\n url: buildOrgxApiUrl(`/plugin/openclaw/pairings/${options.pairingId}/ack`, options.baseUrl),\n method: \"POST\",\n body: JSON.stringify({ pollToken: options.pollToken }),\n fetchImpl,\n });\n}\n\nexport function openBrowser(url: string): BrowserPairingOpenResult {\n const platform = process.platform;\n const result = platform === \"darwin\"\n ? spawnSync(\"open\", [url], { stdio: \"ignore\" })\n : platform === \"win32\"\n ? spawnSync(\"cmd\", [\"/c\", \"start\", \"\", url], { stdio: \"ignore\" })\n : spawnSync(\"xdg-open\", [url], { stdio: \"ignore\" });\n\n if (result.error) {\n return { ok: false, error: result.error.message };\n }\n\n if (typeof result.status === \"number\" && result.status !== 0) {\n return { ok: false, error: `Browser open command exited with code ${result.status}.` };\n }\n\n return { ok: true };\n}\n","import {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport function fileExists(path: string): boolean {\n return existsSync(path);\n}\n\nexport function readTextIfExists(path: string): string | null {\n if (!existsSync(path)) return null;\n\n try {\n if (!statSync(path).isFile()) {\n return null;\n }\n\n return readFileSync(path, \"utf8\");\n } catch (error) {\n const code = typeof error === \"object\" && error && \"code\" in error\n ? String(error.code)\n : undefined;\n\n if (code === \"ENOENT\" || code === \"ENOTDIR\" || code === \"EISDIR\") {\n return null;\n }\n\n throw error;\n }\n}\n\nexport function writeTextFile(\n path: string,\n content: string,\n options: { mode?: number } = {},\n): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, content, {\n encoding: \"utf8\",\n ...(options.mode === undefined ? {} : { mode: options.mode }),\n });\n\n if (options.mode !== undefined) {\n chmodSync(path, options.mode);\n }\n}\n\nexport function writeJsonFile(\n path: string,\n value: unknown,\n options: { mode?: number } = {},\n): void {\n writeTextFile(path, `${JSON.stringify(value, null, 2)}\\n`, options);\n}\n\nexport function deleteFileIfExists(path: string): boolean {\n if (!existsSync(path)) return false;\n\n try {\n if (!statSync(path).isFile()) {\n return false;\n }\n\n unlinkSync(path);\n return true;\n } catch (error) {\n const code = typeof error === \"object\" && error && \"code\" in error\n ? String(error.code)\n : undefined;\n\n if (code === \"ENOENT\" || code === \"ENOTDIR\" || code === \"EISDIR\") {\n return false;\n }\n\n throw error;\n }\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nexport function parseJsonObject(input: string | null): Record<string, unknown> {\n if (!input) return {};\n\n try {\n const parsed = JSON.parse(input);\n return isRecord(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nexport function readObject(\n value: unknown,\n fallback: Record<string, unknown> = {},\n): Record<string, unknown> {\n return isRecord(value) ? value : fallback;\n}\n","import {\n DEFAULT_OPENCLAW_GATEWAY_PORT,\n DEFAULT_ORGX_BASE_URL,\n} from \"../constants.js\";\nimport { isRecord, parseJsonObject, readObject } from \"../lib/fs.js\";\n\ntype JsonObject = Record<string, unknown>;\n\nexport interface OpenClawInspection {\n configured: boolean;\n installed: boolean;\n pluginKey: \"orgx\" | \"openclaw-plugin\" | null;\n details: string[];\n}\n\nexport interface OpenClawAuthConfig {\n apiKey: string;\n baseUrl: string;\n pluginKey: \"orgx\" | \"openclaw-plugin\" | null;\n enabled: boolean;\n}\n\nexport interface OpenClawOrgxDefaultsInput {\n apiKey?: string;\n baseUrl?: string;\n}\n\nfunction cleanupEmptyObjects(value: JsonObject): void {\n for (const [key, child] of Object.entries(value)) {\n if (!isRecord(child)) continue;\n cleanupEmptyObjects(child);\n if (Object.keys(child).length === 0) {\n delete value[key];\n }\n }\n}\n\nexport function readOpenClawGatewayPort(raw: unknown): number {\n const isValidPort = (value: number): boolean =>\n Number.isFinite(value) && value >= 1 && value <= 65_535;\n\n const root = isRecord(raw) ? raw : {};\n const gateway = readObject(root.gateway);\n const port = gateway.port;\n\n if (typeof port === \"number\" && isValidPort(port)) {\n return Math.floor(port);\n }\n\n if (typeof port === \"string\") {\n const parsed = Number.parseInt(port, 10);\n if (isValidPort(parsed)) {\n return parsed;\n }\n }\n\n return DEFAULT_OPENCLAW_GATEWAY_PORT;\n}\n\nexport function buildLocalMcpUrl(raw: unknown): string {\n return `http://127.0.0.1:${readOpenClawGatewayPort(raw)}/orgx/mcp`;\n}\n\nfunction resolvePluginKey(entries: JsonObject): \"orgx\" | \"openclaw-plugin\" {\n if (isRecord(entries[\"openclaw-plugin\"])) {\n return \"openclaw-plugin\";\n }\n\n if (isRecord(entries.orgx)) {\n return \"orgx\";\n }\n\n return \"orgx\";\n}\n\nexport function readOpenClawAuth(input: string | null): OpenClawAuthConfig {\n const current = parseJsonObject(input);\n const plugins = readObject(current.plugins);\n const entries = readObject(plugins.entries);\n const pluginKey = isRecord(entries[\"openclaw-plugin\"])\n ? \"openclaw-plugin\"\n : isRecord(entries.orgx)\n ? \"orgx\"\n : null;\n const entry = pluginKey ? readObject(entries[pluginKey]) : {};\n const config = readObject(entry.config);\n\n return {\n apiKey: typeof config.apiKey === \"string\" ? config.apiKey.trim() : \"\",\n baseUrl:\n typeof config.baseUrl === \"string\" && config.baseUrl.trim().length > 0\n ? config.baseUrl.trim()\n : DEFAULT_ORGX_BASE_URL,\n pluginKey,\n enabled: entry.enabled !== false,\n };\n}\n\nexport function patchOpenClawConfig(\n input: string | null,\n auth: OpenClawOrgxDefaultsInput = {},\n): string {\n const current = parseJsonObject(input);\n const plugins = readObject(current.plugins);\n const entries = readObject(plugins.entries);\n const pluginKey = resolvePluginKey(entries);\n const entry = readObject(entries[pluginKey]);\n const config = readObject(entry.config);\n const apiKey =\n typeof auth.apiKey === \"string\" && auth.apiKey.trim().length > 0\n ? auth.apiKey.trim()\n : typeof config.apiKey === \"string\" && config.apiKey.trim().length > 0\n ? config.apiKey.trim()\n : undefined;\n const baseUrl =\n typeof auth.baseUrl === \"string\" && auth.baseUrl.trim().length > 0\n ? auth.baseUrl.trim()\n : typeof config.baseUrl === \"string\" && config.baseUrl.trim().length > 0\n ? config.baseUrl.trim()\n : DEFAULT_ORGX_BASE_URL;\n\n entries[pluginKey] = {\n ...entry,\n enabled: true,\n config: {\n ...config,\n ...(apiKey ? { apiKey } : {}),\n baseUrl,\n dashboardEnabled:\n typeof config.dashboardEnabled === \"boolean\"\n ? config.dashboardEnabled\n : true,\n autoInstallAgentSuiteOnConnect:\n typeof config.autoInstallAgentSuiteOnConnect === \"boolean\"\n ? config.autoInstallAgentSuiteOnConnect\n : true,\n autoConfigureMcpClientsOnConnect:\n typeof config.autoConfigureMcpClientsOnConnect === \"boolean\"\n ? config.autoConfigureMcpClientsOnConnect\n : true,\n },\n };\n\n plugins.entries = entries;\n current.plugins = plugins;\n\n return `${JSON.stringify(current, null, 2)}\\n`;\n}\n\nexport function removeOpenClawConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const plugins = readObject(current.plugins);\n const entries = readObject(plugins.entries);\n\n for (const key of [\"openclaw-plugin\", \"orgx\"]) {\n const entry = readObject(entries[key]);\n if (!Object.keys(entry).length) continue;\n const config = readObject(entry.config);\n delete config.baseUrl;\n delete config.dashboardEnabled;\n delete config.autoInstallAgentSuiteOnConnect;\n delete config.autoConfigureMcpClientsOnConnect;\n if (Object.keys(config).length > 0) {\n entry.config = config;\n } else {\n delete entry.config;\n }\n entries[key] = entry;\n }\n\n plugins.entries = entries;\n current.plugins = plugins;\n cleanupEmptyObjects(current);\n\n return `${JSON.stringify(current, null, 2)}\\n`;\n}\n\nexport function inspectOpenClawConfig(input: string | null): OpenClawInspection {\n const current = parseJsonObject(input);\n const plugins = readObject(current.plugins);\n const entries = readObject(plugins.entries);\n const installs = readObject(plugins.installs);\n const pluginKey = isRecord(entries[\"openclaw-plugin\"])\n ? \"openclaw-plugin\"\n : isRecord(entries.orgx)\n ? \"orgx\"\n : null;\n const entry = pluginKey ? readObject(entries[pluginKey]) : {};\n const config = readObject(entry.config);\n const installed =\n pluginKey !== null ||\n isRecord(installs[\"openclaw-plugin\"]) ||\n isRecord(installs.orgx);\n const configured =\n installed &&\n entry.enabled === true &&\n (typeof config.baseUrl === \"string\" ||\n typeof config.autoInstallAgentSuiteOnConnect === \"boolean\" ||\n typeof config.autoConfigureMcpClientsOnConnect === \"boolean\");\n\n return {\n configured,\n installed,\n pluginKey,\n details: [\n `plugin key: ${pluginKey ?? \"missing\"}`,\n `enabled: ${entry.enabled === true ? \"yes\" : \"no\"}`,\n `gateway port: ${readOpenClawGatewayPort(current)}`,\n ],\n };\n}\n","import {\n ORGX_WIZARD_AUTH_PATH,\n ORGX_WIZARD_KEYTAR_ACCOUNT,\n ORGX_WIZARD_KEYTAR_SERVICE,\n} from \"../constants.js\";\nimport {\n deleteFileIfExists,\n parseJsonObject,\n readTextIfExists,\n writeJsonFile,\n} from \"./fs.js\";\n\nexport type WizardAuthStorage = \"file\" | \"keytar\";\nexport type WizardAuthSource = \"manual\" | \"pkce\";\n\nexport interface WizardAuthRecord {\n apiKey: string;\n keyPrefix: string;\n baseUrl: string;\n source: WizardAuthSource;\n storage: WizardAuthStorage;\n verifiedAt: string;\n /** Present when source is \"pkce\" — used to silently refresh access_token. */\n refreshToken?: string;\n /** OAuth client_id used to obtain this token (needed for refresh). */\n oauthClientId?: string;\n}\n\nexport interface WizardAuthMetadata {\n baseUrl: string;\n keyPrefix: string;\n source: WizardAuthSource;\n storage: WizardAuthStorage;\n verifiedAt: string;\n}\n\nexport interface WizardSecretStore {\n deletePassword(service: string, account: string): Promise<boolean>;\n getPassword(service: string, account: string): Promise<string | null>;\n setPassword(service: string, account: string, password: string): Promise<void>;\n}\n\ninterface StoredWizardAuthRecord {\n apiKey?: string;\n baseUrl: string;\n keyPrefix: string;\n source?: WizardAuthSource;\n storage: WizardAuthStorage;\n verifiedAt: string;\n refreshToken?: string;\n oauthClientId?: string;\n}\n\ninterface WizardAuthStoreOptions {\n preferSecureStorage?: boolean;\n secretStore?: WizardSecretStore | null;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\nexport function extractKeyPrefix(apiKey: string): string {\n return apiKey.trim().slice(0, 12);\n}\n\nfunction parseStoredWizardAuthRecord(raw: string | null): StoredWizardAuthRecord | null {\n const parsed = parseJsonObject(raw);\n\n if (\n !isNonEmptyString(parsed.keyPrefix) ||\n !isNonEmptyString(parsed.baseUrl) ||\n !isNonEmptyString(parsed.verifiedAt)\n ) {\n return null;\n }\n\n const storage = parsed.storage === \"keytar\" ? \"keytar\" : \"file\";\n const source: WizardAuthSource = parsed.source === \"pkce\" ? \"pkce\" : \"manual\";\n\n return {\n baseUrl: parsed.baseUrl.trim(),\n ...(isNonEmptyString(parsed.apiKey) ? { apiKey: parsed.apiKey.trim() } : {}),\n keyPrefix: parsed.keyPrefix.trim(),\n source,\n storage,\n verifiedAt: parsed.verifiedAt.trim(),\n ...(isNonEmptyString(parsed.refreshToken) ? { refreshToken: parsed.refreshToken.trim() } : {}),\n ...(isNonEmptyString(parsed.oauthClientId) ? { oauthClientId: parsed.oauthClientId.trim() } : {}),\n };\n}\n\nasync function loadDefaultSecretStore(): Promise<WizardSecretStore | null> {\n if (process.env.ORGX_WIZARD_DISABLE_KEYTAR === \"1\") {\n return null;\n }\n\n try {\n const imported = await import(\"keytar\");\n const candidate = (\n \"default\" in imported && imported.default ? imported.default : imported\n ) as Partial<WizardSecretStore>;\n\n if (\n typeof candidate.getPassword === \"function\" &&\n typeof candidate.setPassword === \"function\" &&\n typeof candidate.deletePassword === \"function\"\n ) {\n return candidate as WizardSecretStore;\n }\n } catch {\n return null;\n }\n\n return null;\n}\n\nasync function resolveSecretStore(\n options: WizardAuthStoreOptions,\n): Promise<WizardSecretStore | null> {\n if (options.secretStore !== undefined) {\n return options.secretStore;\n }\n\n return loadDefaultSecretStore();\n}\n\nfunction buildStoredRecord(\n value: WizardAuthRecord,\n): StoredWizardAuthRecord {\n return {\n ...(value.storage === \"file\" ? { apiKey: value.apiKey } : {}),\n baseUrl: value.baseUrl,\n keyPrefix: value.keyPrefix,\n source: value.source,\n storage: value.storage,\n verifiedAt: value.verifiedAt,\n ...(value.refreshToken ? { refreshToken: value.refreshToken } : {}),\n ...(value.oauthClientId ? { oauthClientId: value.oauthClientId } : {}),\n };\n}\n\nexport function readWizardAuthMetadata(\n authPath: string = ORGX_WIZARD_AUTH_PATH,\n): WizardAuthMetadata | null {\n const stored = parseStoredWizardAuthRecord(readTextIfExists(authPath));\n if (!stored) {\n return null;\n }\n\n return {\n baseUrl: stored.baseUrl,\n keyPrefix: stored.keyPrefix,\n source: stored.source ?? \"manual\",\n storage: stored.storage,\n verifiedAt: stored.verifiedAt,\n };\n}\n\nexport async function readWizardAuth(\n authPath: string = ORGX_WIZARD_AUTH_PATH,\n options: WizardAuthStoreOptions = {},\n): Promise<WizardAuthRecord | null> {\n const stored = parseStoredWizardAuthRecord(readTextIfExists(authPath));\n if (!stored) {\n return null;\n }\n\n const source: WizardAuthSource = stored.source ?? \"manual\";\n\n const apiKeyFromFile =\n stored.storage === \"file\" && isNonEmptyString(stored.apiKey)\n ? stored.apiKey.trim()\n : null;\n\n if (apiKeyFromFile) {\n return {\n apiKey: apiKeyFromFile,\n baseUrl: stored.baseUrl,\n keyPrefix: stored.keyPrefix,\n source,\n storage: \"file\",\n verifiedAt: stored.verifiedAt,\n ...(stored.refreshToken ? { refreshToken: stored.refreshToken } : {}),\n ...(stored.oauthClientId ? { oauthClientId: stored.oauthClientId } : {}),\n };\n }\n\n if (stored.storage !== \"keytar\") {\n return null;\n }\n\n const secretStore = await resolveSecretStore(options);\n if (!secretStore) {\n return null;\n }\n\n const apiKey = await secretStore.getPassword(\n ORGX_WIZARD_KEYTAR_SERVICE,\n ORGX_WIZARD_KEYTAR_ACCOUNT,\n );\n\n if (!isNonEmptyString(apiKey)) {\n return null;\n }\n\n return {\n apiKey: apiKey.trim(),\n baseUrl: stored.baseUrl,\n keyPrefix: stored.keyPrefix,\n source,\n storage: \"keytar\",\n verifiedAt: stored.verifiedAt,\n ...(stored.refreshToken ? { refreshToken: stored.refreshToken } : {}),\n ...(stored.oauthClientId ? { oauthClientId: stored.oauthClientId } : {}),\n };\n}\n\nexport async function writeWizardAuth(\n value: {\n apiKey: string;\n baseUrl: string;\n keyPrefix?: string;\n verifiedAt: string;\n source?: WizardAuthSource;\n refreshToken?: string;\n oauthClientId?: string;\n },\n authPath: string = ORGX_WIZARD_AUTH_PATH,\n options: WizardAuthStoreOptions = {},\n): Promise<WizardAuthRecord> {\n const secretStore = options.preferSecureStorage === false\n ? null\n : await resolveSecretStore(options);\n\n const record: WizardAuthRecord = {\n apiKey: value.apiKey.trim(),\n keyPrefix: value.keyPrefix?.trim() || extractKeyPrefix(value.apiKey),\n baseUrl: value.baseUrl.trim(),\n source: value.source ?? \"manual\",\n storage: secretStore ? \"keytar\" : \"file\",\n verifiedAt: value.verifiedAt.trim(),\n ...(value.refreshToken ? { refreshToken: value.refreshToken } : {}),\n ...(value.oauthClientId ? { oauthClientId: value.oauthClientId } : {}),\n };\n\n if (secretStore) {\n await secretStore.setPassword(\n ORGX_WIZARD_KEYTAR_SERVICE,\n ORGX_WIZARD_KEYTAR_ACCOUNT,\n record.apiKey,\n );\n }\n\n writeJsonFile(authPath, buildStoredRecord(record), { mode: 0o600 });\n return record;\n}\n\nexport async function clearWizardAuth(\n authPath: string = ORGX_WIZARD_AUTH_PATH,\n options: WizardAuthStoreOptions = {},\n): Promise<boolean> {\n const secretStore = await resolveSecretStore(options);\n const secretRemoved = secretStore\n ? await secretStore.deletePassword(\n ORGX_WIZARD_KEYTAR_SERVICE,\n ORGX_WIZARD_KEYTAR_ACCOUNT,\n )\n : false;\n const fileRemoved = deleteFileIfExists(authPath);\n return secretRemoved || fileRemoved;\n}\n","import {\n DEFAULT_ORGX_BASE_URL,\n OPENCLAW_CONFIG_PATH,\n ORGX_WIZARD_AUTH_PATH,\n} from \"../constants.js\";\nimport { readOpenClawAuth } from \"../surfaces/openclaw-config.js\";\nimport { readTextIfExists } from \"./fs.js\";\nimport {\n extractKeyPrefix,\n readWizardAuth,\n readWizardAuthMetadata,\n} from \"./auth-store.js\";\n\nexport type OrgxAuthSource =\n | \"environment\"\n | \"wizard-store\"\n | \"openclaw-config-file\";\n\nexport interface ResolvedOrgxAuth {\n apiKey: string;\n keyPrefix: string;\n baseUrl: string;\n source: OrgxAuthSource;\n path?: string;\n verifiedAt?: string;\n}\n\nexport interface OrgxAuthCheckResult {\n configured: boolean;\n ok: boolean;\n skipped: boolean;\n source: OrgxAuthSource | \"none\";\n keyPrefix?: string;\n baseUrl?: string;\n path?: string;\n verifiedAt?: string;\n status?: number;\n url?: string;\n error?: string;\n data?: unknown;\n}\n\nexport interface ResolveOrgxAuthOptions {\n authPath?: string;\n openclawConfigPath?: string;\n}\n\nexport interface OrgxAuthHint {\n keyPrefix: string;\n baseUrl: string;\n source: OrgxAuthSource;\n path?: string;\n verifiedAt?: string;\n}\n\nfunction normalizeHost(value: string): string {\n return value.trim().toLowerCase().replace(/^\\[|\\]$/g, \"\");\n}\n\nfunction isLoopbackHostname(hostname: string): boolean {\n const normalized = normalizeHost(hostname);\n return normalized === \"localhost\" || normalized === \"127.0.0.1\" || normalized === \"::1\";\n}\n\nexport function normalizeOrgxBaseUrl(raw?: string): string {\n const candidate = raw?.trim() || DEFAULT_ORGX_BASE_URL;\n\n try {\n const parsed = new URL(candidate);\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n return DEFAULT_ORGX_BASE_URL;\n }\n\n if (parsed.username || parsed.password) {\n return DEFAULT_ORGX_BASE_URL;\n }\n\n if (parsed.protocol === \"http:\" && !isLoopbackHostname(parsed.hostname)) {\n return DEFAULT_ORGX_BASE_URL;\n }\n\n parsed.search = \"\";\n parsed.hash = \"\";\n parsed.pathname = parsed.pathname.replace(/\\/api\\/?$/, \"\").replace(/\\/+$/, \"\");\n return parsed.toString().replace(/\\/+$/, \"\");\n } catch {\n return DEFAULT_ORGX_BASE_URL;\n }\n}\n\nexport function buildOrgxApiUrl(path: string, baseUrl?: string): string {\n const parsedBase = new URL(normalizeOrgxBaseUrl(baseUrl));\n const normalizedBase = parsedBase.toString().replace(/\\/+$/, \"\");\n const apiBase = normalizedBase.endsWith(\"/api\") ? normalizedBase : `${normalizedBase}/api`;\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n return `${apiBase}${normalizedPath}`;\n}\n\nfunction withResolvedBaseUrl(baseUrl: string, envBaseUrl?: string): string {\n return normalizeOrgxBaseUrl(envBaseUrl?.trim() || baseUrl);\n}\n\nfunction buildResolvedAuth(\n apiKey: string,\n baseUrl: string,\n source: OrgxAuthSource,\n extras: Pick<ResolvedOrgxAuth, \"path\" | \"verifiedAt\"> = {},\n): ResolvedOrgxAuth {\n return {\n apiKey: apiKey.trim(),\n keyPrefix: extractKeyPrefix(apiKey),\n baseUrl,\n source,\n ...(extras.path ? { path: extras.path } : {}),\n ...(extras.verifiedAt ? { verifiedAt: extras.verifiedAt } : {}),\n };\n}\n\nfunction buildAuthHint(\n keyPrefix: string,\n baseUrl: string,\n source: OrgxAuthSource,\n extras: Pick<OrgxAuthHint, \"path\" | \"verifiedAt\"> = {},\n): OrgxAuthHint {\n return {\n keyPrefix: keyPrefix.trim(),\n baseUrl,\n source,\n ...(extras.path ? { path: extras.path } : {}),\n ...(extras.verifiedAt ? { verifiedAt: extras.verifiedAt } : {}),\n };\n}\n\nexport function peekResolvedOrgxAuth(\n options: ResolveOrgxAuthOptions = {},\n): OrgxAuthHint | null {\n const envApiKey = process.env.ORGX_API_KEY?.trim();\n const envBaseUrl = process.env.ORGX_BASE_URL?.trim();\n if (envApiKey) {\n return buildAuthHint(\n extractKeyPrefix(envApiKey),\n withResolvedBaseUrl(DEFAULT_ORGX_BASE_URL, envBaseUrl),\n \"environment\",\n );\n }\n\n const authPath = options.authPath ?? ORGX_WIZARD_AUTH_PATH;\n const stored = readWizardAuthMetadata(authPath);\n if (stored) {\n return buildAuthHint(\n stored.keyPrefix,\n withResolvedBaseUrl(stored.baseUrl, envBaseUrl),\n \"wizard-store\",\n {\n path: authPath,\n verifiedAt: stored.verifiedAt,\n },\n );\n }\n\n const openclawConfigPath = options.openclawConfigPath ?? OPENCLAW_CONFIG_PATH;\n const openclawAuth = readOpenClawAuth(\n openclawConfigPath ? readTextIfExists(openclawConfigPath) : null,\n );\n if (openclawAuth.apiKey && openclawConfigPath) {\n return buildAuthHint(\n extractKeyPrefix(openclawAuth.apiKey),\n withResolvedBaseUrl(openclawAuth.baseUrl || DEFAULT_ORGX_BASE_URL, envBaseUrl),\n \"openclaw-config-file\",\n { path: openclawConfigPath },\n );\n }\n\n return null;\n}\n\nexport async function resolveOrgxAuth(\n options: ResolveOrgxAuthOptions = {},\n): Promise<ResolvedOrgxAuth | null> {\n const envApiKey = process.env.ORGX_API_KEY?.trim();\n const envBaseUrl = process.env.ORGX_BASE_URL?.trim();\n if (envApiKey) {\n return buildResolvedAuth(\n envApiKey,\n withResolvedBaseUrl(DEFAULT_ORGX_BASE_URL, envBaseUrl),\n \"environment\",\n );\n }\n\n const authPath = options.authPath ?? ORGX_WIZARD_AUTH_PATH;\n const stored = await readWizardAuth(authPath);\n if (stored) {\n return buildResolvedAuth(\n stored.apiKey,\n withResolvedBaseUrl(stored.baseUrl, envBaseUrl),\n \"wizard-store\",\n {\n path: authPath,\n verifiedAt: stored.verifiedAt,\n },\n );\n }\n\n const openclawConfigPath = options.openclawConfigPath ?? OPENCLAW_CONFIG_PATH;\n const openclawAuth = readOpenClawAuth(\n openclawConfigPath ? readTextIfExists(openclawConfigPath) : null,\n );\n if (openclawAuth.apiKey && openclawConfigPath) {\n return buildResolvedAuth(\n openclawAuth.apiKey,\n withResolvedBaseUrl(openclawAuth.baseUrl || DEFAULT_ORGX_BASE_URL, envBaseUrl),\n \"openclaw-config-file\",\n { path: openclawConfigPath },\n );\n }\n\n return null;\n}\n\nasync function parseResponseBody(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nexport async function verifyOrgxAuth(\n auth: Pick<ResolvedOrgxAuth, \"apiKey\" | \"baseUrl\" | \"source\" | \"keyPrefix\"> & {\n path?: string;\n verifiedAt?: string;\n },\n): Promise<OrgxAuthCheckResult> {\n const url = buildOrgxApiUrl(\"/client/sync\", auth.baseUrl);\n\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: \"{}\",\n signal: AbortSignal.timeout(7_000),\n });\n\n const data = await parseResponseBody(response);\n\n return {\n configured: true,\n ok: response.ok,\n skipped: false,\n source: auth.source,\n keyPrefix: auth.keyPrefix,\n baseUrl: auth.baseUrl,\n ...(auth.path ? { path: auth.path } : {}),\n ...(auth.verifiedAt ? { verifiedAt: auth.verifiedAt } : {}),\n status: response.status,\n url,\n data,\n ...(response.ok ? {} : { error: `HTTP ${response.status}` }),\n };\n } catch (error) {\n return {\n configured: true,\n ok: false,\n skipped: false,\n source: auth.source,\n keyPrefix: auth.keyPrefix,\n baseUrl: auth.baseUrl,\n ...(auth.path ? { path: auth.path } : {}),\n ...(auth.verifiedAt ? { verifiedAt: auth.verifiedAt } : {}),\n url,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport async function checkOrgxAuth(\n options: ResolveOrgxAuthOptions = {},\n): Promise<OrgxAuthCheckResult> {\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n return {\n configured: false,\n ok: false,\n skipped: true,\n source: \"none\",\n error: \"No OrgX account connected. Run `orgx-wizard auth login` to connect.\",\n url: buildOrgxApiUrl(\"/client/sync\", DEFAULT_ORGX_BASE_URL),\n };\n }\n\n return verifyOrgxAuth(auth);\n}\n\nexport function describeSetupStatusScope(): string {\n return \"The setup-status endpoint is still service-key-only and uses ORGX_SERVICE_KEY.\";\n}\n","import { createServer } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\n\nexport interface OAuthCallbackResult {\n code: string;\n state: string;\n}\n\nexport interface LocalAuthServerOptions {\n /** Preferred port; falls back through preferredPort+1..+9 until one binds. */\n preferredPort: number;\n /** Expected state value — rejects callbacks with mismatched state. */\n expectedState: string;\n /** Milliseconds to wait before timing out. Default: 5 minutes. */\n timeoutMs?: number;\n /** Path to listen on. Default: /oauth/callback */\n callbackPath?: string;\n /** HTML to show in the browser on success. */\n successHtml?: string;\n /** HTML to show in the browser on error. */\n errorHtml?: string;\n}\n\nconst DEFAULT_SUCCESS_HTML = `<!DOCTYPE html>\n<html>\n<head><title>OrgX connected</title>\n<style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#f9fafb}\n.card{text-align:center;padding:2rem;max-width:400px}\nh1{font-size:1.5rem;color:#111}p{color:#555;margin-top:.5rem}</style>\n</head>\n<body><div class=\"card\">\n<h1>&#10003; Connected to OrgX</h1>\n<p>You can close this tab and return to your terminal.</p>\n</div></body></html>`;\n\nconst DEFAULT_ERROR_HTML = `<!DOCTYPE html>\n<html>\n<head><title>OrgX auth error</title>\n<style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#fef2f2}\n.card{text-align:center;padding:2rem;max-width:400px}\nh1{font-size:1.5rem;color:#b91c1c}p{color:#555;margin-top:.5rem}</style>\n</head>\n<body><div class=\"card\">\n<h1>&#10007; Authentication failed</h1>\n<p>Return to your terminal and try again.</p>\n</div></body></html>`;\n\nfunction tryListen(port: number, hostname: string): Promise<ReturnType<typeof createServer>> {\n return new Promise((resolve, reject) => {\n const server = createServer();\n server.once(\"error\", reject);\n server.listen(port, hostname, () => {\n server.removeListener(\"error\", reject);\n resolve(server);\n });\n });\n}\n\nasync function bindServer(\n preferredPort: number,\n hostname: string,\n): Promise<{ server: ReturnType<typeof createServer>; port: number }> {\n // Port 0 lets the OS pick a free port — read the actual port back from address()\n if (preferredPort === 0) {\n const server = await tryListen(0, hostname);\n const port = (server.address() as AddressInfo).port;\n return { server, port };\n }\n\n for (let offset = 0; offset < 10; offset++) {\n const port = preferredPort + offset;\n try {\n const server = await tryListen(port, hostname);\n return { server, port };\n } catch {\n // port busy — try next\n }\n }\n throw new Error(\n `Could not bind local auth server: ports ${preferredPort}–${preferredPort + 9} are all in use.`,\n );\n}\n\n/**\n * Starts a local HTTP server that waits for a single OAuth callback redirect,\n * validates the state parameter, and returns the authorization code.\n *\n * Returns the bound port so callers can build the redirect_uri before opening\n * the browser.\n */\nexport async function startLocalAuthServer(\n options: LocalAuthServerOptions,\n): Promise<{ port: number; result: Promise<OAuthCallbackResult> }> {\n const hostname = \"127.0.0.1\";\n const callbackPath = options.callbackPath ?? \"/oauth/callback\";\n const timeoutMs = options.timeoutMs ?? 5 * 60_000;\n const successHtml = options.successHtml ?? DEFAULT_SUCCESS_HTML;\n const errorHtml = options.errorHtml ?? DEFAULT_ERROR_HTML;\n\n const { server, port } = await bindServer(options.preferredPort, hostname);\n\n const result = new Promise<OAuthCallbackResult>((resolve, reject) => {\n const timer = setTimeout(() => {\n server.close();\n reject(new Error(\"Timed out waiting for browser authorization.\"));\n }, timeoutMs);\n\n server.on(\"request\", (req, res) => {\n if (!req.url) {\n res.writeHead(400).end(errorHtml);\n return;\n }\n\n const url = new URL(req.url, `http://${hostname}:${port}`);\n\n if (url.pathname !== callbackPath) {\n res.writeHead(404).end(\"Not found\");\n return;\n }\n\n const error = url.searchParams.get(\"error\");\n const errorDescription = url.searchParams.get(\"error_description\");\n\n if (error) {\n res.writeHead(400, { \"Content-Type\": \"text/html\" }).end(errorHtml);\n clearTimeout(timer);\n server.close();\n reject(new Error(errorDescription ?? error));\n return;\n }\n\n const code = url.searchParams.get(\"code\");\n const state = url.searchParams.get(\"state\");\n\n if (!code || !state) {\n res.writeHead(400, { \"Content-Type\": \"text/html\" }).end(errorHtml);\n clearTimeout(timer);\n server.close();\n reject(new Error(\"Missing code or state in callback.\"));\n return;\n }\n\n if (state !== options.expectedState) {\n res.writeHead(400, { \"Content-Type\": \"text/html\" }).end(errorHtml);\n clearTimeout(timer);\n server.close();\n reject(new Error(\"State mismatch — possible CSRF. Retry auth.\"));\n return;\n }\n\n res.writeHead(200, { \"Content-Type\": \"text/html\" }).end(successHtml);\n clearTimeout(timer);\n server.close();\n resolve({ code, state });\n });\n });\n\n return { port, result };\n}\n\nexport function buildRedirectUri(port: number, callbackPath = \"/oauth/callback\"): string {\n return `http://127.0.0.1:${port}${callbackPath}`;\n}\n\n/** Returns the actual port the server is listening on (useful if OS assigned it). */\nexport function getServerPort(server: ReturnType<typeof createServer>): number {\n return (server.address() as AddressInfo).port;\n}\n","import { createHash, randomBytes } from \"node:crypto\";\n\nexport interface PkceChallenge {\n codeVerifier: string;\n codeChallenge: string;\n codeChallengeMethod: \"S256\";\n}\n\n/**\n * Generates a PKCE code_verifier and S256 code_challenge per RFC 7636.\n * Uses 32 random bytes → 43-char base64url string (within the 43–128 char spec range).\n */\nexport function generatePkce(): PkceChallenge {\n const codeVerifier = randomBytes(32).toString(\"base64url\");\n const codeChallenge = createHash(\"sha256\")\n .update(codeVerifier)\n .digest(\"base64url\");\n return { codeVerifier, codeChallenge, codeChallengeMethod: \"S256\" };\n}\n\nexport function generateState(): string {\n return randomBytes(16).toString(\"base64url\");\n}\n\nexport interface AuthorizeUrlOptions {\n authorizeEndpoint: string;\n clientId: string;\n redirectUri: string;\n scope: string;\n codeChallenge: string;\n codeChallengeMethod: \"S256\" | \"plain\";\n state: string;\n}\n\nexport function buildAuthorizeUrl(options: AuthorizeUrlOptions): string {\n const url = new URL(options.authorizeEndpoint);\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"client_id\", options.clientId);\n url.searchParams.set(\"redirect_uri\", options.redirectUri);\n url.searchParams.set(\"scope\", options.scope);\n url.searchParams.set(\"code_challenge\", options.codeChallenge);\n url.searchParams.set(\"code_challenge_method\", options.codeChallengeMethod);\n url.searchParams.set(\"state\", options.state);\n return url.toString();\n}\n","import {\n ORGX_HOSTED_OAUTH_AUTHORIZE_URL,\n ORGX_HOSTED_OAUTH_REGISTER_URL,\n ORGX_HOSTED_OAUTH_TOKEN_URL,\n ORGX_WIZARD_OAUTH_CALLBACK_PATH,\n ORGX_WIZARD_OAUTH_PREFERRED_PORT,\n ORGX_WIZARD_OAUTH_SCOPE,\n} from \"../constants.js\";\nimport { isRecord } from \"./fs.js\";\nimport { buildRedirectUri, startLocalAuthServer } from \"./local-auth-server.js\";\nimport { buildAuthorizeUrl, generatePkce, generateState } from \"./pkce.js\";\n\nexport interface OAuthTokenResponse {\n access_token: string;\n token_type: string;\n expires_in?: number;\n refresh_token?: string;\n scope?: string;\n}\n\nexport interface RegisteredOAuthClient {\n client_id: string;\n client_secret?: string;\n}\n\nexport interface PkceLoginResult {\n accessToken: string;\n refreshToken: string | undefined;\n redirectUri: string;\n clientId: string;\n expiresIn: number | undefined;\n}\n\nasync function registerPublicClient(\n options: {\n redirectUri: string;\n fetchImpl?: typeof fetch;\n },\n): Promise<RegisteredOAuthClient> {\n const fetchImpl = options.fetchImpl ?? fetch;\n const response = await fetchImpl(ORGX_HOSTED_OAUTH_REGISTER_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n client_name: \"OrgX Wizard CLI\",\n redirect_uris: [options.redirectUri],\n token_endpoint_auth_method: \"none\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n }),\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(`OAuth client registration failed (HTTP ${response.status}): ${text}`);\n }\n\n const data = await response.json();\n if (!isRecord(data) || typeof data.client_id !== \"string\") {\n throw new Error(\"OAuth registration response missing client_id.\");\n }\n\n return { client_id: data.client_id as string };\n}\n\nasync function exchangeCodeForTokens(\n options: {\n code: string;\n codeVerifier: string;\n redirectUri: string;\n clientId: string;\n fetchImpl?: typeof fetch;\n },\n): Promise<OAuthTokenResponse> {\n const fetchImpl = options.fetchImpl ?? fetch;\n const body = new URLSearchParams({\n grant_type: \"authorization_code\",\n code: options.code,\n redirect_uri: options.redirectUri,\n client_id: options.clientId,\n code_verifier: options.codeVerifier,\n });\n\n const response = await fetchImpl(ORGX_HOSTED_OAUTH_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: body.toString(),\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(`Token exchange failed (HTTP ${response.status}): ${text}`);\n }\n\n const data = await response.json();\n if (!isRecord(data) || typeof data.access_token !== \"string\") {\n throw new Error(\"Token response missing access_token.\");\n }\n\n return {\n access_token: data.access_token as string,\n token_type: typeof data.token_type === \"string\" ? data.token_type : \"Bearer\",\n ...(typeof data.expires_in === \"number\" ? { expires_in: data.expires_in } : {}),\n ...(typeof data.refresh_token === \"string\" ? { refresh_token: data.refresh_token } : {}),\n ...(typeof data.scope === \"string\" ? { scope: data.scope } : {}),\n };\n}\n\nexport async function refreshAccessToken(\n options: {\n refreshToken: string;\n clientId: string;\n fetchImpl?: typeof fetch;\n },\n): Promise<OAuthTokenResponse> {\n const fetchImpl = options.fetchImpl ?? fetch;\n const body = new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: options.refreshToken,\n client_id: options.clientId,\n });\n\n const response = await fetchImpl(ORGX_HOSTED_OAUTH_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: body.toString(),\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(`Token refresh failed (HTTP ${response.status}): ${text}`);\n }\n\n const data = await response.json();\n if (!isRecord(data) || typeof data.access_token !== \"string\") {\n throw new Error(\"Refresh response missing access_token.\");\n }\n\n return {\n access_token: data.access_token as string,\n token_type: typeof data.token_type === \"string\" ? data.token_type : \"Bearer\",\n ...(typeof data.expires_in === \"number\" ? { expires_in: data.expires_in } : {}),\n ...(typeof data.refresh_token === \"string\" ? { refresh_token: data.refresh_token } : {}),\n };\n}\n\nexport interface StartPkceLoginOptions {\n /** Called with the URL the user should open. Return false to skip auto-open. */\n onAuthorizeUrl?: (url: string) => void;\n /** Override preferred callback port (default from constants). */\n preferredPort?: number;\n /** Override OAuth scopes. */\n scope?: string;\n /** Timeout in ms (default 5 min). */\n timeoutMs?: number;\n /** Injected fetch for testing. */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Full PKCE authorization_code flow:\n * 1. Register a public dynamic client\n * 2. Start local callback server\n * 3. Build authorize URL and open browser\n * 4. Wait for callback, validate state\n * 5. Exchange code for tokens\n *\n * Returns access_token + optional refresh_token — no OpenClaw required.\n */\nexport async function startPkceLogin(\n options: StartPkceLoginOptions = {},\n): Promise<PkceLoginResult> {\n const port = options.preferredPort ?? ORGX_WIZARD_OAUTH_PREFERRED_PORT;\n const scope = options.scope ?? ORGX_WIZARD_OAUTH_SCOPE;\n const { codeVerifier, codeChallenge, codeChallengeMethod } = generatePkce();\n const state = generateState();\n\n // Start local server first so we know the actual bound port\n const serverOpts = {\n preferredPort: port,\n expectedState: state,\n callbackPath: ORGX_WIZARD_OAUTH_CALLBACK_PATH,\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n };\n const { port: boundPort, result: callbackPromise } = await startLocalAuthServer(serverOpts);\n\n const redirectUri = buildRedirectUri(boundPort, ORGX_WIZARD_OAUTH_CALLBACK_PATH);\n\n const clientOpts = {\n redirectUri,\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n };\n const client = await registerPublicClient(clientOpts);\n\n const authorizeUrl = buildAuthorizeUrl({\n authorizeEndpoint: ORGX_HOSTED_OAUTH_AUTHORIZE_URL,\n clientId: client.client_id,\n redirectUri,\n scope,\n codeChallenge,\n codeChallengeMethod,\n state,\n });\n\n options.onAuthorizeUrl?.(authorizeUrl);\n\n const { code } = await callbackPromise;\n\n const exchangeOpts = {\n code,\n codeVerifier,\n redirectUri,\n clientId: client.client_id,\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n };\n const tokens = await exchangeCodeForTokens(exchangeOpts);\n\n return {\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token,\n redirectUri,\n clientId: client.client_id,\n expiresIn: tokens.expires_in,\n };\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { ORGX_WIZARD_STATE_PATH } from \"../constants.js\";\nimport { deleteFileIfExists, parseJsonObject, readTextIfExists, writeJsonFile } from \"./fs.js\";\nimport { SURFACE_NAMES, type SurfaceName } from \"../surfaces/names.js\";\n\nexport interface WizardContinuityDefaults {\n executionMode?: \"cloud\" | \"local\";\n reviewSurface?: SurfaceName;\n workspaceId?: string;\n workspaceName?: string;\n}\n\nexport interface WizardDemoInitiativeRecord {\n createdAt: string;\n artifactId?: string;\n artifactName?: string;\n artifactType?: string;\n artifactUrl?: string;\n decisionId?: string;\n decisionStatus?: string;\n decisionTitle?: string;\n id: string;\n liveUrl: string;\n title: string;\n workspaceId?: string;\n workspaceName?: string;\n}\n\nexport interface WizardFirstValueInitiativeRecord {\n createdAt: string;\n id: string;\n liveUrl: string;\n summary?: string;\n title: string;\n workspaceId?: string;\n workspaceName?: string;\n}\n\nexport interface WizardOnboardingTaskRecord {\n createdAt: string;\n id: string;\n initiativeId?: string;\n status?: string;\n title: string;\n workstreamId?: string;\n workspaceId?: string;\n workspaceName?: string;\n}\n\nexport interface WizardAgentRosterEntry {\n agentType: string;\n domain: string;\n name: string;\n}\n\nexport interface WizardAgentRosterRecord {\n agents: WizardAgentRosterEntry[];\n configuredAt: string;\n workspaceId?: string;\n workspaceName?: string;\n}\n\nexport interface WizardSkillFileRecord {\n contentSha256: string;\n coreSha256?: string;\n path: string;\n skillId: string;\n updatedAt: string;\n}\n\nexport interface WizardSkillFilesRecord {\n files: WizardSkillFileRecord[];\n updatedAt: string;\n}\n\n/**\n * People-first capture idempotency record — keyed by workspace id so the\n * wizard does not re-prompt Wave 3b capture on every run. Mirrors the\n * pattern the Daily Brief uses server-side (`onboardingCompletedAt`). This\n * local record is authoritative while the server endpoints are still\n * landing (Wave 2).\n */\nexport interface WizardPeopleFirstCaptureEntry {\n workspaceId: string;\n completedAt: string;\n personId?: string;\n templatePersona?: string;\n /** True when the server endpoints were not live at capture time and the\n * payload was staged to `~/.orgx-wizard/pending-people.json`. */\n stagedLocally?: boolean;\n}\n\nexport interface WizardPeopleFirstCaptureRecord {\n updatedAt: string;\n entries: WizardPeopleFirstCaptureEntry[];\n}\n\nexport type WizardDailyBriefOnboardingStatus = \"completed\" | \"skipped\";\n\nexport interface WizardDailyBriefOnboardingEntry {\n workspaceId: string;\n status: WizardDailyBriefOnboardingStatus;\n completedAt?: string;\n skippedAt?: string;\n workspaceName?: string;\n}\n\nexport interface WizardDailyBriefOnboardingRecord {\n updatedAt: string;\n entries: WizardDailyBriefOnboardingEntry[];\n}\n\nexport type WizardSetupPromptKey =\n | \"first_initiative\"\n | \"onboarding_task\"\n | \"agent_roster\"\n | \"setup_intent\";\n\nexport interface WizardSetupPromptDecisionEntry {\n promptKey: WizardSetupPromptKey;\n skippedAt: string;\n status: \"skipped\";\n workspaceId: string;\n workspaceName?: string;\n}\n\nexport interface WizardSetupPromptDecisionsRecord {\n updatedAt: string;\n entries: WizardSetupPromptDecisionEntry[];\n}\n\nexport interface WizardStateRecord {\n continuity?: WizardContinuityDefaults;\n installationId: string;\n agentRoster?: WizardAgentRosterRecord;\n demoInitiative?: WizardDemoInitiativeRecord;\n firstValueInitiative?: WizardFirstValueInitiativeRecord;\n onboardingTask?: WizardOnboardingTaskRecord;\n skillFiles?: WizardSkillFilesRecord;\n peopleFirstCapture?: WizardPeopleFirstCaptureRecord;\n dailyBriefOnboarding?: WizardDailyBriefOnboardingRecord;\n setupPromptDecisions?: WizardSetupPromptDecisionsRecord;\n createdAt: string;\n updatedAt: string;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\nfunction isSurfaceName(value: unknown): value is SurfaceName {\n return typeof value === \"string\" && SURFACE_NAMES.includes(value as SurfaceName);\n}\n\nfunction parseContinuityDefaults(value: unknown): WizardContinuityDefaults | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n const parsed: WizardContinuityDefaults = {};\n\n if (record.executionMode === \"cloud\" || record.executionMode === \"local\") {\n parsed.executionMode = record.executionMode;\n }\n\n if (isSurfaceName(record.reviewSurface)) {\n parsed.reviewSurface = record.reviewSurface;\n }\n\n if (isNonEmptyString(record.workspaceId)) {\n parsed.workspaceId = record.workspaceId.trim();\n }\n\n if (isNonEmptyString(record.workspaceName)) {\n parsed.workspaceName = record.workspaceName.trim();\n }\n\n return Object.keys(parsed).length > 0 ? parsed : undefined;\n}\n\nfunction parseDemoInitiative(value: unknown): WizardDemoInitiativeRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.id) ||\n !isNonEmptyString(record.title) ||\n !isNonEmptyString(record.liveUrl) ||\n !isNonEmptyString(record.createdAt)\n ) {\n return undefined;\n }\n\n return {\n createdAt: record.createdAt.trim(),\n ...(isNonEmptyString(record.artifactId)\n ? { artifactId: record.artifactId.trim() }\n : {}),\n ...(isNonEmptyString(record.artifactName)\n ? { artifactName: record.artifactName.trim() }\n : {}),\n ...(isNonEmptyString(record.artifactType)\n ? { artifactType: record.artifactType.trim() }\n : {}),\n ...(isNonEmptyString(record.artifactUrl)\n ? { artifactUrl: record.artifactUrl.trim() }\n : {}),\n ...(isNonEmptyString(record.decisionId)\n ? { decisionId: record.decisionId.trim() }\n : {}),\n ...(isNonEmptyString(record.decisionStatus)\n ? { decisionStatus: record.decisionStatus.trim() }\n : {}),\n ...(isNonEmptyString(record.decisionTitle)\n ? { decisionTitle: record.decisionTitle.trim() }\n : {}),\n id: record.id.trim(),\n liveUrl: record.liveUrl.trim(),\n title: record.title.trim(),\n ...(isNonEmptyString(record.workspaceId)\n ? { workspaceId: record.workspaceId.trim() }\n : {}),\n ...(isNonEmptyString(record.workspaceName)\n ? { workspaceName: record.workspaceName.trim() }\n : {}),\n };\n}\n\nfunction parseFirstValueInitiative(\n value: unknown,\n): WizardFirstValueInitiativeRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.id) ||\n !isNonEmptyString(record.title) ||\n !isNonEmptyString(record.liveUrl) ||\n !isNonEmptyString(record.createdAt)\n ) {\n return undefined;\n }\n\n return {\n createdAt: record.createdAt.trim(),\n id: record.id.trim(),\n liveUrl: record.liveUrl.trim(),\n ...(isNonEmptyString(record.summary) ? { summary: record.summary.trim() } : {}),\n title: record.title.trim(),\n ...(isNonEmptyString(record.workspaceId)\n ? { workspaceId: record.workspaceId.trim() }\n : {}),\n ...(isNonEmptyString(record.workspaceName)\n ? { workspaceName: record.workspaceName.trim() }\n : {}),\n };\n}\n\nfunction parseOnboardingTask(value: unknown): WizardOnboardingTaskRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.id) ||\n !isNonEmptyString(record.title) ||\n !isNonEmptyString(record.createdAt)\n ) {\n return undefined;\n }\n\n return {\n createdAt: record.createdAt.trim(),\n id: record.id.trim(),\n ...(isNonEmptyString(record.initiativeId)\n ? { initiativeId: record.initiativeId.trim() }\n : {}),\n ...(isNonEmptyString(record.status)\n ? { status: record.status.trim() }\n : {}),\n title: record.title.trim(),\n ...(isNonEmptyString(record.workstreamId)\n ? { workstreamId: record.workstreamId.trim() }\n : {}),\n ...(isNonEmptyString(record.workspaceId)\n ? { workspaceId: record.workspaceId.trim() }\n : {}),\n ...(isNonEmptyString(record.workspaceName)\n ? { workspaceName: record.workspaceName.trim() }\n : {}),\n };\n}\n\nfunction parseAgentRosterEntry(value: unknown): WizardAgentRosterEntry | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.agentType) ||\n !isNonEmptyString(record.domain) ||\n !isNonEmptyString(record.name)\n ) {\n return undefined;\n }\n\n return {\n agentType: record.agentType.trim(),\n domain: record.domain.trim(),\n name: record.name.trim(),\n };\n}\n\nfunction parseAgentRoster(value: unknown): WizardAgentRosterRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (!isNonEmptyString(record.configuredAt) || !Array.isArray(record.agents)) {\n return undefined;\n }\n\n const agents = record.agents\n .map((entry) => parseAgentRosterEntry(entry))\n .filter((entry): entry is WizardAgentRosterEntry => Boolean(entry));\n if (agents.length === 0) {\n return undefined;\n }\n\n return {\n agents,\n configuredAt: record.configuredAt.trim(),\n ...(isNonEmptyString(record.workspaceId)\n ? { workspaceId: record.workspaceId.trim() }\n : {}),\n ...(isNonEmptyString(record.workspaceName)\n ? { workspaceName: record.workspaceName.trim() }\n : {}),\n };\n}\n\nfunction parseSkillFileRecord(value: unknown): WizardSkillFileRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.path) ||\n !isNonEmptyString(record.skillId) ||\n !isNonEmptyString(record.contentSha256) ||\n !isNonEmptyString(record.updatedAt)\n ) {\n return undefined;\n }\n\n return {\n contentSha256: record.contentSha256.trim(),\n path: record.path.trim(),\n skillId: record.skillId.trim(),\n updatedAt: record.updatedAt.trim(),\n ...(isNonEmptyString(record.coreSha256)\n ? { coreSha256: record.coreSha256.trim() }\n : {}),\n };\n}\n\nfunction parseSkillFiles(value: unknown): WizardSkillFilesRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (!isNonEmptyString(record.updatedAt) || !Array.isArray(record.files)) {\n return undefined;\n }\n\n const files = record.files\n .map((entry) => parseSkillFileRecord(entry))\n .filter((entry): entry is WizardSkillFileRecord => Boolean(entry));\n if (files.length === 0) {\n return undefined;\n }\n\n return {\n files,\n updatedAt: record.updatedAt.trim(),\n };\n}\n\nfunction parsePeopleFirstCaptureEntry(\n value: unknown,\n): WizardPeopleFirstCaptureEntry | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.workspaceId) ||\n !isNonEmptyString(record.completedAt)\n ) {\n return undefined;\n }\n return {\n workspaceId: record.workspaceId.trim(),\n completedAt: record.completedAt.trim(),\n ...(isNonEmptyString(record.personId) ? { personId: record.personId.trim() } : {}),\n ...(isNonEmptyString(record.templatePersona)\n ? { templatePersona: record.templatePersona.trim() }\n : {}),\n ...(record.stagedLocally === true ? { stagedLocally: true } : {}),\n };\n}\n\nfunction parsePeopleFirstCapture(\n value: unknown,\n): WizardPeopleFirstCaptureRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n const record = value as Record<string, unknown>;\n if (!isNonEmptyString(record.updatedAt) || !Array.isArray(record.entries)) {\n return undefined;\n }\n const entries = record.entries\n .map((entry) => parsePeopleFirstCaptureEntry(entry))\n .filter(\n (entry): entry is WizardPeopleFirstCaptureEntry => Boolean(entry),\n );\n if (entries.length === 0) return undefined;\n return {\n updatedAt: record.updatedAt.trim(),\n entries,\n };\n}\n\nfunction parseDailyBriefOnboardingEntry(\n value: unknown,\n): WizardDailyBriefOnboardingEntry | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n const status = record.status;\n if (\n !isNonEmptyString(record.workspaceId) ||\n (status !== \"completed\" && status !== \"skipped\")\n ) {\n return undefined;\n }\n\n const completedAt = isNonEmptyString(record.completedAt)\n ? record.completedAt.trim()\n : undefined;\n const skippedAt = isNonEmptyString(record.skippedAt)\n ? record.skippedAt.trim()\n : undefined;\n\n if (status === \"completed\" && !completedAt) return undefined;\n if (status === \"skipped\" && !skippedAt) return undefined;\n\n return {\n workspaceId: record.workspaceId.trim(),\n status,\n ...(completedAt ? { completedAt } : {}),\n ...(skippedAt ? { skippedAt } : {}),\n ...(isNonEmptyString(record.workspaceName)\n ? { workspaceName: record.workspaceName.trim() }\n : {}),\n };\n}\n\nfunction parseDailyBriefOnboarding(\n value: unknown,\n): WizardDailyBriefOnboardingRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (!isNonEmptyString(record.updatedAt) || !Array.isArray(record.entries)) {\n return undefined;\n }\n\n const entries = record.entries\n .map((entry) => parseDailyBriefOnboardingEntry(entry))\n .filter(\n (entry): entry is WizardDailyBriefOnboardingEntry => Boolean(entry),\n );\n if (entries.length === 0) return undefined;\n\n return {\n updatedAt: record.updatedAt.trim(),\n entries,\n };\n}\n\nfunction isSetupPromptKey(value: unknown): value is WizardSetupPromptKey {\n return (\n value === \"first_initiative\" ||\n value === \"onboarding_task\" ||\n value === \"agent_roster\" ||\n value === \"setup_intent\"\n );\n}\n\nfunction parseSetupPromptDecisionEntry(\n value: unknown,\n): WizardSetupPromptDecisionEntry | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.workspaceId) ||\n !isSetupPromptKey(record.promptKey) ||\n record.status !== \"skipped\" ||\n !isNonEmptyString(record.skippedAt)\n ) {\n return undefined;\n }\n\n return {\n promptKey: record.promptKey,\n skippedAt: record.skippedAt.trim(),\n status: \"skipped\",\n workspaceId: record.workspaceId.trim(),\n ...(isNonEmptyString(record.workspaceName)\n ? { workspaceName: record.workspaceName.trim() }\n : {}),\n };\n}\n\nfunction parseSetupPromptDecisions(\n value: unknown,\n): WizardSetupPromptDecisionsRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (!isNonEmptyString(record.updatedAt) || !Array.isArray(record.entries)) {\n return undefined;\n }\n\n const entries = record.entries\n .map((entry) => parseSetupPromptDecisionEntry(entry))\n .filter(\n (entry): entry is WizardSetupPromptDecisionEntry => Boolean(entry),\n );\n if (entries.length === 0) return undefined;\n\n return {\n updatedAt: record.updatedAt.trim(),\n entries,\n };\n}\n\nfunction createWizardState(now = new Date().toISOString()): WizardStateRecord {\n return {\n installationId: `wizard-${randomUUID()}`,\n createdAt: now,\n updatedAt: now,\n };\n}\n\nfunction sanitizeWizardStateRecord(record: WizardStateRecord): WizardStateRecord {\n const continuity = parseContinuityDefaults(record.continuity);\n const agentRoster = parseAgentRoster(record.agentRoster);\n const demoInitiative = parseDemoInitiative(record.demoInitiative);\n const firstValueInitiative = parseFirstValueInitiative(record.firstValueInitiative);\n const onboardingTask = parseOnboardingTask(record.onboardingTask);\n const skillFiles = parseSkillFiles(record.skillFiles);\n const peopleFirstCapture = parsePeopleFirstCapture(record.peopleFirstCapture);\n const dailyBriefOnboarding = parseDailyBriefOnboarding(record.dailyBriefOnboarding);\n const setupPromptDecisions = parseSetupPromptDecisions(record.setupPromptDecisions);\n\n return {\n installationId: record.installationId.trim(),\n createdAt: record.createdAt.trim(),\n updatedAt: record.updatedAt.trim(),\n ...(continuity ? { continuity } : {}),\n ...(agentRoster ? { agentRoster } : {}),\n ...(demoInitiative ? { demoInitiative } : {}),\n ...(firstValueInitiative ? { firstValueInitiative } : {}),\n ...(onboardingTask ? { onboardingTask } : {}),\n ...(skillFiles ? { skillFiles } : {}),\n ...(peopleFirstCapture ? { peopleFirstCapture } : {}),\n ...(dailyBriefOnboarding ? { dailyBriefOnboarding } : {}),\n ...(setupPromptDecisions ? { setupPromptDecisions } : {}),\n };\n}\n\nexport function readWizardState(\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardStateRecord | null {\n const parsed = parseJsonObject(readTextIfExists(statePath));\n\n if (\n !isNonEmptyString(parsed.installationId) ||\n !isNonEmptyString(parsed.createdAt) ||\n !isNonEmptyString(parsed.updatedAt)\n ) {\n return null;\n }\n\n const state: WizardStateRecord = {\n installationId: parsed.installationId.trim(),\n createdAt: parsed.createdAt.trim(),\n updatedAt: parsed.updatedAt.trim(),\n };\n const continuity = parseContinuityDefaults(parsed.continuity);\n if (continuity !== undefined) state.continuity = continuity;\n const agentRoster = parseAgentRoster(parsed.agentRoster);\n if (agentRoster !== undefined) state.agentRoster = agentRoster;\n const demoInitiative = parseDemoInitiative(parsed.demoInitiative);\n if (demoInitiative !== undefined) state.demoInitiative = demoInitiative;\n const firstValueInitiative = parseFirstValueInitiative(parsed.firstValueInitiative);\n if (firstValueInitiative !== undefined) {\n state.firstValueInitiative = firstValueInitiative;\n }\n const onboardingTask = parseOnboardingTask(parsed.onboardingTask);\n if (onboardingTask !== undefined) state.onboardingTask = onboardingTask;\n const skillFiles = parseSkillFiles(parsed.skillFiles);\n if (skillFiles !== undefined) state.skillFiles = skillFiles;\n const peopleFirstCapture = parsePeopleFirstCapture(parsed.peopleFirstCapture);\n if (peopleFirstCapture !== undefined) state.peopleFirstCapture = peopleFirstCapture;\n const dailyBriefOnboarding = parseDailyBriefOnboarding(parsed.dailyBriefOnboarding);\n if (dailyBriefOnboarding !== undefined) {\n state.dailyBriefOnboarding = dailyBriefOnboarding;\n }\n const setupPromptDecisions = parseSetupPromptDecisions(parsed.setupPromptDecisions);\n if (setupPromptDecisions !== undefined) {\n state.setupPromptDecisions = setupPromptDecisions;\n }\n return state;\n}\n\n/**\n * Idempotency helpers for people-first capture. `hasCompleted` is called\n * before prompting; `recordCompletion` is called after a successful capture\n * (server-backed or local-fallback) so subsequent wizard runs skip.\n */\nexport function hasPeopleFirstCaptureCompleted(\n workspaceId: string,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): boolean {\n const state = readWizardState(statePath);\n if (!state?.peopleFirstCapture) return false;\n return state.peopleFirstCapture.entries.some(\n (entry) => entry.workspaceId === workspaceId,\n );\n}\n\nexport function recordPeopleFirstCaptureCompletion(\n entry: WizardPeopleFirstCaptureEntry,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardStateRecord {\n return updateWizardState((current) => {\n const existingEntries = current.peopleFirstCapture?.entries ?? [];\n const withoutExisting = existingEntries.filter(\n (e) => e.workspaceId !== entry.workspaceId,\n );\n return {\n ...current,\n peopleFirstCapture: {\n updatedAt: new Date().toISOString(),\n entries: [...withoutExisting, entry],\n },\n };\n }, statePath);\n}\n\nexport function getDailyBriefOnboardingDecision(\n workspaceId: string,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardDailyBriefOnboardingEntry | null {\n const state = readWizardState(statePath);\n return state?.dailyBriefOnboarding?.entries.find(\n (entry) => entry.workspaceId === workspaceId,\n ) ?? null;\n}\n\nexport function hasDailyBriefOnboardingDecision(\n workspaceId: string,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): boolean {\n return getDailyBriefOnboardingDecision(workspaceId, statePath) !== null;\n}\n\nexport function recordDailyBriefOnboardingDecision(\n entry: WizardDailyBriefOnboardingEntry,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardStateRecord {\n return updateWizardState((current) => {\n const existingEntries = current.dailyBriefOnboarding?.entries ?? [];\n const withoutExisting = existingEntries.filter(\n (e) => e.workspaceId !== entry.workspaceId,\n );\n return {\n ...current,\n dailyBriefOnboarding: {\n updatedAt: new Date().toISOString(),\n entries: [...withoutExisting, entry],\n },\n };\n }, statePath);\n}\n\nexport function getSetupPromptDecision(\n workspaceId: string,\n promptKey: WizardSetupPromptKey,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardSetupPromptDecisionEntry | null {\n const state = readWizardState(statePath);\n return (\n state?.setupPromptDecisions?.entries.find(\n (entry) =>\n entry.workspaceId === workspaceId && entry.promptKey === promptKey,\n ) ?? null\n );\n}\n\nexport function hasSetupPromptSkip(\n workspaceId: string,\n promptKey: WizardSetupPromptKey,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): boolean {\n return getSetupPromptDecision(workspaceId, promptKey, statePath) !== null;\n}\n\nexport function recordSetupPromptSkip(\n entry: {\n promptKey: WizardSetupPromptKey;\n skippedAt?: string;\n workspaceId: string;\n workspaceName?: string;\n },\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardStateRecord {\n return updateWizardState((current) => {\n const existingEntries = current.setupPromptDecisions?.entries ?? [];\n const withoutExisting = existingEntries.filter(\n (existing) =>\n !(\n existing.workspaceId === entry.workspaceId &&\n existing.promptKey === entry.promptKey\n ),\n );\n return {\n ...current,\n setupPromptDecisions: {\n updatedAt: new Date().toISOString(),\n entries: [\n ...withoutExisting,\n {\n promptKey: entry.promptKey,\n skippedAt: entry.skippedAt ?? new Date().toISOString(),\n status: \"skipped\",\n workspaceId: entry.workspaceId,\n ...(entry.workspaceName ? { workspaceName: entry.workspaceName } : {}),\n },\n ],\n },\n };\n }, statePath);\n}\n\nexport function writeWizardState(\n value: WizardStateRecord,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardStateRecord {\n const record = sanitizeWizardStateRecord(value);\n writeJsonFile(statePath, record, { mode: 0o600 });\n return record;\n}\n\nexport function updateWizardState(\n updater: (current: WizardStateRecord) => WizardStateRecord,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardStateRecord {\n const current = readWizardState(statePath) ?? createWizardState();\n const next = updater(current);\n const sanitized = sanitizeWizardStateRecord({\n ...next,\n installationId: next.installationId || current.installationId,\n createdAt: next.createdAt || current.createdAt,\n updatedAt: new Date().toISOString(),\n });\n writeJsonFile(statePath, sanitized, { mode: 0o600 });\n return sanitized;\n}\n\nexport function getOrCreateWizardInstallationId(\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): string {\n const existing = readWizardState(statePath);\n if (existing) {\n return existing.installationId;\n }\n\n const record = createWizardState();\n writeWizardState(record, statePath);\n return record.installationId;\n}\n\nexport function clearWizardState(\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): boolean {\n return deleteFileIfExists(statePath);\n}\n","export const SURFACE_NAMES = [\n \"claude\",\n \"cursor\",\n \"codex\",\n \"openclaw\",\n \"vscode\",\n \"windsurf\",\n \"zed\",\n \"chatgpt\",\n] as const;\n\nexport type SurfaceName = (typeof SURFACE_NAMES)[number];\nexport type SurfaceMode = \"automated\" | \"manual\";\n\nexport const AUTOMATED_SURFACE_NAMES = [\n \"claude\",\n \"cursor\",\n \"codex\",\n \"openclaw\",\n \"vscode\",\n \"windsurf\",\n \"zed\",\n] as const satisfies readonly SurfaceName[];\n\nexport const MCP_SURFACE_NAMES = [\n \"claude\",\n \"cursor\",\n \"codex\",\n \"vscode\",\n \"windsurf\",\n \"zed\",\n] as const;\n","import type { OrgxWorkspace } from \"./workspaces.js\";\nimport {\n readWizardState,\n updateWizardState,\n type WizardAgentRosterEntry,\n type WizardAgentRosterRecord,\n} from \"./wizard-state.js\";\n\nexport interface AgentRosterProfile {\n agentType: string;\n defaultDomain: string;\n name: string;\n}\n\nexport interface AgentRosterAssignment {\n domain: string;\n name: string;\n}\n\nexport const AGENT_ROSTER_PROFILES: AgentRosterProfile[] = [\n { agentType: \"orchestrator-agent\", defaultDomain: \"orchestrator\", name: \"Xandy\" },\n { agentType: \"product-agent\", defaultDomain: \"product\", name: \"Pace\" },\n { agentType: \"engineering-agent\", defaultDomain: \"engineering\", name: \"Eli\" },\n { agentType: \"marketing-agent\", defaultDomain: \"marketing\", name: \"Mark\" },\n { agentType: \"sales-agent\", defaultDomain: \"sales\", name: \"Sage\" },\n { agentType: \"operations-agent\", defaultDomain: \"operations\", name: \"Orion\" },\n { agentType: \"design-agent\", defaultDomain: \"design\", name: \"Dana\" },\n];\n\nexport const AGENT_ROSTER_DOMAINS = AGENT_ROSTER_PROFILES.map((profile) => profile.defaultDomain);\n\nexport const DEFAULT_AGENT_ROSTER: WizardAgentRosterEntry[] = AGENT_ROSTER_PROFILES.map(\n ({ agentType, defaultDomain, name }) => ({\n agentType,\n domain: defaultDomain,\n name,\n }),\n);\n\nfunction findAgentRosterProfile(name: string): AgentRosterProfile | undefined {\n return AGENT_ROSTER_PROFILES.find((profile) => profile.name === name);\n}\n\nexport function listAgentRosterProfiles(): AgentRosterProfile[] {\n return AGENT_ROSTER_PROFILES.map((profile) => ({ ...profile }));\n}\n\nexport function buildAgentRosterEntries(\n assignments: AgentRosterAssignment[],\n): WizardAgentRosterEntry[] {\n const seenNames = new Set<string>();\n\n return assignments.map((assignment) => {\n const name = assignment.name.trim();\n const domain = assignment.domain.trim();\n if (domain.length === 0) {\n throw new Error(\"OrgX agent roster domains must be non-empty.\");\n }\n\n const profile = findAgentRosterProfile(name);\n if (!profile) {\n throw new Error(`Unknown OrgX agent '${assignment.name}'.`);\n }\n\n if (seenNames.has(profile.name)) {\n throw new Error(`OrgX agent '${profile.name}' can only be assigned once.`);\n }\n seenNames.add(profile.name);\n\n return {\n agentType: profile.agentType,\n domain,\n name: profile.name,\n };\n });\n}\n\nfunction toAgentRosterRecord(\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n agents: WizardAgentRosterEntry[],\n): WizardAgentRosterRecord {\n return {\n agents: agents.map((agent) => ({ ...agent })),\n configuredAt: new Date().toISOString(),\n workspaceId: workspace.id,\n workspaceName: workspace.name,\n };\n}\n\nexport function configureAgentRoster(\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n assignments: AgentRosterAssignment[],\n options: { statePath?: string } = {},\n): WizardAgentRosterRecord {\n const agents = buildAgentRosterEntries(assignments);\n if (agents.length === 0) {\n throw new Error(\"Select at least one OrgX agent before saving the roster.\");\n }\n\n const roster = toAgentRosterRecord(workspace, agents);\n updateWizardState(\n (current) => ({\n ...current,\n agentRoster: roster,\n }),\n options.statePath,\n );\n return roster;\n}\n\nexport function ensureDefaultAgentRoster(\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n options: { statePath?: string } = {},\n): WizardAgentRosterRecord {\n const existing = readWizardState(options.statePath)?.agentRoster;\n if (existing?.workspaceId === workspace.id && existing.agents.length > 0) {\n return existing;\n }\n\n const roster = toAgentRosterRecord(workspace, DEFAULT_AGENT_ROSTER);\n updateWizardState(\n (current) => ({\n ...current,\n agentRoster: roster,\n }),\n options.statePath,\n );\n return roster;\n}\n","import { spawnSync } from \"node:child_process\";\n\nimport { readTextIfExists } from \"./fs.js\";\nimport { readOpenClawGatewayPort } from \"../surfaces/openclaw-config.js\";\n\nexport interface OpenClawHealthCheck {\n ok: boolean;\n skipped: boolean;\n method: \"cli\" | \"http\" | \"none\";\n url?: string;\n details: string[];\n error?: string;\n}\n\nfunction trimOutput(value: string | null | undefined): string | undefined {\n const next = value?.trim();\n return next ? next : undefined;\n}\n\nexport async function checkOpenClawHealth(\n configPath?: string,\n): Promise<OpenClawHealthCheck> {\n const rawConfig = configPath ? readTextIfExists(configPath) : null;\n const port = readOpenClawGatewayPort(rawConfig);\n const url = `http://127.0.0.1:${port}/orgx/live`;\n\n const cli = spawnSync(\"openclaw\", [\"gateway\", \"status\"], {\n encoding: \"utf8\",\n timeout: 5_000,\n });\n\n if (!cli.error) {\n const stdout = trimOutput(cli.stdout);\n const stderr = trimOutput(cli.stderr);\n const details = [`gateway port: ${port}`];\n if (stdout) details.push(`cli: ${stdout}`);\n if (stderr) details.push(`cli stderr: ${stderr}`);\n\n if (cli.status === 0) {\n return {\n ok: true,\n skipped: false,\n method: \"cli\",\n url,\n details,\n };\n }\n }\n\n try {\n const response = await fetch(url, {\n redirect: \"manual\",\n signal: AbortSignal.timeout(5_000),\n });\n\n if (response.ok || (response.status >= 300 && response.status < 400)) {\n return {\n ok: true,\n skipped: false,\n method: \"http\",\n url,\n details: [`gateway port: ${port}`, `http status: ${response.status}`],\n };\n }\n\n return {\n ok: false,\n skipped: false,\n method: \"http\",\n url,\n error: `HTTP ${response.status}`,\n details: [`gateway port: ${port}`, `http status: ${response.status}`],\n };\n } catch (error) {\n const cliError = cli.error instanceof Error ? cli.error.message : undefined;\n return {\n ok: false,\n skipped: false,\n method: cliError ? \"none\" : \"http\",\n url,\n error: error instanceof Error ? error.message : String(error),\n details: [\n `gateway port: ${port}`,\n ...(cliError ? [`openclaw cli unavailable: ${cliError}`] : []),\n ],\n };\n }\n}\n","import { ORGX_HOSTED_MCP_HEALTH_URL } from \"../constants.js\";\n\nexport interface HostedMcpHealthCheck {\n ok: boolean;\n skipped: boolean;\n status?: number;\n url: string;\n body?: string;\n error?: string;\n details: string[];\n}\n\nfunction trimBody(value: string): string | undefined {\n const next = value.trim();\n if (!next) return undefined;\n return next.length > 120 ? `${next.slice(0, 117)}...` : next;\n}\n\nexport async function checkHostedMcpHealth(): Promise<HostedMcpHealthCheck> {\n try {\n const response = await fetch(ORGX_HOSTED_MCP_HEALTH_URL, {\n method: \"GET\",\n signal: AbortSignal.timeout(5_000),\n });\n const text = await response.text();\n const body = trimBody(text);\n\n return {\n ok: response.ok,\n skipped: false,\n status: response.status,\n url: ORGX_HOSTED_MCP_HEALTH_URL,\n ...(body ? { body } : {}),\n ...(response.ok ? {} : { error: `HTTP ${response.status}` }),\n details: [\n `http status: ${response.status}`,\n ...(body ? [`body: ${body}`] : []),\n ],\n };\n } catch (error) {\n return {\n ok: false,\n skipped: false,\n url: ORGX_HOSTED_MCP_HEALTH_URL,\n error: error instanceof Error ? error.message : String(error),\n details: [],\n };\n }\n}\n","import { ORGX_HOSTED_MCP_URL } from \"../constants.js\";\nimport {\n resolveOrgxAuth,\n type OrgxAuthSource,\n type ResolveOrgxAuthOptions,\n} from \"./auth.js\";\n\nconst DEFAULT_TOOL_NAME = \"get_setup_status\";\n\nexport interface HostedMcpToolCheck {\n configured: boolean;\n ok: boolean;\n skipped: boolean;\n source: OrgxAuthSource | \"none\";\n toolName: string;\n url: string;\n baseUrl?: string;\n initializeStatus?: number;\n callStatus?: number;\n error?: string;\n details: string[];\n response?: unknown;\n}\n\nexport async function checkHostedMcpToolAccess(\n options: ResolveOrgxAuthOptions = {},\n toolName = DEFAULT_TOOL_NAME,\n): Promise<HostedMcpToolCheck> {\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n return {\n configured: false,\n ok: false,\n skipped: true,\n source: \"none\",\n toolName,\n url: ORGX_HOSTED_MCP_URL,\n error: \"No OrgX API key configured; hosted MCP tool verification skipped.\",\n details: [],\n };\n }\n\n return {\n configured: true,\n ok: false,\n skipped: true,\n source: auth.source,\n toolName,\n url: ORGX_HOSTED_MCP_URL,\n baseUrl: auth.baseUrl,\n error: \"Hosted OrgX MCP uses OAuth; API-key tool verification is skipped.\",\n details: [\n `auth source: ${auth.source}`,\n \"Hosted OrgX MCP connectors complete OAuth during client setup, so the wizard cannot preflight tools with an oxk_ API key.\",\n ],\n };\n}\n","import {\n NPM_REGISTRY_BASE_URL,\n ORGX_WIZARD_NPM_PACKAGE_NAME,\n} from \"../constants.js\";\nimport { isRecord } from \"./fs.js\";\n\nexport interface NpmRegistryCheck {\n ok: boolean;\n skipped: boolean;\n reachable: boolean;\n published: boolean;\n url: string;\n packageName: string;\n version?: string;\n error?: string;\n details: string[];\n}\n\nfunction resolvePackageUrl(packageName: string): string {\n return `${NPM_REGISTRY_BASE_URL}/${encodeURIComponent(packageName)}`;\n}\n\nfunction getLatestVersion(payload: unknown): string | undefined {\n if (!isRecord(payload) || !isRecord(payload[\"dist-tags\"])) {\n return undefined;\n }\n\n const latest = payload[\"dist-tags\"].latest;\n return typeof latest === \"string\" && latest.trim().length > 0 ? latest : undefined;\n}\n\nexport async function checkNpmRegistryHealth(\n packageName: string = ORGX_WIZARD_NPM_PACKAGE_NAME,\n): Promise<NpmRegistryCheck> {\n const url = resolvePackageUrl(packageName);\n\n try {\n const response = await fetch(url, {\n method: \"GET\",\n headers: { Accept: \"application/json\" },\n signal: AbortSignal.timeout(7_000),\n });\n\n const text = await response.text();\n let payload: unknown = text;\n try {\n payload = text.length > 0 ? JSON.parse(text) : null;\n } catch {\n payload = text;\n }\n\n if (response.ok) {\n const version = getLatestVersion(payload);\n return {\n ok: true,\n skipped: false,\n reachable: true,\n published: true,\n url,\n packageName,\n ...(version ? { version } : {}),\n details: [\n `http status: ${response.status}`,\n ...(version ? [`latest version: ${version}`] : [\"latest version: unavailable\"]),\n ],\n };\n }\n\n if (response.status === 404) {\n return {\n ok: true,\n skipped: false,\n reachable: true,\n published: false,\n url,\n packageName,\n error: `${packageName} is not published on npm yet.`,\n details: [`http status: ${response.status}`],\n };\n }\n\n return {\n ok: false,\n skipped: false,\n reachable: false,\n published: false,\n url,\n packageName,\n error: `npm registry returned HTTP ${response.status}`,\n details: [`http status: ${response.status}`],\n };\n } catch (error) {\n return {\n ok: false,\n skipped: false,\n reachable: false,\n published: false,\n url,\n packageName,\n error: error instanceof Error ? error.message : String(error),\n details: [],\n };\n }\n}\n","import { buildOrgxApiUrl, resolveOrgxAuth, type ResolveOrgxAuthOptions } from \"./auth.js\";\nimport { isRecord } from \"./fs.js\";\n\nexport interface OrgxWorkspace {\n id: string;\n name: string;\n description?: string;\n isDefault: boolean;\n createdAt?: string;\n updatedAt?: string;\n}\n\nexport interface CreateWorkspaceInput {\n name: string;\n description?: string;\n}\n\nexport interface SetDefaultWorkspaceInput {\n id: string;\n}\n\nexport interface OrgxWorkspaceClientOptions extends ResolveOrgxAuthOptions {}\n\nasync function requireOrgxAuth(options: OrgxWorkspaceClientOptions = {}) {\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n throw new Error(\n \"No OrgX API key configured. Run `wizard auth login` or `wizard auth set-key <oxk_...>` first.\",\n );\n }\n\n return auth;\n}\n\nasync function parseResponseBody(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction parseWorkspace(value: unknown): OrgxWorkspace | null {\n if (!isRecord(value)) return null;\n\n const id = typeof value.id === \"string\" ? value.id : null;\n const name = typeof value.name === \"string\" ? value.name : null;\n if (!id || !name) return null;\n\n return {\n id,\n name,\n ...(typeof value.description === \"string\" && value.description.trim().length > 0\n ? { description: value.description }\n : {}),\n isDefault: value.is_default === true,\n ...(typeof value.created_at === \"string\" ? { createdAt: value.created_at } : {}),\n ...(typeof value.updated_at === \"string\" ? { updatedAt: value.updated_at } : {}),\n };\n}\n\nfunction sortWorkspaces(workspaces: OrgxWorkspace[]): OrgxWorkspace[] {\n return [...workspaces].sort((left, right) => {\n if (left.isDefault !== right.isDefault) {\n return left.isDefault ? -1 : 1;\n }\n\n const nameCompare = left.name.localeCompare(right.name);\n if (nameCompare !== 0) {\n return nameCompare;\n }\n\n return left.id.localeCompare(right.id);\n });\n}\n\nfunction parseWorkspaceList(payload: unknown): OrgxWorkspace[] {\n if (!isRecord(payload) || !Array.isArray(payload.data)) {\n return [];\n }\n\n return sortWorkspaces(payload.data.map(parseWorkspace).filter((item): item is OrgxWorkspace => item !== null));\n}\n\nfunction parseWorkspaceResponse(payload: unknown): OrgxWorkspace | null {\n if (!isRecord(payload)) return null;\n return parseWorkspace(payload.data);\n}\n\nfunction parseCurrentWorkspaceResponse(payload: unknown): OrgxWorkspace | null {\n if (!isRecord(payload)) return null;\n\n const id = typeof payload.id === \"string\" ? payload.id : null;\n const name = typeof payload.name === \"string\" ? payload.name : null;\n if (!id || !name) return null;\n\n return {\n id,\n name,\n isDefault: true,\n ...(typeof payload.createdAt === \"string\" ? { createdAt: payload.createdAt } : {}),\n };\n}\n\nfunction buildRequestHeaders(apiKey: string): Record<string, string> {\n return {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n}\n\nfunction formatHttpError(status: number, body: unknown): string {\n if (typeof body === \"string\" && body.trim().length > 0) {\n return `HTTP ${status}: ${body}`;\n }\n\n if (isRecord(body) && typeof body.error === \"string\" && body.error.trim().length > 0) {\n return `HTTP ${status}: ${body.error}`;\n }\n\n return `HTTP ${status}`;\n}\n\nexport async function listWorkspaces(\n options: OrgxWorkspaceClientOptions = {},\n): Promise<OrgxWorkspace[]> {\n const auth = await requireOrgxAuth(options);\n const url = buildOrgxApiUrl(\"/entities?type=workspace&limit=100\", auth.baseUrl);\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n },\n signal: AbortSignal.timeout(7_000),\n });\n const body = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new Error(`Failed to list workspaces. ${formatHttpError(response.status, body)}`);\n }\n\n return parseWorkspaceList(body);\n}\n\nexport async function getCurrentWorkspace(\n options: OrgxWorkspaceClientOptions = {},\n): Promise<OrgxWorkspace | null> {\n const auth = await requireOrgxAuth(options);\n const url = buildOrgxApiUrl(\"/v1/workspaces/current\", auth.baseUrl);\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n },\n signal: AbortSignal.timeout(7_000),\n });\n const body = await parseResponseBody(response);\n\n if (response.ok) {\n const workspace = parseCurrentWorkspaceResponse(body);\n if (!workspace) {\n throw new Error(\"OrgX returned an unexpected current workspace payload.\");\n }\n return workspace;\n }\n\n if (response.status === 401 || response.status === 404) {\n const workspaces = await listWorkspaces(options);\n return workspaces[0] ?? null;\n }\n\n throw new Error(`Failed to load current workspace. ${formatHttpError(response.status, body)}`);\n}\n\nexport async function createWorkspace(\n input: CreateWorkspaceInput,\n options: OrgxWorkspaceClientOptions = {},\n): Promise<OrgxWorkspace> {\n const name = input.name.trim();\n if (!name) {\n throw new Error(\"Workspace name is required.\");\n }\n\n const auth = await requireOrgxAuth(options);\n const url = buildOrgxApiUrl(\"/entities\", auth.baseUrl);\n const payload = {\n type: \"workspace\",\n name,\n ...(input.description?.trim()\n ? { description: input.description.trim() }\n : {}),\n };\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: buildRequestHeaders(auth.apiKey),\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(7_000),\n });\n const body = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new Error(`Failed to create workspace. ${formatHttpError(response.status, body)}`);\n }\n\n const workspace = parseWorkspaceResponse(body);\n if (!workspace) {\n throw new Error(\"OrgX returned an unexpected workspace payload.\");\n }\n\n return workspace;\n}\n\nasync function updateWorkspace(\n input: SetDefaultWorkspaceInput,\n patch: Record<string, unknown>,\n options: OrgxWorkspaceClientOptions = {},\n): Promise<OrgxWorkspace> {\n const auth = await requireOrgxAuth(options);\n const url = buildOrgxApiUrl(\"/entities\", auth.baseUrl);\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: buildRequestHeaders(auth.apiKey),\n body: JSON.stringify({\n type: \"workspace\",\n id: input.id,\n ...patch,\n }),\n signal: AbortSignal.timeout(7_000),\n });\n const body = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new Error(`Failed to update workspace. ${formatHttpError(response.status, body)}`);\n }\n\n const workspace = parseWorkspaceResponse(body);\n if (!workspace) {\n throw new Error(\"OrgX returned an unexpected workspace update payload.\");\n }\n\n return workspace;\n}\n\nexport async function setDefaultWorkspace(\n input: SetDefaultWorkspaceInput,\n options: OrgxWorkspaceClientOptions = {},\n): Promise<{ changed: boolean; workspace: OrgxWorkspace }> {\n const workspaceId = input.id.trim();\n if (!workspaceId) {\n throw new Error(\"Workspace id is required.\");\n }\n\n const workspaces = await listWorkspaces(options);\n const target = workspaces.find((workspace) => workspace.id === workspaceId);\n if (!target) {\n throw new Error(`Workspace ${workspaceId} was not found in the current OrgX account.`);\n }\n\n if (target.isDefault) {\n return {\n changed: false,\n workspace: target,\n };\n }\n\n const currentDefault = workspaces.find((workspace) => workspace.isDefault);\n if (currentDefault) {\n await updateWorkspace({ id: currentDefault.id }, { is_default: false }, options);\n }\n\n try {\n const updated = await updateWorkspace({ id: workspaceId }, { is_default: true }, options);\n return {\n changed: true,\n workspace: updated,\n };\n } catch (error) {\n if (currentDefault) {\n try {\n await updateWorkspace({ id: currentDefault.id }, { is_default: true }, options);\n } catch {\n // Preserve the original failure while best-effort restoring the prior default.\n }\n }\n throw error;\n }\n}\n","import {\n resolveOrgxAuth,\n type OrgxAuthSource,\n type ResolveOrgxAuthOptions,\n} from \"./auth.js\";\nimport { getCurrentWorkspace, type OrgxWorkspace } from \"./workspaces.js\";\n\nexport interface WorkspaceConnectivityCheck {\n configured: boolean;\n ok: boolean;\n skipped: boolean;\n source: OrgxAuthSource | \"none\";\n baseUrl?: string;\n workspace?: OrgxWorkspace;\n error?: string;\n details: string[];\n}\n\nexport async function checkWorkspaceConnectivity(\n options: ResolveOrgxAuthOptions = {},\n): Promise<WorkspaceConnectivityCheck> {\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n return {\n configured: false,\n ok: false,\n skipped: true,\n source: \"none\",\n error: \"No OrgX API key configured; workspace connectivity check skipped.\",\n details: [],\n };\n }\n\n try {\n const workspace = await getCurrentWorkspace(options);\n if (!workspace) {\n return {\n configured: true,\n ok: false,\n skipped: false,\n source: auth.source,\n baseUrl: auth.baseUrl,\n error: \"OrgX auth resolved, but no accessible workspace was returned.\",\n details: [],\n };\n }\n\n return {\n configured: true,\n ok: true,\n skipped: false,\n source: auth.source,\n baseUrl: auth.baseUrl,\n workspace,\n details: [\n `workspace id: ${workspace.id}`,\n ...(workspace.isDefault ? [\"workspace is marked as default\"] : []),\n ],\n };\n } catch (error) {\n return {\n configured: true,\n ok: false,\n skipped: false,\n source: auth.source,\n baseUrl: auth.baseUrl,\n error: error instanceof Error ? error.message : String(error),\n details: [],\n };\n }\n}\n","import { spawn } from \"node:child_process\";\nimport {\n existsSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n readdirSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, relative } from \"node:path\";\n\nimport {\n CLAUDE_MANAGED_MARKETPLACE_DIR,\n CLAUDE_MANAGED_MARKETPLACE_MANIFEST_PATH,\n CLAUDE_MANAGED_PLUGIN_DIR,\n CODEX_MARKETPLACE_PATH,\n CODEX_ORGX_PLUGIN_DIR,\n CURSOR_DIR,\n CURSOR_MCP_PATH,\n CURSOR_ORGX_PLUGIN_DIR,\n CURSOR_ORGX_RULE_PATH,\n NPM_REGISTRY_BASE_URL,\n} from \"../constants.js\";\nimport { inspectCursorMcpConfig } from \"../surfaces/mcp-config.js\";\nimport { detectSurface } from \"../surfaces/detection.js\";\nimport { CURSOR_RULES_CONTENT } from \"./skills.js\";\nimport { deleteFileIfExists, parseJsonObject, readObject, readTextIfExists } from \"./fs.js\";\n\nexport const DEFAULT_ORGX_PLUGIN_TARGETS = [\"cursor\", \"claude\", \"codex\", \"openclaw\"] as const;\n\nexport type OrgxPluginTarget = typeof DEFAULT_ORGX_PLUGIN_TARGETS[number];\n\nexport interface OrgxPluginStatus {\n target: OrgxPluginTarget;\n available: boolean;\n installed: boolean;\n message: string;\n}\n\nexport interface OrgxPluginMutation {\n target: OrgxPluginTarget;\n changed: boolean;\n message: string;\n}\n\nexport interface OrgxPluginMutationReport {\n results: OrgxPluginMutation[];\n}\n\nexport interface PluginCommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n errorCode?: string;\n}\n\nexport type PluginCommandRunner = (\n command: string,\n args: readonly string[],\n) => Promise<PluginCommandResult>;\n\nexport interface OrgxPluginPaths {\n claudeMarketplaceDir: string;\n claudeMarketplaceManifestPath: string;\n claudePluginDir: string;\n codexMarketplacePath: string;\n codexPluginDir: string;\n cursorPluginDir: string;\n cursorRulePath: string;\n}\n\nexport interface ListOrgxPluginStatusesOptions {\n commandRunner?: PluginCommandRunner;\n paths?: Partial<OrgxPluginPaths>;\n}\n\nexport interface InstallOrgxPluginsOptions {\n targets?: readonly string[];\n commandRunner?: PluginCommandRunner;\n fetchImpl?: typeof fetch;\n paths?: Partial<OrgxPluginPaths>;\n}\n\nexport interface UninstallOrgxPluginsOptions {\n targets?: readonly string[];\n commandRunner?: PluginCommandRunner;\n paths?: Partial<OrgxPluginPaths>;\n}\n\ninterface RepoDirectoryEntry {\n name: string;\n path: string;\n type: \"dir\" | \"file\";\n download_url: string | null;\n}\n\ninterface RemoteRepoFile {\n localPath: string;\n path: string;\n sourceUrl: string;\n}\n\ninterface RepoSyncSpec {\n owner: string;\n repo: string;\n ref: string;\n include: Array<{ localPath: string; remotePath: string }>;\n}\n\nconst ORGX_PLUGIN_GITHUB_OWNER = \"useorgx\";\nconst ORGX_PLUGIN_GITHUB_REF = \"main\";\nconst ORGX_CLAUDE_PLUGIN_NAME = \"orgx-claude-code-plugin\";\nconst ORGX_CLAUDE_MARKETPLACE_NAME = \"orgx-local\";\nconst ORGX_CODEX_PLUGIN_NAME = \"orgx-codex-plugin\";\nconst ORGX_CURSOR_PLUGIN_NAME = \"cursor-plugin\";\nconst ORGX_OPENCLAW_PLUGIN_ID = \"orgx\";\nconst ORGX_OPENCLAW_PLUGIN_PACKAGE_NAME = \"@useorgx/openclaw-plugin\";\n\nconst CLAUDE_PLUGIN_SYNC_SPEC: RepoSyncSpec = {\n owner: ORGX_PLUGIN_GITHUB_OWNER,\n repo: ORGX_CLAUDE_PLUGIN_NAME,\n ref: ORGX_PLUGIN_GITHUB_REF,\n include: [\n { localPath: \".claude-plugin\", remotePath: \".claude-plugin\" },\n { localPath: \"agents\", remotePath: \"agents\" },\n { localPath: \"commands\", remotePath: \"commands\" },\n { localPath: \"hooks\", remotePath: \"hooks\" },\n { localPath: \"lib\", remotePath: \"lib\" },\n { localPath: \"scripts\", remotePath: \"scripts\" },\n { localPath: \"skills\", remotePath: \"skills\" },\n ],\n};\n\nconst CODEX_PLUGIN_SYNC_SPEC: RepoSyncSpec = {\n owner: ORGX_PLUGIN_GITHUB_OWNER,\n repo: ORGX_CODEX_PLUGIN_NAME,\n ref: ORGX_PLUGIN_GITHUB_REF,\n include: [\n { localPath: \".codex-plugin\", remotePath: \".codex-plugin\" },\n { localPath: \".mcp.json\", remotePath: \".mcp.json\" },\n { localPath: \"assets\", remotePath: \"assets\" },\n { localPath: \"skills\", remotePath: \"skills\" },\n ],\n};\n\nconst CURSOR_PLUGIN_SYNC_SPEC: RepoSyncSpec = {\n owner: ORGX_PLUGIN_GITHUB_OWNER,\n repo: ORGX_CURSOR_PLUGIN_NAME,\n ref: ORGX_PLUGIN_GITHUB_REF,\n include: [\n { localPath: \".cursor-plugin\", remotePath: \".cursor-plugin\" },\n { localPath: \".mcp.json\", remotePath: \".mcp.json\" },\n { localPath: \"agents\", remotePath: \"agents\" },\n { localPath: \"assets\", remotePath: \"assets\" },\n { localPath: \"commands\", remotePath: \"commands\" },\n { localPath: \"hooks\", remotePath: \"hooks\" },\n { localPath: \"rules\", remotePath: \"rules\" },\n { localPath: \"scripts\", remotePath: \"scripts\" },\n { localPath: \"skills\", remotePath: \"skills\" },\n ],\n};\n\nfunction defaultPluginPaths(): OrgxPluginPaths {\n return {\n claudeMarketplaceDir: CLAUDE_MANAGED_MARKETPLACE_DIR,\n claudeMarketplaceManifestPath: CLAUDE_MANAGED_MARKETPLACE_MANIFEST_PATH,\n claudePluginDir: CLAUDE_MANAGED_PLUGIN_DIR,\n codexMarketplacePath: CODEX_MARKETPLACE_PATH,\n codexPluginDir: CODEX_ORGX_PLUGIN_DIR,\n cursorPluginDir: CURSOR_ORGX_PLUGIN_DIR,\n cursorRulePath: CURSOR_ORGX_RULE_PATH,\n };\n}\n\nfunction resolvePluginPaths(paths: Partial<OrgxPluginPaths> = {}): OrgxPluginPaths {\n return {\n ...defaultPluginPaths(),\n ...paths,\n };\n}\n\nfunction isRepoDirectoryEntry(value: unknown): value is RepoDirectoryEntry {\n if (!value || typeof value !== \"object\") return false;\n\n const entry = value as Partial<RepoDirectoryEntry>;\n const hasType = entry.type === \"file\" || entry.type === \"dir\";\n return typeof entry.name === \"string\" && typeof entry.path === \"string\" && hasType;\n}\n\nfunction encodeRepoPath(value: string): string {\n return value\n .split(\"/\")\n .filter((segment) => segment.length > 0)\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n}\n\nfunction isLikelyRepoFilePath(path: string): boolean {\n const basename = path.split(\"/\").pop() ?? path;\n return basename.includes(\".\") && !/^\\.[^./]+$/.test(basename);\n}\n\nfunction buildContentsUrl(spec: RepoSyncSpec, path: string): string {\n const encodedPath = encodeRepoPath(path);\n return `https://api.github.com/repos/${spec.owner}/${spec.repo}/contents/${encodedPath}?ref=${encodeURIComponent(spec.ref)}`;\n}\n\nfunction resolveGitHubError(spec: RepoSyncSpec, status: number, path: string): string {\n const repoName = `${spec.owner}/${spec.repo}`;\n if (status === 404) {\n return `Could not find '${path}' in ${repoName}.`;\n }\n\n return `GitHub returned HTTP ${status} while loading '${path}' from ${repoName}.`;\n}\n\nasync function fetchDirectoryEntries(\n spec: RepoSyncSpec,\n path: string,\n fetchImpl: typeof fetch,\n): Promise<RepoDirectoryEntry[]> {\n const response = await fetchImpl(buildContentsUrl(spec, path), {\n headers: {\n Accept: \"application/vnd.github+json\",\n },\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n throw new Error(resolveGitHubError(spec, response.status, path));\n }\n\n const data = await response.json();\n if (!Array.isArray(data)) {\n throw new Error(`Expected '${path}' to be a directory in ${spec.owner}/${spec.repo}.`);\n }\n\n return data\n .filter(isRepoDirectoryEntry)\n .sort((left, right) => left.path.localeCompare(right.path));\n}\n\nasync function fetchRepoFile(\n spec: RepoSyncSpec,\n path: string,\n fetchImpl: typeof fetch,\n): Promise<RepoDirectoryEntry> {\n const response = await fetchImpl(buildContentsUrl(spec, path), {\n headers: {\n Accept: \"application/vnd.github+json\",\n },\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n throw new Error(resolveGitHubError(spec, response.status, path));\n }\n\n const data = await response.json();\n if (!isRepoDirectoryEntry(data) || data.type !== \"file\" || typeof data.download_url !== \"string\") {\n throw new Error(`Expected '${path}' to be a file in ${spec.owner}/${spec.repo}.`);\n }\n\n return data;\n}\n\nasync function listRemoteRepoFiles(\n spec: RepoSyncSpec,\n path: string,\n localPath: string,\n fetchImpl: typeof fetch,\n): Promise<RemoteRepoFile[]> {\n const files: RemoteRepoFile[] = [];\n\n if (isLikelyRepoFilePath(path) && !path.endsWith(\"/\")) {\n const file = await fetchRepoFile(spec, path, fetchImpl);\n files.push({\n localPath,\n path: file.path,\n sourceUrl: file.download_url ?? \"\",\n });\n return files;\n }\n\n const entries = await fetchDirectoryEntries(spec, path, fetchImpl);\n for (const entry of entries) {\n if (entry.type === \"dir\") {\n files.push(\n ...await listRemoteRepoFiles(\n spec,\n entry.path,\n join(localPath, entry.name),\n fetchImpl,\n ),\n );\n continue;\n }\n\n if (!entry.download_url) {\n throw new Error(`GitHub did not provide a download URL for '${entry.path}'.`);\n }\n\n files.push({\n localPath: join(localPath, entry.name),\n path: entry.path,\n sourceUrl: entry.download_url,\n });\n }\n\n return files;\n}\n\nasync function collectRemoteRepoFiles(spec: RepoSyncSpec, fetchImpl: typeof fetch): Promise<RemoteRepoFile[]> {\n const files: RemoteRepoFile[] = [];\n for (const entry of spec.include) {\n const isFile = isLikelyRepoFilePath(entry.remotePath) && !entry.remotePath.endsWith(\"/\");\n if (isFile) {\n const file = await fetchRepoFile(spec, entry.remotePath, fetchImpl);\n files.push({\n localPath: entry.localPath,\n path: file.path,\n sourceUrl: file.download_url ?? \"\",\n });\n continue;\n }\n\n files.push(...await listRemoteRepoFiles(spec, entry.remotePath, entry.localPath, fetchImpl));\n }\n\n return files.sort((left, right) => left.localPath.localeCompare(right.localPath));\n}\n\nasync function fetchRemoteBytes(sourceUrl: string, fetchImpl: typeof fetch): Promise<Buffer> {\n const response = await fetchImpl(sourceUrl, {\n headers: {\n Accept: \"application/octet-stream\",\n },\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n throw new Error(`GitHub returned HTTP ${response.status} while downloading ${sourceUrl}.`);\n }\n\n return Buffer.from(await response.arrayBuffer());\n}\n\nfunction readBytesIfExists(path: string): Buffer | null {\n if (!existsSync(path)) return null;\n\n try {\n if (!statSync(path).isFile()) {\n return null;\n }\n return readFileSync(path);\n } catch (error) {\n const code = typeof error === \"object\" && error && \"code\" in error\n ? String(error.code)\n : undefined;\n if (code === \"ENOENT\" || code === \"ENOTDIR\" || code === \"EISDIR\") {\n return null;\n }\n throw error;\n }\n}\n\nfunction writeBytesIfChanged(path: string, bytes: Buffer): boolean {\n const existing = readBytesIfExists(path);\n if (existing && Buffer.compare(existing, bytes) === 0) {\n return false;\n }\n\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, bytes);\n return true;\n}\n\nfunction removePathIfExists(path: string): boolean {\n if (!existsSync(path)) return false;\n rmSync(path, { force: true, recursive: true });\n return true;\n}\n\nfunction listRelativeFiles(root: string, base = root): string[] {\n if (!existsSync(root)) return [];\n if (!statSync(root).isDirectory()) {\n return [];\n }\n\n const files: string[] = [];\n for (const entry of readdirSync(root, { withFileTypes: true })) {\n const nextPath = join(root, entry.name);\n if (entry.isDirectory()) {\n files.push(...listRelativeFiles(nextPath, base));\n continue;\n }\n if (entry.isFile()) {\n files.push(relative(base, nextPath));\n }\n }\n return files.sort();\n}\n\nfunction pruneEmptyDirectories(root: string, current = root): boolean {\n if (!existsSync(current) || !statSync(current).isDirectory()) {\n return false;\n }\n\n let changed = false;\n for (const entry of readdirSync(current, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n changed = pruneEmptyDirectories(root, join(current, entry.name)) || changed;\n }\n\n if (current !== root && readdirSync(current).length === 0) {\n rmSync(current, { force: true, recursive: true });\n return true;\n }\n\n return changed;\n}\n\nasync function syncManagedRepoTree(\n spec: RepoSyncSpec,\n destinationRoot: string,\n fetchImpl: typeof fetch,\n): Promise<{ changed: boolean; fileCount: number }> {\n const remoteFiles = await collectRemoteRepoFiles(spec, fetchImpl);\n let changed = false;\n const expected = new Set(remoteFiles.map((file) => file.localPath));\n\n if (existsSync(destinationRoot) && !statSync(destinationRoot).isDirectory()) {\n rmSync(destinationRoot, { force: true, recursive: true });\n changed = true;\n }\n\n for (const file of listRelativeFiles(destinationRoot)) {\n if (expected.has(file)) continue;\n rmSync(join(destinationRoot, file), { force: true });\n changed = true;\n }\n changed = pruneEmptyDirectories(destinationRoot) || changed;\n\n for (const file of remoteFiles) {\n const bytes = await fetchRemoteBytes(file.sourceUrl, fetchImpl);\n if (writeBytesIfChanged(join(destinationRoot, file.localPath), bytes)) {\n changed = true;\n }\n }\n\n return { changed, fileCount: remoteFiles.length };\n}\n\nfunction serializeJson(value: unknown): string {\n return `${JSON.stringify(value, null, 2)}\\n`;\n}\n\nfunction writeJsonIfChanged(path: string, value: unknown): boolean {\n const next = serializeJson(value);\n const existing = readTextIfExists(path);\n if (existing === next) {\n return false;\n }\n\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, next, \"utf8\");\n return true;\n}\n\nfunction buildClaudeMarketplaceManifest(): Record<string, unknown> {\n return {\n $schema: \"https://anthropic.com/claude-code/marketplace.schema.json\",\n name: ORGX_CLAUDE_MARKETPLACE_NAME,\n description: \"Local OrgX plugins\",\n owner: {\n name: \"OrgX Team\",\n },\n plugins: [\n {\n name: ORGX_CLAUDE_PLUGIN_NAME,\n description: \"OrgX MCP tools and runtime telemetry hooks for Claude Code.\",\n source: `./plugins/${ORGX_CLAUDE_PLUGIN_NAME}`,\n },\n ],\n };\n}\n\nfunction buildCodexMarketplaceEntry(): Record<string, unknown> {\n return {\n name: ORGX_CODEX_PLUGIN_NAME,\n source: {\n source: \"local\",\n path: `./.codex/plugins/${ORGX_CODEX_PLUGIN_NAME}`,\n },\n policy: {\n installation: \"AVAILABLE\",\n authentication: \"ON_INSTALL\",\n },\n category: \"Productivity\",\n };\n}\n\nfunction readMarketplacePlugins(path: string): {\n document: Record<string, unknown>;\n plugins: Record<string, unknown>[];\n} {\n const document = parseJsonObject(readTextIfExists(path));\n const plugins = Array.isArray(document.plugins)\n ? document.plugins.filter((value): value is Record<string, unknown> => Boolean(value) && typeof value === \"object\" && !Array.isArray(value))\n : [];\n\n return { document, plugins };\n}\n\nfunction upsertCodexMarketplaceEntry(path: string): boolean {\n const { document, plugins } = readMarketplacePlugins(path);\n const nextEntry = buildCodexMarketplaceEntry();\n let replaced = false;\n\n const nextPlugins = plugins.map((plugin) => {\n if (plugin.name !== ORGX_CODEX_PLUGIN_NAME) {\n return plugin;\n }\n replaced = true;\n return nextEntry;\n });\n\n if (!replaced) {\n nextPlugins.push(nextEntry);\n }\n\n const nextDocument: Record<string, unknown> = {\n ...document,\n ...(document.name ? {} : { name: ORGX_CLAUDE_MARKETPLACE_NAME }),\n ...(readObject(document.interface).displayName ? {} : { interface: { displayName: \"OrgX Local\" } }),\n plugins: nextPlugins,\n };\n\n return writeJsonIfChanged(path, nextDocument);\n}\n\nfunction removeCodexMarketplaceEntry(path: string): boolean {\n if (!existsSync(path)) {\n return false;\n }\n\n const { document, plugins } = readMarketplacePlugins(path);\n const nextPlugins = plugins.filter((plugin) => plugin.name !== ORGX_CODEX_PLUGIN_NAME);\n if (nextPlugins.length === plugins.length) {\n return false;\n }\n\n if (nextPlugins.length === 0) {\n rmSync(path, { force: true });\n return true;\n }\n\n return writeJsonIfChanged(path, {\n ...document,\n plugins: nextPlugins,\n });\n}\n\nfunction codexMarketplaceHasOrgxEntry(path: string): boolean {\n const { plugins } = readMarketplacePlugins(path);\n return plugins.some((plugin) => plugin.name === ORGX_CODEX_PLUGIN_NAME);\n}\n\nfunction extractClaudePluginNames(payload: string): string[] {\n try {\n const parsed = JSON.parse(payload);\n if (!Array.isArray(parsed)) return [];\n return parsed.flatMap((entry) => {\n if (typeof entry === \"string\") return [entry];\n if (!entry || typeof entry !== \"object\") return [];\n if (typeof entry.name === \"string\") return [entry.name];\n if (typeof entry.id === \"string\") return [entry.id];\n return [];\n });\n } catch {\n return [];\n }\n}\n\nfunction extractOpenclawPluginIds(payload: string): string[] {\n try {\n const parsed = JSON.parse(payload);\n if (Array.isArray(parsed)) {\n return parsed.flatMap((entry) => {\n if (!entry || typeof entry !== \"object\") return [];\n if (typeof entry.id === \"string\") return [entry.id];\n if (typeof entry.name === \"string\") return [entry.name];\n return [];\n });\n }\n\n const root = readObject(parsed);\n const plugins = Array.isArray(root.plugins) ? root.plugins : [];\n return plugins.flatMap((entry) => {\n if (!entry || typeof entry !== \"object\") return [];\n const item = entry as Record<string, unknown>;\n if (typeof item.id === \"string\") return [item.id];\n if (typeof item.name === \"string\") return [item.name];\n return [];\n });\n } catch {\n return [];\n }\n}\n\nfunction formatCommandFailure(\n command: string,\n args: readonly string[],\n result: PluginCommandResult,\n): string {\n const detail = [result.stderr.trim(), result.stdout.trim()].find((value) => value.length > 0);\n if (result.errorCode === \"ENOENT\") {\n return `Command '${command}' is not available on PATH.`;\n }\n\n return `${command} ${args.join(\" \")} failed${result.exitCode >= 0 ? ` with exit code ${result.exitCode}` : \"\"}${detail ? `: ${detail}` : \".\"}`;\n}\n\nasync function defaultCommandRunner(command: string, args: readonly string[]): Promise<PluginCommandResult> {\n return await new Promise((resolve) => {\n const child = spawn(command, [...args], {\n env: process.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n\n child.stdout.on(\"data\", (chunk) => {\n stdout += chunk.toString();\n });\n child.stderr.on(\"data\", (chunk) => {\n stderr += chunk.toString();\n });\n\n child.on(\"error\", (error) => {\n const errorCode = typeof error === \"object\" && error && \"code\" in error\n ? String(error.code)\n : undefined;\n resolve({\n exitCode: -1,\n stdout,\n stderr,\n ...(errorCode ? { errorCode } : {}),\n });\n });\n\n child.on(\"close\", (code) => {\n resolve({\n exitCode: code ?? -1,\n stdout,\n stderr,\n });\n });\n });\n}\n\nfunction resolveCommandRunner(runner?: PluginCommandRunner): PluginCommandRunner {\n return runner ?? defaultCommandRunner;\n}\n\nasync function commandExists(command: string, runner: PluginCommandRunner): Promise<boolean> {\n const result = await runner(command, [\"--help\"]);\n return result.errorCode !== \"ENOENT\" && result.exitCode !== 127;\n}\n\nasync function getClaudeInstallState(runner: PluginCommandRunner): Promise<{ available: boolean; installed: boolean }> {\n const available = detectSurface(\"claude\").detected || await commandExists(\"claude\", runner);\n if (!available) {\n return { available: false, installed: false };\n }\n\n const result = await runner(\"claude\", [\"plugin\", \"list\", \"--json\"]);\n if (result.exitCode !== 0) {\n return { available: true, installed: false };\n }\n\n return {\n available: true,\n installed: extractClaudePluginNames(result.stdout).includes(ORGX_CLAUDE_PLUGIN_NAME),\n };\n}\n\nasync function getOpenclawInstallState(runner: PluginCommandRunner): Promise<{ available: boolean; installed: boolean }> {\n const available = detectSurface(\"openclaw\").detected || await commandExists(\"openclaw\", runner);\n if (!available) {\n return { available: false, installed: false };\n }\n\n const result = await runner(\"openclaw\", [\"plugins\", \"list\", \"--json\"]);\n if (result.exitCode !== 0) {\n return { available: true, installed: false };\n }\n\n return {\n available: true,\n installed: extractOpenclawPluginIds(result.stdout).includes(ORGX_OPENCLAW_PLUGIN_ID),\n };\n}\n\nfunction cursorPluginManifestPath(paths: OrgxPluginPaths): string {\n return join(paths.cursorPluginDir, \".cursor-plugin\", \"plugin.json\");\n}\n\nfunction cursorPluginMcpPath(paths: OrgxPluginPaths): string {\n return join(paths.cursorPluginDir, \".mcp.json\");\n}\n\nfunction isCursorPluginInstalled(paths: OrgxPluginPaths): boolean {\n return existsSync(cursorPluginManifestPath(paths)) && existsSync(cursorPluginMcpPath(paths));\n}\n\n/**\n * Distinguishes companion-plugin bundle (skills, hooks, rules in ~/.cursor/plugins/local/cursor-plugin)\n * from user-level ~/.cursor/mcp.json wiring only.\n */\nexport interface CursorToolingState {\n /** Managed bundle from `wizard plugins add cursor` (or equivalent). */\n pluginBundleInstalled: boolean;\n /** `orgx-openclaw` MCP entry in user ~/.cursor/mcp.json. */\n mcpLocalOpenclaw: boolean;\n /** Hosted `orgx` → mcp.useorgx.com in user ~/.cursor/mcp.json. */\n mcpHostedOrgx: boolean;\n}\n\nexport function getCursorToolingState(\n options: { paths?: Partial<OrgxPluginPaths>; mcpPath?: string } = {},\n): CursorToolingState {\n const paths = resolvePluginPaths(options.paths);\n const mcpFile: string = options.mcpPath ?? CURSOR_MCP_PATH ?? join(CURSOR_DIR, \"mcp.json\");\n const mcpText = readTextIfExists(mcpFile);\n const inspection = inspectCursorMcpConfig(mcpText);\n return {\n pluginBundleInstalled: isCursorPluginInstalled(paths),\n mcpLocalOpenclaw: inspection.localConfigured === true,\n mcpHostedOrgx: inspection.hostedConfigured === true,\n };\n}\n\nfunction isCursorPluginAvailable(paths: OrgxPluginPaths): boolean {\n return detectSurface(\"cursor\").detected ||\n existsSync(paths.cursorPluginDir) ||\n existsSync(dirname(paths.cursorPluginDir)) ||\n readTextIfExists(paths.cursorRulePath) !== null;\n}\n\nfunction buildCursorStatus(paths: OrgxPluginPaths): OrgxPluginStatus {\n const existingRules = readTextIfExists(paths.cursorRulePath);\n const available = isCursorPluginAvailable(paths);\n const installed = isCursorPluginInstalled(paths);\n\n if (installed) {\n return {\n target: \"cursor\",\n available: true,\n installed: true,\n message: \"Cursor OrgX plugin bundle is installed.\",\n };\n }\n\n if (existingRules === CURSOR_RULES_CONTENT) {\n return {\n target: \"cursor\",\n available: true,\n installed: false,\n message: \"Legacy Cursor OrgX rules are installed; run plugins add cursor to install the full plugin bundle.\",\n };\n }\n\n if (existingRules !== null) {\n return {\n target: \"cursor\",\n available: true,\n installed: false,\n message: \"Cursor rules file exists, but the OrgX plugin bundle is missing.\",\n };\n }\n\n return {\n target: \"cursor\",\n available,\n installed: false,\n message: available\n ? \"Cursor is available and ready for OrgX plugin install.\"\n : \"Cursor was not detected.\",\n };\n}\n\nasync function buildClaudeStatus(paths: OrgxPluginPaths, runner: PluginCommandRunner): Promise<OrgxPluginStatus> {\n const state = await getClaudeInstallState(runner);\n if (state.installed) {\n return {\n target: \"claude\",\n available: true,\n installed: true,\n message: \"Claude Code plugin is installed.\",\n };\n }\n\n if (!state.available) {\n return {\n target: \"claude\",\n available: false,\n installed: false,\n message: \"Claude Code was not detected.\",\n };\n }\n\n const marketplaceExists = existsSync(paths.claudeMarketplaceManifestPath);\n return {\n target: \"claude\",\n available: true,\n installed: false,\n message: marketplaceExists\n ? \"Claude marketplace wrapper exists, but the plugin is not installed.\"\n : \"Claude Code is available and ready for plugin install.\",\n };\n}\n\nfunction buildCodexStatus(paths: OrgxPluginPaths, runner: PluginCommandRunner): Promise<OrgxPluginStatus> {\n return (async () => {\n const available = detectSurface(\"codex\").detected || await commandExists(\"codex\", runner);\n const pluginExists = existsSync(paths.codexPluginDir);\n const marketplaceExists = codexMarketplaceHasOrgxEntry(paths.codexMarketplacePath);\n const installed = pluginExists && marketplaceExists;\n\n if (installed) {\n return {\n target: \"codex\",\n available: true,\n installed: true,\n message: \"Codex plugin files and marketplace entry are present.\",\n };\n }\n\n if (!available) {\n return {\n target: \"codex\",\n available: false,\n installed: false,\n message: \"Codex was not detected.\",\n };\n }\n\n if (pluginExists && !marketplaceExists) {\n return {\n target: \"codex\",\n available: true,\n installed: false,\n message: \"Codex plugin files exist, but the marketplace entry is missing.\",\n };\n }\n\n if (!pluginExists && marketplaceExists) {\n return {\n target: \"codex\",\n available: true,\n installed: false,\n message: \"Codex marketplace entry exists, but plugin files are missing.\",\n };\n }\n\n return {\n target: \"codex\",\n available: true,\n installed: false,\n message: \"Codex is available and ready for plugin install.\",\n };\n })();\n}\n\nasync function buildOpenclawStatus(runner: PluginCommandRunner): Promise<OrgxPluginStatus> {\n const state = await getOpenclawInstallState(runner);\n if (state.installed) {\n return {\n target: \"openclaw\",\n available: true,\n installed: true,\n message: \"OpenClaw plugin is installed.\",\n };\n }\n\n return {\n target: \"openclaw\",\n available: state.available,\n installed: false,\n message: state.available\n ? \"OpenClaw is available and ready for plugin install.\"\n : \"OpenClaw was not detected.\",\n };\n}\n\nasync function resolveOpenclawTarball(fetchImpl: typeof fetch): Promise<{ tarballUrl: string; version: string }> {\n const response = await fetchImpl(\n `${NPM_REGISTRY_BASE_URL}/${encodeURIComponent(ORGX_OPENCLAW_PLUGIN_PACKAGE_NAME)}`,\n {\n headers: {\n Accept: \"application/json\",\n },\n signal: AbortSignal.timeout(10_000),\n },\n );\n\n if (!response.ok) {\n throw new Error(\n `npm registry returned HTTP ${response.status} while resolving ${ORGX_OPENCLAW_PLUGIN_PACKAGE_NAME}.`,\n );\n }\n\n const data = await response.json() as {\n \"dist-tags\"?: Record<string, string>;\n versions?: Record<string, { dist?: { tarball?: string } }>;\n };\n const latestVersion = data[\"dist-tags\"]?.latest;\n const tarballUrl = latestVersion ? data.versions?.[latestVersion]?.dist?.tarball : undefined;\n\n if (!latestVersion || !tarballUrl) {\n throw new Error(`Could not resolve a tarball URL for ${ORGX_OPENCLAW_PLUGIN_PACKAGE_NAME}.`);\n }\n\n return {\n tarballUrl,\n version: latestVersion,\n };\n}\n\nasync function installCursorPlugin(\n paths: OrgxPluginPaths,\n fetchImpl: typeof fetch,\n): Promise<OrgxPluginMutation> {\n if (!isCursorPluginAvailable(paths)) {\n return {\n target: \"cursor\",\n changed: false,\n message: \"Cursor is not available on this machine.\",\n };\n }\n\n const syncResult = await syncManagedRepoTree(CURSOR_PLUGIN_SYNC_SPEC, paths.cursorPluginDir, fetchImpl);\n return {\n target: \"cursor\",\n changed: syncResult.changed,\n message: syncResult.changed\n ? `Synced ${syncResult.fileCount} Cursor plugin files into ${paths.cursorPluginDir}. Reload Cursor to finish loading the plugin.`\n : \"Cursor plugin bundle is already installed and up to date.\",\n };\n}\n\nasync function installClaudePlugin(\n paths: OrgxPluginPaths,\n fetchImpl: typeof fetch,\n runner: PluginCommandRunner,\n): Promise<OrgxPluginMutation> {\n const state = await getClaudeInstallState(runner);\n if (!state.available) {\n return {\n target: \"claude\",\n changed: false,\n message: \"Claude Code is not available on this machine.\",\n };\n }\n\n const syncResult = await syncManagedRepoTree(CLAUDE_PLUGIN_SYNC_SPEC, paths.claudePluginDir, fetchImpl);\n const manifestChanged = writeJsonIfChanged(\n paths.claudeMarketplaceManifestPath,\n buildClaudeMarketplaceManifest(),\n );\n\n const marketplaceAdd = await runner(\"claude\", [\"plugin\", \"marketplace\", \"add\", paths.claudeMarketplaceDir]);\n if (marketplaceAdd.exitCode !== 0) {\n throw new Error(formatCommandFailure(\"claude\", [\"plugin\", \"marketplace\", \"add\", paths.claudeMarketplaceDir], marketplaceAdd));\n }\n\n let installedChanged = false;\n if (!state.installed) {\n const install = await runner(\"claude\", [\n \"plugin\",\n \"install\",\n `${ORGX_CLAUDE_PLUGIN_NAME}@${ORGX_CLAUDE_MARKETPLACE_NAME}`,\n \"--scope\",\n \"user\",\n ]);\n if (install.exitCode !== 0) {\n throw new Error(\n formatCommandFailure(\n \"claude\",\n [\n \"plugin\",\n \"install\",\n `${ORGX_CLAUDE_PLUGIN_NAME}@${ORGX_CLAUDE_MARKETPLACE_NAME}`,\n \"--scope\",\n \"user\",\n ],\n install,\n ),\n );\n }\n installedChanged = true;\n }\n\n const changed = syncResult.changed || manifestChanged || installedChanged;\n return {\n target: \"claude\",\n changed,\n message: changed\n ? `Synced ${syncResult.fileCount} Claude plugin files and ensured the plugin is installed.`\n : \"Claude Code plugin is already installed and up to date.\",\n };\n}\n\nasync function installCodexPlugin(\n paths: OrgxPluginPaths,\n fetchImpl: typeof fetch,\n runner: PluginCommandRunner,\n): Promise<OrgxPluginMutation> {\n const available = detectSurface(\"codex\").detected || await commandExists(\"codex\", runner);\n if (!available) {\n return {\n target: \"codex\",\n changed: false,\n message: \"Codex is not available on this machine.\",\n };\n }\n\n const syncResult = await syncManagedRepoTree(CODEX_PLUGIN_SYNC_SPEC, paths.codexPluginDir, fetchImpl);\n const marketplaceChanged = upsertCodexMarketplaceEntry(paths.codexMarketplacePath);\n const changed = syncResult.changed || marketplaceChanged;\n\n return {\n target: \"codex\",\n changed,\n message: changed\n ? `Synced ${syncResult.fileCount} Codex plugin files and updated the marketplace entry.`\n : \"Codex plugin files and marketplace entry already match the managed OrgX plugin.\",\n };\n}\n\nasync function installOpenclawPlugin(\n fetchImpl: typeof fetch,\n runner: PluginCommandRunner,\n): Promise<OrgxPluginMutation> {\n const state = await getOpenclawInstallState(runner);\n if (!state.available) {\n return {\n target: \"openclaw\",\n changed: false,\n message: \"OpenClaw is not available on this machine.\",\n };\n }\n if (state.installed) {\n return {\n target: \"openclaw\",\n changed: false,\n message: \"OpenClaw plugin is already installed.\",\n };\n }\n\n const { tarballUrl, version } = await resolveOpenclawTarball(fetchImpl);\n const tarballBytes = await fetchRemoteBytes(tarballUrl, fetchImpl);\n const tempRoot = mkdtempSync(join(tmpdir(), \"orgx-wizard-openclaw-\"));\n const archivePath = join(tempRoot, `orgx-openclaw-plugin-${version}.tgz`);\n\n try {\n writeFileSync(archivePath, tarballBytes);\n const install = await runner(\"openclaw\", [\"plugins\", \"install\", archivePath]);\n if (install.exitCode !== 0) {\n throw new Error(\n formatCommandFailure(\"openclaw\", [\"plugins\", \"install\", archivePath], install),\n );\n }\n } finally {\n rmSync(tempRoot, { force: true, recursive: true });\n }\n\n return {\n target: \"openclaw\",\n changed: true,\n message: `Installed OpenClaw plugin ${ORGX_OPENCLAW_PLUGIN_ID} from ${ORGX_OPENCLAW_PLUGIN_PACKAGE_NAME}@${version}.`,\n };\n}\n\nfunction uninstallCursorPlugin(paths: OrgxPluginPaths): OrgxPluginMutation {\n const existingRules = readTextIfExists(paths.cursorRulePath);\n const removedPluginDir = removePathIfExists(paths.cursorPluginDir);\n const removedLegacyRules = existingRules === CURSOR_RULES_CONTENT\n ? deleteFileIfExists(paths.cursorRulePath)\n : false;\n const changed = removedPluginDir || removedLegacyRules;\n return {\n target: \"cursor\",\n changed,\n message: changed\n ? existingRules !== null && existingRules !== CURSOR_RULES_CONTENT\n ? \"Removed the managed Cursor OrgX plugin bundle. Existing Cursor rules differ from managed OrgX rules, so they were left in place.\"\n : \"Removed the managed Cursor OrgX plugin bundle and legacy managed Cursor rules.\"\n : existingRules !== null && existingRules !== CURSOR_RULES_CONTENT\n ? \"Cursor plugin was not installed. Existing Cursor rules differ from managed OrgX rules, so they were left in place.\"\n : \"Cursor plugin was not installed.\",\n };\n}\n\nasync function uninstallClaudePlugin(\n paths: OrgxPluginPaths,\n runner: PluginCommandRunner,\n): Promise<OrgxPluginMutation> {\n const state = await getClaudeInstallState(runner);\n let changed = false;\n\n if (state.available && state.installed) {\n const uninstall = await runner(\"claude\", [\n \"plugin\",\n \"uninstall\",\n ORGX_CLAUDE_PLUGIN_NAME,\n \"--scope\",\n \"user\",\n ]);\n if (uninstall.exitCode !== 0) {\n throw new Error(\n formatCommandFailure(\n \"claude\",\n [\"plugin\", \"uninstall\", ORGX_CLAUDE_PLUGIN_NAME, \"--scope\", \"user\"],\n uninstall,\n ),\n );\n }\n changed = true;\n }\n\n if (state.available) {\n const removeMarketplace = await runner(\"claude\", [\"plugin\", \"marketplace\", \"remove\", ORGX_CLAUDE_MARKETPLACE_NAME]);\n if (removeMarketplace.exitCode === 0) {\n changed = true;\n }\n }\n\n changed = removePathIfExists(paths.claudeMarketplaceDir) || changed;\n\n return {\n target: \"claude\",\n changed,\n message: changed\n ? \"Removed the managed Claude Code plugin and marketplace wrapper.\"\n : \"Claude Code plugin was not installed.\",\n };\n}\n\nasync function uninstallCodexPlugin(paths: OrgxPluginPaths): Promise<OrgxPluginMutation> {\n const removedPluginDir = removePathIfExists(paths.codexPluginDir);\n const removedMarketplaceEntry = removeCodexMarketplaceEntry(paths.codexMarketplacePath);\n const changed = removedPluginDir || removedMarketplaceEntry;\n\n return {\n target: \"codex\",\n changed,\n message: changed\n ? \"Removed the managed Codex plugin files and marketplace entry.\"\n : \"Codex plugin was not installed.\",\n };\n}\n\nasync function uninstallOpenclawPlugin(runner: PluginCommandRunner): Promise<OrgxPluginMutation> {\n const state = await getOpenclawInstallState(runner);\n if (!state.available || !state.installed) {\n return {\n target: \"openclaw\",\n changed: false,\n message: \"OpenClaw plugin was not installed.\",\n };\n }\n\n const uninstall = await runner(\"openclaw\", [\"plugins\", \"uninstall\", ORGX_OPENCLAW_PLUGIN_ID, \"--force\"]);\n if (uninstall.exitCode !== 0) {\n throw new Error(\n formatCommandFailure(\n \"openclaw\",\n [\"plugins\", \"uninstall\", ORGX_OPENCLAW_PLUGIN_ID, \"--force\"],\n uninstall,\n ),\n );\n }\n\n return {\n target: \"openclaw\",\n changed: true,\n message: \"Removed the managed OpenClaw plugin.\",\n };\n}\n\nexport function resolvePluginTargets(requested: readonly string[] = []): OrgxPluginTarget[] {\n if (requested.length === 0 || requested.includes(\"all\")) {\n return [...DEFAULT_ORGX_PLUGIN_TARGETS];\n }\n\n const seen = new Set<OrgxPluginTarget>();\n const normalized: OrgxPluginTarget[] = [];\n\n for (const rawTarget of requested) {\n const target = rawTarget.trim().toLowerCase();\n if (target === \"\" || target === \"all\") continue;\n if (!DEFAULT_ORGX_PLUGIN_TARGETS.includes(target as OrgxPluginTarget)) {\n throw new Error(\n `Unknown plugin target '${rawTarget}'. Supported targets: ${DEFAULT_ORGX_PLUGIN_TARGETS.join(\", \")}.`,\n );\n }\n\n const nextTarget = target as OrgxPluginTarget;\n if (seen.has(nextTarget)) continue;\n seen.add(nextTarget);\n normalized.push(nextTarget);\n }\n\n return normalized;\n}\n\nexport async function listOrgxPluginStatuses(\n options: ListOrgxPluginStatusesOptions = {},\n): Promise<OrgxPluginStatus[]> {\n const paths = resolvePluginPaths(options.paths);\n const runner = resolveCommandRunner(options.commandRunner);\n\n return await Promise.all([\n buildCursorStatus(paths),\n buildClaudeStatus(paths, runner),\n buildCodexStatus(paths, runner),\n buildOpenclawStatus(runner),\n ]);\n}\n\nexport async function installOrgxPlugins(\n options: InstallOrgxPluginsOptions = {},\n): Promise<OrgxPluginMutationReport> {\n const targets = resolvePluginTargets(options.targets ?? []);\n const fetchImpl = options.fetchImpl ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new Error(\"Global fetch is unavailable in this runtime.\");\n }\n\n const paths = resolvePluginPaths(options.paths);\n const runner = resolveCommandRunner(options.commandRunner);\n const results: OrgxPluginMutation[] = [];\n\n for (const target of targets) {\n switch (target) {\n case \"cursor\":\n results.push(await installCursorPlugin(paths, fetchImpl));\n break;\n case \"claude\":\n results.push(await installClaudePlugin(paths, fetchImpl, runner));\n break;\n case \"codex\":\n results.push(await installCodexPlugin(paths, fetchImpl, runner));\n break;\n case \"openclaw\":\n results.push(await installOpenclawPlugin(fetchImpl, runner));\n break;\n }\n }\n\n return { results };\n}\n\nexport async function uninstallOrgxPlugins(\n options: UninstallOrgxPluginsOptions = {},\n): Promise<OrgxPluginMutationReport> {\n const targets = resolvePluginTargets(options.targets ?? []);\n const paths = resolvePluginPaths(options.paths);\n const runner = resolveCommandRunner(options.commandRunner);\n const results: OrgxPluginMutation[] = [];\n\n for (const target of targets) {\n switch (target) {\n case \"cursor\":\n results.push(uninstallCursorPlugin(paths));\n break;\n case \"claude\":\n results.push(await uninstallClaudePlugin(paths, runner));\n break;\n case \"codex\":\n results.push(await uninstallCodexPlugin(paths));\n break;\n case \"openclaw\":\n results.push(await uninstallOpenclawPlugin(runner));\n break;\n }\n }\n\n return { results };\n}\n\nexport function countPluginReportChanges(report: OrgxPluginMutationReport): number {\n return report.results.filter((result) => result.changed).length;\n}\n","import * as TOML from \"@iarna/toml\";\n\nimport {\n ORGX_HOSTED_MCP_KEY,\n ORGX_HOSTED_MCP_URL,\n ORGX_LOCAL_MCP_KEY,\n} from \"../constants.js\";\nimport { isRecord, parseJsonObject, readObject } from \"../lib/fs.js\";\n\ntype JsonObject = Record<string, unknown>;\n\nexport interface McpConfigInspection {\n configured: boolean;\n hostedConfigured?: boolean;\n localConfigured?: boolean;\n details: string[];\n}\n\nfunction cloneConfigCollection(config: JsonObject, key: string): JsonObject {\n return { ...readObject(config[key]) };\n}\n\nfunction removeLegacyScopedMcpServers(servers: JsonObject): boolean {\n const scopedPrefix = `${ORGX_LOCAL_MCP_KEY}-`;\n let updated = false;\n\n for (const key of Object.keys(servers)) {\n if (key === ORGX_LOCAL_MCP_KEY) continue;\n if (!key.startsWith(scopedPrefix)) continue;\n delete servers[key];\n updated = true;\n }\n\n return updated;\n}\n\nfunction stringifyJsonConfig(config: JsonObject): string {\n return `${JSON.stringify(config, null, 2)}\\n`;\n}\n\nfunction clearStdioFields(entry: JsonObject): JsonObject {\n const next = { ...entry };\n delete next.command;\n delete next.args;\n delete next.env;\n return next;\n}\n\nfunction matchHttpEntry(value: unknown, url: string): boolean {\n if (!isRecord(value)) return false;\n return value.type === \"http\" && value.url === url;\n}\n\nfunction matchUrlEntry(value: unknown, url: string): boolean {\n if (!isRecord(value)) return false;\n return value.url === url;\n}\n\nexport function patchClaudeMcpConfig(\n input: string | null,\n localMcpUrl?: string,\n): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n const existingOrgx = readObject(servers[ORGX_HOSTED_MCP_KEY]);\n const existingLocal = readObject(servers[ORGX_LOCAL_MCP_KEY]);\n const hostedUrl = typeof existingOrgx.url === \"string\" ? existingOrgx.url : \"\";\n const hostedType = typeof existingOrgx.type === \"string\" ? existingOrgx.type : \"\";\n const shouldSetHostedOrgx =\n !isRecord(servers[ORGX_HOSTED_MCP_KEY]) ||\n (hostedUrl === localMcpUrl && hostedType === \"http\");\n\n if (shouldSetHostedOrgx) {\n servers[ORGX_HOSTED_MCP_KEY] = {\n ...existingOrgx,\n type: \"http\",\n url: ORGX_HOSTED_MCP_URL,\n description:\n typeof existingOrgx.description === \"string\" &&\n existingOrgx.description.trim().length > 0\n ? existingOrgx.description\n : \"OrgX cloud MCP (OAuth)\",\n };\n }\n\n if (localMcpUrl) {\n servers[ORGX_LOCAL_MCP_KEY] = {\n ...existingLocal,\n type: \"http\",\n url: localMcpUrl,\n description:\n typeof existingLocal.description === \"string\" &&\n existingLocal.description.trim().length > 0\n ? existingLocal.description\n : \"OrgX platform via local OpenClaw plugin (no OAuth)\",\n };\n }\n\n removeLegacyScopedMcpServers(servers);\n\n return stringifyJsonConfig({\n ...current,\n mcpServers: servers,\n });\n}\n\nexport function removeClaudeMcpConfig(\n input: string | null,\n): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n\n if (isRecord(servers[ORGX_LOCAL_MCP_KEY])) {\n delete servers[ORGX_LOCAL_MCP_KEY];\n }\n\n if (matchHttpEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL)) {\n delete servers[ORGX_HOSTED_MCP_KEY];\n }\n\n removeLegacyScopedMcpServers(servers);\n\n return stringifyJsonConfig({\n ...current,\n mcpServers: servers,\n });\n}\n\nexport function inspectClaudeMcpConfig(input: string | null): McpConfigInspection {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n const local = readObject(servers[ORGX_LOCAL_MCP_KEY]);\n const hostedConfigured = matchHttpEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL);\n const localConfigured =\n local.type === \"http\" &&\n typeof local.url === \"string\";\n const localUrl = localConfigured ? String(local.url) : \"missing\";\n\n return {\n configured: hostedConfigured && localConfigured,\n hostedConfigured,\n localConfigured,\n details: [\n `hosted orgx: ${hostedConfigured ? \"ok\" : \"missing\"}`,\n `local orgx-openclaw: ${localUrl}`,\n ],\n };\n}\n\nexport function patchCursorMcpConfig(\n input: string | null,\n localMcpUrl: string,\n): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n const existingLocal = readObject(servers[ORGX_LOCAL_MCP_KEY]);\n\n servers[ORGX_LOCAL_MCP_KEY] = {\n ...clearStdioFields(existingLocal),\n url: localMcpUrl,\n };\n\n removeLegacyScopedMcpServers(servers);\n\n return stringifyJsonConfig({\n ...current,\n mcpServers: servers,\n });\n}\n\nexport function removeCursorMcpConfig(\n input: string | null,\n): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n\n if (isRecord(servers[ORGX_LOCAL_MCP_KEY])) {\n delete servers[ORGX_LOCAL_MCP_KEY];\n }\n\n removeLegacyScopedMcpServers(servers);\n\n return stringifyJsonConfig({\n ...current,\n mcpServers: servers,\n });\n}\n\nexport function inspectCursorMcpConfig(input: string | null): McpConfigInspection {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n const local = readObject(servers[ORGX_LOCAL_MCP_KEY]);\n const localConfigured = typeof local.url === \"string\";\n const localUrl = localConfigured ? String(local.url) : \"missing\";\n const hostedConfigured = matchHttpEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL);\n\n return {\n // Back-compat: \"configured\" on Cursor historically meant the OpenClaw bridge line only.\n configured: localConfigured,\n hostedConfigured,\n localConfigured,\n details: [\n `hosted orgx: ${hostedConfigured ? \"ok\" : \"missing\"}`,\n `local orgx-openclaw: ${localUrl}`,\n ],\n };\n}\n\nexport function patchVscodeMcpConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"servers\");\n const existingHosted = readObject(servers[ORGX_HOSTED_MCP_KEY]);\n\n servers[ORGX_HOSTED_MCP_KEY] = {\n ...clearStdioFields(existingHosted),\n type: \"http\",\n url: ORGX_HOSTED_MCP_URL,\n };\n\n return stringifyJsonConfig({\n ...current,\n servers,\n });\n}\n\nexport function removeVscodeMcpConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"servers\");\n\n if (matchHttpEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL)) {\n delete servers[ORGX_HOSTED_MCP_KEY];\n }\n\n return stringifyJsonConfig({\n ...current,\n servers,\n });\n}\n\nexport function inspectVscodeMcpConfig(input: string | null): McpConfigInspection {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"servers\");\n const hostedConfigured = matchHttpEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL);\n\n return {\n configured: hostedConfigured,\n hostedConfigured,\n details: [`hosted orgx: ${hostedConfigured ? \"ok\" : \"missing\"}`],\n };\n}\n\nfunction matchServerUrlEntry(value: unknown, url: string): boolean {\n if (!isRecord(value)) return false;\n return value.serverUrl === url || value.url === url;\n}\n\nexport function patchWindsurfMcpConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n const existingHosted = readObject(servers[ORGX_HOSTED_MCP_KEY]);\n const nextEntry = clearStdioFields(existingHosted);\n\n delete nextEntry.url;\n servers[ORGX_HOSTED_MCP_KEY] = {\n ...nextEntry,\n serverUrl: ORGX_HOSTED_MCP_URL,\n };\n\n return stringifyJsonConfig({\n ...current,\n mcpServers: servers,\n });\n}\n\nexport function removeWindsurfMcpConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n\n if (matchServerUrlEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL)) {\n delete servers[ORGX_HOSTED_MCP_KEY];\n }\n\n return stringifyJsonConfig({\n ...current,\n mcpServers: servers,\n });\n}\n\nexport function inspectWindsurfMcpConfig(input: string | null): McpConfigInspection {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n const hostedConfigured = matchServerUrlEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL);\n\n return {\n configured: hostedConfigured,\n hostedConfigured,\n details: [`hosted orgx: ${hostedConfigured ? \"ok\" : \"missing\"}`],\n };\n}\n\nexport function patchZedMcpConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"context_servers\");\n const existingHosted = readObject(servers[ORGX_HOSTED_MCP_KEY]);\n\n servers[ORGX_HOSTED_MCP_KEY] = {\n ...clearStdioFields(existingHosted),\n url: ORGX_HOSTED_MCP_URL,\n };\n\n return stringifyJsonConfig({\n ...current,\n context_servers: servers,\n });\n}\n\nexport function removeZedMcpConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"context_servers\");\n\n if (matchUrlEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL)) {\n delete servers[ORGX_HOSTED_MCP_KEY];\n }\n\n return stringifyJsonConfig({\n ...current,\n context_servers: servers,\n });\n}\n\nexport function inspectZedMcpConfig(input: string | null): McpConfigInspection {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"context_servers\");\n const hostedConfigured = matchUrlEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL);\n\n return {\n configured: hostedConfigured,\n hostedConfigured,\n details: [`hosted orgx: ${hostedConfigured ? \"ok\" : \"missing\"}`],\n };\n}\n\nfunction parseTomlDocument(input: string | null): JsonObject {\n if (!input) return {};\n\n try {\n const parsed = TOML.parse(input) as unknown;\n return isRecord(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nfunction stringifyTomlDocument(document: JsonObject): string {\n const rendered = TOML.stringify(document as TOML.JsonMap);\n return rendered.endsWith(\"\\n\") ? rendered : `${rendered}\\n`;\n}\n\nfunction upsertCodexEntry(servers: JsonObject, key: string, url: string): void {\n const current = readObject(servers[key]);\n const next: JsonObject = {\n ...current,\n url,\n };\n delete next.command;\n delete next.args;\n delete next.startup_timeout_sec;\n servers[key] = next;\n}\n\nfunction removeLegacyCodexEntries(servers: JsonObject): boolean {\n const scopedPrefix = `${ORGX_LOCAL_MCP_KEY}-`;\n let updated = false;\n\n for (const key of Object.keys(servers)) {\n if (key === ORGX_LOCAL_MCP_KEY) continue;\n if (!key.startsWith(scopedPrefix)) continue;\n delete servers[key];\n updated = true;\n }\n\n return updated;\n}\n\nexport function patchCodexConfigToml(\n input: string | null,\n localMcpUrl?: string,\n): string {\n const current = parseTomlDocument(input);\n const servers = readObject(current.mcp_servers);\n\n upsertCodexEntry(servers, ORGX_HOSTED_MCP_KEY, ORGX_HOSTED_MCP_URL);\n if (localMcpUrl) {\n upsertCodexEntry(servers, ORGX_LOCAL_MCP_KEY, localMcpUrl);\n }\n removeLegacyCodexEntries(servers);\n\n current.mcp_servers = servers;\n return stringifyTomlDocument(current);\n}\n\nexport function removeCodexConfigToml(\n input: string | null,\n): string {\n const current = parseTomlDocument(input);\n const servers = readObject(current.mcp_servers);\n const hosted = readObject(servers[ORGX_HOSTED_MCP_KEY]);\n\n if (isRecord(servers[ORGX_LOCAL_MCP_KEY])) {\n delete servers[ORGX_LOCAL_MCP_KEY];\n }\n\n if (hosted.url === ORGX_HOSTED_MCP_URL) {\n delete servers[ORGX_HOSTED_MCP_KEY];\n }\n\n removeLegacyCodexEntries(servers);\n current.mcp_servers = servers;\n\n return stringifyTomlDocument(current);\n}\n\nexport function inspectCodexConfigToml(input: string | null): McpConfigInspection {\n const current = parseTomlDocument(input);\n const servers = readObject(current.mcp_servers);\n const hosted = readObject(servers[ORGX_HOSTED_MCP_KEY]);\n const local = readObject(servers[ORGX_LOCAL_MCP_KEY]);\n const hostedConfigured = hosted.url === ORGX_HOSTED_MCP_URL;\n const localConfigured = typeof local.url === \"string\";\n\n return {\n configured: hostedConfigured && localConfigured,\n hostedConfigured,\n localConfigured,\n details: [\n `hosted orgx: ${hostedConfigured ? \"ok\" : \"missing\"}`,\n `local orgx-openclaw: ${localConfigured ? local.url : \"missing\"}`,\n ],\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nimport {\n CHATGPT_APP_PATHS,\n CLAUDE_INSTALL_PATHS,\n CLAUDE_MCP_PATHS,\n CODEX_CONFIG_PATHS,\n CODEX_INSTALL_PATHS,\n CURSOR_INSTALL_PATHS,\n CURSOR_MCP_PATHS,\n OPENCLAW_CONFIG_PATHS,\n OPENCLAW_INSTALL_PATHS,\n VSCODE_INSTALL_PATHS,\n VSCODE_MCP_PATHS,\n WINDSURF_INSTALL_PATHS,\n WINDSURF_MCP_PATHS,\n ZED_INSTALL_PATHS,\n ZED_SETTINGS_PATHS,\n} from \"../constants.js\";\nimport type { SurfaceName } from \"./names.js\";\n\nexport interface SurfaceLocator {\n configPaths: string[];\n installPaths: string[];\n}\n\nexport interface SurfaceDetection {\n detected: boolean;\n preferredPath?: string;\n existingPath?: string;\n evidence: string[];\n}\n\ntype Exists = (path: string) => boolean;\n\nconst SURFACE_LOCATORS: Record<SurfaceName, SurfaceLocator> = {\n claude: {\n configPaths: CLAUDE_MCP_PATHS,\n installPaths: CLAUDE_INSTALL_PATHS,\n },\n cursor: {\n configPaths: CURSOR_MCP_PATHS,\n installPaths: CURSOR_INSTALL_PATHS,\n },\n codex: {\n configPaths: CODEX_CONFIG_PATHS,\n installPaths: CODEX_INSTALL_PATHS,\n },\n openclaw: {\n configPaths: OPENCLAW_CONFIG_PATHS,\n installPaths: OPENCLAW_INSTALL_PATHS,\n },\n vscode: {\n configPaths: VSCODE_MCP_PATHS,\n installPaths: VSCODE_INSTALL_PATHS,\n },\n windsurf: {\n configPaths: WINDSURF_MCP_PATHS,\n installPaths: WINDSURF_INSTALL_PATHS,\n },\n zed: {\n configPaths: ZED_SETTINGS_PATHS,\n installPaths: ZED_INSTALL_PATHS,\n },\n chatgpt: {\n configPaths: [],\n installPaths: CHATGPT_APP_PATHS,\n },\n};\n\nfunction firstExistingPath(paths: string[], exists: Exists): string | undefined {\n return paths.find((path) => exists(path));\n}\n\nfunction buildFallbackInstallPaths(configPaths: string[]): string[] {\n return [...new Set(configPaths.map((path) => dirname(path)))];\n}\n\nexport function getSurfaceLocator(name: SurfaceName): SurfaceLocator {\n return SURFACE_LOCATORS[name];\n}\n\nexport function detectSurface(name: SurfaceName, exists: Exists = existsSync): SurfaceDetection {\n const locator = getSurfaceLocator(name);\n const existingConfigPath = firstExistingPath(locator.configPaths, exists);\n const preferredPath = locator.configPaths[0] ?? locator.installPaths[0];\n const installCandidates = [\n ...locator.installPaths,\n ...buildFallbackInstallPaths(locator.configPaths),\n ];\n const existingInstallPath = firstExistingPath(installCandidates, exists);\n const existingPath = existingConfigPath ?? existingInstallPath;\n const evidence: string[] = [];\n\n if (existingConfigPath) {\n evidence.push(`config found: ${existingConfigPath}`);\n }\n if (existingInstallPath && existingInstallPath !== existingConfigPath) {\n evidence.push(`install marker found: ${existingInstallPath}`);\n }\n if (!existingConfigPath && !existingInstallPath) {\n evidence.push(\"no candidate paths found on disk\");\n }\n\n const detection: SurfaceDetection = {\n detected: Boolean(existingConfigPath || existingInstallPath),\n evidence,\n };\n\n if (preferredPath) {\n detection.preferredPath = preferredPath;\n }\n if (existingPath) {\n detection.existingPath = existingPath;\n }\n\n return detection;\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, readdirSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\n\nimport {\n CLAUDE_ORGX_SKILL_PATH,\n CLAUDE_SKILLS_DIR,\n CURSOR_ORGX_RULE_PATH,\n ORGX_SKILL_EXTENSIONS_DIR,\n ORGX_WIZARD_STATE_PATH,\n} from \"../constants.js\";\nimport { readTextIfExists, writeTextFile } from \"./fs.js\";\nimport type { OrgxPluginTarget } from \"./plugins.js\";\nimport { readWizardState, updateWizardState, type WizardSkillFileRecord } from \"./wizard-state.js\";\n\nexport const DEFAULT_ORGX_SKILL_PACKS = [\n \"morning-briefing\",\n \"initiative-kickoff\",\n \"bulk-create\",\n \"nightly-recap\",\n] as const;\nexport const PLUGIN_MANAGED_SKILL_TARGETS = [\"claude\", \"codex\"] as const;\n\n// Directory entries in the useorgx/skills repo root that are not skill packs.\nconst EXCLUDED_PACK_DIRS = new Set([\".github\", \"scripts\"]);\n\nconst ORGX_SKILLS_OWNER = \"useorgx\";\nconst ORGX_SKILLS_REPO = \"skills\";\nconst ORGX_SKILLS_REF = \"main\";\nconst SKILL_EXTENSION_SCOPES = [\"user\", \"workspace\", \"project\"] as const;\nconst COMPOSED_SKILL_MARKER = \"ORGX SKILL COMPOSED v1\";\nconst EXTENSION_FRONTMATTER_DELIMITER = \"---\";\n\nexport interface ManagedFileWrite {\n label: string;\n path: string;\n changed: boolean;\n reason?: string;\n skipped?: boolean;\n sourceUrl?: string;\n}\n\nexport interface InstalledSkillPack {\n name: string;\n files: ManagedFileWrite[];\n}\n\nexport interface SkillsInstallReport {\n writes: ManagedFileWrite[];\n packs: InstalledSkillPack[];\n notes: string[];\n extensions: SkillExtension[];\n}\n\nexport interface InstallOrgxSkillsOptions {\n skillNames?: readonly string[];\n claudeSkillsDir?: string;\n claudeOrgxSkillPath?: string;\n cursorRulePath?: string;\n force?: boolean;\n fetchImpl?: typeof fetch;\n pluginTargets?: readonly string[];\n ref?: string;\n skillExtensionsDir?: string;\n statePath?: string;\n}\n\nexport interface OrgxSkillsInstallPlan {\n installClaudeSkillBootstrap: boolean;\n installClaudeSkillPacks: boolean;\n notes: string[];\n pluginManagedTargets: OrgxPluginTarget[];\n}\n\ninterface GithubDirectoryEntry {\n name: string;\n path: string;\n type: \"file\" | \"dir\";\n download_url: string | null;\n}\n\ninterface RemoteSkillFile {\n path: string;\n sourceUrl: string;\n}\n\nexport type SkillExtensionScope = \"user\" | \"workspace\" | \"project\";\n\nexport interface SkillExtension {\n content: string;\n enabled: boolean;\n id: string;\n path: string;\n scope: SkillExtensionScope;\n skillId: string;\n title: string;\n}\n\nexport interface AddSkillExtensionOptions {\n content?: string;\n extensionsDir?: string;\n overwrite?: boolean;\n scope?: SkillExtensionScope;\n skillId: string;\n title?: string;\n}\n\nexport interface SkillExtensionWrite {\n changed: boolean;\n created: boolean;\n extension: SkillExtension;\n path: string;\n}\n\nexport interface ListSkillExtensionsOptions {\n extensionsDir?: string;\n}\n\nexport interface SkillStatusReport {\n extensions: SkillExtension[];\n trackedFiles: WizardSkillFileRecord[];\n}\n\nexport interface SkillStatusOptions {\n extensionsDir?: string;\n statePath?: string;\n}\n\nexport const CURSOR_RULES_CONTENT = `# OrgX Rules\n\n- Prefer \\`workspace_id\\` on OrgX tool calls. \\`command_center_id\\` is a deprecated alias and should only be used for backwards compatibility. If both are present, they must match.\n- Treat \\`entity_action\\` with \\`force: true\\` as an escape hatch. It bypasses hierarchy and proof checks, so only use it when the user explicitly wants that behavior and say why.\n- Treat \\`scaffold_initiative continue_on_error\\` as best-effort creation. Use it only when partial scaffolds are acceptable, and follow up on any failed children.\n- Preserve \\`_context\\` when widget or app-rendering flows depend on client, conversation, session, or user metadata. Do not strip or rename it.\n- Prefer \\`list_entities\\` for pending approvals and state inspection before reaching for legacy aliases.\n- Keep hosted OrgX MCP calls distinct from local OpenClaw/plugin surfaces before mutating config or entity state.\n- Artifact proof must use durable sources: GitHub PR/commit/blob permalinks, published/public URLs, or absolute file paths / \\`file://...\\`.\n- Never use OrgX wrapper pages like \\`/live/...\\`, \\`/artifacts/...\\`, or \\`/console/...\\` as proof links. \\`preview_markdown\\` is supplemental, not proof.\n`;\n\nconst CLAUDE_ORGX_SKILL_CONTENT = `---\nname: orgx\ndescription: Use when working against the hosted OrgX MCP server for workspace-scoped planning, entity mutations, progress reporting, and decision handling.\nversion: 1.0.0\nuser-invocable: true\ntags:\n - orchestration\n - productivity\n - workspace\n---\n\n# OrgX Hosted MCP\n\nUse this skill when Claude is connected to the hosted OrgX MCP server at \\`https://mcp.useorgx.com/mcp\\`.\n\nThis skill is for the hosted OrgX tool surface, not the local OpenClaw plugin. Keep those surfaces distinct before mutating config or entity state.\n\n## Operating Rules\n\n- Prefer \\`workspace_id\\` on OrgX tools. \\`command_center_id\\` is a deprecated alias kept for compatibility.\n- Treat \\`entity_action\\` with \\`force: true\\` as a deliberate override only. It bypasses hierarchy and proof-chain checks.\n- Treat \\`scaffold_initiative continue_on_error\\` as best-effort scaffolding. Use it only when partial creation is acceptable and inspect failures afterward.\n- Preserve \\`_context\\` when widget or app rendering depends on client, conversation, session, or user metadata.\n- Prefer \\`list_entities\\` over older aliases when you need pending decisions, blockers, or entity state.\n- Artifact proof must use durable sources: GitHub PR/commit/blob permalinks, published/public URLs, or absolute file paths / \\`file://...\\`.\n- Never use OrgX wrapper pages like \\`/live/...\\`, \\`/artifacts/...\\`, or \\`/console/...\\` as proof links. \\`preview_markdown\\` is supporting context only.\n\n## Suggested Skill Packs\n\nInstall and use these packs alongside this base skill:\n\n- \\`morning-briefing\\`\n- \\`initiative-kickoff\\`\n- \\`bulk-create\\`\n- \\`nightly-recap\\`\n\n## Suggested Workflow\n\n1. Inspect state with \\`mcp__orgx__list_entities\\`, \\`mcp__orgx__get_initiative_pulse\\`, or the relevant workspace-scoped read tool.\n2. Mutate state with the narrowest tool that matches the task.\n3. When you need a hard override, explain why before using \\`force: true\\`.\n4. When you scaffold, decide up front whether \\`continue_on_error\\` is acceptable.\n5. Carry \\`_context\\` through any widget-producing flows so the UI can render and resume correctly.\n`;\n\nfunction sha256(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction normalizeSkillId(value: string): string {\n const normalized = value.trim().toLowerCase();\n if (!/^[a-z0-9][a-z0-9._-]*$/.test(normalized)) {\n throw new Error(\n \"Skill id must start with a letter or number and only contain letters, numbers, '.', '_' or '-'.\",\n );\n }\n return normalized;\n}\n\nfunction normalizeSkillExtensionScope(value: string | undefined): SkillExtensionScope {\n const normalized = (value ?? \"user\").trim().toLowerCase();\n if (!SKILL_EXTENSION_SCOPES.includes(normalized as SkillExtensionScope)) {\n throw new Error(\"Skill extension scope must be one of: user, workspace, project.\");\n }\n return normalized as SkillExtensionScope;\n}\n\nfunction defaultExtensionTitle(skillId: string, scope: SkillExtensionScope): string {\n const prefix = scope === \"user\" ? \"Personal\" : scope === \"workspace\" ? \"Workspace\" : \"Project\";\n return `${prefix} ${skillId} behavior`;\n}\n\nfunction extensionFilePath(\n skillId: string,\n scope: SkillExtensionScope,\n extensionsDir = ORGX_SKILL_EXTENSIONS_DIR,\n): string {\n return join(extensionsDir, `${scope}.${skillId}.md`);\n}\n\nfunction extensionTemplate(input: {\n skillId: string;\n scope: SkillExtensionScope;\n title: string;\n content?: string;\n}): string {\n const body = input.content?.trim()\n ? input.content.trim()\n : [\n `# ${input.title}`,\n \"\",\n \"- Add your custom behavior here.\",\n \"- These instructions are appended after the OrgX-managed core skill when the wizard syncs skills.\",\n ].join(\"\\n\");\n\n return [\n EXTENSION_FRONTMATTER_DELIMITER,\n `skill: ${input.skillId}`,\n `scope: ${input.scope}`,\n \"enabled: true\",\n `title: ${input.title}`,\n EXTENSION_FRONTMATTER_DELIMITER,\n \"\",\n body,\n \"\",\n ].join(\"\\n\");\n}\n\nfunction parseFrontmatter(content: string): {\n body: string;\n data: Record<string, string>;\n} {\n if (!content.startsWith(`${EXTENSION_FRONTMATTER_DELIMITER}\\n`)) {\n return { body: content, data: {} };\n }\n\n const closeIndex = content.indexOf(`\\n${EXTENSION_FRONTMATTER_DELIMITER}\\n`, 4);\n if (closeIndex === -1) {\n return { body: content, data: {} };\n }\n\n const raw = content.slice(4, closeIndex);\n const body = content.slice(closeIndex + 5);\n const data: Record<string, string> = {};\n for (const line of raw.split(\"\\n\")) {\n const index = line.indexOf(\":\");\n if (index === -1) {\n continue;\n }\n const key = line.slice(0, index).trim();\n const value = line.slice(index + 1).trim();\n if (key) {\n data[key] = value;\n }\n }\n\n return { body, data };\n}\n\nfunction serializeFrontmatter(data: Record<string, string>, body: string): string {\n return [\n EXTENSION_FRONTMATTER_DELIMITER,\n ...Object.entries(data).map(([key, value]) => `${key}: ${value}`),\n EXTENSION_FRONTMATTER_DELIMITER,\n \"\",\n body.trimEnd(),\n \"\",\n ].join(\"\\n\");\n}\n\nfunction parseSkillExtension(path: string, content: string): SkillExtension | null {\n const fallbackId = basename(path, \".md\");\n const fallbackParts = fallbackId.split(\".\");\n const fallbackScope = normalizeSkillExtensionScope(\n SKILL_EXTENSION_SCOPES.includes(fallbackParts[0] as SkillExtensionScope)\n ? fallbackParts.shift()\n : \"user\",\n );\n const fallbackSkillId = normalizeSkillId(fallbackParts.join(\".\") || fallbackId);\n const parsed = parseFrontmatter(content);\n const skillId = normalizeSkillId(parsed.data.skill || fallbackSkillId);\n const scope = normalizeSkillExtensionScope(parsed.data.scope || fallbackScope);\n const title = parsed.data.title?.trim() || defaultExtensionTitle(skillId, scope);\n\n return {\n content: parsed.body.trim(),\n enabled: parsed.data.enabled?.trim().toLowerCase() !== \"false\",\n id: `${scope}.${skillId}`,\n path,\n scope,\n skillId,\n title,\n };\n}\n\nexport function listSkillExtensions(\n options: ListSkillExtensionsOptions = {},\n): SkillExtension[] {\n const extensionsDir = options.extensionsDir ?? ORGX_SKILL_EXTENSIONS_DIR;\n if (!existsSync(extensionsDir)) {\n return [];\n }\n\n return readdirSync(extensionsDir, { withFileTypes: true })\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".md\"))\n .map((entry) => {\n const path = join(extensionsDir, entry.name);\n const content = readTextIfExists(path);\n return content === null ? null : parseSkillExtension(path, content);\n })\n .filter((entry): entry is SkillExtension => Boolean(entry))\n .sort((left, right) => left.id.localeCompare(right.id));\n}\n\nexport function addSkillExtension(\n options: AddSkillExtensionOptions,\n): SkillExtensionWrite {\n const skillId = normalizeSkillId(options.skillId);\n const scope = normalizeSkillExtensionScope(options.scope);\n const path = extensionFilePath(skillId, scope, options.extensionsDir);\n const title = options.title?.trim() || defaultExtensionTitle(skillId, scope);\n const existing = readTextIfExists(path);\n\n if (existing !== null && options.overwrite !== true) {\n const extension = parseSkillExtension(path, existing);\n if (!extension) {\n throw new Error(`Could not parse existing skill extension at ${path}.`);\n }\n\n return {\n changed: false,\n created: false,\n extension,\n path,\n };\n }\n\n const nextContent = extensionTemplate({\n scope,\n skillId,\n title,\n ...(options.content !== undefined ? { content: options.content } : {}),\n });\n writeTextFile(path, nextContent);\n const extension = parseSkillExtension(path, nextContent);\n if (!extension) {\n throw new Error(`Could not parse newly written skill extension at ${path}.`);\n }\n\n return {\n changed: existing !== nextContent,\n created: existing === null,\n extension,\n path,\n };\n}\n\nexport function setSkillExtensionEnabled(input: {\n enabled: boolean;\n extensionsDir?: string;\n scope?: SkillExtensionScope;\n skillId: string;\n}): SkillExtensionWrite {\n const skillId = normalizeSkillId(input.skillId);\n const scope = normalizeSkillExtensionScope(input.scope);\n const path = extensionFilePath(skillId, scope, input.extensionsDir);\n const existing = readTextIfExists(path);\n if (existing === null) {\n if (!input.enabled) {\n throw new Error(`No ${scope} extension exists for ${skillId}.`);\n }\n\n return addSkillExtension({\n scope,\n skillId,\n ...(input.extensionsDir !== undefined ? { extensionsDir: input.extensionsDir } : {}),\n });\n }\n\n const parsed = parseFrontmatter(existing);\n const data = {\n skill: parsed.data.skill || skillId,\n scope: parsed.data.scope || scope,\n enabled: input.enabled ? \"true\" : \"false\",\n title: parsed.data.title || defaultExtensionTitle(skillId, scope),\n };\n const nextContent = serializeFrontmatter(data, parsed.body);\n if (nextContent !== existing) {\n writeTextFile(path, nextContent);\n }\n const extension = parseSkillExtension(path, nextContent);\n if (!extension) {\n throw new Error(`Could not parse skill extension at ${path}.`);\n }\n\n return {\n changed: nextContent !== existing,\n created: false,\n extension,\n path,\n };\n}\n\nfunction composeSkillContent(\n skillId: string,\n coreContent: string,\n extensions: readonly SkillExtension[],\n): string {\n const enabled = extensions.filter((extension) => extension.enabled && extension.skillId === skillId);\n if (enabled.length === 0) {\n return coreContent;\n }\n\n const extensionBlocks = enabled.map((extension) => [\n `<!-- extension: ${extension.id} -->`,\n extension.content.trim(),\n ].join(\"\\n\"));\n\n return [\n `<!-- ${COMPOSED_SKILL_MARKER}`,\n `skill: ${skillId}`,\n `core-sha256: ${sha256(coreContent)}`,\n \"generated: true\",\n `edit-with: orgx-wizard skills extensions edit ${skillId}`,\n \"-->\",\n `<!-- ORGX CORE BEGIN ${skillId} -->`,\n coreContent.trimEnd(),\n `<!-- ORGX CORE END ${skillId} -->`,\n \"\",\n \"<!-- ORGX USER EXTENSIONS BEGIN -->\",\n ...extensionBlocks,\n \"<!-- ORGX USER EXTENSIONS END -->\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction encodeRepoPath(value: string): string {\n return value\n .split(\"/\")\n .filter((segment) => segment.length > 0)\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n}\n\nfunction buildContentsUrl(path: string, ref: string): string {\n const encodedPath = encodeRepoPath(path);\n return `https://api.github.com/repos/${ORGX_SKILLS_OWNER}/${ORGX_SKILLS_REPO}/contents/${encodedPath}?ref=${encodeURIComponent(ref)}`;\n}\n\nfunction resolveGitHubError(status: number, path: string): string {\n if (status === 404) {\n return `OrgX skill pack '${path}' was not found in ${ORGX_SKILLS_OWNER}/${ORGX_SKILLS_REPO}.`;\n }\n\n return `GitHub returned HTTP ${status} while loading '${path}' from ${ORGX_SKILLS_OWNER}/${ORGX_SKILLS_REPO}.`;\n}\n\nasync function readResponseText(response: Response): Promise<string> {\n return response.text();\n}\n\nasync function fetchDirectoryEntries(\n path: string,\n fetchImpl: typeof fetch,\n ref: string,\n): Promise<GithubDirectoryEntry[]> {\n const response = await fetchImpl(buildContentsUrl(path, ref), {\n headers: {\n Accept: \"application/vnd.github+json\",\n },\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n throw new Error(resolveGitHubError(response.status, path));\n }\n\n const data = await response.json();\n if (!Array.isArray(data)) {\n throw new Error(`Expected '${path}' to be a directory in ${ORGX_SKILLS_OWNER}/${ORGX_SKILLS_REPO}.`);\n }\n\n return data\n .filter((entry): entry is GithubDirectoryEntry => {\n if (!entry || typeof entry !== \"object\") return false;\n return entry.type === \"file\" || entry.type === \"dir\";\n })\n .sort((left, right) => left.path.localeCompare(right.path));\n}\n\nasync function listRemoteSkillFiles(\n path: string,\n fetchImpl: typeof fetch,\n ref: string,\n): Promise<RemoteSkillFile[]> {\n const entries = await fetchDirectoryEntries(path, fetchImpl, ref);\n const files: RemoteSkillFile[] = [];\n\n for (const entry of entries) {\n if (entry.type === \"dir\") {\n files.push(...await listRemoteSkillFiles(entry.path, fetchImpl, ref));\n continue;\n }\n\n if (!entry.download_url) {\n throw new Error(`GitHub did not provide a download URL for '${entry.path}'.`);\n }\n\n files.push({\n path: entry.path,\n sourceUrl: entry.download_url,\n });\n }\n\n return files;\n}\n\nasync function fetchRemoteText(sourceUrl: string, fetchImpl: typeof fetch): Promise<string> {\n const response = await fetchImpl(sourceUrl, {\n headers: {\n Accept: \"text/plain\",\n },\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n throw new Error(`GitHub returned HTTP ${response.status} while downloading ${sourceUrl}.`);\n }\n\n return readResponseText(response);\n}\n\nfunction getTrackedSkillFile(\n records: readonly WizardSkillFileRecord[],\n path: string,\n): WizardSkillFileRecord | undefined {\n return records.find((record) => record.path === path);\n}\n\nfunction writeManagedFile(\n path: string,\n content: string,\n label: string,\n sourceUrl?: string,\n tracking?: {\n coreContent?: string;\n force?: boolean;\n records: readonly WizardSkillFileRecord[];\n skillId: string;\n stagedRecords: Map<string, WizardSkillFileRecord>;\n },\n): ManagedFileWrite {\n const existing = readTextIfExists(path);\n const tracked = tracking ? getTrackedSkillFile(tracking.records, path) : undefined;\n if (\n tracking &&\n existing !== null &&\n tracked &&\n sha256(existing) !== tracked.contentSha256 &&\n tracking.force !== true\n ) {\n return {\n label,\n path,\n changed: false,\n skipped: true,\n reason: \"manual edits detected; move them into a skill extension or rerun with --force\",\n ...(sourceUrl ? { sourceUrl } : {}),\n };\n }\n\n const changed = existing !== content;\n\n if (changed) {\n writeTextFile(path, content);\n }\n\n if (tracking) {\n tracking.stagedRecords.set(path, {\n contentSha256: sha256(content),\n ...(tracking.coreContent ? { coreSha256: sha256(tracking.coreContent) } : {}),\n path,\n skillId: tracking.skillId,\n updatedAt: new Date().toISOString(),\n });\n }\n\n return {\n label,\n path,\n changed,\n ...(sourceUrl ? { sourceUrl } : {}),\n };\n}\n\nexport function resolveSkillPackNames(\n requested: readonly string[] = [],\n): string[] {\n if (requested.length === 0 || requested.includes(\"all\")) {\n return [...DEFAULT_ORGX_SKILL_PACKS];\n }\n\n const seen = new Set<string>();\n const normalized: string[] = [];\n\n for (const name of requested) {\n const next = name.trim();\n if (!next || seen.has(next)) {\n continue;\n }\n seen.add(next);\n normalized.push(next);\n }\n\n return normalized;\n}\n\nexport function resolvePluginManagedSkillTargets(\n requested: readonly string[] = [],\n): OrgxPluginTarget[] {\n const seen = new Set<OrgxPluginTarget>();\n const targets: OrgxPluginTarget[] = [];\n\n for (const rawTarget of requested) {\n const target = rawTarget.trim().toLowerCase() as OrgxPluginTarget;\n if (!PLUGIN_MANAGED_SKILL_TARGETS.includes(target as typeof PLUGIN_MANAGED_SKILL_TARGETS[number])) {\n continue;\n }\n if (seen.has(target)) {\n continue;\n }\n\n seen.add(target);\n targets.push(target);\n }\n\n return targets;\n}\n\nexport function planOrgxSkillsInstall(\n pluginTargets: readonly string[] = [],\n): OrgxSkillsInstallPlan {\n const pluginManagedTargets = resolvePluginManagedSkillTargets(pluginTargets);\n const managesClaudeSkills = pluginManagedTargets.includes(\"claude\");\n const notes: string[] = [];\n\n if (managesClaudeSkills) {\n notes.push(\n \"Claude Code plugin is installed, so the wizard skipped overlapping standalone Claude OrgX skill files and Claude skill-pack sync.\",\n );\n }\n if (pluginManagedTargets.includes(\"codex\")) {\n notes.push(\n \"Codex companion plugin bundles its own OrgX skills, so `wizard skills add` only manages standalone editor assets outside Codex.\",\n );\n }\n\n return {\n installClaudeSkillBootstrap: !managesClaudeSkills,\n installClaudeSkillPacks: !managesClaudeSkills,\n notes,\n pluginManagedTargets,\n };\n}\n\nasync function fetchAvailablePackNames(\n fetchImpl: typeof fetch,\n ref: string,\n): Promise<string[]> {\n const entries = await fetchDirectoryEntries(\"\", fetchImpl, ref);\n return entries\n .filter((e) => e.type === \"dir\" && !EXCLUDED_PACK_DIRS.has(e.name))\n .map((e) => e.name);\n}\n\nasync function installSkillPack(\n skillName: string,\n claudeSkillsDir: string,\n fetchImpl: typeof fetch,\n ref: string,\n tracking: {\n extensions: readonly SkillExtension[];\n force?: boolean;\n records: readonly WizardSkillFileRecord[];\n stagedRecords: Map<string, WizardSkillFileRecord>;\n },\n): Promise<InstalledSkillPack> {\n const rootPath = skillName;\n const files = await listRemoteSkillFiles(rootPath, fetchImpl, ref);\n const writes: ManagedFileWrite[] = [];\n\n for (const file of files) {\n const coreContent = await fetchRemoteText(file.sourceUrl, fetchImpl);\n const relativePath = file.path.slice(`${rootPath}/`.length);\n const content = relativePath === \"SKILL.md\"\n ? composeSkillContent(skillName, coreContent, tracking.extensions)\n : coreContent;\n writes.push(\n writeManagedFile(\n join(claudeSkillsDir, skillName, relativePath),\n content,\n `${skillName}/${relativePath}`,\n file.sourceUrl,\n {\n coreContent,\n records: tracking.records,\n skillId: skillName,\n stagedRecords: tracking.stagedRecords,\n ...(tracking.force !== undefined ? { force: tracking.force } : {}),\n },\n ),\n );\n }\n\n return {\n name: skillName,\n files: writes,\n };\n}\n\nexport async function installOrgxSkills(\n options: InstallOrgxSkillsOptions = {},\n): Promise<SkillsInstallReport> {\n const fetchImpl = options.fetchImpl ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new Error(\"Global fetch is unavailable in this runtime.\");\n }\n\n const ref = options.ref ?? ORGX_SKILLS_REF;\n const claudeSkillsDir = options.claudeSkillsDir ?? CLAUDE_SKILLS_DIR;\n const claudeOrgxSkillPath = options.claudeOrgxSkillPath ?? CLAUDE_ORGX_SKILL_PATH;\n const cursorRulePath = options.cursorRulePath ?? CURSOR_ORGX_RULE_PATH;\n const statePath = options.statePath ?? ORGX_WIZARD_STATE_PATH;\n const extensions = listSkillExtensions(\n options.skillExtensionsDir !== undefined ? { extensionsDir: options.skillExtensionsDir } : {},\n );\n const enabledExtensions = extensions.filter((extension) => extension.enabled);\n const trackedRecords = readWizardState(statePath)?.skillFiles?.files ?? [];\n const stagedRecords = new Map<string, WizardSkillFileRecord>();\n const plan = planOrgxSkillsInstall(options.pluginTargets ?? []);\n const requestedNames = options.skillNames ?? [];\n let skillNames: string[];\n if (requestedNames.length === 0 || requestedNames.includes(\"all\")) {\n try {\n skillNames = await fetchAvailablePackNames(fetchImpl, ref);\n } catch {\n skillNames = [...DEFAULT_ORGX_SKILL_PACKS];\n }\n } else {\n skillNames = resolveSkillPackNames(requestedNames);\n }\n\n const writes: ManagedFileWrite[] = [\n writeManagedFile(\n cursorRulePath,\n composeSkillContent(\"cursor-rules\", CURSOR_RULES_CONTENT, extensions),\n \"cursor-rules\",\n undefined,\n {\n coreContent: CURSOR_RULES_CONTENT,\n records: trackedRecords,\n skillId: \"cursor-rules\",\n stagedRecords,\n ...(options.force !== undefined ? { force: options.force } : {}),\n },\n ),\n ];\n if (plan.installClaudeSkillBootstrap) {\n writes.push(\n writeManagedFile(\n claudeOrgxSkillPath,\n composeSkillContent(\"orgx\", CLAUDE_ORGX_SKILL_CONTENT, extensions),\n \"claude-orgx-skill\",\n undefined,\n {\n coreContent: CLAUDE_ORGX_SKILL_CONTENT,\n records: trackedRecords,\n skillId: \"orgx\",\n stagedRecords,\n ...(options.force !== undefined ? { force: options.force } : {}),\n },\n ),\n );\n }\n\n const packs: InstalledSkillPack[] = [];\n if (plan.installClaudeSkillPacks) {\n for (const skillName of skillNames) {\n packs.push(await installSkillPack(skillName, claudeSkillsDir, fetchImpl, ref, {\n extensions,\n records: trackedRecords,\n stagedRecords,\n ...(options.force !== undefined ? { force: options.force } : {}),\n }));\n }\n }\n\n if (stagedRecords.size > 0) {\n updateWizardState((current) => {\n const previousFiles = current.skillFiles?.files ?? [];\n const nextFiles = new Map<string, WizardSkillFileRecord>();\n for (const record of previousFiles) {\n nextFiles.set(record.path, record);\n }\n for (const record of stagedRecords.values()) {\n nextFiles.set(record.path, record);\n }\n\n return {\n ...current,\n skillFiles: {\n files: [...nextFiles.values()].sort((left, right) => left.path.localeCompare(right.path)),\n updatedAt: new Date().toISOString(),\n },\n };\n }, statePath);\n }\n\n const notes = [...plan.notes];\n if (enabledExtensions.length > 0) {\n notes.push(\n `Applied ${enabledExtensions.length} enabled OrgX skill extension${enabledExtensions.length === 1 ? \"\" : \"s\"} while syncing skills/rules.`,\n );\n }\n if (\n writes.some((write) => write.skipped) ||\n packs.some((pack) => pack.files.some((file) => file.skipped))\n ) {\n notes.push(\"Some generated skill files were skipped because local manual edits were detected.\");\n }\n\n return {\n extensions,\n notes,\n writes,\n packs,\n };\n}\n\nexport function getSkillStatus(\n options: SkillStatusOptions = {},\n): SkillStatusReport {\n const state = readWizardState(options.statePath ?? ORGX_WIZARD_STATE_PATH);\n return {\n extensions: listSkillExtensions(\n options.extensionsDir !== undefined ? { extensionsDir: options.extensionsDir } : {},\n ),\n trackedFiles: state?.skillFiles?.files ?? [],\n };\n}\n","import {\n checkOrgxAuth,\n peekResolvedOrgxAuth,\n resolveOrgxAuth,\n type OrgxAuthHint,\n type OrgxAuthCheckResult,\n} from \"../lib/auth.js\";\nimport { checkOpenClawHealth, type OpenClawHealthCheck } from \"../lib/openclaw-health.js\";\nimport { checkHostedMcpHealth, type HostedMcpHealthCheck } from \"../lib/hosted-mcp-health.js\";\nimport {\n checkHostedMcpToolAccess,\n type HostedMcpToolCheck,\n} from \"../lib/hosted-mcp-tool-check.js\";\nimport { checkNpmRegistryHealth, type NpmRegistryCheck } from \"../lib/npm-registry-health.js\";\nimport {\n checkWorkspaceConnectivity,\n type WorkspaceConnectivityCheck,\n} from \"../lib/workspace-connectivity.js\";\nimport { getCursorToolingState } from \"../lib/plugins.js\";\nimport { readTextIfExists, writeTextFile } from \"../lib/fs.js\";\nimport { ORGX_HOSTED_MCP_URL } from \"../constants.js\";\nimport {\n inspectClaudeMcpConfig,\n inspectCodexConfigToml,\n inspectCursorMcpConfig,\n inspectVscodeMcpConfig,\n inspectWindsurfMcpConfig,\n inspectZedMcpConfig,\n patchClaudeMcpConfig,\n patchCodexConfigToml,\n patchCursorMcpConfig,\n patchVscodeMcpConfig,\n patchWindsurfMcpConfig,\n patchZedMcpConfig,\n removeClaudeMcpConfig,\n removeCodexConfigToml,\n removeCursorMcpConfig,\n removeVscodeMcpConfig,\n removeWindsurfMcpConfig,\n removeZedMcpConfig,\n} from \"./mcp-config.js\";\nimport {\n buildLocalMcpUrl,\n inspectOpenClawConfig,\n patchOpenClawConfig,\n removeOpenClawConfig,\n} from \"./openclaw-config.js\";\nimport {\n AUTOMATED_SURFACE_NAMES,\n MCP_SURFACE_NAMES,\n SURFACE_NAMES,\n type SurfaceMode,\n type SurfaceName,\n} from \"./names.js\";\nimport {\n detectSurface,\n getSurfaceLocator,\n type SurfaceDetection,\n} from \"./detection.js\";\n\nexport { SURFACE_NAMES } from \"./names.js\";\nexport type { SurfaceName } from \"./names.js\";\n\nexport interface SurfaceStatus {\n name: SurfaceName;\n mode: SurfaceMode;\n detected: boolean;\n configured: boolean;\n path?: string;\n details: string[];\n summary: string;\n /**\n * When `name` is \"cursor\", distinguishes MCP lines in `~/.cursor/mcp.json` from the\n * managed companion bundle under `~/.cursor/plugins/local/cursor-plugin`.\n */\n cursorIntegration?: {\n mcpLocalOpenclaw: boolean;\n mcpHostedOrgx: boolean;\n pluginBundleInstalled: boolean;\n };\n}\n\nexport interface SurfaceMutationResult {\n name: SurfaceName;\n changed: boolean;\n path?: string;\n message: string;\n}\n\ntype SurfaceSelection<T extends string> = T | \"all\" | readonly (T | \"all\")[];\n\ninterface OpenClawDependencyState {\n detected: boolean;\n configured: boolean;\n path?: string;\n url?: string;\n}\n\nconst AUTH_SETUP_HINT = \"orgx-wizard auth login\";\nconst AUTH_SET_KEY_HINT = \"orgx-wizard auth set-key\";\nconst DOCTOR_HINT = \"orgx-wizard doctor\";\n\nfunction getSurfaceMode(name: SurfaceName): SurfaceMode {\n return AUTOMATED_SURFACE_NAMES.includes(name as (typeof AUTOMATED_SURFACE_NAMES)[number])\n ? \"automated\"\n : \"manual\";\n}\n\nfunction getSurfacePath(name: SurfaceName): string | undefined {\n const detection = detectSurface(name);\n const locator = getSurfaceLocator(name);\n const existingPath = detection.existingPath;\n\n if (existingPath && locator.configPaths.includes(existingPath)) {\n return existingPath;\n }\n\n return locator.configPaths[0] ?? detection.preferredPath ?? existingPath;\n}\n\nfunction getOpenClawDependencyState(): OpenClawDependencyState {\n const detection = detectSurface(\"openclaw\");\n const path = detection.existingPath ?? detection.preferredPath;\n const raw = path ? readTextIfExists(path) : null;\n const inspection = inspectOpenClawConfig(raw);\n\n const result: OpenClawDependencyState = {\n detected: detection.detected,\n configured: inspection.configured,\n };\n\n if (path) {\n result.path = path;\n }\n\n if (detection.detected) {\n result.url = buildLocalMcpUrl(raw);\n }\n\n return result;\n}\n\nfunction automatedSurfaceStatus(\n name: Extract<\n SurfaceName,\n \"claude\" | \"cursor\" | \"codex\" | \"openclaw\" | \"vscode\" | \"windsurf\" | \"zed\"\n >,\n): SurfaceStatus {\n const detection = detectSurface(name);\n const path = detection.existingPath ?? detection.preferredPath;\n const openclaw = getOpenClawDependencyState();\n\n if (name === \"claude\") {\n const inspection = inspectClaudeMcpConfig(path ? readTextIfExists(path) : null);\n const configured = inspection.hostedConfigured === true &&\n (openclaw.detected ? inspection.localConfigured === true : true);\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured,\n ...(path ? { path } : {}),\n details: [\n ...inspection.details,\n ...(openclaw.detected\n ? [`OpenClaw bridge: ${openclaw.configured ? \"configured\" : \"detected but not configured\"}`]\n : [\"OpenClaw bridge: not detected; hosted OrgX is the only available route.\"]),\n ...detection.evidence,\n ],\n summary: configured\n ? openclaw.detected\n ? \"OrgX is connected in Claude with the local OpenClaw bridge.\"\n : \"OrgX cloud MCP is connected in Claude.\"\n : detection.detected\n ? openclaw.detected\n ? `Claude is missing either hosted OrgX or the local OpenClaw bridge (${openclaw.url ?? \"unknown\"}).`\n : \"Claude is missing the hosted OrgX MCP entry.\"\n : \"Claude config directory was not detected on disk.\",\n };\n }\n\n if (name === \"cursor\") {\n const inspection = inspectCursorMcpConfig(path ? readTextIfExists(path) : null);\n const tooling = getCursorToolingState();\n const configured = openclaw.detected && inspection.localConfigured === true;\n const mcpWired = tooling.mcpLocalOpenclaw || tooling.mcpHostedOrgx;\n const summary = (() => {\n if (!detection.detected) {\n return \"Cursor config directory was not detected on disk.\";\n }\n if (configured) {\n return tooling.pluginBundleInstalled\n ? \"OrgX is connected in Cursor through the local OpenClaw bridge; companion plugin bundle is installed.\"\n : \"OrgX is connected in Cursor through the local OpenClaw bridge; companion plugin bundle (skills, hooks, rules) is not installed.\";\n }\n if (mcpWired && !tooling.pluginBundleInstalled) {\n if (tooling.mcpHostedOrgx && !openclaw.detected) {\n return \"OrgX hosted MCP is present in Cursor mcp.json; install OpenClaw for the local bridge, or add the companion plugin bundle for the full pack.\";\n }\n return \"OrgX MCP is present in Cursor mcp.json, but the companion plugin bundle (skills, hooks, rules) is not installed.\";\n }\n if (detection.detected) {\n return openclaw.detected\n ? `Cursor is missing the local OrgX OpenClaw bridge (${openclaw.url ?? \"unknown\"}).`\n : \"Cursor is ready to wire, but OpenClaw must be installed first.\";\n }\n return \"Cursor config directory was not detected on disk.\";\n })();\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured,\n ...(path ? { path } : {}),\n cursorIntegration: tooling,\n details: [\n `companion plugin bundle: ${tooling.pluginBundleInstalled ? \"installed\" : \"not installed\"}`,\n ...inspection.details,\n ...(openclaw.detected\n ? [`OpenClaw bridge: ${openclaw.configured ? \"configured\" : \"detected but not configured\"}`]\n : [\"OpenClaw bridge: not detected; Cursor cannot use the local OrgX bridge yet.\"]),\n ...detection.evidence,\n ],\n summary,\n };\n }\n\n if (name === \"codex\") {\n const inspection = inspectCodexConfigToml(path ? readTextIfExists(path) : null);\n const configured = inspection.hostedConfigured === true &&\n (openclaw.detected ? inspection.localConfigured === true : true);\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured,\n ...(path ? { path } : {}),\n details: [\n ...inspection.details,\n ...(openclaw.detected\n ? [`OpenClaw bridge: ${openclaw.configured ? \"configured\" : \"detected but not configured\"}`]\n : [\"OpenClaw bridge: not detected; hosted OrgX is the only available route.\"]),\n ...detection.evidence,\n ],\n summary: configured\n ? openclaw.detected\n ? \"OrgX is connected in Codex with the local OpenClaw bridge.\"\n : \"OrgX cloud MCP is connected in Codex.\"\n : detection.detected\n ? openclaw.detected\n ? `Codex is missing either hosted OrgX or the local OpenClaw bridge (${openclaw.url ?? \"unknown\"}).`\n : \"Codex is missing the hosted OrgX MCP entry.\"\n : \"Codex config directory was not detected on disk.\",\n };\n }\n\n if (name === \"vscode\") {\n const inspection = inspectVscodeMcpConfig(path ? readTextIfExists(path) : null);\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured: inspection.hostedConfigured === true,\n ...(path ? { path } : {}),\n details: [...inspection.details, ...detection.evidence],\n summary: inspection.hostedConfigured\n ? \"OrgX cloud MCP is connected in VS Code.\"\n : detection.detected\n ? \"VS Code is missing the hosted OrgX MCP entry.\"\n : \"VS Code config directory was not detected on disk.\",\n };\n }\n\n if (name === \"windsurf\") {\n const inspection = inspectWindsurfMcpConfig(path ? readTextIfExists(path) : null);\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured: inspection.hostedConfigured === true,\n ...(path ? { path } : {}),\n details: [...inspection.details, ...detection.evidence],\n summary: inspection.hostedConfigured\n ? \"OrgX cloud MCP is connected in Windsurf.\"\n : detection.detected\n ? \"Windsurf is missing the hosted OrgX MCP entry.\"\n : \"Windsurf config directory was not detected on disk.\",\n };\n }\n\n if (name === \"zed\") {\n const inspection = inspectZedMcpConfig(path ? readTextIfExists(path) : null);\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured: inspection.hostedConfigured === true,\n ...(path ? { path } : {}),\n details: [...inspection.details, ...detection.evidence],\n summary: inspection.hostedConfigured\n ? \"OrgX cloud MCP is connected in Zed.\"\n : detection.detected\n ? \"Zed is missing the hosted OrgX MCP entry.\"\n : \"Zed config directory was not detected on disk.\",\n };\n }\n\n const inspection = inspectOpenClawConfig(path ? readTextIfExists(path) : null);\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured: inspection.configured,\n ...(path ? { path } : {}),\n details: [...inspection.details, ...detection.evidence],\n summary: inspection.configured\n ? `OpenClaw plugin entry ${inspection.pluginKey ?? \"missing\"} is configured.`\n : inspection.installed\n ? \"OpenClaw is installed but OrgX defaults have not been written.\"\n : detection.detected\n ? \"OpenClaw support files exist but no OrgX plugin entry was found.\"\n : \"OpenClaw is not installed or no support files were found.\",\n };\n}\n\nfunction formatAuthHintSource(authHint: OrgxAuthHint): string {\n switch (authHint.source) {\n case \"environment\":\n return \"env ORGX_API_KEY\";\n case \"wizard-store\":\n return \"wizard auth store\";\n case \"openclaw-config-file\":\n return \"openclaw config\";\n }\n}\n\nexport function buildChatgptManualStatus(\n detection: SurfaceDetection,\n authHint: OrgxAuthHint | null,\n): SurfaceStatus {\n const path = detection.existingPath ?? detection.preferredPath;\n\n const details = [...detection.evidence];\n if (authHint) {\n details.push(\n `OrgX auth ready via ${formatAuthHintSource(authHint)} (${authHint.keyPrefix})`,\n );\n details.push(`Hosted connector URL: ${ORGX_HOSTED_MCP_URL}`);\n details.push(\n \"Manual step: in ChatGPT desktop developer mode, add a custom connector pointing at the hosted OrgX MCP URL.\",\n );\n details.push(\n \"ChatGPT completes OAuth during connector setup; the wizard cannot preflight hosted MCP tools with an oxk_ API key.\",\n );\n details.push(\n \"After connecting ChatGPT, run `orgx-wizard doctor` to verify hosted MCP health from this machine.\",\n );\n } else {\n details.push(\n \"OrgX auth is not configured yet. Run `orgx-wizard auth login` or `orgx-wizard auth set-key` first.\",\n );\n details.push(\n \"After auth is configured, add a custom ChatGPT developer connector pointing at the hosted OrgX MCP URL.\",\n );\n }\n\n let summary: string;\n if (!authHint) {\n summary = detection.detected\n ? \"ChatGPT is installed, but OrgX auth is not configured yet.\"\n : \"ChatGPT support files were not found; configure OrgX auth first, then add the hosted connector manually.\";\n } else {\n summary = detection.detected\n ? \"ChatGPT is installed; finish the manual developer connector setup.\"\n : \"OrgX auth is ready, but ChatGPT desktop support files were not found on disk.\";\n }\n\n return {\n name: \"chatgpt\",\n mode: \"manual\",\n detected: detection.detected,\n configured: false,\n ...(path ? { path } : {}),\n details,\n summary,\n };\n}\n\nexport function buildChatgptAddResult(\n path: string | undefined,\n authHint: OrgxAuthHint | null,\n toolCheck?: HostedMcpToolCheck,\n): SurfaceMutationResult {\n if (!authHint) {\n return {\n name: \"chatgpt\",\n changed: false,\n ...(path ? { path } : {}),\n message:\n `Run \\`${AUTH_SETUP_HINT}\\` or \\`${AUTH_SET_KEY_HINT}\\` first, then add ${ORGX_HOSTED_MCP_URL} as a custom connector in ChatGPT developer mode.`,\n };\n }\n\n if (toolCheck && !toolCheck.ok && !toolCheck.skipped) {\n const failure = toolCheck?.error ?? \"hosted MCP verification did not complete.\";\n return {\n name: \"chatgpt\",\n changed: false,\n ...(path ? { path } : {}),\n message:\n `OrgX auth is configured via ${formatAuthHintSource(authHint)}, but hosted MCP verification failed (${failure}). Fix that first, then add ${ORGX_HOSTED_MCP_URL} in ChatGPT developer mode.`,\n };\n }\n\n return {\n name: \"chatgpt\",\n changed: false,\n ...(path ? { path } : {}),\n message:\n `OrgX auth is ready via ${formatAuthHintSource(authHint)}. Add ${ORGX_HOSTED_MCP_URL} as a custom connector in ChatGPT developer mode; ChatGPT will complete the OAuth flow there. Then run \\`${DOCTOR_HINT}\\` to verify hosted MCP health from this machine.`,\n };\n}\n\nexport function buildChatgptRemoveResult(path: string | undefined): SurfaceMutationResult {\n return {\n name: \"chatgpt\",\n changed: false,\n ...(path ? { path } : {}),\n message:\n \"Remove the custom OrgX connector from ChatGPT developer mode; the wizard does not manage ChatGPT config files directly.\",\n };\n}\n\nfunction manualSurfaceStatus(name: Extract<SurfaceName, \"chatgpt\">): SurfaceStatus {\n const detection = detectSurface(name);\n\n switch (name) {\n case \"chatgpt\":\n return buildChatgptManualStatus(detection, peekResolvedOrgxAuth());\n }\n}\n\nfunction getSurfaceStatus(name: SurfaceName): SurfaceStatus {\n if (AUTOMATED_SURFACE_NAMES.includes(name as (typeof AUTOMATED_SURFACE_NAMES)[number])) {\n return automatedSurfaceStatus(\n name as Extract<\n SurfaceName,\n \"claude\" | \"cursor\" | \"codex\" | \"openclaw\" | \"vscode\" | \"windsurf\" | \"zed\"\n >,\n );\n }\n\n return manualSurfaceStatus(name as Extract<SurfaceName, \"chatgpt\">);\n}\n\nexport function listSurfaceStatuses(): SurfaceStatus[] {\n return SURFACE_NAMES.map(getSurfaceStatus);\n}\n\nfunction resolveTargets<T extends string>(\n selection: SurfaceSelection<T>,\n allTargets: readonly T[],\n): T[] {\n const values = Array.isArray(selection) ? selection : [selection];\n\n if (values.includes(\"all\")) {\n return [...allTargets];\n }\n\n return [...new Set(values)] as T[];\n}\n\nexport function resolveSurfaceSelection(\n selection: SurfaceSelection<SurfaceName>,\n): SurfaceName[] {\n return resolveTargets(selection, SURFACE_NAMES);\n}\n\nexport function resolveMcpSurfaceSelection(\n selection: SurfaceSelection<(typeof MCP_SURFACE_NAMES)[number]>,\n): Array<(typeof MCP_SURFACE_NAMES)[number]> {\n return resolveTargets(selection, MCP_SURFACE_NAMES);\n}\n\nasync function addAutomatedSurface(name: SurfaceName): Promise<SurfaceMutationResult> {\n const path = getSurfacePath(name);\n const openclaw = getOpenClawDependencyState();\n\n if (!path) {\n return {\n name,\n changed: false,\n message: `${name} has no writable config path on this platform.`,\n };\n }\n\n switch (name) {\n case \"claude\": {\n const previous = readTextIfExists(path);\n const next = patchClaudeMcpConfig(previous, openclaw.url);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: openclaw.detected\n ? \"OrgX is connected in Claude with the local OpenClaw bridge.\"\n : \"OrgX cloud MCP is connected in Claude.\",\n };\n }\n case \"cursor\": {\n if (!openclaw.detected || !openclaw.url) {\n return {\n name,\n changed: false,\n path,\n message: \"Cursor needs OpenClaw installed before OrgX can be connected locally.\",\n };\n }\n const previous = readTextIfExists(path);\n const next = patchCursorMcpConfig(previous, openclaw.url);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX is connected in Cursor through the local OpenClaw bridge.\",\n };\n }\n case \"codex\": {\n const previous = readTextIfExists(path);\n const next = patchCodexConfigToml(previous, openclaw.url);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: openclaw.detected\n ? \"OrgX is connected in Codex with the local OpenClaw bridge.\"\n : \"OrgX cloud MCP is connected in Codex.\",\n };\n }\n case \"openclaw\": {\n const previous = readTextIfExists(path);\n const auth = await resolveOrgxAuth();\n const next = patchOpenClawConfig(previous, auth ?? {});\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: auth\n ? \"OpenClaw is configured as the local OrgX bridge with the resolved OrgX auth.\"\n : \"OpenClaw is configured as the local OrgX bridge.\",\n };\n }\n case \"vscode\": {\n const previous = readTextIfExists(path);\n if (inspectVscodeMcpConfig(previous).hostedConfigured) {\n return { name, changed: false, path, message: \"OrgX cloud MCP is connected in VS Code.\" };\n }\n const next = patchVscodeMcpConfig(previous);\n writeTextFile(path, next);\n return { name, changed: true, path, message: \"OrgX cloud MCP is connected in VS Code.\" };\n }\n case \"windsurf\": {\n const previous = readTextIfExists(path);\n if (inspectWindsurfMcpConfig(previous).hostedConfigured) {\n return { name, changed: false, path, message: \"OrgX cloud MCP is connected in Windsurf.\" };\n }\n const next = patchWindsurfMcpConfig(previous);\n writeTextFile(path, next);\n return { name, changed: true, path, message: \"OrgX cloud MCP is connected in Windsurf.\" };\n }\n case \"zed\": {\n const previous = readTextIfExists(path);\n if (inspectZedMcpConfig(previous).hostedConfigured) {\n return { name, changed: false, path, message: \"OrgX cloud MCP is connected in Zed.\" };\n }\n const next = patchZedMcpConfig(previous);\n writeTextFile(path, next);\n return { name, changed: true, path, message: \"OrgX cloud MCP is connected in Zed.\" };\n }\n case \"chatgpt\": {\n const authHint = peekResolvedOrgxAuth();\n if (!authHint) {\n return buildChatgptAddResult(path, null);\n }\n return buildChatgptAddResult(path, authHint);\n }\n default:\n return {\n name,\n changed: false,\n message: `${name} is not supported by the wizard.`,\n };\n }\n}\n\nfunction removeAutomatedSurface(name: SurfaceName): SurfaceMutationResult {\n const path = getSurfacePath(name);\n\n if (!path) {\n return {\n name,\n changed: false,\n message: `${name} has no writable config path on this platform.`,\n };\n }\n\n switch (name) {\n case \"claude\": {\n const previous = readTextIfExists(path);\n const next = removeClaudeMcpConfig(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX connection was removed from Claude.\",\n };\n }\n case \"cursor\": {\n const previous = readTextIfExists(path);\n const next = removeCursorMcpConfig(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX connection was removed from Cursor.\",\n };\n }\n case \"codex\": {\n const previous = readTextIfExists(path);\n const next = removeCodexConfigToml(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX connection was removed from Codex.\",\n };\n }\n case \"openclaw\": {\n const previous = readTextIfExists(path);\n const next = removeOpenClawConfig(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OpenClaw OrgX defaults were removed.\",\n };\n }\n case \"vscode\": {\n const previous = readTextIfExists(path);\n const next = removeVscodeMcpConfig(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX connection was removed from VS Code.\",\n };\n }\n case \"windsurf\": {\n const previous = readTextIfExists(path);\n const next = removeWindsurfMcpConfig(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX connection was removed from Windsurf.\",\n };\n }\n case \"zed\": {\n const previous = readTextIfExists(path);\n const next = removeZedMcpConfig(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX connection was removed from Zed.\",\n };\n }\n case \"chatgpt\":\n return buildChatgptRemoveResult(path);\n default:\n return {\n name,\n changed: false,\n message: `${name} is not supported by the wizard.`,\n };\n }\n}\n\nexport async function addSurface(\n selection: SurfaceSelection<SurfaceName>,\n): Promise<SurfaceMutationResult[]> {\n const targets = resolveSurfaceSelection(selection);\n const results: SurfaceMutationResult[] = [];\n\n for (const surface of targets) {\n results.push(await addAutomatedSurface(surface));\n }\n\n return results;\n}\n\nexport function removeSurface(selection: SurfaceSelection<SurfaceName>): SurfaceMutationResult[] {\n const targets = resolveSurfaceSelection(selection);\n return targets.map((surface) => removeAutomatedSurface(surface));\n}\n\nexport async function addMcpSurface(\n selection: SurfaceSelection<(typeof MCP_SURFACE_NAMES)[number]>,\n): Promise<SurfaceMutationResult[]> {\n const targets = resolveMcpSurfaceSelection(selection);\n const results: SurfaceMutationResult[] = [];\n\n for (const surface of targets) {\n results.push(await addAutomatedSurface(surface));\n }\n\n return results;\n}\n\nexport function removeMcpSurface(\n selection: SurfaceSelection<(typeof MCP_SURFACE_NAMES)[number]>,\n): SurfaceMutationResult[] {\n const targets = resolveMcpSurfaceSelection(selection);\n return targets.map((surface) => removeAutomatedSurface(surface));\n}\n\nexport async function setupDetectedSurfaces(): Promise<SurfaceMutationResult[]> {\n const targets = AUTOMATED_SURFACE_NAMES.filter((name) => getSurfaceStatus(name).detected);\n\n targets.sort((left, right) => {\n if (left === \"openclaw\") return -1;\n if (right === \"openclaw\") return 1;\n return 0;\n });\n\n const results: SurfaceMutationResult[] = [];\n\n for (const name of targets) {\n results.push(await addAutomatedSurface(name));\n }\n\n return results;\n}\n\nexport interface DoctorReport {\n surfaces: SurfaceStatus[];\n auth: OrgxAuthCheckResult;\n hostedMcp: HostedMcpHealthCheck;\n hostedMcpTool: HostedMcpToolCheck;\n npmRegistry: NpmRegistryCheck;\n workspace: WorkspaceConnectivityCheck;\n openclaw: OpenClawHealthCheck;\n}\n\nexport interface DoctorAssessmentIssue {\n level: \"error\" | \"warning\";\n title: string;\n suggestion: string;\n}\n\nexport interface DoctorAssessment {\n ok: boolean;\n issues: DoctorAssessmentIssue[];\n}\n\nfunction skippedOpenClawHealth(): OpenClawHealthCheck {\n return {\n ok: false,\n skipped: true,\n method: \"none\",\n error: \"OpenClaw support files were not detected; skipping gateway health check.\",\n details: [],\n };\n}\n\nexport async function runDoctor(): Promise<DoctorReport> {\n const surfaces = listSurfaceStatuses();\n const openclawSurface = surfaces.find((surface) => surface.name === \"openclaw\");\n const auth = await checkOrgxAuth();\n const hostedMcp = await checkHostedMcpHealth();\n const hostedMcpTool = await checkHostedMcpToolAccess();\n const npmRegistry = await checkNpmRegistryHealth();\n const workspace = await checkWorkspaceConnectivity();\n const openclaw = openclawSurface?.detected\n ? await checkOpenClawHealth(openclawSurface.path)\n : skippedOpenClawHealth();\n return { surfaces, auth, hostedMcp, hostedMcpTool, npmRegistry, workspace, openclaw };\n}\n\nexport function assessDoctorReport(report: DoctorReport): DoctorAssessment {\n const issues: DoctorAssessmentIssue[] = [];\n\n if (!report.hostedMcp.ok) {\n issues.push({\n level: \"error\",\n title: \"Hosted OrgX MCP is unreachable.\",\n suggestion:\n \"Retry later or verify https://mcp.useorgx.com/health. Hosted-only clients will stay broken until that endpoint recovers.\",\n });\n }\n\n if (\n report.hostedMcp.ok &&\n report.hostedMcpTool.configured &&\n !report.hostedMcpTool.ok &&\n !report.hostedMcpTool.skipped\n ) {\n issues.push({\n level: \"error\",\n title: `Hosted OrgX MCP tool verification failed (${report.hostedMcpTool.toolName}).`,\n suggestion:\n \"Re-run `wizard auth login` to refresh the per-user key, then retry `wizard doctor` to confirm the hosted MCP can initialize and execute tools.\",\n });\n }\n\n if (report.auth.configured && !report.auth.ok && !report.auth.skipped) {\n issues.push({\n level: \"error\",\n title: \"OrgX user auth could not be verified.\",\n suggestion:\n \"Run `wizard auth set-key <oxk_...>` again or correct the resolved ORGX_API_KEY / base URL before retrying.\",\n });\n }\n\n if (report.workspace.configured && !report.workspace.ok) {\n issues.push({\n level: \"error\",\n title: \"Current workspace lookup failed.\",\n suggestion:\n \"Verify the resolved OrgX base URL and that the authenticated user still has access to a workspace.\",\n });\n }\n\n if (!report.npmRegistry.reachable) {\n issues.push({\n level: \"warning\",\n title: \"npm registry is unreachable.\",\n suggestion:\n \"Check outbound network access to https://registry.npmjs.org before relying on npm-based installation flows.\",\n });\n } else if (!report.npmRegistry.published) {\n issues.push({\n level: \"warning\",\n title: `${report.npmRegistry.packageName} is not published on npm yet.`,\n suggestion:\n \"This is expected before launch. Publish the package in the release workstream before asking users to install from npm.\",\n });\n }\n\n if (!report.openclaw.skipped && !report.openclaw.ok) {\n issues.push({\n level: \"warning\",\n title: \"OpenClaw is installed but its local gateway health check failed.\",\n suggestion:\n \"Run `openclaw doctor` or `openclaw doctor --repair` before relying on local bridge clients like Cursor.\",\n });\n }\n\n const cursor = report.surfaces.find((surface) => surface.name === \"cursor\");\n const ci = cursor?.cursorIntegration;\n if (cursor?.detected && ci && (ci.mcpLocalOpenclaw || ci.mcpHostedOrgx) && !ci.pluginBundleInstalled) {\n issues.push({\n level: \"warning\",\n title: \"Cursor has OrgX MCP wiring but not the full companion plugin bundle.\",\n suggestion:\n \"Run `orgx-wizard plugins add cursor` to install the managed pack (skills, rules, hooks, commands), then reload Cursor. Skip this if you intentionally use MCP-only mode.\",\n });\n }\n\n return {\n ok: !issues.some((issue) => issue.level === \"error\"),\n issues,\n };\n}\n","import { listSurfaceStatuses, type SurfaceStatus } from \"../surfaces/registry.js\";\nimport type { SurfaceName } from \"../surfaces/names.js\";\nimport type { OrgxWorkspace } from \"./workspaces.js\";\nimport {\n updateWizardState,\n type WizardContinuityDefaults,\n type WizardStateRecord,\n} from \"./wizard-state.js\";\n\nconst REVIEW_SURFACE_ORDER: SurfaceName[] = [\n \"claude\",\n \"cursor\",\n \"codex\",\n \"vscode\",\n \"windsurf\",\n \"zed\",\n \"chatgpt\",\n];\n\nexport interface ContinuitySeed {\n executionMode?: \"cloud\" | \"local\" | null;\n statuses?: SurfaceStatus[];\n workspace?: Pick<OrgxWorkspace, \"id\" | \"name\"> | null;\n workspaceName?: string | null;\n}\n\nfunction selectReviewSurface(statuses: SurfaceStatus[]): SurfaceName | undefined {\n for (const name of REVIEW_SURFACE_ORDER) {\n const configured = statuses.find((status) => status.name === name && status.configured);\n if (configured) {\n return configured.name;\n }\n }\n\n for (const name of REVIEW_SURFACE_ORDER) {\n const detected = statuses.find((status) => status.name === name && status.detected);\n if (detected) {\n return detected.name;\n }\n }\n\n return undefined;\n}\n\nfunction inferExecutionMode(\n explicitMode: \"cloud\" | \"local\" | null | undefined,\n statuses: SurfaceStatus[],\n): \"cloud\" | \"local\" | undefined {\n if (explicitMode) {\n return explicitMode;\n }\n\n const openclaw = statuses.find((status) => status.name === \"openclaw\");\n if (openclaw?.configured || openclaw?.detected) {\n return \"local\";\n }\n\n const hostedSurface = statuses.find(\n (status) => status.name !== \"openclaw\" && (status.configured || status.detected),\n );\n\n return hostedSurface ? \"cloud\" : undefined;\n}\n\nexport function inferContinuityDefaults(seed: ContinuitySeed = {}): WizardContinuityDefaults {\n const statuses = seed.statuses ?? listSurfaceStatuses();\n const continuity: WizardContinuityDefaults = {};\n\n const reviewSurface = selectReviewSurface(statuses);\n if (reviewSurface) {\n continuity.reviewSurface = reviewSurface;\n }\n\n const executionMode = inferExecutionMode(seed.executionMode, statuses);\n if (executionMode) {\n continuity.executionMode = executionMode;\n }\n\n if (seed.workspace?.id) {\n continuity.workspaceId = seed.workspace.id;\n }\n\n const workspaceName = seed.workspace?.name ?? seed.workspaceName ?? undefined;\n if (workspaceName?.trim()) {\n continuity.workspaceName = workspaceName.trim();\n }\n\n return continuity;\n}\n\nfunction mergeContinuityDefaults(\n current: WizardContinuityDefaults | undefined,\n next: WizardContinuityDefaults,\n): WizardContinuityDefaults {\n return {\n ...(current ?? {}),\n ...next,\n };\n}\n\nexport function persistContinuityDefaults(\n seed: ContinuitySeed = {},\n statePath?: string,\n): WizardStateRecord {\n const next = inferContinuityDefaults(seed);\n\n return updateWizardState(\n (current) => ({\n ...current,\n continuity: mergeContinuityDefaults(current.continuity, next),\n }),\n statePath,\n );\n}\n","import {\n buildOrgxApiUrl,\n normalizeOrgxBaseUrl,\n resolveOrgxAuth,\n type ResolveOrgxAuthOptions,\n} from \"./auth.js\";\nimport { isRecord } from \"./fs.js\";\nimport type { OrgxWorkspace } from \"./workspaces.js\";\nimport {\n readWizardState,\n updateWizardState,\n type WizardDemoInitiativeRecord,\n type WizardFirstValueInitiativeRecord,\n type WizardOnboardingTaskRecord,\n} from \"./wizard-state.js\";\n\nconst FOUNDER_DEMO_INITIATIVE_TITLE = \"Founder Demo Initiative\";\nconst FOUNDER_DEMO_INITIATIVE_SUMMARY =\n \"Starter initiative created by @useorgx/wizard to validate workspace routing, live views, and the default OrgX skill pack.\";\nconst FOUNDER_DEMO_DECISION_TITLE = \"Approve founder demo workspace\";\nconst FOUNDER_DEMO_DECISION_SUMMARY =\n \"Initial decision created by @useorgx/wizard so the founder preset leaves the workspace with a resolved approval trail.\";\nconst FOUNDER_DEMO_DECISION_RESOLUTION =\n \"Approved automatically by @useorgx/wizard after the founder preset finished creating the live demo workspace.\";\nconst FOUNDER_DEMO_ARTIFACT_NAME = \"Founder Demo Live View\";\nconst FOUNDER_DEMO_ARTIFACT_TYPE = \"document\";\nconst FOUNDER_DEMO_ARTIFACT_DESCRIPTION =\n \"Live founder demo generated by @useorgx/wizard after workspace bootstrap completed.\";\nexport const ONBOARDING_TASK_TITLE = \"Complete OrgX onboarding\";\nexport const ONBOARDING_TASK_SUMMARY =\n \"Starter onboarding task created by @useorgx/wizard so the first workspace has a clear follow-up after setup.\";\nconst ONBOARDING_WORKSTREAM_TITLE = \"OrgX onboarding\";\nconst ONBOARDING_WORKSTREAM_SUMMARY =\n \"Starter onboarding workstream created by @useorgx/wizard so the first workspace has a home for setup follow-up tasks.\";\nexport const FIRST_VALUE_INITIATIVE_TITLE = \"Make OrgX useful on this machine\";\nexport const FIRST_VALUE_INITIATIVE_SUMMARY =\n \"First initiative created by @useorgx/wizard so setup ends with a live workspace, an onboarding workstream, and a clean handoff into the user's configured AI tools.\";\n\nexport interface OrgxInitiative {\n id: string;\n summary?: string;\n title: string;\n}\n\nexport interface OrgxDecision {\n id: string;\n status?: string;\n summary?: string;\n title: string;\n}\n\nexport interface OrgxArtifact {\n id: string;\n name: string;\n type?: string;\n url?: string;\n}\n\nexport interface OrgxTask {\n id: string;\n status?: string;\n summary?: string;\n title: string;\n}\n\ninterface OrgxWorkstream {\n id: string;\n title: string;\n}\n\nexport interface FounderDemoInitiativeResult {\n created: boolean;\n artifact: OrgxArtifact;\n decision: OrgxDecision;\n initiative: OrgxInitiative;\n liveUrl: string;\n}\n\nexport interface FirstValueInitiativeResult {\n created: boolean;\n initiative: OrgxInitiative;\n liveUrl: string;\n}\n\ninterface InitiativeClientOptions extends ResolveOrgxAuthOptions {\n statePath?: string;\n}\n\nfunction parseResponseBody(text: string): unknown {\n if (!text) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction formatHttpError(status: number, body: unknown): string {\n if (typeof body === \"string\" && body.trim().length > 0) {\n return `HTTP ${status}: ${body}`;\n }\n\n if (isRecord(body) && typeof body.error === \"string\" && body.error.trim().length > 0) {\n return `HTTP ${status}: ${body.error}`;\n }\n\n return `HTTP ${status}`;\n}\n\nfunction extractEntity(payload: unknown): Record<string, unknown> {\n const entity = isRecord(payload) && isRecord(payload.data) ? payload.data : payload;\n if (!isRecord(entity)) {\n throw new Error(\"OrgX returned an unexpected entity payload.\");\n }\n\n return entity;\n}\n\nfunction parseInitiative(payload: unknown): OrgxInitiative {\n const entity = extractEntity(payload);\n\n const id = typeof entity.id === \"string\" ? entity.id.trim() : \"\";\n const title = typeof entity.title === \"string\"\n ? entity.title.trim()\n : typeof entity.name === \"string\"\n ? entity.name.trim()\n : \"\";\n\n if (!id || !title) {\n throw new Error(\"OrgX returned an incomplete initiative payload.\");\n }\n\n return {\n id,\n title,\n ...(typeof entity.summary === \"string\" && entity.summary.trim().length > 0\n ? { summary: entity.summary.trim() }\n : {}),\n };\n}\n\nfunction parseDecision(payload: unknown): OrgxDecision {\n const entity = extractEntity(payload);\n const id = typeof entity.id === \"string\" ? entity.id.trim() : \"\";\n const title = typeof entity.title === \"string\"\n ? entity.title.trim()\n : typeof entity.name === \"string\"\n ? entity.name.trim()\n : \"\";\n\n if (!id || !title) {\n throw new Error(\"OrgX returned an incomplete decision payload.\");\n }\n\n return {\n id,\n title,\n ...(typeof entity.status === \"string\" && entity.status.trim().length > 0\n ? { status: entity.status.trim() }\n : {}),\n ...(typeof entity.summary === \"string\" && entity.summary.trim().length > 0\n ? { summary: entity.summary.trim() }\n : {}),\n };\n}\n\nfunction parseArtifact(payload: unknown): OrgxArtifact {\n const entity = extractEntity(payload);\n const id = typeof entity.id === \"string\" ? entity.id.trim() : \"\";\n const name = typeof entity.name === \"string\"\n ? entity.name.trim()\n : typeof entity.title === \"string\"\n ? entity.title.trim()\n : \"\";\n const type = typeof entity.artifact_type === \"string\"\n ? entity.artifact_type.trim()\n : typeof entity.type === \"string\"\n ? entity.type.trim()\n : \"\";\n const url = typeof entity.external_url === \"string\"\n ? entity.external_url.trim()\n : typeof entity.url === \"string\"\n ? entity.url.trim()\n : \"\";\n\n if (!id || !name) {\n throw new Error(\"OrgX returned an incomplete artifact payload.\");\n }\n\n return {\n id,\n name,\n ...(type ? { type } : {}),\n ...(url ? { url } : {}),\n };\n}\n\nfunction parseTask(payload: unknown): OrgxTask {\n const entity = extractEntity(payload);\n const id = typeof entity.id === \"string\" ? entity.id.trim() : \"\";\n const title = typeof entity.title === \"string\"\n ? entity.title.trim()\n : typeof entity.name === \"string\"\n ? entity.name.trim()\n : \"\";\n\n if (!id || !title) {\n throw new Error(\"OrgX returned an incomplete task payload.\");\n }\n\n return {\n id,\n title,\n ...(typeof entity.status === \"string\" && entity.status.trim().length > 0\n ? { status: entity.status.trim() }\n : {}),\n ...(typeof entity.summary === \"string\" && entity.summary.trim().length > 0\n ? { summary: entity.summary.trim() }\n : {}),\n };\n}\n\nfunction parseWorkstream(payload: unknown): OrgxWorkstream {\n const entity = extractEntity(payload);\n const id = typeof entity.id === \"string\" ? entity.id.trim() : \"\";\n const title = typeof entity.title === \"string\"\n ? entity.title.trim()\n : typeof entity.name === \"string\"\n ? entity.name.trim()\n : \"\";\n\n if (!id || !title) {\n throw new Error(\"OrgX returned an incomplete workstream payload.\");\n }\n\n return { id, title };\n}\n\nfunction toDemoInitiativeRecord(\n artifact: OrgxArtifact,\n decision: OrgxDecision,\n initiative: OrgxInitiative,\n liveUrl: string,\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n): WizardDemoInitiativeRecord {\n return {\n createdAt: new Date().toISOString(),\n artifactId: artifact.id,\n artifactName: artifact.name,\n ...(artifact.type ? { artifactType: artifact.type } : {}),\n ...(artifact.url ? { artifactUrl: artifact.url } : {}),\n decisionId: decision.id,\n ...(decision.status ? { decisionStatus: decision.status } : {}),\n decisionTitle: decision.title,\n id: initiative.id,\n liveUrl,\n title: initiative.title,\n workspaceId: workspace.id,\n workspaceName: workspace.name,\n };\n}\n\nfunction toOnboardingTaskRecord(\n task: OrgxTask,\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n options: {\n initiativeId?: string;\n workstreamId?: string;\n } = {},\n): WizardOnboardingTaskRecord {\n return {\n createdAt: new Date().toISOString(),\n id: task.id,\n ...(options.initiativeId ? { initiativeId: options.initiativeId } : {}),\n ...(task.status ? { status: task.status } : {}),\n title: task.title,\n ...(options.workstreamId ? { workstreamId: options.workstreamId } : {}),\n workspaceId: workspace.id,\n workspaceName: workspace.name,\n };\n}\n\nfunction toFirstValueInitiativeRecord(\n initiative: OrgxInitiative,\n liveUrl: string,\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n): WizardFirstValueInitiativeRecord {\n return {\n createdAt: new Date().toISOString(),\n id: initiative.id,\n liveUrl,\n ...(initiative.summary ? { summary: initiative.summary } : {}),\n title: initiative.title,\n workspaceId: workspace.id,\n workspaceName: workspace.name,\n };\n}\n\nasync function requireOrgxAuth(options: InitiativeClientOptions = {}) {\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n throw new Error(\n \"No OrgX API key configured. Run `wizard auth login` or `wizard auth set-key <oxk_...>` first.\",\n );\n }\n\n return auth;\n}\n\nasync function createEntity<T>(\n type: string,\n body: Record<string, unknown>,\n parse: (payload: unknown) => T,\n options: InitiativeClientOptions = {},\n): Promise<T> {\n const auth = await requireOrgxAuth(options);\n const response = await fetch(buildOrgxApiUrl(\"/entities\", auth.baseUrl), {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n type,\n ...body,\n }),\n signal: AbortSignal.timeout(7_000),\n });\n\n const responseBody = parseResponseBody(await response.text());\n if (!response.ok) {\n throw new Error(`Failed to create ${type}. ${formatHttpError(response.status, responseBody)}`);\n }\n\n return parse(responseBody);\n}\n\nasync function updateEntity<T>(\n type: string,\n id: string,\n body: Record<string, unknown>,\n parse: (payload: unknown) => T,\n options: InitiativeClientOptions = {},\n): Promise<T> {\n const auth = await requireOrgxAuth(options);\n const response = await fetch(buildOrgxApiUrl(\"/entities\", auth.baseUrl), {\n method: \"PATCH\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n type,\n id,\n ...body,\n }),\n signal: AbortSignal.timeout(7_000),\n });\n\n const responseBody = parseResponseBody(await response.text());\n if (!response.ok) {\n throw new Error(`Failed to update ${type}. ${formatHttpError(response.status, responseBody)}`);\n }\n\n return parse(responseBody);\n}\n\nfunction buildLiveUrl(baseUrl: string, initiativeId: string): string {\n const parsed = new URL(normalizeOrgxBaseUrl(baseUrl));\n parsed.pathname = `/live/${initiativeId}`;\n parsed.search = \"\";\n parsed.hash = \"\";\n return parsed.toString();\n}\n\nasync function createFounderDemoDecision(\n initiative: OrgxInitiative,\n workspaceId: string,\n options: InitiativeClientOptions = {},\n): Promise<OrgxDecision> {\n return createEntity(\n \"decision\",\n {\n initiative_id: initiative.id,\n summary: FOUNDER_DEMO_DECISION_SUMMARY,\n title: FOUNDER_DEMO_DECISION_TITLE,\n workspace_id: workspaceId,\n },\n parseDecision,\n options,\n );\n}\n\nasync function approveFounderDemoDecision(\n decisionId: string,\n options: InitiativeClientOptions = {},\n): Promise<OrgxDecision> {\n return updateEntity(\n \"decision\",\n decisionId,\n {\n resolution_summary: FOUNDER_DEMO_DECISION_RESOLUTION,\n status: \"approved\",\n },\n parseDecision,\n options,\n );\n}\n\nasync function createFounderDemoArtifact(\n initiative: OrgxInitiative,\n liveUrl: string,\n workspaceId: string,\n options: InitiativeClientOptions = {},\n): Promise<OrgxArtifact> {\n return createEntity(\n \"artifact\",\n {\n artifact_type: FOUNDER_DEMO_ARTIFACT_TYPE,\n description: FOUNDER_DEMO_ARTIFACT_DESCRIPTION,\n entity_id: initiative.id,\n entity_type: \"initiative\",\n external_url: liveUrl,\n initiative_id: initiative.id,\n name: FOUNDER_DEMO_ARTIFACT_NAME,\n workspace_id: workspaceId,\n },\n parseArtifact,\n options,\n );\n}\n\nexport async function createInitiative(\n input: {\n summary?: string;\n title: string;\n workspaceId?: string;\n },\n options: InitiativeClientOptions = {},\n): Promise<OrgxInitiative> {\n const title = input.title.trim();\n if (!title) {\n throw new Error(\"Initiative title is required.\");\n }\n\n return createEntity(\n \"initiative\",\n {\n title,\n status: \"active\",\n ...(input.summary?.trim() ? { summary: input.summary.trim() } : {}),\n ...(input.workspaceId?.trim() ? { workspace_id: input.workspaceId.trim() } : {}),\n },\n parseInitiative,\n options,\n );\n}\n\nexport async function ensureFounderDemoInitiative(\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n options: InitiativeClientOptions = {},\n): Promise<FounderDemoInitiativeResult> {\n const existingRecord = readWizardState(options.statePath)?.demoInitiative;\n const matchingRecord = existingRecord?.workspaceId === workspace.id ? existingRecord : undefined;\n const auth = await requireOrgxAuth(options);\n\n const initiative = matchingRecord\n ? {\n id: matchingRecord.id,\n title: matchingRecord.title,\n }\n : await createInitiative(\n {\n title: FOUNDER_DEMO_INITIATIVE_TITLE,\n summary: FOUNDER_DEMO_INITIATIVE_SUMMARY,\n workspaceId: workspace.id,\n },\n options,\n );\n const liveUrl = matchingRecord?.liveUrl || buildLiveUrl(auth.baseUrl, initiative.id);\n const decision = matchingRecord?.decisionId\n ? matchingRecord.decisionStatus === \"approved\" && matchingRecord.decisionTitle\n ? {\n id: matchingRecord.decisionId,\n status: matchingRecord.decisionStatus,\n title: matchingRecord.decisionTitle,\n }\n : await approveFounderDemoDecision(matchingRecord.decisionId, options)\n : await approveFounderDemoDecision(\n (\n await createFounderDemoDecision(initiative, workspace.id, options)\n ).id,\n options,\n );\n const artifact = matchingRecord?.artifactId && matchingRecord.artifactName\n ? {\n id: matchingRecord.artifactId,\n name: matchingRecord.artifactName,\n ...(matchingRecord.artifactType ? { type: matchingRecord.artifactType } : {}),\n ...(matchingRecord.artifactUrl ? { url: matchingRecord.artifactUrl } : {}),\n }\n : await createFounderDemoArtifact(initiative, liveUrl, workspace.id, options);\n const record = toDemoInitiativeRecord(artifact, decision, initiative, liveUrl, workspace);\n\n updateWizardState(\n (current) => ({\n ...current,\n demoInitiative: record,\n }),\n options.statePath,\n );\n\n return {\n artifact,\n created: !matchingRecord,\n decision,\n initiative,\n liveUrl,\n };\n}\n\nexport async function ensureFirstValueInitiative(\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n options: InitiativeClientOptions & {\n summary?: string;\n title?: string;\n } = {},\n): Promise<FirstValueInitiativeResult> {\n const existingRecord = readWizardState(options.statePath)?.firstValueInitiative;\n const matchingRecord = existingRecord?.workspaceId === workspace.id ? existingRecord : undefined;\n const auth = await requireOrgxAuth(options);\n\n if (matchingRecord) {\n return {\n created: false,\n initiative: {\n id: matchingRecord.id,\n title: matchingRecord.title,\n ...(matchingRecord.summary ? { summary: matchingRecord.summary } : {}),\n },\n liveUrl: matchingRecord.liveUrl || buildLiveUrl(auth.baseUrl, matchingRecord.id),\n };\n }\n\n const initiative = await createInitiative(\n {\n title: options.title?.trim() || FIRST_VALUE_INITIATIVE_TITLE,\n summary: options.summary?.trim() || FIRST_VALUE_INITIATIVE_SUMMARY,\n workspaceId: workspace.id,\n },\n options,\n );\n const liveUrl = buildLiveUrl(auth.baseUrl, initiative.id);\n\n updateWizardState(\n (current) => ({\n ...current,\n firstValueInitiative: toFirstValueInitiativeRecord(initiative, liveUrl, workspace),\n }),\n options.statePath,\n );\n\n return {\n created: true,\n initiative,\n liveUrl,\n };\n}\n\nexport async function ensureOnboardingTask(\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n options: InitiativeClientOptions & { initiativeId?: string } = {},\n): Promise<OrgxTask> {\n const existingRecord = readWizardState(options.statePath)?.onboardingTask;\n if (existingRecord?.workspaceId === workspace.id) {\n return {\n id: existingRecord.id,\n title: existingRecord.title,\n ...(existingRecord.status ? { status: existingRecord.status } : {}),\n };\n }\n\n const initiativeId = options.initiativeId?.trim();\n if (!initiativeId) {\n throw new Error(\n \"Starter onboarding task requires an initiative context. Re-run setup with the founder preset or create an initiative before requesting onboarding tasks.\",\n );\n }\n\n const workstream = await createEntity(\n \"workstream\",\n {\n initiative_id: initiativeId,\n status: \"active\",\n summary: ONBOARDING_WORKSTREAM_SUMMARY,\n title: ONBOARDING_WORKSTREAM_TITLE,\n workspace_id: workspace.id,\n },\n parseWorkstream,\n options,\n );\n\n const task = await createEntity(\n \"task\",\n {\n initiative_id: initiativeId,\n status: \"todo\",\n summary: ONBOARDING_TASK_SUMMARY,\n title: ONBOARDING_TASK_TITLE,\n workstream_id: workstream.id,\n workspace_id: workspace.id,\n },\n parseTask,\n options,\n );\n\n updateWizardState(\n (current) => ({\n ...current,\n onboardingTask: toOnboardingTaskRecord(task, workspace, {\n initiativeId,\n workstreamId: workstream.id,\n }),\n }),\n options.statePath,\n );\n\n return task;\n}\n","import type { CreateWorkspaceInput, OrgxWorkspace, SetDefaultWorkspaceInput } from \"./workspaces.js\";\n\nconst CREATE_WORKSPACE_VALUE = \"__create_workspace__\";\nconst SKIP_WORKSPACE_VALUE = \"__skip_workspace__\";\nconst REAUTH_WORKSPACE_VALUE = \"__reauth_workspace__\";\n\nexport interface WorkspaceSetupClient {\n createWorkspace(input: CreateWorkspaceInput): Promise<OrgxWorkspace>;\n getCurrentWorkspace(): Promise<OrgxWorkspace | null>;\n listWorkspaces(): Promise<OrgxWorkspace[]>;\n setDefaultWorkspace(\n input: SetDefaultWorkspaceInput,\n ): Promise<{ changed: boolean; workspace: OrgxWorkspace }>;\n}\n\nexport interface WorkspaceSelectOption {\n hint?: string;\n label: string;\n value: string;\n}\n\nexport interface WorkspaceSetupPrompts {\n cancel(message: string): void;\n isCancel(value: unknown): boolean;\n select(input: {\n initialValue?: string | undefined;\n message: string;\n options: WorkspaceSelectOption[];\n }): Promise<string | symbol>;\n text(input: {\n initialValue?: string | undefined;\n message: string;\n placeholder?: string;\n validate?: (value: string | undefined) => Error | string | undefined;\n }): Promise<string | symbol>;\n}\n\nexport interface WorkspaceSetupOptions {\n interactive: boolean;\n skipIfConfigured?: boolean;\n}\n\nexport interface WorkspaceSetupResult {\n created?: boolean;\n defaultChanged?: boolean;\n message: string;\n /**\n * \"reauth_requested\" — the caller should trigger the OAuth login flow and\n * then rerun setup. This is used when the key authenticates but returns no\n * workspaces — a strong signal the key is bound to a different Supabase\n * user than the one the human signs into via OAuth.\n */\n status: \"cancelled\" | \"skipped\" | \"unchanged\" | \"updated\" | \"reauth_requested\";\n workspace?: OrgxWorkspace;\n}\n\nfunction trimDescription(value: string): string | undefined {\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction cancelResult(\n prompts: WorkspaceSetupPrompts,\n message = \"Workspace bootstrap cancelled.\",\n): WorkspaceSetupResult {\n prompts.cancel(message);\n return {\n message,\n status: \"cancelled\",\n };\n}\n\nfunction buildWorkspaceLabel(workspace: OrgxWorkspace, currentWorkspaceId?: string): string {\n const suffixes: string[] = [];\n\n if (workspace.isDefault) {\n suffixes.push(\"default\");\n }\n\n if (workspace.id === currentWorkspaceId) {\n suffixes.push(\"current\");\n }\n\n if (suffixes.length === 0) {\n return workspace.name;\n }\n\n return `${workspace.name} (${suffixes.join(\", \")})`;\n}\n\nexport function buildWorkspaceSelectOptions(\n workspaces: OrgxWorkspace[],\n currentWorkspaceId?: string,\n): WorkspaceSelectOption[] {\n const options = workspaces.map((workspace) => ({\n value: workspace.id,\n label: buildWorkspaceLabel(workspace, currentWorkspaceId),\n ...(workspace.description ? { hint: workspace.description } : {}),\n }));\n\n options.push(\n {\n value: CREATE_WORKSPACE_VALUE,\n label: \"Create a new workspace\",\n hint: \"Name it here and set it as the default for this machine.\",\n },\n {\n value: SKIP_WORKSPACE_VALUE,\n label: \"Skip for now\",\n hint: \"Leave workspace selection unchanged and finish setup.\",\n },\n );\n\n return options;\n}\n\nasync function promptForWorkspaceName(prompts: WorkspaceSetupPrompts): Promise<string | symbol> {\n return prompts.text({\n message: \"Workspace name\",\n placeholder: \"Founders\",\n validate(value) {\n if (!value || value.trim().length === 0) {\n return \"Workspace name is required.\";\n }\n\n return undefined;\n },\n });\n}\n\nasync function promptForWorkspaceDescription(\n prompts: WorkspaceSetupPrompts,\n): Promise<string | symbol> {\n return prompts.text({\n message: \"Workspace description\",\n placeholder: \"Optional\",\n });\n}\n\nasync function createAndSelectWorkspace(\n client: WorkspaceSetupClient,\n prompts: WorkspaceSetupPrompts,\n): Promise<WorkspaceSetupResult> {\n const name = await promptForWorkspaceName(prompts);\n if (prompts.isCancel(name)) {\n return cancelResult(prompts);\n }\n if (typeof name !== \"string\") {\n return cancelResult(prompts);\n }\n\n const description = await promptForWorkspaceDescription(prompts);\n if (prompts.isCancel(description)) {\n return cancelResult(prompts);\n }\n if (typeof description !== \"string\") {\n return cancelResult(prompts);\n }\n\n const trimmedDescription = trimDescription(description);\n const createWorkspaceInput: CreateWorkspaceInput = trimmedDescription\n ? { name, description: trimmedDescription }\n : { name };\n\n const created = await client.createWorkspace(createWorkspaceInput);\n\n if (created.isDefault) {\n return {\n created: true,\n defaultChanged: false,\n message: `Created \"${created.name}\" and it is already the default OrgX workspace.`,\n status: \"updated\",\n workspace: created,\n };\n }\n\n const promoted = await client.setDefaultWorkspace({ id: created.id });\n return {\n created: true,\n defaultChanged: promoted.changed,\n message: `Created \"${promoted.workspace.name}\" and set it as the default OrgX workspace.`,\n status: \"updated\",\n workspace: promoted.workspace,\n };\n}\n\nexport async function runWorkspaceSetup(\n client: WorkspaceSetupClient,\n prompts: WorkspaceSetupPrompts,\n options: WorkspaceSetupOptions,\n): Promise<WorkspaceSetupResult> {\n if (!options.interactive) {\n return {\n message:\n \"Interactive workspace bootstrap skipped because this shell is not attached to a TTY.\",\n status: \"skipped\",\n };\n }\n\n const workspaces = await client.listWorkspaces();\n const currentWorkspace =\n workspaces.length > 0\n ? await client.getCurrentWorkspace().catch(() => workspaces.find((workspace) => workspace.isDefault) ?? null)\n : null;\n\n if (workspaces.length === 0) {\n // The API key authenticated successfully (we reached this function) but\n // the server returned zero workspaces for the resolved user. That is\n // ambiguous: it could mean a genuinely new account, OR the key is bound\n // to a different Supabase user row than the one that owns this person's\n // workspaces (e.g. the key was provisioned before the OAuth/Clerk sign-in\n // unified the user record). Creating a new workspace in that second case\n // silently forks the user's data — so surface the choice explicitly and\n // offer re-authentication as the first-class recovery path.\n const action = await prompts.select({\n message:\n \"OrgX authenticated, but returned 0 workspaces for this key. How should setup proceed?\",\n options: [\n {\n value: REAUTH_WORKSPACE_VALUE,\n label: \"Re-authenticate (recommended if you expected workspaces)\",\n hint: \"Run `wizard auth login` to re-link via OAuth if your API key is bound to a different user identity.\",\n },\n {\n value: CREATE_WORKSPACE_VALUE,\n label: \"Create a new workspace\",\n hint: \"Use this only for a truly new account — this will fork data if your key is misbound.\",\n },\n {\n value: SKIP_WORKSPACE_VALUE,\n label: \"Skip for now\",\n hint: \"Finish surface setup without touching workspaces.\",\n },\n ],\n initialValue: REAUTH_WORKSPACE_VALUE,\n });\n\n if (prompts.isCancel(action)) {\n return cancelResult(prompts);\n }\n\n if (action === REAUTH_WORKSPACE_VALUE) {\n return {\n message:\n \"Re-authentication requested. Run `wizard auth login`, then rerun `wizard setup`.\",\n status: \"reauth_requested\",\n };\n }\n\n if (action === SKIP_WORKSPACE_VALUE) {\n return {\n message: \"Workspace bootstrap skipped.\",\n status: \"skipped\",\n };\n }\n\n return createAndSelectWorkspace(client, prompts);\n }\n\n if (options.skipIfConfigured && currentWorkspace) {\n return {\n defaultChanged: false,\n message: `Using \"${currentWorkspace.name}\" as the default OrgX workspace.`,\n status: \"unchanged\",\n workspace: currentWorkspace,\n };\n }\n\n const initialWorkspaceId =\n currentWorkspace?.id ??\n workspaces.find((workspace) => workspace.isDefault)?.id ??\n workspaces[0]?.id;\n const selected = await prompts.select({\n message: \"Choose the OrgX workspace this machine should use by default.\",\n options: buildWorkspaceSelectOptions(\n workspaces,\n currentWorkspace?.id ?? workspaces.find((workspace) => workspace.isDefault)?.id,\n ),\n ...(initialWorkspaceId ? { initialValue: initialWorkspaceId } : {}),\n });\n\n if (prompts.isCancel(selected)) {\n return cancelResult(prompts);\n }\n if (typeof selected !== \"string\") {\n return cancelResult(prompts);\n }\n\n if (selected === SKIP_WORKSPACE_VALUE) {\n return {\n message: \"Workspace bootstrap skipped.\",\n status: \"skipped\",\n ...(currentWorkspace ? { workspace: currentWorkspace } : {}),\n };\n }\n\n if (selected === CREATE_WORKSPACE_VALUE) {\n return createAndSelectWorkspace(client, prompts);\n }\n\n const chosenWorkspace = workspaces.find((workspace) => workspace.id === selected);\n if (!chosenWorkspace) {\n throw new Error(`Selected workspace ${selected} is no longer available.`);\n }\n\n if (chosenWorkspace.isDefault) {\n return {\n defaultChanged: false,\n message: `\"${chosenWorkspace.name}\" is already the default OrgX workspace.`,\n status: \"unchanged\",\n workspace: chosenWorkspace,\n };\n }\n\n const promoted = await client.setDefaultWorkspace({ id: chosenWorkspace.id });\n return {\n defaultChanged: promoted.changed,\n message: `Set \"${promoted.workspace.name}\" as the default OrgX workspace.`,\n status: promoted.changed ? \"updated\" : \"unchanged\",\n workspace: promoted.workspace,\n };\n}\n","import {\n ensureFounderDemoInitiative,\n type FounderDemoInitiativeResult,\n} from \"./initiatives.js\";\nimport { persistContinuityDefaults, type ContinuitySeed } from \"./continuity.js\";\nimport {\n DEFAULT_ORGX_SKILL_PACKS,\n installOrgxSkills,\n type SkillsInstallReport,\n} from \"./skills.js\";\nimport { listOrgxPluginStatuses } from \"./plugins.js\";\nimport {\n runWorkspaceSetup,\n type WorkspaceSetupOptions,\n type WorkspaceSetupPrompts,\n type WorkspaceSetupResult,\n} from \"./setup-workspace.js\";\nimport { listSurfaceStatuses, setupDetectedSurfaces, type SurfaceMutationResult } from \"../surfaces/registry.js\";\nimport {\n createWorkspace,\n getCurrentWorkspace,\n listWorkspaces,\n setDefaultWorkspace,\n type OrgxWorkspace,\n} from \"./workspaces.js\";\nimport type { WizardStateRecord } from \"./wizard-state.js\";\n\nexport interface FounderPresetResult {\n continuity: WizardStateRecord;\n demoInitiative?: FounderDemoInitiativeResult;\n skillReport: SkillsInstallReport;\n surfaceResults: SurfaceMutationResult[];\n workspace: OrgxWorkspace | null;\n workspaceSetup?: WorkspaceSetupResult;\n}\n\nexport async function runFounderPreset(\n prompts: WorkspaceSetupPrompts,\n options: WorkspaceSetupOptions & { pluginTargets?: readonly string[] },\n): Promise<FounderPresetResult | WorkspaceSetupResult> {\n const surfaceResults = await setupDetectedSurfaces();\n const pluginTargets = options.pluginTargets ?? (\n await listOrgxPluginStatuses()\n )\n .filter((status) => status.installed)\n .map((status) => status.target);\n const skillReport = await installOrgxSkills({\n pluginTargets,\n skillNames: [...DEFAULT_ORGX_SKILL_PACKS],\n });\n\n let workspaceSetup: WorkspaceSetupResult | undefined;\n let workspace = await getCurrentWorkspace().catch(() => null);\n\n if (workspace || options.interactive) {\n workspaceSetup = await runWorkspaceSetup(\n {\n createWorkspace,\n getCurrentWorkspace,\n listWorkspaces,\n setDefaultWorkspace,\n },\n prompts,\n options,\n );\n\n if (workspaceSetup.status === \"cancelled\") {\n return workspaceSetup;\n }\n\n workspace = workspaceSetup.workspace ?? workspace ?? await getCurrentWorkspace().catch(() => null);\n }\n\n const continuity = persistContinuityDefaults({\n statuses: listSurfaceStatuses(),\n workspace,\n });\n\n let demoInitiative: FounderDemoInitiativeResult | undefined;\n if (workspace) {\n demoInitiative = await ensureFounderDemoInitiative(workspace);\n }\n\n return {\n continuity,\n ...(demoInitiative ? { demoInitiative } : {}),\n skillReport,\n surfaceResults,\n workspace,\n ...(workspaceSetup ? { workspaceSetup } : {}),\n };\n}\n","import type { SurfaceMutationResult } from \"../surfaces/registry.js\";\n\nexport type MutationSummary = {\n name: string;\n state: \"updated\" | \"unchanged\";\n message: string;\n};\n\nexport function summarizeMutationResults(\n results: SurfaceMutationResult[],\n): MutationSummary[] {\n return results.map((result) => ({\n name: result.name,\n state: result.changed ? \"updated\" : \"unchanged\",\n message: result.message,\n }));\n}\n","import type { DoctorAssessment } from \"../surfaces/registry.js\";\n\nexport const HOSTED_MCP_OUTAGE_TITLE = \"Hosted OrgX MCP is unreachable.\";\n\nexport interface SetupVerificationSummary {\n hostedMcpDegraded: boolean;\n status: \"degraded\" | \"error\" | \"ok\" | \"warning\";\n}\n\nexport function getSetupVerificationHeadline(summary: SetupVerificationSummary): string {\n switch (summary.status) {\n case \"degraded\":\n return \"Hosted OrgX MCP is down; local setup can still continue.\";\n case \"error\":\n return \"Issues detected\";\n case \"warning\":\n return \"Warnings detected\";\n case \"ok\":\n return \"All systems ready.\";\n }\n}\n\nexport function summarizeSetupVerification(\n assessment: DoctorAssessment,\n): SetupVerificationSummary {\n const errors = assessment.issues.filter((issue) => issue.level === \"error\");\n if (errors.length === 0) {\n return {\n hostedMcpDegraded: false,\n status: assessment.issues.length > 0 ? \"warning\" : \"ok\",\n };\n }\n\n const hostedMcpDegraded = errors.every((issue) => issue.title === HOSTED_MCP_OUTAGE_TITLE);\n return {\n hostedMcpDegraded,\n status: hostedMcpDegraded ? \"degraded\" : \"error\",\n };\n}\n","import type { DoctorAssessment, DoctorReport } from \"../surfaces/registry.js\";\nimport type { FirstValueInitiativeResult, FounderDemoInitiativeResult, OrgxTask } from \"./initiatives.js\";\nimport type { SetupVerificationSummary } from \"./setup-verification.js\";\nimport type { WorkspaceSetupResult } from \"./setup-workspace.js\";\nimport type { WizardAgentRosterRecord } from \"./wizard-state.js\";\n\nfunction withBaseProperties(\n properties: Record<string, unknown>,\n base: Record<string, unknown>,\n): Record<string, unknown> {\n return {\n ...base,\n ...properties,\n };\n}\n\nexport function buildWorkspaceSetupTelemetryProperties(\n result: WorkspaceSetupResult,\n base: Record<string, unknown> = {},\n): Record<string, unknown> {\n return withBaseProperties(\n {\n created: result.created === true,\n default_changed: result.defaultChanged === true,\n has_workspace: Boolean(result.workspace),\n status: result.status,\n },\n base,\n );\n}\n\nexport function buildOnboardingTaskTelemetryProperties(\n input: {\n created: boolean;\n hasInitiative: boolean;\n task: Pick<OrgxTask, \"status\">;\n },\n base: Record<string, unknown> = {},\n): Record<string, unknown> {\n return withBaseProperties(\n {\n created: input.created,\n has_initiative: input.hasInitiative,\n task_status: input.task.status ?? \"unknown\",\n },\n base,\n );\n}\n\nexport function buildAgentRosterTelemetryProperties(\n input: {\n roster: WizardAgentRosterRecord;\n strategy: \"default\" | \"guided\";\n },\n base: Record<string, unknown> = {},\n): Record<string, unknown> {\n return withBaseProperties(\n {\n agent_count: input.roster.agents.length,\n domain_count: new Set(input.roster.agents.map((agent) => agent.domain)).size,\n strategy: input.strategy,\n },\n base,\n );\n}\n\nexport function buildFounderDemoTelemetryProperties(\n result: FounderDemoInitiativeResult,\n base: Record<string, unknown> = {},\n): Record<string, unknown> {\n return withBaseProperties(\n {\n created: result.created,\n decision_status: result.decision.status ?? \"unknown\",\n has_artifact_url: Boolean(result.artifact.url),\n },\n base,\n );\n}\n\nexport function buildFirstValueInitiativeTelemetryProperties(\n result: FirstValueInitiativeResult,\n base: Record<string, unknown> = {},\n): Record<string, unknown> {\n return withBaseProperties(\n {\n created: result.created,\n has_live_url: Boolean(result.liveUrl),\n },\n base,\n );\n}\n\nexport function buildDoctorTelemetryProperties(\n report: DoctorReport,\n assessment: DoctorAssessment,\n verification: SetupVerificationSummary,\n base: Record<string, unknown> = {},\n): Record<string, unknown> {\n const errorCount = assessment.issues.filter((issue) => issue.level === \"error\").length;\n const warningCount = assessment.issues.filter((issue) => issue.level === \"warning\").length;\n\n return withBaseProperties(\n {\n auth_configured: report.auth.configured,\n auth_ok: report.auth.ok,\n configured_surface_count: report.surfaces.filter((surface) => surface.configured).length,\n detected_surface_count: report.surfaces.filter((surface) => surface.detected).length,\n error_count: errorCount,\n hosted_mcp_degraded: verification.hostedMcpDegraded,\n hosted_mcp_ok: report.hostedMcp.ok,\n hosted_mcp_tool_ok: report.hostedMcpTool.ok,\n issue_count: assessment.issues.length,\n openclaw_available: !report.openclaw.skipped,\n openclaw_ok: report.openclaw.ok,\n status: verification.status,\n warning_count: warningCount,\n workspace_configured: report.workspace.configured,\n workspace_ok: report.workspace.ok,\n },\n base,\n );\n}\n","import { getOrCreateWizardInstallationId } from \"./wizard-state.js\";\n\nconst POSTHOG_DEFAULT_HOST = \"https://us.i.posthog.com\";\nconst WIZARD_LIB = \"@useorgx/wizard\";\n\nfunction isTruthyEnv(value: string | undefined): boolean {\n if (!value) return false;\n\n switch (value.trim().toLowerCase()) {\n case \"1\":\n case \"true\":\n case \"yes\":\n case \"y\":\n case \"on\":\n return true;\n default:\n return false;\n }\n}\n\nfunction isWizardTelemetryDisabled(): boolean {\n const explicitEnable = isTruthyEnv(process.env.ORGX_TELEMETRY_ENABLED);\n if (!explicitEnable) return true;\n\n return (\n isTruthyEnv(process.env.ORGX_TELEMETRY_DISABLED) ||\n isTruthyEnv(process.env.OPENCLAW_TELEMETRY_DISABLED) ||\n isTruthyEnv(process.env.POSTHOG_DISABLED)\n );\n}\n\nfunction resolvePosthogApiKey(): string | null {\n const value =\n process.env.ORGX_POSTHOG_API_KEY ??\n process.env.POSTHOG_API_KEY ??\n process.env.ORGX_POSTHOG_KEY ??\n process.env.POSTHOG_KEY ??\n \"\";\n const trimmed = value.trim();\n return trimmed || null;\n}\n\nfunction resolvePosthogHost(): string {\n const value =\n process.env.ORGX_POSTHOG_HOST ??\n process.env.POSTHOG_HOST ??\n process.env.ORGX_POSTHOG_API_HOST ??\n process.env.POSTHOG_API_HOST ??\n \"\";\n const trimmed = value.trim();\n return trimmed || POSTHOG_DEFAULT_HOST;\n}\n\nfunction toPosthogBatchUrl(host: string): string {\n try {\n return new URL(\"/batch/\", host).toString();\n } catch {\n return `${POSTHOG_DEFAULT_HOST}/batch/`;\n }\n}\n\nexport async function trackWizardTelemetry(\n event: string,\n properties: Record<string, unknown> = {},\n options: { statePath?: string; timestamp?: string } = {},\n): Promise<boolean> {\n if (isWizardTelemetryDisabled()) return false;\n\n const apiKey = resolvePosthogApiKey();\n if (!apiKey) return false;\n\n const installationId = getOrCreateWizardInstallationId(options.statePath);\n const timestamp = options.timestamp ?? new Date().toISOString();\n const response = await fetch(toPosthogBatchUrl(resolvePosthogHost()), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n api_key: apiKey,\n batch: [\n {\n type: \"capture\",\n event,\n distinct_id: installationId,\n properties: {\n $lib: WIZARD_LIB,\n source: WIZARD_LIB,\n wizard_installation_id: installationId,\n ...properties,\n },\n timestamp,\n },\n ],\n sent_at: timestamp,\n }),\n }).catch(() => null);\n\n return response?.ok === true;\n}\n","/**\n * Phase II · M-P5 — CLI intent capture\n *\n * Client-side bindings for the OrgX intents API (M-P2). The wizard POSTs a raw\n * intent, the server classifies it to an agent + generates a plan preview, and\n * the CLI surface renders that payload with the OrgX terminal vocabulary\n * (agent-colored routing line, mono confidence decimal, box-drawn plan, `>>`\n * hotkey bar). Approve / archive PATCH the row; \"edit in browser\" hands off to\n * `/command?intent=<slug>`.\n *\n * The contract mirrors `orgx/types/intents.ts` in the main monorepo; the shape\n * is duplicated here (not imported) because orgx-wizard is a separate npm\n * package shipped independently. Keeping the types narrow + local lets us\n * avoid a cross-repo dependency while still being strict at the boundary.\n */\n\nimport {\n buildOrgxApiUrl,\n resolveOrgxAuth,\n type ResolveOrgxAuthOptions,\n} from \"./auth.js\";\nimport { isRecord } from \"./fs.js\";\n\n/** Canonical agent slugs the classifier can emit (mirror of @/types/intents). */\nexport const AGENT_SLUGS = [\n \"mark\",\n \"eli\",\n \"dana\",\n \"pace\",\n \"sage\",\n \"orion\",\n \"xandy\",\n] as const;\n\nexport type AgentSlug = (typeof AGENT_SLUGS)[number];\n\nexport const INTENT_STATUSES = [\n \"pending\",\n \"approved\",\n \"adjusted\",\n \"archived\",\n] as const;\n\nexport type IntentStatus = (typeof INTENT_STATUSES)[number];\n\n/** Confidence bucket returned by the server. */\nexport type IntentConfidence = \"low\" | \"med\" | \"high\";\n\nexport interface IntentPlanStep {\n title: string;\n detail?: string;\n agent_slug?: AgentSlug;\n}\n\nexport interface IntentPlanPreview {\n steps: IntentPlanStep[];\n eta: string;\n confidence: IntentConfidence;\n}\n\nexport interface Intent {\n id: string;\n workspace_id: string;\n slug: string;\n text: string;\n status: IntentStatus;\n suggested_agent_slug: AgentSlug | null;\n plan_preview: IntentPlanPreview;\n approved_at: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface CreateIntentInput {\n workspace_id: string;\n text: string;\n}\n\nexport interface UpdateIntentInput {\n status: Exclude<IntentStatus, \"pending\">;\n text?: string;\n plan_preview?: IntentPlanPreview;\n}\n\nexport interface OrgxIntentsClientOptions extends ResolveOrgxAuthOptions {}\n\n/** Role labels for the `→ Agent · Role` routing line. */\nexport const AGENT_ROLES: Record<AgentSlug, string> = {\n mark: \"Partnerships\",\n eli: \"Engineering\",\n dana: \"Brand\",\n pace: \"Product\",\n sage: \"Strategy\",\n orion: \"Routing\",\n xandy: \"Default\",\n};\n\n/**\n * Deterministic bucket → decimal mapping used by the CLI render layer.\n *\n * The design spec (Phase II · M-P0 Surface 3) locks the CLI to a mono\n * confidence decimal (`0.87`) and explicitly rejects `low / med / high`\n * buckets. The M-P2 API still returns the bucket, so we render a\n * representative decimal per bucket here. Values are chosen to match the\n * spec's example band (0.55 / 0.78 / 0.92) and to read like the output of\n * a real classifier rather than round magic numbers.\n */\nexport const CONFIDENCE_DECIMAL: Record<IntentConfidence, number> = {\n low: 0.55,\n med: 0.78,\n high: 0.92,\n};\n\n/**\n * Per-agent ANSI 256-color codes used to tint the `→ Agent · Role` routing\n * line. Values mirror the tokens called out in the M-P0 spec so the terminal\n * identity stays aligned with the web `--agent-accent-rgb` directory.\n */\nexport const AGENT_ANSI_256: Record<AgentSlug, number> = {\n pace: 34, // green\n eli: 44, // cyan\n mark: 208, // orange\n sage: 135, // purple\n orion: 214, // amber\n dana: 199, // pink\n xandy: 37, // teal\n};\n\nfunction parseAgentSlug(value: unknown): AgentSlug | null {\n if (typeof value !== \"string\") return null;\n return (AGENT_SLUGS as readonly string[]).includes(value)\n ? (value as AgentSlug)\n : null;\n}\n\nfunction parseStatus(value: unknown): IntentStatus | null {\n if (typeof value !== \"string\") return null;\n return (INTENT_STATUSES as readonly string[]).includes(value)\n ? (value as IntentStatus)\n : null;\n}\n\nfunction parseConfidence(value: unknown): IntentConfidence {\n if (value === \"low\" || value === \"med\" || value === \"high\") return value;\n return \"med\";\n}\n\nfunction parsePlanStep(value: unknown): IntentPlanStep | null {\n if (!isRecord(value)) return null;\n const title = typeof value.title === \"string\" ? value.title.trim() : \"\";\n if (!title) return null;\n\n const detail =\n typeof value.detail === \"string\" && value.detail.trim().length > 0\n ? value.detail\n : undefined;\n const agentSlug = parseAgentSlug(value.agent_slug);\n\n const step: IntentPlanStep = { title };\n if (detail !== undefined) step.detail = detail;\n if (agentSlug !== null) step.agent_slug = agentSlug;\n return step;\n}\n\nfunction parsePlanPreview(value: unknown): IntentPlanPreview {\n if (!isRecord(value)) {\n return { steps: [], eta: \"under a week\", confidence: \"med\" };\n }\n\n const steps = Array.isArray(value.steps)\n ? value.steps\n .map(parsePlanStep)\n .filter((step): step is IntentPlanStep => step !== null)\n : [];\n const eta =\n typeof value.eta === \"string\" && value.eta.trim().length > 0\n ? value.eta\n : \"under a week\";\n return {\n steps,\n eta,\n confidence: parseConfidence(value.confidence),\n };\n}\n\nexport function parseIntent(value: unknown): Intent | null {\n if (!isRecord(value)) return null;\n\n const id = typeof value.id === \"string\" ? value.id : null;\n const workspaceId =\n typeof value.workspace_id === \"string\" ? value.workspace_id : null;\n const slug = typeof value.slug === \"string\" ? value.slug : null;\n const text = typeof value.text === \"string\" ? value.text : null;\n const status = parseStatus(value.status);\n const createdAt =\n typeof value.created_at === \"string\" ? value.created_at : null;\n const updatedAt =\n typeof value.updated_at === \"string\" ? value.updated_at : null;\n\n if (!id || !workspaceId || !slug || !text || !status || !createdAt || !updatedAt) {\n return null;\n }\n\n return {\n id,\n workspace_id: workspaceId,\n slug,\n text,\n status,\n suggested_agent_slug: parseAgentSlug(value.suggested_agent_slug),\n plan_preview: parsePlanPreview(value.plan_preview),\n approved_at:\n typeof value.approved_at === \"string\" ? value.approved_at : null,\n created_at: createdAt,\n updated_at: updatedAt,\n };\n}\n\nasync function parseResponseBody(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction formatHttpError(status: number, body: unknown): string {\n if (typeof body === \"string\" && body.trim().length > 0) {\n return `HTTP ${status}: ${body}`;\n }\n if (isRecord(body)) {\n // The intents API wraps errors as `{ error: { code, message } }`.\n if (isRecord(body.error)) {\n const message =\n typeof body.error.message === \"string\" ? body.error.message : null;\n const code = typeof body.error.code === \"string\" ? body.error.code : null;\n if (message) return `HTTP ${status} (${code ?? \"error\"}): ${message}`;\n }\n if (typeof body.error === \"string\" && body.error.trim().length > 0) {\n return `HTTP ${status}: ${body.error}`;\n }\n }\n return `HTTP ${status}`;\n}\n\nasync function requireOrgxAuth(options: OrgxIntentsClientOptions = {}) {\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n throw new Error(\n \"No OrgX API key configured. Run `orgx-wizard auth login` or `orgx-wizard auth set-key <oxk_...>` first.\",\n );\n }\n return auth;\n}\n\n/**\n * POST /api/v1/intents — create a pending intent.\n *\n * The server classifies the raw text to an agent slug and generates a plan\n * preview before persisting. The returned `Intent` row carries the slug used\n * for the browser handoff URL (`/command?intent=<slug>`).\n */\nexport async function createIntent(\n input: CreateIntentInput,\n options: OrgxIntentsClientOptions = {},\n): Promise<Intent> {\n const text = input.text.trim();\n if (!text) {\n throw new Error(\"Intent text is required.\");\n }\n if (text.length > 4_000) {\n throw new Error(\"Intent text exceeds 4,000 characters.\");\n }\n\n const workspaceId = input.workspace_id.trim();\n if (!workspaceId) {\n throw new Error(\"Workspace id is required.\");\n }\n\n const auth = await requireOrgxAuth(options);\n const url = buildOrgxApiUrl(\"/v1/intents\", auth.baseUrl);\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ workspace_id: workspaceId, text }),\n signal: AbortSignal.timeout(15_000),\n });\n const body = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new Error(\n `Failed to create intent. ${formatHttpError(response.status, body)}`,\n );\n }\n\n const intent = parseIntent(body);\n if (!intent) {\n throw new Error(\"OrgX returned an unexpected intent payload.\");\n }\n return intent;\n}\n\n/**\n * PATCH /api/v1/intents/:id — transition an intent to approved / adjusted /\n * archived. The hotkey bar uses this for `[A]pprove` and `[X]archive`.\n */\nexport async function updateIntent(\n id: string,\n input: UpdateIntentInput,\n options: OrgxIntentsClientOptions = {},\n): Promise<Intent> {\n const trimmedId = id.trim();\n if (!trimmedId) {\n throw new Error(\"Intent id is required.\");\n }\n\n const auth = await requireOrgxAuth(options);\n const url = buildOrgxApiUrl(`/v1/intents/${encodeURIComponent(trimmedId)}`, auth.baseUrl);\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(input),\n signal: AbortSignal.timeout(15_000),\n });\n const body = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new Error(\n `Failed to update intent. ${formatHttpError(response.status, body)}`,\n );\n }\n\n const intent = parseIntent(body);\n if (!intent) {\n throw new Error(\"OrgX returned an unexpected intent update payload.\");\n }\n return intent;\n}\n\n/**\n * Build the handoff URL for the web composer. Used by the `[E]dit in browser`\n * hotkey and by the approve flow's confirmation line.\n */\nexport function buildIntentHandoffUrl(\n slug: string,\n options: { baseUrl?: string } = {},\n): string {\n const base = options.baseUrl?.trim() || \"https://useorgx.com\";\n const normalized = base.replace(/\\/+$/, \"\");\n return `${normalized}/command?intent=${encodeURIComponent(slug)}`;\n}\n","/**\n * Phase II · M-P5 — Terminal rendering for Surface 3 (CLI Intent capture).\n *\n * Pure, side-effect-free render helpers. The CLI action layer calls these to\n * build strings it then prints — keeping the module testable without stubbing\n * `process.stdout` or picocolors.\n *\n * Style budget comes from the M-P0 design spec:\n * - Agent-colored `→ Agent · Role` routing line (ANSI 256 per-agent)\n * - Mono confidence decimal (never a bucket word)\n * - Box-drawn plan preview — no ASCII art, no drop-shadow-via-shading\n * - `>>` hotkey bar with single-letter verbs `[A]pprove [E]dit [X]archive [Q]uit`\n * - Respect NO_COLOR (fall back to plain ASCII) + CI / non-TTY (skip spinners)\n */\n\nimport {\n AGENT_ANSI_256,\n AGENT_ROLES,\n CONFIDENCE_DECIMAL,\n type AgentSlug,\n type IntentPlanPreview,\n} from \"./intents.js\";\n\nexport interface RenderOptions {\n /** Disable ANSI color output. Derived from NO_COLOR env by default. */\n noColor?: boolean;\n /**\n * Disable unicode box-drawing / glyphs. Falls back to ASCII equivalents —\n * used when the locale cannot represent the characters. Distinct from\n * `noColor`: a truecolor terminal in a plain LC_ALL=C locale wants color on,\n * unicode off.\n */\n asciiOnly?: boolean;\n}\n\n/**\n * Cheap env snapshot so CLI action code can pass the same options to every\n * render helper without repeatedly consulting process.env.\n */\nexport function detectRenderCapabilities(\n env: NodeJS.ProcessEnv = process.env,\n): Required<RenderOptions> {\n const noColor = Boolean(env.NO_COLOR && env.NO_COLOR.length > 0);\n // Many CI runners (`CI=1`) honor NO_COLOR automatically, but some don't.\n // We defer to NO_COLOR for color decisions and only use CI/non-TTY to\n // downgrade motion (see isInteractive).\n const asciiOnly =\n (env.LC_ALL ?? \"\").toUpperCase() === \"C\" ||\n (env.LANG ?? \"\").toUpperCase() === \"C\";\n return { noColor, asciiOnly };\n}\n\n/**\n * Whether the wizard should render motion (spinners, line-by-line stagger).\n * Returns false in CI, when stdout is not a TTY, or when reduced-motion\n * heuristics apply. CLI action code checks this before starting a spinner\n * and prints a plain status line instead.\n */\nexport function isInteractive(\n env: NodeJS.ProcessEnv = process.env,\n isTTY: boolean = Boolean((process.stdout as { isTTY?: boolean }).isTTY),\n): boolean {\n if (!isTTY) return false;\n if (env.CI === \"1\" || env.CI === \"true\") return false;\n // GitHub Actions / Circle / etc. generally set CI; this is belt + suspenders.\n if (env.GITHUB_ACTIONS === \"true\") return false;\n return true;\n}\n\nconst CSI = \"\\u001b[\";\n\nfunction wrap(code: string, text: string, enabled: boolean): string {\n if (!enabled) return text;\n return `${CSI}${code}m${text}${CSI}0m`;\n}\n\nexport function colorize(\n text: string,\n ansi256: number,\n options: RenderOptions = {},\n): string {\n return wrap(`38;5;${ansi256}`, text, !options.noColor);\n}\n\nexport function bold(text: string, options: RenderOptions = {}): string {\n return wrap(\"1\", text, !options.noColor);\n}\n\nexport function dim(text: string, options: RenderOptions = {}): string {\n return wrap(\"2\", text, !options.noColor);\n}\n\n/**\n * Format a confidence decimal with two digits (`0.87`). The design spec locks\n * this to the mono two-digit form; we never emit a bucket word.\n */\nexport function formatConfidence(value: number): string {\n const bounded = Math.max(0, Math.min(1, value));\n return bounded.toFixed(2);\n}\n\n/**\n * `→ Pace · Product confidence 0.87`\n *\n * The agent name is colored via the ANSI 256 directory; the rest of the line\n * stays in default foreground so the eye anchors on the identity. Role comes\n * from AGENT_ROLES so copy is stable across CLI and web.\n */\nexport function renderRoutingLine(\n agent: AgentSlug,\n confidence: number,\n options: RenderOptions = {},\n): string {\n const arrow = options.asciiOnly ? \"->\" : \"→\";\n const separator = options.asciiOnly ? \" - \" : \" · \";\n const role = AGENT_ROLES[agent];\n const name = agent.charAt(0).toUpperCase() + agent.slice(1);\n const coloredName = colorize(name, AGENT_ANSI_256[agent], options);\n const confidenceLabel = dim(\"confidence\", options);\n const confidenceValue = formatConfidence(confidence);\n return ` ${arrow} ${bold(coloredName, options)}${separator}${role} ${confidenceLabel} ${confidenceValue}`;\n}\n\n/**\n * Derive the CLI confidence decimal from the server payload. The M-P2 API\n * returns a bucket (`low | med | high`); the spec requires a decimal on this\n * surface, so we map through a deterministic directory. When a later\n * milestone upgrades the classifier to emit a real score, the CLI can switch\n * to that number without changing the render layer.\n */\nexport function resolveConfidenceDecimal(\n plan: IntentPlanPreview,\n): number {\n return CONFIDENCE_DECIMAL[plan.confidence];\n}\n\n/**\n * Render the box-drawn plan preview block.\n *\n * ┌─ Plan preview ─────────────────────┐\n * │ 1. Draft outreach positioning │\n * │ 2. Build target list (50 accounts) │\n * │ 3. Send first wave this week │\n * │ │\n * │ ETA under a week │\n * └────────────────────────────────────┘\n *\n * No drop shadow, no color fills, no rainbow borders — box-drawing only,\n * per the mediocrity risk call-outs in the spec (\"over-ASCII-art trap\").\n */\nexport function renderPlanPreview(\n plan: IntentPlanPreview,\n options: RenderOptions = {},\n): string {\n const horizontal = options.asciiOnly ? \"-\" : \"─\";\n const topLeft = options.asciiOnly ? \"+\" : \"┌\";\n const topRight = options.asciiOnly ? \"+\" : \"┐\";\n const bottomLeft = options.asciiOnly ? \"+\" : \"└\";\n const bottomRight = options.asciiOnly ? \"+\" : \"┘\";\n const vertical = options.asciiOnly ? \"|\" : \"│\";\n\n const steps = plan.steps.map((step, index) => {\n const number = `${index + 1}.`.padEnd(3, \" \");\n return `${number} ${step.title}`;\n });\n const etaLine = `ETA ${plan.eta}`;\n\n const lines = [...steps, \"\", etaLine];\n const label = \"Plan preview\";\n // Body row format is `│ <content> │` — content gets one space padding on\n // each side, so the inner-content column has width `contentWidth`.\n const contentWidth = Math.max(\n // Keep enough room for the top-chrome label plus its \"─ \" prefix and\n // a minimum trailing dash so the border visually wraps the label.\n label.length + 4,\n ...lines.map((line) => line.length),\n );\n\n // Total horizontal glyph count inside the chrome (matches bottom border).\n const innerWidth = contentWidth + 2; // leading + trailing space per body row\n // Top chrome: \"┌─ Plan preview ─────────────┐\" — same glyph count as bottom.\n const leadingDashes = horizontal.repeat(1);\n const trailingDashes = horizontal.repeat(\n Math.max(1, innerWidth - label.length - 3), // leading dash + 2 spaces\n );\n const top = `${topLeft}${leadingDashes} ${label} ${trailingDashes}${topRight}`;\n\n const body = lines\n .map((line) => {\n const padded = line.padEnd(contentWidth, \" \");\n return `${vertical} ${padded} ${vertical}`;\n })\n .join(\"\\n\");\n\n const bottom = `${bottomLeft}${horizontal.repeat(innerWidth)}${bottomRight}`;\n\n return [top, body, bottom].join(\"\\n\");\n}\n\n/**\n * `>> [A]pprove [E]dit in browser [X]archive [Q]uit`\n *\n * Single-letter hotkeys, mono-spaced, opinionated verb order. Approve is the\n * default. Colors mirror the web token directory: lime for the primary verb,\n * amber for adjust/edit, rose for archive, dim for quit.\n */\nexport interface HotkeyBarEntry {\n key: string;\n label: string;\n tone?: \"primary\" | \"warning\" | \"danger\" | \"neutral\";\n}\n\nconst TONE_ANSI: Record<NonNullable<HotkeyBarEntry[\"tone\"]>, number> = {\n primary: 190, // lime (--ox-primary)\n warning: 214, // amber (adjust)\n danger: 203, // rose (archive)\n neutral: 244, // bright black (quit)\n};\n\nexport function renderHotkeyBar(\n entries: HotkeyBarEntry[],\n options: RenderOptions = {},\n): string {\n const prefix = options.asciiOnly ? \">>\" : \">>\";\n const segments = entries.map((entry) => {\n const tone = entry.tone ?? \"neutral\";\n const keyLabel = `[${entry.key.toUpperCase()}]`;\n const coloredKey = colorize(keyLabel, TONE_ANSI[tone], options);\n return `${coloredKey}${entry.label}`;\n });\n return `${prefix} ${segments.join(\" \")}`;\n}\n\nexport const DEFAULT_HOTKEYS: HotkeyBarEntry[] = [\n { key: \"a\", label: \"pprove\", tone: \"primary\" },\n { key: \"e\", label: \"dit in browser\", tone: \"warning\" },\n { key: \"x\", label: \"archive\", tone: \"danger\" },\n { key: \"q\", label: \"uit\", tone: \"neutral\" },\n];\n\n/**\n * Normalize a keystroke to one of the hotkey verbs. Returns `null` for\n * ignored keys (CLI re-prompts instead of misinterpreting ambiguous input).\n */\nexport type IntentAction = \"approve\" | \"edit\" | \"archive\" | \"quit\";\n\nexport function normalizeHotkey(input: string): IntentAction | null {\n const trimmed = input.trim().toLowerCase();\n if (trimmed.length === 0) return null;\n const ch = trimmed.charAt(0);\n switch (ch) {\n case \"a\":\n return \"approve\";\n case \"e\":\n return \"edit\";\n case \"x\":\n return \"archive\";\n case \"q\":\n return \"quit\";\n default:\n return null;\n }\n}\n","import {\n buildOrgxApiUrl,\n resolveOrgxAuth,\n type ResolveOrgxAuthOptions,\n} from \"./auth.js\";\nimport type { OrgxWorkspace } from \"./workspaces.js\";\nimport {\n getDailyBriefOnboardingDecision,\n recordDailyBriefOnboardingDecision,\n} from \"./wizard-state.js\";\n\n/**\n * Pull a short, user-readable hint out of an HTTP error body. Handles the\n * three shapes the orgx backend emits:\n * { error: \"string\" }\n * { error: { code?, message? } }\n * { error: \"...\", details: { fieldErrors?: {...} } }\n * Falls back to null if nothing useful is present (caller uses `HTTP NNN`).\n */\nfunction extractErrorHint(body: string): string | null {\n if (!body) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return body.slice(0, 160);\n }\n if (!parsed || typeof parsed !== \"object\") return null;\n const obj = parsed as Record<string, unknown>;\n const err = obj.error;\n if (typeof err === \"string\") return err;\n if (err && typeof err === \"object\") {\n const message = (err as Record<string, unknown>).message;\n if (typeof message === \"string\") return message;\n const code = (err as Record<string, unknown>).code;\n if (typeof code === \"string\") return code;\n }\n return null;\n}\n\n/**\n * Daily Brief + Trust Loop — wizard onboarding capture.\n *\n * Mirrors the web OnboardingCaptureScreen component at four steps:\n * Step A — agent roster preview (defaults, no customization in CLI for v1)\n * Step B — baseline prompts for task-type minutes\n * Step C — optional weekly time-saved goal\n * Step D — send-time preference (local time + timezone auto-detected)\n *\n * Commits atomically via POST /api/v1/onboarding/daily-brief.\n *\n * Gated on GET /api/v1/onboarding/daily-brief returning\n * workspaces[n].onboardingCompletedAt IS NULL — existing paired users\n * (v0.1.16 fast-path) skip unless they've never completed the capture.\n */\n\nexport interface DailyBriefOnboardingPrompts {\n cancel(message: string): void;\n isCancel(value: unknown): boolean;\n text(input: {\n initialValue?: string | undefined;\n message: string;\n placeholder?: string;\n validate?: (value: string | undefined) => Error | string | undefined;\n }): Promise<string | symbol>;\n select(input: {\n initialValue?: string | undefined;\n message: string;\n options: { label: string; value: string; hint?: string }[];\n }): Promise<string | symbol>;\n confirm(input: { message: string; initialValue?: boolean }): Promise<boolean | symbol>;\n}\n\nexport interface DailyBriefOnboardingOptions {\n authOptions?: ResolveOrgxAuthOptions;\n force?: boolean;\n interactive: boolean;\n skip?: boolean;\n statePath?: string;\n workspace: OrgxWorkspace | null;\n prompts: DailyBriefOnboardingPrompts;\n}\n\nexport interface DailyBriefOnboardingResult {\n status:\n | \"completed\"\n | \"skipped_non_interactive\"\n | \"skipped_already_completed\"\n | \"skipped_no_workspace\"\n | \"skipped_user\"\n | \"cancelled\"\n | \"failed\";\n message: string;\n previewUrl?: string;\n error?: string;\n}\n\ninterface BaselinePrompt {\n task_type: string;\n label: string;\n placeholder: string;\n}\n\nconst BASELINE_PROMPTS: BaselinePrompt[] = [\n { task_type: \"code_review\", label: \"Code review\", placeholder: \"20\" },\n { task_type: \"prd_draft\", label: \"PRD draft\", placeholder: \"45\" },\n { task_type: \"test_writeup\", label: \"Test writeup\", placeholder: \"25\" },\n { task_type: \"pr_description\", label: \"PR description\", placeholder: \"10\" },\n { task_type: \"launch_post\", label: \"Launch post\", placeholder: \"60\" },\n { task_type: \"architecture_doc\", label: \"Architecture doc\", placeholder: \"90\" },\n];\n\nconst DAILY_BRIEF_SETUP_CHOICES = {\n defaults: \"defaults\",\n customize: \"customize\",\n skip: \"skip\",\n} as const;\n\nfunction buildDefaultBaselines(): { task_type: string; minutes: number; confidence: number }[] {\n return BASELINE_PROMPTS.map((bp) => ({\n task_type: bp.task_type,\n minutes: Number.parseInt(bp.placeholder, 10),\n confidence: 0.4,\n }));\n}\n\nfunction buildDefaultGoals(): {\n goal_type: \"time_saved_weekly\";\n target_value: number;\n unit: string;\n period: \"weekly\";\n}[] {\n return [\n {\n goal_type: \"time_saved_weekly\",\n target_value: 180,\n unit: \"minutes\",\n period: \"weekly\",\n },\n ];\n}\n\nfunction normalizeSendTime(value: string): string {\n return value.trim().length === 4 ? `0${value.trim()}` : value.trim();\n}\n\nfunction recordSkipped(\n workspace: OrgxWorkspace,\n statePath?: string,\n): DailyBriefOnboardingResult {\n recordDailyBriefOnboardingDecision(\n {\n workspaceId: workspace.id,\n workspaceName: workspace.name,\n status: \"skipped\",\n skippedAt: new Date().toISOString(),\n },\n statePath,\n );\n return {\n status: \"skipped_user\",\n message: \"Daily Brief setup skipped. Run `wizard setup --daily-brief` when ready.\",\n };\n}\n\nexport async function runDailyBriefOnboarding(\n options: DailyBriefOnboardingOptions,\n): Promise<DailyBriefOnboardingResult> {\n if (!options.workspace) {\n return {\n status: \"skipped_no_workspace\",\n message: \"Daily Brief onboarding skipped — no workspace resolved.\",\n };\n }\n\n if (options.skip) {\n return recordSkipped(options.workspace, options.statePath);\n }\n\n const localDecision = getDailyBriefOnboardingDecision(\n options.workspace.id,\n options.statePath,\n );\n if (!options.force && localDecision) {\n return {\n status: \"skipped_already_completed\",\n message:\n localDecision.status === \"completed\"\n ? \"Daily Brief onboarding already completed for this workspace.\"\n : \"Daily Brief setup was skipped for this workspace. Run `wizard setup --daily-brief` to configure.\",\n };\n }\n\n if (!options.interactive) {\n return {\n status: \"skipped_non_interactive\",\n message: \"Daily Brief onboarding skipped — not attached to a TTY.\",\n };\n }\n\n const auth = await resolveOrgxAuth(options.authOptions);\n if (!auth) {\n return {\n status: \"failed\",\n message: \"Daily Brief onboarding needs OrgX auth.\",\n error: \"no_auth\",\n };\n }\n\n // Gate: is this workspace already onboarded?\n const state = await fetchOnboardingState(auth).catch(() => null);\n if (state) {\n const row = state.workspaces.find((w) => w.id === options.workspace!.id);\n if (row?.onboardingCompletedAt) {\n recordDailyBriefOnboardingDecision(\n {\n workspaceId: options.workspace.id,\n workspaceName: options.workspace.name,\n status: \"completed\",\n completedAt: row.onboardingCompletedAt,\n },\n options.statePath,\n );\n return {\n status: \"skipped_already_completed\",\n message: \"Daily Brief onboarding already completed for this workspace.\",\n };\n }\n }\n\n const { prompts } = options;\n\n const setupChoice = await prompts.select({\n message: \"Set up Daily Brief now?\",\n initialValue: DAILY_BRIEF_SETUP_CHOICES.defaults,\n options: [\n {\n value: DAILY_BRIEF_SETUP_CHOICES.defaults,\n label: \"Use defaults\",\n hint: \"20m code review, 45m PRD, 07:00 daily.\",\n },\n {\n value: DAILY_BRIEF_SETUP_CHOICES.customize,\n label: \"Customize baselines\",\n hint: \"Answer baseline and delivery questions.\",\n },\n {\n value: DAILY_BRIEF_SETUP_CHOICES.skip,\n label: \"Skip and remember\",\n hint: \"Do not ask again unless you pass --daily-brief.\",\n },\n ],\n });\n if (prompts.isCancel(setupChoice)) {\n return { status: \"cancelled\", message: \"Daily Brief onboarding cancelled.\" };\n }\n if (setupChoice === DAILY_BRIEF_SETUP_CHOICES.skip) {\n return recordSkipped(options.workspace, options.statePath);\n }\n\n const shouldCustomize = setupChoice === DAILY_BRIEF_SETUP_CHOICES.customize;\n\n const baselines: { task_type: string; minutes: number; confidence: number }[] =\n shouldCustomize ? [] : buildDefaultBaselines();\n if (shouldCustomize) {\n for (const bp of BASELINE_PROMPTS) {\n const answer = await prompts.text({\n message: `${bp.label} minutes`,\n placeholder: bp.placeholder,\n validate(value) {\n if (!value || value.trim() === \"\") return undefined;\n const n = Number.parseInt(value, 10);\n if (!Number.isFinite(n) || n <= 0 || n > 24 * 60) {\n return \"Enter 1-1440 or leave blank.\";\n }\n return undefined;\n },\n });\n if (prompts.isCancel(answer)) {\n return { status: \"cancelled\", message: \"Daily Brief onboarding cancelled.\" };\n }\n if (typeof answer === \"string\" && answer.trim() !== \"\") {\n const minutes = Number.parseInt(answer, 10);\n if (Number.isFinite(minutes) && minutes > 0) {\n baselines.push({ task_type: bp.task_type, minutes, confidence: 0.5 });\n }\n }\n }\n }\n\n const goals: {\n goal_type: \"time_saved_weekly\";\n target_value: number;\n unit: string;\n period: \"weekly\";\n }[] = shouldCustomize ? [] : buildDefaultGoals();\n if (shouldCustomize) {\n const goalAnswer = await prompts.text({\n message: \"Weekly time-saved target minutes\",\n placeholder: \"180\",\n validate(value) {\n if (!value || value.trim() === \"\") return undefined;\n const n = Number.parseInt(value, 10);\n if (!Number.isFinite(n) || n <= 0) {\n return \"Enter a positive number or leave blank.\";\n }\n return undefined;\n },\n });\n if (prompts.isCancel(goalAnswer)) {\n return { status: \"cancelled\", message: \"Daily Brief onboarding cancelled.\" };\n }\n if (typeof goalAnswer === \"string\" && goalAnswer.trim() !== \"\") {\n const target = Number.parseInt(goalAnswer, 10);\n if (Number.isFinite(target) && target > 0) {\n goals.push({\n goal_type: \"time_saved_weekly\",\n target_value: target,\n unit: \"minutes\",\n period: \"weekly\",\n });\n }\n }\n }\n\n let sendTimeLocal = \"07:00\";\n let onlyOnAttention = false;\n if (shouldCustomize) {\n const sendTimeAnswer = await prompts.text({\n message: \"Daily brief time (HH:MM)\",\n placeholder: \"07:00\",\n validate(value) {\n if (!value || value.trim() === \"\") return undefined;\n if (!/^\\d{1,2}:\\d{2}$/.test(value.trim())) {\n return \"Use HH:MM (24h).\";\n }\n return undefined;\n },\n });\n if (prompts.isCancel(sendTimeAnswer)) {\n return { status: \"cancelled\", message: \"Daily Brief onboarding cancelled.\" };\n }\n sendTimeLocal =\n typeof sendTimeAnswer === \"string\" && sendTimeAnswer.trim()\n ? normalizeSendTime(sendTimeAnswer)\n : \"07:00\";\n\n const onlyOnAttentionAnswer = await prompts.confirm({\n message: \"Email only when attention is needed?\",\n initialValue: false,\n });\n if (prompts.isCancel(onlyOnAttentionAnswer)) {\n return { status: \"cancelled\", message: \"Daily Brief onboarding cancelled.\" };\n }\n onlyOnAttention = Boolean(onlyOnAttentionAnswer);\n }\n\n // Commit\n const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n\n const commitPayload = {\n workspace_id: options.workspace.id,\n agent_roster: [\n { id: \"engineering-agent\", display_name: \"Eli\", color: \"6, 182, 212\", enabled: true },\n { id: \"product-agent\", display_name: \"Pace\", color: \"22, 163, 74\", enabled: true },\n { id: \"marketing-agent\", display_name: \"Mark\", color: \"249, 115, 22\", enabled: true },\n { id: \"orchestrator-agent\", display_name: \"Xandy\", color: \"20, 184, 166\", enabled: true },\n ],\n baselines,\n goals,\n starter_skill_loadouts: [],\n notification_preference: {\n channel: \"email\" as const,\n digest_kind: \"daily_brief\" as const,\n enabled: true,\n send_time_local: `${sendTimeLocal}:00`,\n timezone,\n only_on_attention: onlyOnAttention,\n },\n };\n\n const commitResponse = await fetch(buildOrgxApiUrl(\"/v1/onboarding/daily-brief\", auth.baseUrl), {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(commitPayload),\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!commitResponse.ok) {\n const text = await commitResponse.text().catch(() => \"\");\n const hint = extractErrorHint(text) ?? `HTTP ${commitResponse.status}`;\n return {\n status: \"failed\",\n message: `Could not commit onboarding capture — ${hint}`,\n error: `HTTP ${commitResponse.status}: ${text.slice(0, 200)}`,\n };\n }\n\n const commitBody = (await commitResponse.json().catch(() => ({}))) as {\n daily_brief_preview_url?: unknown;\n };\n const previewUrl =\n typeof commitBody.daily_brief_preview_url === \"string\"\n ? commitBody.daily_brief_preview_url\n : \"/today?mode=preview\";\n recordDailyBriefOnboardingDecision(\n {\n workspaceId: options.workspace.id,\n workspaceName: options.workspace.name,\n status: \"completed\",\n completedAt: new Date().toISOString(),\n },\n options.statePath,\n );\n return {\n status: \"completed\",\n message: \"Your Daily Brief is configured. First brief lands tomorrow.\",\n previewUrl,\n };\n}\n\ninterface OnboardingStateResponse {\n ok: boolean;\n workspaces: Array<{\n id: string;\n name: string;\n onboardingCompletedAt: string | null;\n }>;\n}\n\nasync function fetchOnboardingState(\n auth: { apiKey: string; baseUrl: string },\n): Promise<OnboardingStateResponse | null> {\n try {\n const res = await fetch(\n buildOrgxApiUrl(\"/v1/onboarding/daily-brief\", auth.baseUrl),\n {\n method: \"GET\",\n headers: { Authorization: `Bearer ${auth.apiKey}` },\n signal: AbortSignal.timeout(5_000),\n },\n );\n if (!res.ok) return null;\n const body = (await res.json()) as OnboardingStateResponse;\n if (!body || !Array.isArray(body.workspaces)) return null;\n return body;\n } catch {\n return null;\n }\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, join, relative } from \"node:path\";\n\nimport { CLAUDE_PROJECTS_DIR, CODEX_SESSIONS_DIR } from \"../constants.js\";\nimport { isRecord } from \"./fs.js\";\nimport type { FounderLoopImport } from \"./self-audit.js\";\n\nexport const AI_SESSION_SOURCES = [\"codex\", \"claude\"] as const;\n\nexport type AiSessionSource = (typeof AI_SESSION_SOURCES)[number];\n\nexport interface LoadAiSessionImportsOptions {\n claudeProjectsDir?: string;\n codexSessionsDir?: string;\n limitPerSource?: number;\n maxBytesPerFile?: number;\n now?: Date;\n sinceDays?: number;\n sources: readonly AiSessionSource[];\n}\n\nexport interface LoadAiSessionImportsResult {\n connectedSources: string[];\n imports: FounderLoopImport[];\n missingSources: string[];\n scannedFiles: number;\n skippedFiles: number;\n}\n\ninterface CandidateFile {\n mtimeMs: number;\n path: string;\n source: AiSessionSource;\n}\n\nconst DEFAULT_LIMIT_PER_SOURCE = 3;\nconst DEFAULT_SINCE_DAYS = 30;\nconst DEFAULT_MAX_BYTES_PER_FILE = 1_000_000;\nconst AUDIT_RELEVANT_LINE_PATTERN =\n /\\b(decision|decided|artifact|receipt|proof|commitment|committed|next action|follow[- ]?up|outcome|result|impact|roi|economics|token|cost|saved|open loop|gap|blocker|risk|owner|dri|writeback|rollback|quality score|mcp|tool call|orgx_emit_activity|orgx_apply_changeset|complete_with_proof|scaffold_initiative|mcp__orgx__)\\b/i;\nconst STRONG_AUDIT_LINE_PATTERN =\n /^(?:[-*]\\s*)?(?:decision|artifact|receipt|proof|commitment|next action|follow[- ]?up|outcome|result|impact|roi|economics|open loop|gap|blocker|risk|owner|dri|rollback|quality score)\\s*:/i;\nconst ORGX_TOOL_SIGNAL_PATTERN =\n /\\b(?:mcp__orgx__|orgx_emit_activity|orgx_apply_changeset|complete_with_proof|scaffold_initiative|get_task_with_context|ship_batch|record_outcome|orgx_free_audit)\\b/i;\nconst INSTRUCTION_BOILERPLATE_PATTERN =\n /^(?:#{1,6}\\s*)?(?:agents\\.md|instructions?|codex guardrails|precedence|read before you write|use exactly what was specified|don'?t confuse technologies|repo \\+ scope hygiene|initiative \\/ mcp discipline|ui quality bar|verification standards|secrets \\+ safety|patch\\/editing rules|commit \\/ pr \\/ merge protocol|output style|mcp integration|agent domains|skills|conventions)\\b/i;\nconst IMPERATIVE_BOILERPLATE_PATTERN =\n /^[-*]\\s+(?:if the user|when the user|if mcp|when agents|never|always|do not|don'?t|default to|treat|produce|pick|verify|avoid|match|use exactly|keep system boundaries|quote bracketed|for orgx|when capture tooling|if no meaningful|do \\*\\*not\\*\\*)\\b/i;\nconst CODE_OR_DOC_NOISE_PATTERN =\n /^(?:[-*]\\s*)?(?:https?:\\/\\/|\\/|\\.{0,2}\\/|[A-Za-z]:\\/|`{1,3}|\"{1,2}[A-Za-z0-9:_-]+\":|\\d+\\s*$|\\d+\\t|import\\s|export\\s|const\\s|let\\s|var\\s|function\\s|type\\s|interface\\s|CREATE\\s+TABLE|ALTER\\s+TABLE|SELECT\\s+|INSERT\\s+|UPDATE\\s+|DELETE\\s+)/i;\nconst EMPTY_AUDIT_LABEL_PATTERN =\n /^(?:[-*]\\s*)?(?:decision|artifact|receipt|proof|commitment|next action|follow[- ]?up|outcome|result|impact|roi|economics|open loop|gap|blocker|risk|owner|dri|rollback|quality score)\\s*:\\s*[\\[{(;,]*$/i;\nconst TYPE_SIGNATURE_NOISE_PATTERN =\n /^(?:[-*]\\s*)?(?:decision|artifact|receipt|proof|commitment|next action|follow[- ]?up|outcome|result|impact|roi|economics|open loop|gap|blocker|risk|owner|dri|rollback|quality score)\\s*:\\s*[A-Za-z_$][\\w$]*(?:<[^>]+>)?[\\s,;)]*$/i;\nconst TOOL_CATALOG_NOISE_PATTERN =\n /^(?:[-*]\\s*)?(?:[a-z][\\w.:-]*\\s*\\([^)]+\\),?\\s*){2,}$/i;\nconst BARE_TOOL_SIGNAL_PATTERN =\n /^(?:\\d+\\.\\s*|[-*]\\s*)?(?:mcp__orgx__[\\w-]*|orgx_emit_activity|orgx_apply_changeset|complete_with_proof|scaffold_initiative|get_task_with_context|ship_batch|record_outcome|orgx_free_audit)\\s*$/i;\nconst TOOL_QUESTION_NOISE_PATTERN =\n /^(?:\\d+\\.\\s*)?\\*\\*[^*]+\\*\\*.*\\?\\s*(?:\\([^)]*\\b(?:mcp|scaffold_initiative|start_plan_session)\\b[^)]*\\)\\.?)?$/i;\nconst SOURCE_REFERENCE_NOISE_PATTERN =\n /(?:^|\\s)(?:\\.{0,2}\\/)?(?:orgx|src|lib|workers|public|scripts|tests|apps|packages)\\/[\\w./-]+\\.(?:ts|tsx|js|jsx|json|md|txt|sql|py)(?::\\d+)?\\b/i;\nconst FILE_REFERENCE_NOISE_PATTERN =\n /\\b[\\w.-]+\\.(?:ts|tsx|js|jsx|json|md|txt|sql|py)(?::\\d+(?:[–-]\\d+)?)?\\b/i;\nconst LOCAL_ASSET_REFERENCE_PATTERN =\n /(?:<BlogImage\\b|source:\\s*\\/Users\\/|\\/blog\\/[\\w./-]+\\.(?:png|jpg|jpeg|webp|gif))/i;\nconst LINE_NUMBER_SOURCE_NOISE_PATTERN =\n /^\\d+(?::|\\s+)\\s*/i;\nconst TOOL_WORKFLOW_NOISE_PATTERN =\n /(?:→|->).*\\b(?:scaffold_initiative|spawn_agent_task|record_outcome|submit_learning|get_outcome_attribution|mcp__orgx__)\\b/i;\nconst TOOL_FAILURE_PATTERN =\n /^(?:\\d+\\.\\s*)?(?:mcp__orgx__[\\w-]*|orgx_emit_activity|orgx_apply_changeset|complete_with_proof|scaffold_initiative|get_task_with_context|ship_batch|record_outcome|orgx_free_audit)\\b.*\\b(?:rejected|requires|failed|fails|error|invalid|unavailable|timeout|timed out|not\\s+(?:called|dispatched|wired|created|available)|missing|broken)\\b/i;\nconst RUNTIME_FAILURE_PATTERN =\n /\\b(?:mcp__orgx__[\\w-]*|orgx_emit_activity|orgx_apply_changeset|complete_with_proof|scaffold_initiative|get_task_with_context|ship_batch|record_outcome|submit_learning|spawn_agent_task|agent run)\\b.*\\b(?:rejected|requires|failed|fails|error|invalid|unavailable|timeout|timed out|never|no\\s+\\w+|not\\s+(?:called|dispatched|wired|created|available|append)|missing|broken|only\\s+in\\s+agent\\s+skill\\s+prompts)\\b/i;\nconst PROCESS_NARRATION_NOISE_PATTERN =\n /^(?:now i\\b|let me\\b|i (?:have|need|will|can)\\b|i['’]ll\\b|i['’]m\\b|so\\b.*\\b(?:confirm|check|verify|fetches)\\b)/i;\n\nexport function parseAiSessionSources(value?: string): AiSessionSource[] {\n if (!value?.trim()) return [];\n\n const requested = value\n .split(\",\")\n .map((item) => item.trim().toLowerCase())\n .filter(Boolean);\n const expanded = requested.includes(\"all\") ? [...AI_SESSION_SOURCES] : requested;\n const deduped = [...new Set(expanded)];\n const invalid = deduped.filter((source) => !AI_SESSION_SOURCES.includes(source as AiSessionSource));\n if (invalid.length > 0) {\n throw new Error(`Unsupported AI-session source: ${invalid.join(\", \")}. Use codex, claude, or all.`);\n }\n\n return deduped as AiSessionSource[];\n}\n\nfunction parseJsonLine(line: string): unknown {\n try {\n return JSON.parse(line);\n } catch {\n return null;\n }\n}\n\nfunction asText(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) {\n return value\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (!isRecord(item)) return \"\";\n if (typeof item.text === \"string\") return item.text;\n if (typeof item.content === \"string\") return item.content;\n return \"\";\n })\n .filter(Boolean)\n .join(\"\\n\");\n }\n if (isRecord(value) && typeof value.text === \"string\") return value.text;\n return \"\";\n}\n\nfunction stringFromRecord(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key];\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction numberFromRecord(record: Record<string, unknown>, key: string): number | undefined {\n const value = record[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction normalizeJsonAuditLine(line: string): string | null {\n if (!line.startsWith(\"{\")) return null;\n\n const parsed = parseJsonLine(line);\n if (!isRecord(parsed)) return null;\n\n const summary = stringFromRecord(parsed, \"summary\");\n const stats = isRecord(parsed.summary_stats) ? parsed.summary_stats : undefined;\n const requestedCount = stats ? numberFromRecord(stats, \"requested_count\") : undefined;\n const createdCount = stats ? numberFromRecord(stats, \"created_count\") : undefined;\n const failedCount = stats ? numberFromRecord(stats, \"failed_count\") : undefined;\n\n const hierarchy = isRecord(parsed.hierarchy) ? parsed.hierarchy : undefined;\n const initiative = hierarchy && isRecord(hierarchy.initiative) ? hierarchy.initiative : undefined;\n const initiativeTitle = initiative ? stringFromRecord(initiative, \"title\") ?? stringFromRecord(initiative, \"name\") : undefined;\n const initiativeError = initiative ? stringFromRecord(initiative, \"error\") : undefined;\n\n if (\n summary &&\n requestedCount !== undefined &&\n createdCount !== undefined &&\n failedCount !== undefined &&\n /\\bcreated\\b/i.test(summary)\n ) {\n const titleSuffix = initiativeTitle ? ` for ${initiativeTitle}` : \"\";\n const errorSuffix = initiativeError ? `; ${initiativeError.replace(/\\.+$/, \"\")}` : \"\";\n if (failedCount > 0) {\n return `Blocker: OrgX scaffold created ${createdCount}/${requestedCount} entities${titleSuffix}${errorSuffix}.`;\n }\n return `Artifact: OrgX scaffold created ${createdCount}/${requestedCount} entities${titleSuffix}.`;\n }\n\n return null;\n}\n\nfunction normalizeAuditRelevantLine(line: string): string | null {\n const trimmed = line.trim();\n if (!trimmed) return null;\n\n const jsonLine = normalizeJsonAuditLine(trimmed);\n if (jsonLine) return jsonLine;\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) return null;\n\n if (SOURCE_REFERENCE_NOISE_PATTERN.test(trimmed)) return null;\n if (FILE_REFERENCE_NOISE_PATTERN.test(trimmed)) return null;\n if (LOCAL_ASSET_REFERENCE_PATTERN.test(trimmed)) return null;\n if (LINE_NUMBER_SOURCE_NOISE_PATTERN.test(trimmed)) return null;\n if (/^audit\\s+\\/Users\\//i.test(trimmed)) return null;\n if (/^#{1,6}\\s/.test(trimmed)) return null;\n if (PROCESS_NARRATION_NOISE_PATTERN.test(trimmed)) return null;\n if (/^(?:\\d+\\.\\s*)?(?:[-*]\\s*)?(?:\\*\\*)?\\b(?:integration gaps|gaps between)\\b/i.test(trimmed)) return null;\n if (/^\\s*[-*]\\s+the `?orgx`? mcp tools listed/i.test(trimmed)) return null;\n if (TOOL_WORKFLOW_NOISE_PATTERN.test(trimmed)) return null;\n\n const toolFailure = trimmed.match(TOOL_FAILURE_PATTERN);\n if (toolFailure) {\n return `Blocker: ${trimmed.replace(/^\\d+\\.\\s*/, \"\")}`;\n }\n if (RUNTIME_FAILURE_PATTERN.test(trimmed)) {\n const label = /^no programmatic\\b/i.test(trimmed) ? \"Gap\" : \"Blocker\";\n return `${label}: ${trimmed.replace(/^\\d+\\.\\s*/, \"\")}`;\n }\n\n if (!AUDIT_RELEVANT_LINE_PATTERN.test(trimmed)) return null;\n if (!STRONG_AUDIT_LINE_PATTERN.test(trimmed) && !ORGX_TOOL_SIGNAL_PATTERN.test(trimmed)) return null;\n if (INSTRUCTION_BOILERPLATE_PATTERN.test(trimmed)) return null;\n if (IMPERATIVE_BOILERPLATE_PATTERN.test(trimmed)) return null;\n if (CODE_OR_DOC_NOISE_PATTERN.test(trimmed)) return null;\n if (EMPTY_AUDIT_LABEL_PATTERN.test(trimmed)) return null;\n if (TYPE_SIGNATURE_NOISE_PATTERN.test(trimmed)) return null;\n if (TOOL_CATALOG_NOISE_PATTERN.test(trimmed)) return null;\n if ((trimmed.match(/\\b[a-z][\\w.:-]*\\s*\\([^)]+\\)/g) ?? []).length >= 2) return null;\n if (BARE_TOOL_SIGNAL_PATTERN.test(trimmed)) return null;\n if (TOOL_QUESTION_NOISE_PATTERN.test(trimmed)) return null;\n if (/^[-*]\\s+all agents\\b/i.test(trimmed)) return null;\n\n return trimmed;\n}\n\nfunction extractCodexMessageText(record: unknown): string {\n if (!isRecord(record) || record.type !== \"response_item\" || !isRecord(record.payload)) {\n return \"\";\n }\n\n const payload = record.payload;\n if (payload.type !== \"message\" || (payload.role !== \"user\" && payload.role !== \"assistant\")) {\n return \"\";\n }\n\n return asText(payload.content);\n}\n\nfunction extractClaudeMessageText(record: unknown): string {\n if (!isRecord(record) || record.isMeta === true || !isRecord(record.message)) {\n return \"\";\n }\n\n const message = record.message;\n if (message.role !== \"user\" && message.role !== \"assistant\") {\n return \"\";\n }\n\n const text = asText(message.content);\n if (/^<local-command-caveat>/i.test(text.trim())) return \"\";\n return text;\n}\n\nfunction keepAuditRelevantLines(text: string): string[] {\n return text\n .split(/\\r?\\n/)\n .map((line) => normalizeAuditRelevantLine(line))\n .filter((line): line is string => Boolean(line));\n}\n\nfunction collectJsonlFiles(root: string, source: AiSessionSource): CandidateFile[] {\n if (!existsSync(root)) return [];\n\n const files: CandidateFile[] = [];\n const stack = [root];\n\n while (stack.length > 0) {\n const current = stack.pop();\n if (!current) continue;\n\n let entries: string[];\n try {\n entries = readdirSync(current);\n } catch {\n continue;\n }\n\n for (const entry of entries) {\n const path = join(current, entry);\n let stats;\n try {\n stats = statSync(path);\n } catch {\n continue;\n }\n\n if (stats.isDirectory()) {\n stack.push(path);\n continue;\n }\n if (stats.isFile() && path.endsWith(\".jsonl\")) {\n files.push({ mtimeMs: stats.mtimeMs, path, source });\n }\n }\n }\n\n return files;\n}\n\nfunction readSessionImport(\n candidate: CandidateFile,\n root: string,\n options: {\n maxBytesPerFile: number;\n },\n): FounderLoopImport | null {\n let stats;\n try {\n stats = statSync(candidate.path);\n } catch {\n return null;\n }\n if (stats.size > options.maxBytesPerFile) return null;\n\n const extractor = candidate.source === \"codex\" ? extractCodexMessageText : extractClaudeMessageText;\n const lines = readFileSync(candidate.path, \"utf8\").split(/\\r?\\n/);\n const relevantLines: string[] = [];\n\n for (const line of lines) {\n const record = parseJsonLine(line);\n const text = extractor(record);\n if (!text) continue;\n relevantLines.push(...keepAuditRelevantLines(text));\n }\n\n const deduped = [...new Set(relevantLines)].slice(0, 80);\n if (deduped.length === 0) return null;\n\n const relativePath = relative(root, candidate.path);\n return {\n sourceId: `${candidate.source}:${basename(candidate.path, \".jsonl\")}`,\n sourceLabel: `${candidate.source === \"codex\" ? \"Codex\" : \"Claude\"} session ${relativePath}`,\n text: deduped.join(\"\\n\"),\n };\n}\n\nexport function loadAiSessionImports(options: LoadAiSessionImportsOptions): LoadAiSessionImportsResult {\n const now = options.now ?? new Date();\n const sinceMs = now.getTime() - (options.sinceDays ?? DEFAULT_SINCE_DAYS) * 24 * 60 * 60 * 1000;\n const limitPerSource = Math.max(1, options.limitPerSource ?? DEFAULT_LIMIT_PER_SOURCE);\n const maxBytesPerFile = Math.max(1, options.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE);\n const roots: Record<AiSessionSource, string> = {\n claude: options.claudeProjectsDir ?? CLAUDE_PROJECTS_DIR,\n codex: options.codexSessionsDir ?? CODEX_SESSIONS_DIR,\n };\n const imports: FounderLoopImport[] = [];\n const connectedSources: string[] = [];\n const missingSources: string[] = [];\n let scannedFiles = 0;\n let skippedFiles = 0;\n\n for (const source of options.sources) {\n const root = roots[source];\n const candidates = collectJsonlFiles(root, source)\n .filter((file) => file.mtimeMs >= sinceMs)\n .sort((a, b) => b.mtimeMs - a.mtimeMs);\n\n if (candidates.length === 0) {\n missingSources.push(`${source} session store`);\n continue;\n }\n\n let importedForSource = 0;\n for (const candidate of candidates) {\n if (importedForSource >= limitPerSource) break;\n scannedFiles += 1;\n\n const imported = readSessionImport(candidate, root, { maxBytesPerFile });\n if (!imported) {\n skippedFiles += 1;\n continue;\n }\n\n imports.push(imported);\n importedForSource += 1;\n }\n\n if (importedForSource > 0) {\n connectedSources.push(`${source === \"codex\" ? \"Codex\" : \"Claude\"} local sessions`);\n } else {\n missingSources.push(`${source} audit-relevant session lines`);\n }\n }\n\n return {\n connectedSources,\n imports,\n missingSources,\n scannedFiles,\n skippedFiles,\n };\n}\n","import { createHash } from \"node:crypto\";\n\nimport { buildOrgxApiUrl, normalizeOrgxBaseUrl, resolveOrgxAuth, type ResolveOrgxAuthOptions } from \"./auth.js\";\nimport { isRecord } from \"./fs.js\";\n\nexport const SELF_AUDIT_SCHEMA_VERSION = \"2026-04-27\" as const;\n\nexport const AUDIT_DIMENSIONS = [\n \"queryability\",\n \"proof_density\",\n \"loop_closure\",\n \"context_debt\",\n \"autonomy_readiness\",\n \"roi_visibility\",\n] as const;\n\nexport type AuditDimension = (typeof AUDIT_DIMENSIONS)[number];\n\nexport type FounderLoopItemType =\n | \"decision\"\n | \"commitment\"\n | \"artifact\"\n | \"open_loop\"\n | \"next_action\"\n | \"outcome\"\n | \"economics\";\n\nexport interface AuditWorkspaceRef {\n id: string;\n name: string;\n}\n\nexport interface FounderLoopImport {\n sourceId: string;\n sourceLabel: string;\n text: string;\n}\n\nexport interface FounderLoopItem {\n type: FounderLoopItemType;\n text: string;\n sourceId: string;\n sourceLabel: string;\n evidenceRef: string;\n lineNumber: number;\n}\n\nexport interface SelfAuditSignals {\n approvedWritebackTargets: number;\n artifactsWithNextActions: number;\n artifactsWithOwners: number;\n completedWorkItems: number;\n completedWorkWithProof: number;\n connectedSources: number;\n decisionsWithEvidence: number;\n economicSignals: number;\n missingSources: number;\n openLoops: number;\n outcomeLinkedItems: number;\n repeatedContextPrompts: number;\n totalArtifacts: number;\n totalContextItems: number;\n totalDecisions: number;\n unresolvedCommitments: number;\n}\n\nexport type AuditScores = Record<AuditDimension, number>;\n\nexport interface AuditFinding {\n dimension: AuditDimension;\n severity: \"critical\" | \"warning\" | \"info\";\n title: string;\n evidence: string;\n recommendation: string;\n}\n\nexport interface ArtifactInvariant {\n goal_ref: string;\n owner_ref: string;\n decision_refs: string[];\n evidence_refs: string[];\n next_action_ref: string;\n proof_requirement: \"artifact\" | \"verification\" | \"external-link\" | \"human-review\";\n retrieval_scope: string;\n}\n\nexport interface SelfAuditPlan {\n artifact_type: \"ai_native_self_audit_plan\";\n artifact_hash: string;\n artifact_invariant: ArtifactInvariant;\n audit_scope: {\n loop: \"founder\";\n time_window_days: number;\n connected_sources: string[];\n missing_sources: string[];\n };\n extracted_items: FounderLoopItem[];\n findings: AuditFinding[];\n generated_at: string;\n recommended_follow_up: {\n title: string;\n summary: string;\n rollback: string;\n };\n recommended_initiative: {\n title: string;\n summary: string;\n workstreams: Array<{\n title: string;\n purpose: string;\n tasks: Array<{\n title: string;\n proof_requirement: string;\n }>;\n }>;\n };\n safe_writeback_plan: Array<{\n target: \"orgx\";\n action: string;\n approval: \"required\";\n rollback: string;\n }>;\n schema_version: typeof SELF_AUDIT_SCHEMA_VERSION;\n scores: AuditScores;\n self_critique: Array<{\n dimension: AuditDimension;\n target: number;\n score: number;\n passed: boolean;\n gap: string;\n }>;\n signals: SelfAuditSignals;\n workspace: AuditWorkspaceRef;\n}\n\nexport interface BuildSelfAuditPlanInput {\n connectedSources?: string[];\n generatedAt?: string;\n imports: FounderLoopImport[];\n missingSources?: string[];\n timeWindowDays?: number;\n workspace: AuditWorkspaceRef;\n}\n\nexport interface OrgxWriteOptions extends ResolveOrgxAuthOptions {\n dryRun?: boolean;\n}\n\nexport interface CreateAuditArtifactOptions extends OrgxWriteOptions {\n initiativeId: string;\n markdown: string;\n plan: SelfAuditPlan;\n}\n\nexport interface CreateAuditInitiativeOptions extends OrgxWriteOptions {\n plan: SelfAuditPlan;\n}\n\nexport interface CreateAuditFollowUpOptions extends OrgxWriteOptions {\n initiativeId: string;\n milestoneId?: string;\n plan: SelfAuditPlan;\n workstreamId?: string;\n}\n\nexport interface OrgxEntityRef {\n id: string;\n title: string;\n}\n\nfunction clampScore(value: number): number {\n return Math.max(0, Math.min(100, Math.round(value)));\n}\n\nfunction ratio(numerator: number, denominator: number, fallback = 0): number {\n if (denominator <= 0) return fallback;\n return numerator / denominator;\n}\n\nfunction includesAny(value: string, patterns: readonly RegExp[]): boolean {\n return patterns.some((pattern) => pattern.test(value));\n}\n\nfunction classifyLine(line: string): FounderLoopItemType | null {\n const normalized = line.trim();\n if (!normalized) return null;\n\n if (/^(decision|decided|we decided|d:)\\b/i.test(normalized)) return \"decision\";\n if (/^(commitment|committed|promise|promised|todo:|we will)\\b/i.test(normalized)) return \"commitment\";\n if (/^(artifact|receipt|proof|shipped|implemented|commit|pr:)\\b/i.test(normalized)) return \"artifact\";\n if (/^(open loop|gap|blocker|risk|missing|needs|unresolved)\\b/i.test(normalized)) return \"open_loop\";\n if (/^(next action|follow[- ]?up|next step|action:)\\b/i.test(normalized)) return \"next_action\";\n if (/^(outcome|result|impact|metric|adoption)\\b/i.test(normalized)) return \"outcome\";\n if (/^(roi|economics|token|tokens|cost|saved|time saved|api bill)\\b/i.test(normalized)) return \"economics\";\n\n return null;\n}\n\nexport function extractFounderLoopItems(imports: readonly FounderLoopImport[]): FounderLoopItem[] {\n const items: FounderLoopItem[] = [];\n\n for (const source of imports) {\n const lines = source.text.split(/\\r?\\n/);\n lines.forEach((line, index) => {\n const type = classifyLine(line);\n if (!type) return;\n\n const lineNumber = index + 1;\n items.push({\n evidenceRef: `${source.sourceId}:L${lineNumber}`,\n lineNumber,\n sourceId: source.sourceId,\n sourceLabel: source.sourceLabel,\n text: line.trim(),\n type,\n });\n });\n }\n\n return items;\n}\n\nexport function buildSelfAuditSignals(\n imports: readonly FounderLoopImport[],\n items: readonly FounderLoopItem[],\n options: {\n connectedSources?: readonly string[];\n missingSources?: readonly string[];\n } = {},\n): SelfAuditSignals {\n const allText = imports.map((source) => source.text).join(\"\\n\");\n const lower = allText.toLowerCase();\n const decisions = items.filter((item) => item.type === \"decision\");\n const artifacts = items.filter((item) => item.type === \"artifact\");\n const commitments = items.filter((item) => item.type === \"commitment\");\n const nextActions = items.filter((item) => item.type === \"next_action\");\n const outcomes = items.filter((item) => item.type === \"outcome\");\n const economics = items.filter((item) => item.type === \"economics\");\n const proofMentions = (lower.match(/\\b(proof|verified|verification|receipt|quality score|artifact)\\b/g) ?? []).length;\n const ownerMentions = (lower.match(/\\b(owner|dri|responsible|agent:|founder)\\b/g) ?? []).length;\n const artifactNextActionMentions = artifacts.filter((item) =>\n includesAny(item.text.toLowerCase(), [/\\bnext action\\b/, /\\bfollow[- ]?up\\b/, /\\brollback\\b/]),\n ).length;\n const writebackMentions = (lower.match(/\\b(approve|approved|writeback|rollback|create task|follow-up task)\\b/g) ?? []).length;\n const repeatedContextPrompts = (\n lower.match(/\\b(recap|catch you up|context again|restate|reread|remind me)\\b/g) ?? []\n ).length;\n\n return {\n approvedWritebackTargets: Math.min(3, writebackMentions),\n artifactsWithNextActions: Math.min(artifacts.length, nextActions.length + artifactNextActionMentions),\n artifactsWithOwners: Math.min(artifacts.length, ownerMentions),\n completedWorkItems: artifacts.length,\n completedWorkWithProof: Math.min(artifacts.length, proofMentions),\n connectedSources: Math.max(options.connectedSources?.length ?? 0, imports.length),\n decisionsWithEvidence: decisions.length,\n economicSignals: economics.length + (lower.includes(\"token\") || lower.includes(\"cost\") || lower.includes(\"saved\") ? 1 : 0),\n missingSources: options.missingSources?.length ?? 0,\n openLoops: items.filter((item) => item.type === \"open_loop\").length,\n outcomeLinkedItems: outcomes.length,\n repeatedContextPrompts,\n totalArtifacts: artifacts.length,\n totalContextItems: Math.max(items.length, allText.split(/\\s+/).filter(Boolean).length),\n totalDecisions: decisions.length,\n unresolvedCommitments: Math.max(0, commitments.length - nextActions.length - outcomes.length),\n };\n}\n\nexport function scoreSelfAudit(signals: SelfAuditSignals): AuditScores {\n const queryability = clampScore(\n 30\n + ratio(signals.decisionsWithEvidence, Math.max(1, signals.totalDecisions), 0) * 25\n + Math.min(20, signals.connectedSources * 5)\n + Math.min(30, (signals.totalArtifacts + signals.outcomeLinkedItems + signals.approvedWritebackTargets) * 5),\n );\n const proofDensity = clampScore(\n 30\n + ratio(signals.completedWorkWithProof, Math.max(1, signals.completedWorkItems), 0) * 35\n + ratio(signals.artifactsWithOwners, Math.max(1, signals.totalArtifacts), 0) * 20\n + ratio(signals.artifactsWithNextActions, Math.max(1, signals.totalArtifacts), 0) * 15,\n );\n const loopClosure = clampScore(\n 40\n + Math.min(25, signals.outcomeLinkedItems * 25)\n + Math.min(35, signals.approvedWritebackTargets * 20)\n + (signals.openLoops === 0 ? 15 : Math.max(0, 15 - signals.openLoops * 3)),\n );\n const contextDebt = clampScore(\n 100\n - Math.min(35, signals.repeatedContextPrompts * 10)\n - Math.min(35, signals.openLoops * 6)\n - Math.min(20, signals.missingSources * 4)\n - Math.min(10, signals.unresolvedCommitments * 3),\n );\n const autonomyReadiness = clampScore(\n 35\n + Math.min(30, signals.approvedWritebackTargets * 15)\n + Math.min(20, signals.completedWorkWithProof * 5)\n + (signals.openLoops <= 1 ? 15 : 5),\n );\n const roiVisibility = clampScore(\n 30\n + Math.min(40, signals.economicSignals * 18)\n + Math.min(25, signals.outcomeLinkedItems * 25)\n + Math.min(10, signals.completedWorkWithProof * 3),\n );\n\n return {\n autonomy_readiness: autonomyReadiness,\n context_debt: contextDebt,\n loop_closure: loopClosure,\n proof_density: proofDensity,\n queryability,\n roi_visibility: roiVisibility,\n };\n}\n\nfunction buildFindings(scores: AuditScores, signals: SelfAuditSignals): AuditFinding[] {\n const findings: AuditFinding[] = [];\n\n for (const dimension of AUDIT_DIMENSIONS) {\n const score = scores[dimension];\n if (score >= 95) {\n findings.push({\n dimension,\n evidence: `Score ${score}/100 meets the Phase 2 target.`,\n recommendation: \"Keep this dimension gated by evidence so the score stays earned.\",\n severity: \"info\",\n title: `${dimension.replace(/_/g, \" \")} is at the 95+ target`,\n });\n continue;\n }\n\n const recommendationByDimension: Record<AuditDimension, string> = {\n autonomy_readiness: \"Keep writeback approval-gated and add rollback references to every generated action.\",\n context_debt: \"Reduce repeated context prompts and close unresolved open loops with task or decision artifacts.\",\n loop_closure: \"Add outcome references and approved follow-up writebacks so planning changes after execution.\",\n proof_density: \"Attach owners, next actions, and verification proof to every completed work artifact.\",\n queryability: \"Add cited decisions, artifacts, connected sources, and retrieval scope to the audit output.\",\n roi_visibility: \"Add token/time/cost evidence plus an outcome review so ROI is not a narrative claim.\",\n };\n\n findings.push({\n dimension,\n evidence: `Score ${score}/100. Signals: ${JSON.stringify({\n approvedWritebackTargets: signals.approvedWritebackTargets,\n completedWorkWithProof: signals.completedWorkWithProof,\n economicSignals: signals.economicSignals,\n openLoops: signals.openLoops,\n outcomeLinkedItems: signals.outcomeLinkedItems,\n repeatedContextPrompts: signals.repeatedContextPrompts,\n })}`,\n recommendation: recommendationByDimension[dimension],\n severity: score < 60 ? \"critical\" : \"warning\",\n title: `${dimension.replace(/_/g, \" \")} needs evidence before it can be called 95+`,\n });\n }\n\n return findings;\n}\n\nfunction buildSelfCritique(scores: AuditScores): SelfAuditPlan[\"self_critique\"] {\n return AUDIT_DIMENSIONS.map((dimension) => {\n const score = scores[dimension];\n return {\n dimension,\n gap: score >= 95\n ? \"No score gap. Preserve evidence and regression-test this dimension.\"\n : `Needs ${95 - score} more points of verified product evidence before claiming 95+.`,\n passed: score >= 95,\n score,\n target: 95,\n };\n });\n}\n\nfunction hashPlanPayload(payload: unknown): string {\n return createHash(\"sha256\").update(JSON.stringify(payload)).digest(\"hex\");\n}\n\nexport function buildSelfAuditPlan(input: BuildSelfAuditPlanInput): SelfAuditPlan {\n if (input.imports.length === 0) {\n throw new Error(\"At least one AI-session import is required to run the Founder Loop audit.\");\n }\n\n const items = extractFounderLoopItems(input.imports);\n const connectedSources = input.connectedSources ?? input.imports.map((source) => source.sourceLabel);\n const missingSources = input.missingSources ?? [];\n const signals = buildSelfAuditSignals(input.imports, items, {\n connectedSources,\n missingSources,\n });\n const scores = scoreSelfAudit(signals);\n const evidenceRefs = items.slice(0, 12).map((item) => item.evidenceRef);\n const decisions = items.filter((item) => item.type === \"decision\");\n const nextAction = items.find((item) => item.type === \"next_action\");\n\n const basePlan = {\n artifact_type: \"ai_native_self_audit_plan\" as const,\n audit_scope: {\n connected_sources: connectedSources,\n loop: \"founder\" as const,\n missing_sources: missingSources,\n time_window_days: input.timeWindowDays ?? 30,\n },\n extracted_items: items,\n findings: buildFindings(scores, signals),\n generated_at: input.generatedAt ?? new Date().toISOString(),\n recommended_follow_up: {\n rollback: \"Delete or close the generated OrgX follow-up task if the founder rejects the audit recommendation.\",\n summary: nextAction?.text ?? \"Review the audit findings, approve one follow-up action, and attach proof after execution.\",\n title: \"Review AI-native self-audit findings and approve first follow-up\",\n },\n recommended_initiative: {\n summary:\n \"Generated by @useorgx/wizard audit to close the first Founder Loop from AI-session context, proof artifacts, approved writeback, and outcome review.\",\n title: `Close Founder Loop: ${input.workspace.name} AI-native operating loop`,\n workstreams: [\n {\n purpose: \"Capture AI-session context, decisions, commitments, and open loops.\",\n tasks: [\n {\n proof_requirement: \"AI-session import with cited evidence references.\",\n title: \"Import founder AI-session context\",\n },\n ],\n title: \"Founder Context Ingest\",\n },\n {\n purpose: \"Turn completed work into artifacts with owners, proof, and next actions.\",\n tasks: [\n {\n proof_requirement: \"Artifact metadata includes owner, evidence refs, and retrieval scope.\",\n title: \"Attach proof artifacts to completed work\",\n },\n ],\n title: \"Proof Chain\",\n },\n {\n purpose: \"Write one approved follow-up action into OrgX with rollback context.\",\n tasks: [\n {\n proof_requirement: \"Approved OrgX task with rollback and evidence references.\",\n title: \"Approve first OrgX follow-up writeback\",\n },\n ],\n title: \"Safe Writeback\",\n },\n {\n purpose: \"Record outcome and economics so the next plan learns from execution.\",\n tasks: [\n {\n proof_requirement: \"Founder review with time/token/value estimate and attribution confidence.\",\n title: \"Record outcome and economics review\",\n },\n ],\n title: \"Outcome Review\",\n },\n ],\n },\n safe_writeback_plan: [\n {\n action: \"create_follow_up_task\",\n approval: \"required\" as const,\n rollback: \"Delete or close the generated task and preserve the audit artifact as a rejected recommendation.\",\n target: \"orgx\" as const,\n },\n ],\n schema_version: SELF_AUDIT_SCHEMA_VERSION,\n scores,\n self_critique: buildSelfCritique(scores),\n signals,\n workspace: input.workspace,\n };\n const invariant: ArtifactInvariant = {\n decision_refs: decisions.map((item) => item.evidenceRef),\n evidence_refs: evidenceRefs,\n goal_ref: `workspace:${input.workspace.id}:ai-native-self-audit`,\n next_action_ref: nextAction?.evidenceRef ?? \"manual-next-action:review-audit\",\n owner_ref: \"founder:dri\",\n proof_requirement: \"verification\",\n retrieval_scope:\n \"Retrieve the imported AI-session context, extracted Founder Loop items, audit scores, findings, writeback plan, and outcome review.\",\n };\n const artifactHash = hashPlanPayload({ ...basePlan, artifact_invariant: invariant });\n\n return {\n ...basePlan,\n artifact_hash: artifactHash,\n artifact_invariant: invariant,\n };\n}\n\nexport function renderSelfAuditMarkdown(plan: SelfAuditPlan): string {\n const lines = [\n \"# AI-Native Founder Loop Self-Audit\",\n \"\",\n `Generated: ${plan.generated_at}`,\n `Workspace: ${plan.workspace.name} (${plan.workspace.id})`,\n `Artifact hash: ${plan.artifact_hash}`,\n \"\",\n \"## Scores\",\n \"\",\n \"| Dimension | Score | Target | Status |\",\n \"| --- | ---: | ---: | --- |\",\n ...AUDIT_DIMENSIONS.map((dimension) => {\n const score = plan.scores[dimension];\n return `| ${dimension.replace(/_/g, \" \")} | ${score} | 95 | ${score >= 95 ? \"pass\" : \"gap\"} |`;\n }),\n \"\",\n \"## Self-Critique\",\n \"\",\n ...plan.self_critique.map((item) => `- ${item.dimension}: ${item.gap}`),\n \"\",\n \"## Findings\",\n \"\",\n ...plan.findings.map((finding) => [\n `### ${finding.title}`,\n \"\",\n `- Severity: ${finding.severity}`,\n `- Evidence: ${finding.evidence}`,\n `- Recommendation: ${finding.recommendation}`,\n \"\",\n ].join(\"\\n\")),\n \"## Extracted Founder Loop Items\",\n \"\",\n ...plan.extracted_items.map((item) => `- ${item.type}: ${item.text} (${item.evidenceRef})`),\n \"\",\n \"## Recommended Initiative\",\n \"\",\n `Title: ${plan.recommended_initiative.title}`,\n \"\",\n plan.recommended_initiative.summary,\n \"\",\n \"## Approved Follow-Up Candidate\",\n \"\",\n `Title: ${plan.recommended_follow_up.title}`,\n \"\",\n plan.recommended_follow_up.summary,\n \"\",\n `Rollback: ${plan.recommended_follow_up.rollback}`,\n \"\",\n \"## Artifact Invariant\",\n \"\",\n \"```json\",\n JSON.stringify(plan.artifact_invariant, null, 2),\n \"```\",\n \"\",\n ];\n\n return lines.join(\"\\n\");\n}\n\nfunction parseEntityRef(payload: unknown): OrgxEntityRef {\n const entity = isRecord(payload) && isRecord(payload.data) ? payload.data : payload;\n if (!isRecord(entity)) {\n throw new Error(\"OrgX returned an unexpected entity payload.\");\n }\n\n const id = typeof entity.id === \"string\" ? entity.id : \"\";\n const title = typeof entity.title === \"string\"\n ? entity.title\n : typeof entity.name === \"string\"\n ? entity.name\n : \"\";\n if (!id || !title) {\n throw new Error(\"OrgX returned an incomplete entity payload.\");\n }\n\n return { id, title };\n}\n\nasync function parseResponseBody(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction formatHttpError(status: number, body: unknown): string {\n if (typeof body === \"string\" && body.trim().length > 0) {\n return `HTTP ${status}: ${body}`;\n }\n if (isRecord(body) && typeof body.error === \"string\" && body.error.trim().length > 0) {\n return `HTTP ${status}: ${body.error}`;\n }\n if (isRecord(body) && isRecord(body.error) && typeof body.error.message === \"string\") {\n return `HTTP ${status}: ${body.error.message}`;\n }\n return `HTTP ${status}`;\n}\n\nasync function createOrgxEntity(\n body: Record<string, unknown>,\n options: OrgxWriteOptions,\n): Promise<OrgxEntityRef> {\n if (options.dryRun) {\n return {\n id: `dry-run-${String(body.type ?? \"entity\")}`,\n title: String(body.title ?? body.name ?? \"Dry-run entity\"),\n };\n }\n\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n throw new Error(\"No OrgX API key configured. Run `wizard auth login` before using writeback flags.\");\n }\n\n const response = await fetch(buildOrgxApiUrl(\"/entities\", auth.baseUrl), {\n body: JSON.stringify(body),\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n method: \"POST\",\n signal: AbortSignal.timeout(15_000),\n });\n const responseBody = await parseResponseBody(response);\n if (!response.ok) {\n throw new Error(`Failed to create ${String(body.type ?? \"entity\")}. ${formatHttpError(response.status, responseBody)}`);\n }\n\n return parseEntityRef(responseBody);\n}\n\nexport async function createAuditArtifact(\n options: CreateAuditArtifactOptions,\n): Promise<OrgxEntityRef> {\n const { initiativeId, markdown, plan } = options;\n return createOrgxEntity(\n {\n artifact_type: \"shared.project_handbook\",\n description: \"AI-native Founder Loop self-audit generated by @useorgx/wizard audit.\",\n entity_id: initiativeId,\n entity_type: \"initiative\",\n external_url: `orgx-wizard://audit/${plan.artifact_hash}`,\n initiative_id: initiativeId,\n metadata: {\n ...plan.artifact_invariant,\n artifact_hash: plan.artifact_hash,\n atomic_unit_type: \"ai_native_self_audit\",\n completion_state: \"generated\",\n schema_validated: true,\n scores: plan.scores,\n },\n name: `AI-Native Self-Audit: ${plan.workspace.name}`,\n preview_markdown: markdown.slice(0, 8000),\n status: \"in_review\",\n type: \"artifact\",\n workspace_id: plan.workspace.id,\n },\n options,\n );\n}\n\nexport async function createInitiativeFromAuditPlan(\n options: CreateAuditInitiativeOptions,\n): Promise<OrgxEntityRef> {\n const { plan } = options;\n return createOrgxEntity(\n {\n metadata: {\n artifact_hash: plan.artifact_hash,\n audit_score_snapshot: plan.scores,\n source: \"ai_native_self_audit\",\n source_artifact_type: \"ai_native_self_audit_plan\",\n },\n status: \"active\",\n summary: plan.recommended_initiative.summary,\n title: plan.recommended_initiative.title,\n type: \"initiative\",\n workspace_id: plan.workspace.id,\n },\n options,\n );\n}\n\nexport async function createAuditFollowUpTask(\n options: CreateAuditFollowUpOptions,\n): Promise<OrgxEntityRef> {\n const { initiativeId, milestoneId, plan, workstreamId } = options;\n const resolvedWorkstreamId = workstreamId?.trim() || (\n await createOrgxEntity(\n {\n initiative_id: initiativeId,\n metadata: {\n artifact_hash: plan.artifact_hash,\n source: \"ai_native_self_audit\",\n },\n status: \"active\",\n summary: \"Follow-up workstream created by @useorgx/wizard audit so the approved action has execution context.\",\n title: \"AI-native self-audit follow-up\",\n type: \"workstream\",\n workspace_id: plan.workspace.id,\n },\n options,\n )\n ).id;\n const resolvedMilestoneId = milestoneId?.trim() || (\n await createOrgxEntity(\n {\n initiative_id: initiativeId,\n metadata: {\n artifact_hash: plan.artifact_hash,\n source: \"ai_native_self_audit\",\n },\n status: \"planned\",\n summary: \"Milestone created by @useorgx/wizard audit so the approved follow-up task has proof-chain hierarchy.\",\n title: \"AI-native self-audit follow-up\",\n type: \"milestone\",\n workspace_id: plan.workspace.id,\n workstream_id: resolvedWorkstreamId,\n },\n options,\n )\n ).id;\n\n return createOrgxEntity(\n {\n description: `${plan.recommended_follow_up.summary}\\n\\nRollback: ${plan.recommended_follow_up.rollback}`,\n initiative_id: initiativeId,\n milestone_id: resolvedMilestoneId,\n metadata: {\n ...plan.artifact_invariant,\n artifact_hash: plan.artifact_hash,\n source: \"ai_native_self_audit\",\n source_action: \"approved_follow_up_writeback\",\n },\n priority: \"high\",\n status: \"todo\",\n title: plan.recommended_follow_up.title,\n type: \"task\",\n workstream_id: resolvedWorkstreamId,\n workspace_id: plan.workspace.id,\n },\n options,\n );\n}\n\nexport function normalizeAuditBaseUrl(value?: string): string {\n return normalizeOrgxBaseUrl(value);\n}\n","import { createHash } from \"node:crypto\";\n\nimport { extractFounderLoopItems, type FounderLoopImport, type FounderLoopItem } from \"./self-audit.js\";\n\nexport const WORK_GRAPH_SCHEMA_VERSION = \"2026-05-07\" as const;\nexport const WORK_GRAPH_FINGERPRINT_VERSION = \"wgf_v1\" as const;\nexport const WORK_GRAPH_EXTRACTION_SCHEMA_VERSION = \"2026-05-07.ai-client-search.v1\" as const;\n\nexport const WORK_GRAPH_FINDING_TYPES = [\n \"action\",\n \"decision\",\n \"artifact\",\n \"blocker\",\n \"person\",\n \"business\",\n \"product_surface\",\n \"goal\",\n \"initiative_candidate\",\n \"missed_orchestration_opportunity\",\n] as const;\n\nexport type WorkGraphFindingType = (typeof WORK_GRAPH_FINDING_TYPES)[number];\n\nexport type WorkGraphSourceClient =\n | \"codex\"\n | \"claude\"\n | \"claude-code\"\n | \"cursor\"\n | \"openclaw\"\n | \"slack\"\n | \"mcp\"\n | \"github\"\n | \"linear\"\n | \"manual\"\n | \"wizard\"\n | \"api\"\n | \"unknown\";\n\nexport type WorkGraphFinalState = \"completed\" | \"blocked\" | \"in_progress\" | \"unknown\";\n\nexport interface WorkGraphWorkspaceRef {\n id: string;\n name: string;\n}\n\nexport interface WorkGraphSourceCoverage {\n connected: string[];\n missing: string[];\n mcpObserved: boolean;\n orgxObserved: boolean;\n orgxMcpCalled: boolean;\n skillOnlySignal: boolean;\n}\n\nexport interface WorkGraphSourceEvent {\n schema_version: typeof WORK_GRAPH_SCHEMA_VERSION;\n source_client: WorkGraphSourceClient;\n source_id: string;\n source_label: string;\n event_type: \"session_excerpt\" | \"client_extraction\" | \"tool_signal\" | \"source_coverage\";\n text: string;\n evidence_ref: string;\n metadata: Record<string, unknown>;\n}\n\nexport interface WorkGraphFinding {\n type: WorkGraphFindingType;\n title: string;\n summary: string;\n source_client: WorkGraphSourceClient;\n source_id: string;\n evidence_ref: string;\n confidence: number;\n metadata: Record<string, unknown>;\n}\n\nexport interface WorkGraphClientExtractionFinding {\n type: WorkGraphFindingType;\n title: string;\n summary: string;\n source_id?: string;\n source_label?: string;\n evidence_ref?: string;\n confidence?: number;\n occurred_at?: string;\n actor_id?: string;\n redacted_verbatim?: string;\n privacy_state?: \"public\" | \"redacted\" | \"private\";\n metadata?: Record<string, unknown>;\n}\n\nexport interface WorkGraphClientExtraction {\n schema_version?: string;\n extraction_id?: string;\n source_client: WorkGraphSourceClient;\n source_label?: string;\n searched_sources?: string[];\n search_queries?: Array<{\n id: string;\n lens: string;\n query: string;\n result_count?: number;\n }>;\n extraction_quality?: {\n confidence?: number;\n searched_session_count?: number;\n skipped_session_count?: number;\n notes?: string[];\n };\n findings: WorkGraphClientExtractionFinding[];\n}\n\nexport interface WorkGraphClientExtractionSummary {\n extraction_id: string;\n source_client: WorkGraphSourceClient;\n source_label: string;\n searched_source_count: number;\n query_count: number;\n finding_count: number;\n confidence: number;\n}\n\nexport interface WorkGraphExtractionSchema {\n schema_version: typeof WORK_GRAPH_EXTRACTION_SCHEMA_VERSION;\n mode: \"ai_client_session_search\";\n objective: string;\n privacy_contract: string[];\n source_search_strategy: Array<{\n id: string;\n lens: string;\n query: string;\n return_when: string;\n }>;\n required_output: Record<string, unknown>;\n quality_bar: string[];\n reject_as_noise: string[];\n}\n\nexport interface WorkGraphExtractionProtocol {\n schema_version: typeof WORK_GRAPH_EXTRACTION_SCHEMA_VERSION;\n mode: \"ai_client_session_search\";\n prompt: string;\n schema: WorkGraphExtractionSchema;\n}\n\nexport interface WorkGraphOpportunityScore {\n overall: number;\n value_potential: number;\n evidence_quality: number;\n urgency: number;\n owner_clarity: number;\n automation_potential: number;\n orgx_fit: number;\n}\n\nexport interface WorkGraphKickoffCandidate {\n title: string;\n summary: string;\n reason: string;\n finding_refs: string[];\n priority: \"p0\" | \"p1\" | \"p2\";\n}\n\nexport type WorkGraphEntityType =\n | \"idea\"\n | \"initiative\"\n | \"workstream\"\n | \"milestone\"\n | \"task\"\n | \"decision\"\n | \"artifact\"\n | \"person\"\n | \"business\"\n | \"blocker\"\n | \"agent\"\n | \"tool\"\n | \"source\"\n | \"surface\"\n | \"outcome\";\n\nexport type WorkGraphTrailKind =\n | \"idea_trail\"\n | \"initiative_trail\"\n | \"decision_trail\"\n | \"artifact_trail\"\n | \"person_trail\"\n | \"business_trail\"\n | \"blocker_trail\"\n | \"agent_trail\"\n | \"tool_trail\"\n | \"source_trail\"\n | \"outcome_trail\";\n\nexport type WorkGraphTrailState =\n | \"observed\"\n | \"inferred\"\n | \"claimed\"\n | \"verified\"\n | \"missing_evidence\"\n | \"blocked\"\n | \"stale\"\n | \"decaying\"\n | \"resolved\"\n | \"disputed\"\n | \"contradicted\";\n\nexport type WorkGraphTrailValence =\n | \"healthy\"\n | \"useful_recurrence\"\n | \"wasteful_recurrence\"\n | \"risk\"\n | \"leak\"\n | \"opportunity\"\n | \"zombie\"\n | \"escalating\";\n\nexport interface WorkGraphTrailEvent {\n id: string;\n trail_id: string;\n event_type:\n | \"signal_detected\"\n | \"idea_created\"\n | \"initiative_created\"\n | \"decision_inferred\"\n | \"decision_promoted\"\n | \"artifact_created\"\n | \"artifact_verified\"\n | \"owner_assigned\"\n | \"blocker_detected\"\n | \"source_connected\"\n | \"outcome_recorded\"\n | \"recommendation_generated\";\n entity_id: string;\n entity_type: WorkGraphEntityType;\n timestamp: string;\n actor_id?: string;\n source_id: string;\n source_type: WorkGraphSourceClient;\n redacted_verbatim?: string;\n confidence: number;\n evidence_refs: string[];\n privacy_state: \"public\" | \"redacted\" | \"private\";\n}\n\nexport interface WorkGraphTrailEdge {\n id: string;\n from_event_id: string;\n to_event_id: string;\n relation:\n | \"caused\"\n | \"informed\"\n | \"blocked\"\n | \"resolved\"\n | \"created\"\n | \"verified\"\n | \"assigned\"\n | \"depends_on\"\n | \"duplicates\"\n | \"recurred_as\"\n | \"converted_to\"\n | \"contradicted\";\n state: \"captured\" | \"inferred\" | \"missing\";\n confidence: number;\n evidence_refs: string[];\n}\n\nexport interface WorkGraphTrailRecommendation {\n id: string;\n title: string;\n summary: string;\n action_type: \"launch_initiative\" | \"promote_decision\" | \"attach_artifact\" | \"assign_owner\" | \"connect_source\" | \"verify_outcome\";\n trail_ids: string[];\n evidence_refs: string[];\n priority: \"p0\" | \"p1\" | \"p2\";\n expected_lift: string;\n confidence: number;\n}\n\nexport interface WorkGraphTrail {\n id: string;\n kind: WorkGraphTrailKind;\n title: string;\n summary: string;\n subject_entity_id: string;\n subject_entity_type: WorkGraphEntityType;\n state: WorkGraphTrailState;\n valence: WorkGraphTrailValence;\n confidence: number;\n recurrence_score: number;\n impact_score: number;\n privacy_state: \"public\" | \"redacted\" | \"private\";\n events: WorkGraphTrailEvent[];\n edges: WorkGraphTrailEdge[];\n evidence_refs: string[];\n blocker_ids: string[];\n recommendation_ids: string[];\n created_at: string;\n updated_at: string;\n shape:\n | \"dense_recent_cluster\"\n | \"chronic_recurrence\"\n | \"zombie_revival\"\n | \"accelerating_issue\"\n | \"healthy_execution\"\n | \"decision_heavy_artifact_light\"\n | \"artifact_heavy_decision_light\";\n}\n\nexport interface WorkGraphRecurringPattern {\n id: string;\n title: string;\n description: string;\n pattern_type:\n | \"trapped_decision\"\n | \"orphaned_artifact\"\n | \"missing_owner\"\n | \"repeated_work\"\n | \"missing_source\"\n | \"tooling_mismatch\"\n | \"unverified_outcome\"\n | \"handoff_friction\"\n | \"business_signal_unclaimed\";\n affected_trail_ids: string[];\n affected_entity_ids: string[];\n recurrence_count: number;\n severity: \"low\" | \"medium\" | \"high\" | \"critical\";\n confidence: number;\n valence: WorkGraphTrailValence;\n root_cause_hypothesis: string;\n recommended_runtime_action_id?: string;\n}\n\nexport interface WorkGraphMirrorClaim {\n id: string;\n text: string;\n evidence_refs: string[];\n confidence: number;\n}\n\nexport interface WorkGraphMirror {\n headline: string;\n body: string;\n lens: \"all\" | \"ideas\" | \"decisions\" | \"artifacts\" | \"people\" | \"businesses\" | \"blockers\" | \"agents_tools\" | \"sources\";\n claims: WorkGraphMirrorClaim[];\n primary_trail_id?: string;\n generated_at: string;\n}\n\nexport interface WorkGraphTensionMetric {\n id: string;\n label: string;\n value: string;\n tone: \"good\" | \"warning\" | \"danger\" | \"muted\";\n trail_ids: string[];\n evidence_refs: string[];\n explanation: string;\n}\n\nexport interface WorkGraphFingerprintBasis {\n schema_version: typeof WORK_GRAPH_SCHEMA_VERSION;\n fingerprint_version: typeof WORK_GRAPH_FINGERPRINT_VERSION;\n workspace_hash: string;\n source_clients: WorkGraphSourceClient[];\n connected_source_hashes: string[];\n missing_source_hashes: string[];\n finding_type_counts: Partial<Record<WorkGraphFindingType, number>>;\n pattern_hashes: string[];\n trail_shape_hashes: string[];\n recurring_pattern_hashes: string[];\n kickoff_hashes: string[];\n raw_transcripts_included: false;\n}\n\nexport interface WorkGraphSignupHydration {\n strategy: \"work_graph_fingerprint_claim\";\n hydration_key: string;\n eligible: boolean;\n notes: string[];\n}\n\nexport interface SessionReconciliationReport {\n schema_version: typeof WORK_GRAPH_SCHEMA_VERSION;\n report_id: string;\n idempotency_key: string;\n work_graph_fingerprint: string;\n fingerprint_version: typeof WORK_GRAPH_FINGERPRINT_VERSION;\n fingerprint_basis: WorkGraphFingerprintBasis;\n signup_hydration: WorkGraphSignupHydration;\n generated_at: string;\n source_client: \"wizard\";\n session_id: string;\n workspace: WorkGraphWorkspaceRef;\n extraction_protocol: WorkGraphExtractionProtocol;\n client_extractions: WorkGraphClientExtractionSummary[];\n source_coverage: WorkGraphSourceCoverage;\n final_state: WorkGraphFinalState;\n events: WorkGraphSourceEvent[];\n findings: WorkGraphFinding[];\n missed_orchestration_opportunities: WorkGraphFinding[];\n trails: WorkGraphTrail[];\n recurring_patterns: WorkGraphRecurringPattern[];\n recommendations: WorkGraphTrailRecommendation[];\n mirror: WorkGraphMirror;\n tension_metrics: WorkGraphTensionMetric[];\n opportunity_score: WorkGraphOpportunityScore;\n initiative_kickoffs: WorkGraphKickoffCandidate[];\n redaction_level: \"summary_only\";\n raw_transcripts_sent: false;\n}\n\nexport interface BuildSessionReconciliationReportInput {\n clientExtractions?: readonly WorkGraphClientExtraction[];\n connectedSources?: readonly string[];\n generatedAt?: string;\n imports: readonly FounderLoopImport[];\n missingSources?: readonly string[];\n sessionId?: string;\n workspace: WorkGraphWorkspaceRef;\n}\n\nfunction clampScore(value: number): number {\n return Math.max(0, Math.min(100, Math.round(value)));\n}\n\nfunction hashJson(value: unknown): string {\n return createHash(\"sha256\")\n .update(JSON.stringify(value))\n .digest(\"hex\");\n}\n\nfunction normalizeFingerprintText(value: string): string {\n return value\n .toLowerCase()\n .replace(/https?:\\/\\/\\S+/g, \"url\")\n .replace(/[0-9a-f]{12,}/g, \"hash\")\n .replace(/\\b[0-9a-f]{8}-[0-9a-f-]{27,}\\b/g, \"uuid\")\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 600);\n}\n\nfunction shortHash(value: unknown, length = 16): string {\n return hashJson(value).slice(0, length);\n}\n\nfunction sortedUnique<T extends string>(values: readonly T[]): T[] {\n return [...new Set(values)].sort();\n}\n\nfunction slugPart(value: string): string {\n const normalized = normalizeFingerprintText(value)\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .slice(0, 64);\n return normalized || \"unknown\";\n}\n\nfunction sourceClientForImport(source: FounderLoopImport): WorkGraphSourceClient {\n const raw = `${source.sourceId} ${source.sourceLabel}`.toLowerCase();\n if (raw.includes(\"codex\")) return \"codex\";\n if (raw.includes(\"claude-code\")) return \"claude-code\";\n if (raw.includes(\"claude\")) return \"claude\";\n if (raw.includes(\"cursor\")) return \"cursor\";\n if (raw.includes(\"openclaw\")) return \"openclaw\";\n if (raw.includes(\"slack\")) return \"slack\";\n if (raw.includes(\"github\")) return \"github\";\n if (raw.includes(\"linear\")) return \"linear\";\n if (raw.includes(\"mcp\")) return \"mcp\";\n if (raw.includes(\"api\")) return \"api\";\n if (raw.includes(\"manual\") || raw.includes(\"wizard-audit-input\")) return \"manual\";\n return \"unknown\";\n}\n\nfunction normalizeSourceClient(value: unknown): WorkGraphSourceClient {\n if (typeof value !== \"string\") return \"unknown\";\n const normalized = value.trim().toLowerCase();\n if (\n normalized === \"codex\" ||\n normalized === \"claude\" ||\n normalized === \"claude-code\" ||\n normalized === \"cursor\" ||\n normalized === \"openclaw\" ||\n normalized === \"slack\" ||\n normalized === \"mcp\" ||\n normalized === \"github\" ||\n normalized === \"linear\" ||\n normalized === \"manual\" ||\n normalized === \"wizard\" ||\n normalized === \"api\"\n ) {\n return normalized;\n }\n if (normalized.includes(\"claude\")) return \"claude\";\n if (normalized.includes(\"codex\")) return \"codex\";\n if (normalized.includes(\"cursor\")) return \"cursor\";\n if (normalized.includes(\"slack\")) return \"slack\";\n if (normalized.includes(\"github\")) return \"github\";\n if (normalized.includes(\"linear\")) return \"linear\";\n if (normalized.includes(\"mcp\")) return \"mcp\";\n return \"unknown\";\n}\n\nfunction normalizeFindingType(value: unknown): WorkGraphFindingType | null {\n if (typeof value !== \"string\") return null;\n const normalized = value.trim().toLowerCase();\n return WORK_GRAPH_FINDING_TYPES.includes(normalized as WorkGraphFindingType)\n ? normalized as WorkGraphFindingType\n : null;\n}\n\nfunction normalizeConfidence(value: unknown, fallback = 0.72): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return fallback;\n return Math.max(0.1, Math.min(0.99, Number(value.toFixed(2))));\n}\n\nfunction titleFromText(text: string, fallback: string): string {\n const normalized = text\n .replace(/^\\s*(decision|artifact|commitment|next action|follow[- ]?up|outcome|roi|economics|open loop|gap|blocker|risk|goal)\\s*:\\s*/i, \"\")\n .trim();\n const firstSentence = normalized.split(/[.!?]\\s/)[0]?.trim() || normalized;\n return (firstSentence || fallback).slice(0, 160);\n}\n\nfunction normalizeClientExtractionId(extraction: WorkGraphClientExtraction, index: number): string {\n return extraction.extraction_id?.trim()\n || `${extraction.source_client || \"unknown\"}:client-extraction:${index + 1}`;\n}\n\nexport function buildWorkGraphExtractionProtocol(): WorkGraphExtractionProtocol {\n const schema: WorkGraphExtractionSchema = {\n schema_version: WORK_GRAPH_EXTRACTION_SCHEMA_VERSION,\n mode: \"ai_client_session_search\",\n objective:\n \"Search the AI client's own sessions, logs, tool calls, and local transcript index to extract durable work-graph evidence for OrgX.\",\n privacy_contract: [\n \"Do not return raw transcripts.\",\n \"Return short redacted verbatim snippets only when they materially support a finding.\",\n \"Prefer evidence refs, session ids, timestamps, source ids, and hashes over full content.\",\n \"Mark private customer/person data as private or redacted.\",\n \"Do not invent people, decisions, artifacts, or outcomes that are not supported by a source event.\",\n ],\n source_search_strategy: [\n {\n id: \"decisions\",\n lens: \"Decision trails\",\n query:\n \"Find choices, tradeoffs, approvals, rejected options, contradictions, architecture calls, product calls, and decisions that were restated later.\",\n return_when:\n \"A choice shaped future work, blocked work, or should become durable organizational memory.\",\n },\n {\n id: \"artifacts\",\n lens: \"Artifact trails\",\n query:\n \"Find created or modified artifacts: PRs, files, docs, designs, prompts, plans, reports, screenshots, deployed routes, tests, and verification receipts.\",\n return_when:\n \"The artifact has a source event, proof reference, downstream use, owner, or missing verification.\",\n },\n {\n id: \"blockers\",\n lens: \"Blocker trails\",\n query:\n \"Find failed tool calls, timeouts, rejected validators, missing auth, missing source coverage, repeated unresolved questions, stalled owners, and external blockers.\",\n return_when:\n \"The blocker explains why work did not become durable, verified, assigned, or shipped.\",\n },\n {\n id: \"people_businesses\",\n lens: \"People and business trails\",\n query:\n \"Find users, customers, buyers, stakeholders, reviewers, teams, businesses, accounts, and market signals connected to work or decisions.\",\n return_when:\n \"A person or business changes priority, ownership, revenue potential, customer pain, or follow-up urgency.\",\n },\n {\n id: \"product_surfaces\",\n lens: \"Product surface trails\",\n query:\n \"Find surfaces such as live rooms, command center, widgets, plugins, wizard flows, public pages, APIs, MCP tools, Slack/GitHub/Linear integrations, and signup/claim flows.\",\n return_when:\n \"A surface was changed, verified, blocked, requested, or connected to a goal or artifact.\",\n },\n {\n id: \"agents_tools_sources\",\n lens: \"Agent/tool/source trails\",\n query:\n \"Find agent runs, subagents, MCP calls, hook lifecycle events, tool availability, tool misses, source coverage, and runtime writeback behavior.\",\n return_when:\n \"The event proves whether OrgX was called, skipped, unavailable, or only mentioned in instructions.\",\n },\n {\n id: \"outcomes_roi\",\n lens: \"Outcome and ROI trails\",\n query:\n \"Find shipped/completed work, test/browser/deploy verification, outcomes, time saved, cost, revenue, customer impact, attribution, and expected lift.\",\n return_when:\n \"The outcome can be tied to evidence and a prior decision, artifact, blocker, or source.\",\n },\n {\n id: \"recurrence\",\n lens: \"Recurring patterns\",\n query:\n \"Find repeated shapes across sessions: trapped decisions, orphaned artifacts, missing owner, repeated work, source gaps, tooling mismatch, unverified outcomes, handoff friction, and unclaimed business signals.\",\n return_when:\n \"The same pattern appears across multiple sessions, days, tools, actors, or product surfaces.\",\n },\n ],\n required_output: {\n schema_version: WORK_GRAPH_EXTRACTION_SCHEMA_VERSION,\n extraction_id: \"stable id for this extraction run\",\n source_client: \"codex | claude | claude-code | cursor | openclaw | slack | mcp | github | linear | manual | api | unknown\",\n source_label: \"human-readable source label\",\n searched_sources: [\"session/log/source group names searched\"],\n search_queries: [\n {\n id: \"decisions\",\n lens: \"Decision trails\",\n query: \"query actually used\",\n result_count: 0,\n },\n ],\n extraction_quality: {\n confidence: 0.0,\n searched_session_count: 0,\n skipped_session_count: 0,\n notes: [\"limits, permissions, or gaps\"],\n },\n findings: [\n {\n type: \"decision | artifact | blocker | person | business | product_surface | goal | action | initiative_candidate | missed_orchestration_opportunity\",\n title: \"short durable title, not a raw line\",\n summary: \"one sentence explaining why this matters\",\n source_id: \"session/tool/source id\",\n source_label: \"source label\",\n evidence_ref: \"stable evidence pointer\",\n confidence: 0.0,\n occurred_at: \"ISO timestamp if known\",\n actor_id: \"redacted actor id if known\",\n redacted_verbatim: \"short supporting excerpt only\",\n privacy_state: \"public | redacted | private\",\n metadata: {\n related_entity_names: [],\n related_source_ids: [],\n recurrence_count: 0,\n state: \"observed | inferred | verified | blocked | missing_evidence\",\n },\n },\n ],\n },\n quality_bar: [\n \"Search broadly before summarizing; do not stop at the newest session if older sessions contain recurrence.\",\n \"Every finding must include a source id or evidence ref.\",\n \"A trail starts only from evidence-bearing work signals, not empty labels, code type signatures, tool catalogs, or guardrail text.\",\n \"Prefer fewer, higher-confidence findings over many shallow lines.\",\n \"Include negative evidence when OrgX/MCP was available but not called.\",\n \"Separate actual tool calls from textual mentions of tool names.\",\n \"Mark confidence below 0.6 when the finding is inferred from weak or single-source evidence.\",\n \"Do not emit raw JSON tool payloads; summarize the tool result into a blocker/artifact/outcome finding.\",\n ],\n reject_as_noise: [\n \"AGENTS.md or system guardrail instructions.\",\n \"Source-code paths and line-number references unless the code change itself is the artifact.\",\n \"Bare labels like Decision:, Receipt:, Impact:, or proof: {.\",\n \"Type signatures such as outcome: string; or decision: ReviewableDecision;\",\n \"Tool catalogs and lists of available MCP tools.\",\n \"Planning narration like let me check, now I will inspect, or I need to verify.\",\n \"Generic MCP/AI commentary without a concrete work event.\",\n ],\n };\n\n const prompt = [\n \"You are generating an OrgX Work Graph extraction from your own AI-client session/search logs.\",\n \"Search across available local sessions, transcripts, tool-call logs, hook events, and source indexes using every lens in the schema.\",\n \"Return JSON only. Match the required_output shape exactly. Do not return raw transcripts.\",\n \"The output will initiate Work Graph Trails, so every finding must be evidence-bearing and useful enough for a human to inspect.\",\n ].join(\" \");\n\n return {\n schema_version: WORK_GRAPH_EXTRACTION_SCHEMA_VERSION,\n mode: \"ai_client_session_search\",\n prompt,\n schema,\n };\n}\n\nfunction findingTypeForItem(item: FounderLoopItem): WorkGraphFindingType {\n switch (item.type) {\n case \"decision\":\n return \"decision\";\n case \"artifact\":\n return \"artifact\";\n case \"open_loop\":\n return \"blocker\";\n case \"commitment\":\n case \"next_action\":\n case \"outcome\":\n return \"action\";\n case \"economics\":\n return \"business\";\n }\n}\n\nfunction evidenceRefFor(sourceId: string, index: number): string {\n return `${sourceId}:derived:${index + 1}`;\n}\n\nfunction includesAny(text: string, patterns: readonly RegExp[]): boolean {\n return patterns.some((pattern) => pattern.test(text));\n}\n\nfunction buildCoverage(\n imports: readonly FounderLoopImport[],\n connectedSources: readonly string[],\n missingSources: readonly string[],\n clientExtractions: readonly WorkGraphClientExtraction[] = [],\n): WorkGraphSourceCoverage {\n const extractionText = clientExtractions\n .flatMap((extraction) => [\n extraction.source_client,\n extraction.source_label ?? \"\",\n ...(extraction.searched_sources ?? []),\n ...(extraction.findings ?? []).flatMap((finding) => [\n finding.title,\n finding.summary,\n finding.redacted_verbatim ?? \"\",\n ]),\n ])\n .join(\"\\n\");\n const allText = `${imports.map((source) => source.text).join(\"\\n\")}\\n${extractionText}`.toLowerCase();\n const orgxObserved = /\\borgx\\b|useorgx|mcp__orgx__|orgx_/i.test(allText);\n const mcpObserved = /\\bmcp\\b|mcp__|tool call|tools\\/call|call_tool|orgx_emit_activity/i.test(allText);\n const orgxMcpCalled = /mcp__orgx__|orgx_emit_activity|orgx_apply_changeset|complete_with_proof|scaffold_initiative/i.test(allText);\n const skillOnlySignal = orgxObserved && !orgxMcpCalled && /\\bskill|instructions|agent|workflow\\b/i.test(allText);\n\n return {\n connected: [...connectedSources],\n missing: [...missingSources],\n mcpObserved,\n orgxObserved,\n orgxMcpCalled,\n skillOnlySignal,\n };\n}\n\nexport function summarizeClientExtractions(\n clientExtractions: readonly WorkGraphClientExtraction[],\n): WorkGraphClientExtractionSummary[] {\n return clientExtractions.map((extraction, index) => {\n const extractionId = normalizeClientExtractionId(extraction, index);\n return {\n extraction_id: extractionId,\n source_client: normalizeSourceClient(extraction.source_client),\n source_label: extraction.source_label?.trim() || `${extraction.source_client || \"Unknown\"} AI-client extraction`,\n searched_source_count: extraction.searched_sources?.length ?? 0,\n query_count: extraction.search_queries?.length ?? 0,\n finding_count: extraction.findings.length,\n confidence: normalizeConfidence(extraction.extraction_quality?.confidence, 0.74),\n };\n });\n}\n\nexport function buildClientExtractionEvents(\n clientExtractions: readonly WorkGraphClientExtraction[],\n): WorkGraphSourceEvent[] {\n return summarizeClientExtractions(clientExtractions).map((summary) => ({\n schema_version: WORK_GRAPH_SCHEMA_VERSION,\n source_client: summary.source_client,\n source_id: summary.extraction_id,\n source_label: summary.source_label,\n event_type: \"client_extraction\",\n text: [\n `${summary.finding_count} structured findings extracted by ${summary.source_client}.`,\n `${summary.query_count} search queries across ${summary.searched_source_count} searched source groups.`,\n `Extraction confidence: ${summary.confidence}.`,\n ].join(\" \"),\n evidence_ref: `${summary.extraction_id}:summary`,\n metadata: {\n finding_count: summary.finding_count,\n query_count: summary.query_count,\n searched_source_count: summary.searched_source_count,\n raw_transcript_sent: false,\n },\n }));\n}\n\nexport function buildClientExtractionFindings(\n clientExtractions: readonly WorkGraphClientExtraction[],\n): WorkGraphFinding[] {\n const findings: WorkGraphFinding[] = [];\n\n clientExtractions.forEach((extraction, extractionIndex) => {\n const extractionId = normalizeClientExtractionId(extraction, extractionIndex);\n const sourceClient = normalizeSourceClient(extraction.source_client);\n const sourceLabel = extraction.source_label?.trim() || `${sourceClient} AI-client extraction`;\n extraction.findings.forEach((finding, findingIndex) => {\n const type = normalizeFindingType(finding.type);\n const title = finding.title?.trim();\n const summary = finding.summary?.trim();\n if (!type || !title || !summary) return;\n\n findings.push({\n type,\n title: title.slice(0, 180),\n summary,\n source_client: sourceClient,\n source_id: finding.source_id?.trim() || extractionId,\n evidence_ref: finding.evidence_ref?.trim() || `${extractionId}:F${findingIndex + 1}`,\n confidence: normalizeConfidence(finding.confidence, normalizeConfidence(extraction.extraction_quality?.confidence, 0.76)),\n metadata: {\n source_label: finding.source_label?.trim() || sourceLabel,\n extraction_id: extractionId,\n schema_version: extraction.schema_version ?? null,\n occurred_at: finding.occurred_at ?? null,\n actor_id: finding.actor_id ?? null,\n redacted_verbatim: finding.redacted_verbatim ?? null,\n privacy_state: finding.privacy_state ?? \"redacted\",\n ...(finding.metadata ?? {}),\n },\n });\n });\n });\n\n return findings;\n}\n\nfunction buildDerivedFindings(imports: readonly FounderLoopImport[]): WorkGraphFinding[] {\n const findings: WorkGraphFinding[] = [];\n let derivedIndex = 0;\n\n for (const source of imports) {\n const sourceClient = sourceClientForImport(source);\n const lines = source.text.split(/\\r?\\n/).map((line) => line.trim()).filter(Boolean);\n\n for (const line of lines) {\n const lower = line.toLowerCase();\n\n if (includesAny(lower, [/\\b(owner|dri|founder|teammate|customer|user|stakeholder|buyer|reviewer)\\b/])) {\n findings.push({\n type: \"person\",\n title: titleFromText(line, \"Person or stakeholder signal\"),\n summary: line,\n source_client: sourceClient,\n source_id: source.sourceId,\n evidence_ref: evidenceRefFor(source.sourceId, derivedIndex++),\n confidence: 0.62,\n metadata: { source_label: source.sourceLabel },\n });\n }\n\n if (includesAny(lower, [/\\b(product surface|surface|live room|command center|dashboard|widget|plugin|wizard|audit|onboarding|mcp|slack|github|linear)\\b/])) {\n findings.push({\n type: \"product_surface\",\n title: titleFromText(line, \"Product surface signal\"),\n summary: line,\n source_client: sourceClient,\n source_id: source.sourceId,\n evidence_ref: evidenceRefFor(source.sourceId, derivedIndex++),\n confidence: 0.66,\n metadata: { source_label: source.sourceLabel },\n });\n }\n\n if (includesAny(lower, [/\\b(goal|objective|initiative|workstream|milestone|roadmap|launch)\\b/])) {\n findings.push({\n type: \"goal\",\n title: titleFromText(line, \"Goal signal\"),\n summary: line,\n source_client: sourceClient,\n source_id: source.sourceId,\n evidence_ref: evidenceRefFor(source.sourceId, derivedIndex++),\n confidence: 0.64,\n metadata: { source_label: source.sourceLabel },\n });\n }\n }\n }\n\n return findings;\n}\n\nexport function buildWorkGraphEvents(imports: readonly FounderLoopImport[]): WorkGraphSourceEvent[] {\n return imports.map((source, index) => ({\n schema_version: WORK_GRAPH_SCHEMA_VERSION,\n source_client: sourceClientForImport(source),\n source_id: source.sourceId,\n source_label: source.sourceLabel,\n event_type: \"session_excerpt\",\n text: source.text,\n evidence_ref: `${source.sourceId}:excerpt`,\n metadata: {\n import_index: index,\n line_count: source.text.split(/\\r?\\n/).filter(Boolean).length,\n raw_transcript_sent: false,\n },\n }));\n}\n\nexport function buildWorkGraphFindings(imports: readonly FounderLoopImport[]): WorkGraphFinding[] {\n const loopFindings = extractFounderLoopItems(imports).map((item) => {\n const source = imports.find((candidate) => candidate.sourceId === item.sourceId);\n const sourceClient = source ? sourceClientForImport(source) : \"unknown\";\n const type = findingTypeForItem(item);\n return {\n type,\n title: titleFromText(item.text, type),\n summary: item.text,\n source_client: sourceClient,\n source_id: item.sourceId,\n evidence_ref: item.evidenceRef,\n confidence: type === \"decision\" || type === \"artifact\" ? 0.82 : 0.72,\n metadata: {\n source_label: item.sourceLabel,\n founder_loop_type: item.type,\n line_number: item.lineNumber,\n },\n } satisfies WorkGraphFinding;\n });\n\n const seen = new Set<string>();\n return [...loopFindings, ...buildDerivedFindings(imports)].filter((finding) => {\n const key = `${finding.type}:${finding.source_id}:${finding.summary.toLowerCase()}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction buildMissedOpportunities(\n coverage: WorkGraphSourceCoverage,\n findings: readonly WorkGraphFinding[],\n): WorkGraphFinding[] {\n const opportunities: WorkGraphFinding[] = [];\n const hasActionableSignal = findings.some((finding) =>\n [\"decision\", \"artifact\", \"blocker\", \"action\"].includes(finding.type),\n );\n\n if (hasActionableSignal && !coverage.orgxMcpCalled) {\n opportunities.push({\n type: \"missed_orchestration_opportunity\",\n title: \"High-value work happened without an OrgX MCP write\",\n summary:\n \"The source contains decisions, artifacts, blockers, or actions, but no durable OrgX MCP call was detected.\",\n source_client: \"wizard\",\n source_id: \"work-graph\",\n evidence_ref: \"work-graph:coverage:orgx-mcp\",\n confidence: coverage.orgxObserved ? 0.78 : 0.7,\n metadata: {\n orgx_observed: coverage.orgxObserved,\n mcp_observed: coverage.mcpObserved,\n skill_only_signal: coverage.skillOnlySignal,\n },\n });\n }\n\n if (coverage.missing.length > 0) {\n opportunities.push({\n type: \"missed_orchestration_opportunity\",\n title: \"Source coverage is incomplete\",\n summary: `Missing sources: ${coverage.missing.join(\", \")}.`,\n source_client: \"wizard\",\n source_id: \"work-graph\",\n evidence_ref: \"work-graph:coverage:missing\",\n confidence: 0.76,\n metadata: { missing_sources: coverage.missing },\n });\n }\n\n return opportunities;\n}\n\nfunction scoreOpportunity(\n coverage: WorkGraphSourceCoverage,\n findings: readonly WorkGraphFinding[],\n): WorkGraphOpportunityScore {\n const count = (type: WorkGraphFindingType) => findings.filter((finding) => finding.type === type).length;\n const decisions = count(\"decision\");\n const artifacts = count(\"artifact\");\n const blockers = count(\"blocker\");\n const actions = count(\"action\");\n const people = count(\"person\");\n const business = count(\"business\");\n const surfaces = count(\"product_surface\");\n const goals = count(\"goal\");\n\n const evidenceQuality = clampScore(35 + Math.min(35, artifacts * 9 + decisions * 6) + Math.min(20, coverage.connected.length * 6) - coverage.missing.length * 8);\n const urgency = clampScore(20 + blockers * 18 + actions * 7 + decisions * 5);\n const ownerClarity = clampScore(25 + people * 18 + (findings.some((finding) => /\\b(owner|dri|responsible|founder)\\b/i.test(finding.summary)) ? 35 : 0));\n const automationPotential = clampScore(30 + actions * 10 + surfaces * 7 + (coverage.mcpObserved ? 12 : 0));\n const valuePotential = clampScore(25 + business * 20 + artifacts * 8 + goals * 10 + surfaces * 5);\n const orgxFit = clampScore(35 + decisions * 8 + blockers * 10 + artifacts * 7 + (coverage.orgxObserved ? 10 : 0) + (!coverage.orgxMcpCalled ? 10 : 0));\n\n return {\n overall: clampScore((valuePotential + evidenceQuality + urgency + ownerClarity + automationPotential + orgxFit) / 6),\n value_potential: valuePotential,\n evidence_quality: evidenceQuality,\n urgency,\n owner_clarity: ownerClarity,\n automation_potential: automationPotential,\n orgx_fit: orgxFit,\n };\n}\n\nfunction inferFinalState(findings: readonly WorkGraphFinding[]): WorkGraphFinalState {\n if (findings.some((finding) => finding.type === \"blocker\")) return \"blocked\";\n if (findings.some((finding) => finding.type === \"artifact\" || /\\b(shipped|completed|done|verified)\\b/i.test(finding.summary))) {\n return \"completed\";\n }\n if (findings.some((finding) => finding.type === \"action\" || finding.type === \"decision\")) return \"in_progress\";\n return \"unknown\";\n}\n\nfunction buildKickoffs(\n findings: readonly WorkGraphFinding[],\n missed: readonly WorkGraphFinding[],\n score: WorkGraphOpportunityScore,\n): WorkGraphKickoffCandidate[] {\n const blockers = findings.filter((finding) => finding.type === \"blocker\").slice(0, 3);\n const decisions = findings.filter((finding) => finding.type === \"decision\").slice(0, 3);\n const artifacts = findings.filter((finding) => finding.type === \"artifact\").slice(0, 3);\n const kickoffs: WorkGraphKickoffCandidate[] = [];\n\n if (missed.length > 0) {\n kickoffs.push({\n title: \"Install continuous OrgX writeback\",\n summary: \"Turn detected work into live OrgX activity, retro, outcome, and decision records.\",\n reason: missed[0]?.summary ?? \"A source produced work without durable OrgX orchestration.\",\n finding_refs: missed.map((finding) => finding.evidence_ref).slice(0, 4),\n priority: score.overall >= 75 ? \"p0\" : \"p1\",\n });\n }\n\n if (blockers.length > 0 || decisions.length > 0) {\n kickoffs.push({\n title: \"Resolve the hidden decision queue\",\n summary: \"Convert unresolved decisions and blockers into owner-visible OrgX decision cards.\",\n reason: \"The Work Graph found decisions or blockers that can slow execution if they stay buried in transcripts.\",\n finding_refs: [...blockers, ...decisions].map((finding) => finding.evidence_ref).slice(0, 5),\n priority: blockers.length > 0 ? \"p0\" : \"p1\",\n });\n }\n\n if (artifacts.length > 0) {\n kickoffs.push({\n title: \"Attach proof to the operating loop\",\n summary: \"Promote completed work into artifacts with owners, evidence refs, and next actions.\",\n reason: \"Completed work was detected; OrgX can make it queryable and reusable.\",\n finding_refs: artifacts.map((finding) => finding.evidence_ref),\n priority: \"p1\",\n });\n }\n\n if (kickoffs.length === 0) {\n kickoffs.push({\n title: \"Connect first work source\",\n summary: \"Add AI client, Slack, or MCP source coverage so OrgX can build a useful Work Graph.\",\n reason: \"The scan did not find enough structured work to recommend a specific operating initiative.\",\n finding_refs: [],\n priority: \"p2\",\n });\n }\n\n return kickoffs.slice(0, 3);\n}\n\nfunction entityTypeForFinding(finding: WorkGraphFinding): WorkGraphEntityType {\n switch (finding.type) {\n case \"decision\":\n return \"decision\";\n case \"artifact\":\n return \"artifact\";\n case \"blocker\":\n return \"blocker\";\n case \"person\":\n return \"person\";\n case \"business\":\n return \"business\";\n case \"product_surface\":\n return \"surface\";\n case \"goal\":\n case \"initiative_candidate\":\n return \"initiative\";\n case \"action\":\n return /\\b(outcome|shipped|completed|verified)\\b/i.test(finding.summary) ? \"outcome\" : \"task\";\n case \"missed_orchestration_opportunity\":\n return \"source\";\n }\n}\n\nfunction trailKindForEntity(entityType: WorkGraphEntityType): WorkGraphTrailKind {\n switch (entityType) {\n case \"decision\":\n return \"decision_trail\";\n case \"artifact\":\n return \"artifact_trail\";\n case \"person\":\n return \"person_trail\";\n case \"business\":\n return \"business_trail\";\n case \"blocker\":\n return \"blocker_trail\";\n case \"agent\":\n return \"agent_trail\";\n case \"tool\":\n case \"source\":\n return \"source_trail\";\n case \"outcome\":\n return \"outcome_trail\";\n case \"idea\":\n return \"idea_trail\";\n case \"initiative\":\n case \"workstream\":\n case \"milestone\":\n case \"task\":\n case \"surface\":\n return \"initiative_trail\";\n }\n}\n\nfunction eventTypeForFinding(finding: WorkGraphFinding): WorkGraphTrailEvent[\"event_type\"] {\n switch (finding.type) {\n case \"decision\":\n return \"decision_inferred\";\n case \"artifact\":\n return /\\b(verified|proof|tested|passed)\\b/i.test(finding.summary)\n ? \"artifact_verified\"\n : \"artifact_created\";\n case \"blocker\":\n return \"blocker_detected\";\n case \"person\":\n return \"owner_assigned\";\n case \"business\":\n return \"signal_detected\";\n case \"product_surface\":\n return \"signal_detected\";\n case \"goal\":\n case \"initiative_candidate\":\n return \"initiative_created\";\n case \"action\":\n return /\\b(outcome|result|impact|roi)\\b/i.test(finding.summary)\n ? \"outcome_recorded\"\n : \"recommendation_generated\";\n case \"missed_orchestration_opportunity\":\n return \"source_connected\";\n }\n}\n\nfunction trailStateForFindings(findings: readonly WorkGraphFinding[]): WorkGraphTrailState {\n if (findings.some((finding) => finding.type === \"blocker\")) return \"blocked\";\n if (findings.some((finding) => finding.type === \"missed_orchestration_opportunity\")) return \"missing_evidence\";\n if (findings.some((finding) => /\\b(contradict|conflict)\\b/i.test(finding.summary))) return \"contradicted\";\n if (findings.some((finding) => /\\b(verified|proof|passed|complete_with_proof)\\b/i.test(finding.summary))) return \"verified\";\n if (findings.some((finding) => finding.type === \"decision\")) return \"inferred\";\n return \"observed\";\n}\n\nfunction trailValenceForFindings(findings: readonly WorkGraphFinding[], recurrence: number): WorkGraphTrailValence {\n if (findings.some((finding) => finding.type === \"blocker\")) return recurrence > 1 ? \"escalating\" : \"risk\";\n if (findings.some((finding) => finding.type === \"missed_orchestration_opportunity\")) return \"leak\";\n if (findings.some((finding) => finding.type === \"decision\") && recurrence > 1) return \"wasteful_recurrence\";\n if (findings.some((finding) => finding.type === \"business\")) return \"opportunity\";\n if (findings.some((finding) => finding.type === \"artifact\")) return \"healthy\";\n return recurrence > 1 ? \"useful_recurrence\" : \"opportunity\";\n}\n\nfunction trailShapeForFindings(findings: readonly WorkGraphFinding[], recurrence: number): WorkGraphTrail[\"shape\"] {\n const decisions = findings.filter((finding) => finding.type === \"decision\").length;\n const artifacts = findings.filter((finding) => finding.type === \"artifact\").length;\n if (decisions > artifacts && decisions > 0) return \"decision_heavy_artifact_light\";\n if (artifacts > decisions && artifacts > 0 && decisions === 0) return \"artifact_heavy_decision_light\";\n if (findings.some((finding) => finding.type === \"blocker\")) return \"accelerating_issue\";\n if (recurrence >= 3) return \"chronic_recurrence\";\n if (findings.some((finding) => /\\b(resurface|again|back|revived|reappeared)\\b/i.test(finding.summary))) return \"zombie_revival\";\n if (findings.some((finding) => /\\b(verified|passed|shipped|completed)\\b/i.test(finding.summary))) return \"healthy_execution\";\n return \"dense_recent_cluster\";\n}\n\nexport function buildWorkGraphTrails(\n findings: readonly WorkGraphFinding[],\n generatedAt: string,\n): WorkGraphTrail[] {\n const grouped = new Map<string, WorkGraphFinding[]>();\n\n for (const finding of findings) {\n const entityType = entityTypeForFinding(finding);\n const key = `${entityType}:${slugPart(finding.title)}`;\n grouped.set(key, [...(grouped.get(key) ?? []), finding]);\n }\n\n return [...grouped.entries()].map(([key, group], index) => {\n const first = group[0]!;\n const entityType = entityTypeForFinding(first);\n const entityId = `${entityType}:${shortHash(key, 12)}`;\n const trailId = `trail:${shortHash({ key, evidence: group.map((finding) => finding.evidence_ref) }, 14)}`;\n const recurrence = group.length;\n const evidenceRefs = sortedUnique(group.map((finding) => finding.evidence_ref));\n const events: WorkGraphTrailEvent[] = group.map((finding, eventIndex) => ({\n id: `${trailId}:event:${eventIndex + 1}`,\n trail_id: trailId,\n event_type: eventTypeForFinding(finding),\n entity_id: entityId,\n entity_type: entityType,\n timestamp: generatedAt,\n source_id: finding.source_id,\n source_type: finding.source_client,\n redacted_verbatim: finding.summary.slice(0, 320),\n confidence: finding.confidence,\n evidence_refs: [finding.evidence_ref],\n privacy_state: \"redacted\",\n }));\n const edges: WorkGraphTrailEdge[] = events.slice(1).map((event, edgeIndex) => ({\n id: `${trailId}:edge:${edgeIndex + 1}`,\n from_event_id: events[edgeIndex]!.id,\n to_event_id: event.id,\n relation: group.some((finding) => finding.type === \"blocker\") ? \"blocked\" : \"informed\",\n state: recurrence > 1 ? \"captured\" : \"inferred\",\n confidence: Math.min(0.92, Math.max(0.58, event.confidence - 0.04)),\n evidence_refs: event.evidence_refs,\n }));\n const confidence =\n group.reduce((total, finding) => total + finding.confidence, 0) / group.length;\n\n return {\n id: trailId,\n kind: trailKindForEntity(entityType),\n title: first.title,\n summary: first.summary,\n subject_entity_id: entityId,\n subject_entity_type: entityType,\n state: trailStateForFindings(group),\n valence: trailValenceForFindings(group, recurrence),\n confidence: Number(confidence.toFixed(2)),\n recurrence_score: Math.min(100, recurrence * 28 + evidenceRefs.length * 6),\n impact_score: Math.min(100, Math.round(first.confidence * 70) + recurrence * 8 + (index < 4 ? 10 : 0)),\n privacy_state: \"redacted\",\n events,\n edges,\n evidence_refs: evidenceRefs,\n blocker_ids: group.filter((finding) => finding.type === \"blocker\").map((finding) => finding.evidence_ref),\n recommendation_ids: [],\n created_at: generatedAt,\n updated_at: generatedAt,\n shape: trailShapeForFindings(group, recurrence),\n };\n });\n}\n\nfunction severityFor(count: number): WorkGraphRecurringPattern[\"severity\"] {\n if (count >= 6) return \"critical\";\n if (count >= 3) return \"high\";\n if (count >= 2) return \"medium\";\n return \"low\";\n}\n\nfunction trailsForType(trails: readonly WorkGraphTrail[], entityType: WorkGraphEntityType): WorkGraphTrail[] {\n return trails.filter((trail) => trail.subject_entity_type === entityType);\n}\n\nexport function buildRecurringPatterns(\n coverage: WorkGraphSourceCoverage,\n findings: readonly WorkGraphFinding[],\n trails: readonly WorkGraphTrail[],\n): WorkGraphRecurringPattern[] {\n const patterns: WorkGraphRecurringPattern[] = [];\n const decisionTrails = trailsForType(trails, \"decision\");\n const artifactTrails = trailsForType(trails, \"artifact\");\n const blockerTrails = trailsForType(trails, \"blocker\");\n const personTrails = trailsForType(trails, \"person\");\n const businessTrails = trailsForType(trails, \"business\");\n const highRecurrence = trails.filter((trail) => trail.recurrence_score >= 56);\n\n if (decisionTrails.length > 0 && !coverage.orgxMcpCalled) {\n patterns.push({\n id: \"pattern:trapped-decision\",\n title: \"Decisions are being made without durable OrgX writeback\",\n description: `${decisionTrails.length} decision trail${decisionTrails.length === 1 ? \"\" : \"s\"} appeared while no OrgX MCP write was detected.`,\n pattern_type: \"trapped_decision\",\n affected_trail_ids: decisionTrails.map((trail) => trail.id),\n affected_entity_ids: decisionTrails.map((trail) => trail.subject_entity_id),\n recurrence_count: decisionTrails.length,\n severity: severityFor(decisionTrails.length + 1),\n confidence: coverage.orgxObserved ? 0.82 : 0.74,\n valence: \"leak\",\n root_cause_hypothesis: \"Agents and humans are making useful choices, but the runtime is not promoting those choices into organizational memory.\",\n recommended_runtime_action_id: \"recommendation:promote-decisions\",\n });\n }\n\n if (artifactTrails.length > 0 && personTrails.length === 0) {\n patterns.push({\n id: \"pattern:orphaned-artifact\",\n title: \"Artifacts do not have visible ownership\",\n description: `${artifactTrails.length} artifact trail${artifactTrails.length === 1 ? \"\" : \"s\"} appeared without a clear owner trail.`,\n pattern_type: \"orphaned_artifact\",\n affected_trail_ids: artifactTrails.map((trail) => trail.id),\n affected_entity_ids: artifactTrails.map((trail) => trail.subject_entity_id),\n recurrence_count: artifactTrails.length,\n severity: severityFor(artifactTrails.length),\n confidence: 0.72,\n valence: \"risk\",\n root_cause_hypothesis: \"Work is becoming concrete, but downstream accountability is not being attached at creation time.\",\n recommended_runtime_action_id: \"recommendation:assign-owner\",\n });\n }\n\n if (coverage.missing.length > 0) {\n const sourceTrails = trailsForType(trails, \"source\");\n patterns.push({\n id: \"pattern:missing-source\",\n title: \"Important source coverage is missing\",\n description: `Missing sources: ${coverage.missing.join(\", \")}.`,\n pattern_type: \"missing_source\",\n affected_trail_ids: sourceTrails.map((trail) => trail.id),\n affected_entity_ids: sourceTrails.map((trail) => trail.subject_entity_id),\n recurrence_count: coverage.missing.length,\n severity: severityFor(coverage.missing.length),\n confidence: 0.78,\n valence: \"leak\",\n root_cause_hypothesis: \"The scan can see work happening, but coordination and proof sources are not fully connected.\",\n recommended_runtime_action_id: \"recommendation:connect-source\",\n });\n }\n\n if (coverage.mcpObserved && !coverage.orgxMcpCalled) {\n patterns.push({\n id: \"pattern:tooling-mismatch\",\n title: \"MCP was present, but OrgX was not called\",\n description: \"The session mentions MCP/tooling activity, but no durable OrgX MCP call was detected.\",\n pattern_type: \"tooling_mismatch\",\n affected_trail_ids: trails.map((trail) => trail.id).slice(0, 6),\n affected_entity_ids: trails.map((trail) => trail.subject_entity_id).slice(0, 6),\n recurrence_count: findings.filter((finding) => /\\bmcp|tool\\b/i.test(finding.summary)).length || 1,\n severity: \"high\",\n confidence: 0.8,\n valence: \"leak\",\n root_cause_hypothesis: \"The available tool layer is not automatically closing the loop when work finishes.\",\n recommended_runtime_action_id: \"recommendation:install-runtime-hooks\",\n });\n }\n\n if (highRecurrence.length > 0) {\n patterns.push({\n id: \"pattern:repeated-work\",\n title: \"The same work shape is recurring\",\n description: `${highRecurrence.length} trail${highRecurrence.length === 1 ? \"\" : \"s\"} repeat strongly enough to deserve durable operating memory.`,\n pattern_type: \"repeated_work\",\n affected_trail_ids: highRecurrence.map((trail) => trail.id),\n affected_entity_ids: highRecurrence.map((trail) => trail.subject_entity_id),\n recurrence_count: highRecurrence.reduce((total, trail) => total + trail.events.length, 0),\n severity: severityFor(highRecurrence.length),\n confidence: 0.7,\n valence: \"useful_recurrence\",\n root_cause_hypothesis: \"Repeated work is creating a reusable operating pattern, but it is still only implicit.\",\n recommended_runtime_action_id: \"recommendation:launch-initiative\",\n });\n }\n\n if (businessTrails.length > 0 && findings.every((finding) => finding.type !== \"initiative_candidate\")) {\n patterns.push({\n id: \"pattern:business-signal-unclaimed\",\n title: \"Business signal has not become a launchable initiative\",\n description: `${businessTrails.length} business trail${businessTrails.length === 1 ? \"\" : \"s\"} appeared without a matching initiative candidate.`,\n pattern_type: \"business_signal_unclaimed\",\n affected_trail_ids: businessTrails.map((trail) => trail.id),\n affected_entity_ids: businessTrails.map((trail) => trail.subject_entity_id),\n recurrence_count: businessTrails.length,\n severity: severityFor(businessTrails.length),\n confidence: 0.68,\n valence: \"opportunity\",\n root_cause_hypothesis: \"Revenue or ROI signal exists, but the operating graph has not turned it into an account or initiative loop.\",\n recommended_runtime_action_id: \"recommendation:launch-initiative\",\n });\n }\n\n if (blockerTrails.length > 0) {\n patterns.push({\n id: \"pattern:handoff-friction\",\n title: \"Blockers are becoming handoff friction\",\n description: `${blockerTrails.length} blocker trail${blockerTrails.length === 1 ? \"\" : \"s\"} need owner-visible resolution.`,\n pattern_type: \"handoff_friction\",\n affected_trail_ids: blockerTrails.map((trail) => trail.id),\n affected_entity_ids: blockerTrails.map((trail) => trail.subject_entity_id),\n recurrence_count: blockerTrails.length,\n severity: severityFor(blockerTrails.length + 1),\n confidence: 0.76,\n valence: \"risk\",\n root_cause_hypothesis: \"Execution is producing unresolved edges that need to become assigned decisions or tasks.\",\n recommended_runtime_action_id: \"recommendation:assign-owner\",\n });\n }\n\n return patterns.slice(0, 8);\n}\n\nexport function buildTrailRecommendations(\n patterns: readonly WorkGraphRecurringPattern[],\n trails: readonly WorkGraphTrail[],\n): WorkGraphTrailRecommendation[] {\n const recommendations: WorkGraphTrailRecommendation[] = [];\n const add = (recommendation: WorkGraphTrailRecommendation) => {\n if (!recommendations.some((existing) => existing.id === recommendation.id)) {\n recommendations.push(recommendation);\n }\n };\n\n for (const pattern of patterns) {\n const evidenceRefs = sortedUnique(\n trails\n .filter((trail) => pattern.affected_trail_ids.includes(trail.id))\n .flatMap((trail) => trail.evidence_refs),\n ).slice(0, 8);\n if (pattern.pattern_type === \"trapped_decision\") {\n add({\n id: \"recommendation:promote-decisions\",\n title: \"Promote trapped decisions\",\n summary: \"Turn inferred decisions into reviewed OrgX decision records with owners and downstream artifact links.\",\n action_type: \"promote_decision\",\n trail_ids: pattern.affected_trail_ids,\n evidence_refs: evidenceRefs,\n priority: pattern.severity === \"critical\" || pattern.severity === \"high\" ? \"p0\" : \"p1\",\n expected_lift: \"+decision durability\",\n confidence: pattern.confidence,\n });\n } else if (pattern.pattern_type === \"orphaned_artifact\") {\n add({\n id: \"recommendation:assign-owner\",\n title: \"Assign ownership to orphaned artifacts\",\n summary: \"Attach owners and next actions to artifacts before they decay into unqueryable receipts.\",\n action_type: \"assign_owner\",\n trail_ids: pattern.affected_trail_ids,\n evidence_refs: evidenceRefs,\n priority: \"p1\",\n expected_lift: \"+owner clarity\",\n confidence: pattern.confidence,\n });\n } else if (pattern.pattern_type === \"missing_source\") {\n add({\n id: \"recommendation:connect-source\",\n title: \"Connect missing source coverage\",\n summary: \"Close the evidence gap by connecting the coordination or proof sources where trails terminate.\",\n action_type: \"connect_source\",\n trail_ids: pattern.affected_trail_ids,\n evidence_refs: evidenceRefs,\n priority: \"p1\",\n expected_lift: \"+source confidence\",\n confidence: pattern.confidence,\n });\n } else if (pattern.pattern_type === \"tooling_mismatch\") {\n add({\n id: \"recommendation:install-runtime-hooks\",\n title: \"Install runtime writeback hooks\",\n summary: \"Use post-session reconciliation so useful work becomes OrgX activity even when the agent forgets.\",\n action_type: \"verify_outcome\",\n trail_ids: pattern.affected_trail_ids,\n evidence_refs: evidenceRefs,\n priority: \"p0\",\n expected_lift: \"+continuous attribution\",\n confidence: pattern.confidence,\n });\n } else if (pattern.pattern_type === \"business_signal_unclaimed\" || pattern.pattern_type === \"repeated_work\") {\n add({\n id: \"recommendation:launch-initiative\",\n title: \"Launch from this trail\",\n summary: \"Convert the highest-recurring evidence path into an OrgX initiative with proof requirements.\",\n action_type: \"launch_initiative\",\n trail_ids: pattern.affected_trail_ids,\n evidence_refs: evidenceRefs,\n priority: pattern.severity === \"critical\" || pattern.severity === \"high\" ? \"p0\" : \"p1\",\n expected_lift: \"+initiative readiness\",\n confidence: pattern.confidence,\n });\n }\n }\n\n if (recommendations.length === 0 && trails.length > 0) {\n const topTrail = [...trails].sort((a, b) => b.impact_score - a.impact_score)[0]!;\n add({\n id: \"recommendation:inspect-top-trail\",\n title: \"Inspect the strongest trail\",\n summary: \"Review the highest-confidence evidence path and decide whether it should become durable OrgX memory.\",\n action_type: \"launch_initiative\",\n trail_ids: [topTrail.id],\n evidence_refs: topTrail.evidence_refs,\n priority: \"p2\",\n expected_lift: \"+operating memory\",\n confidence: topTrail.confidence,\n });\n }\n\n return recommendations.slice(0, 5);\n}\n\nexport function buildWorkGraphMirror(input: {\n coverage: WorkGraphSourceCoverage;\n generatedAt: string;\n patterns: readonly WorkGraphRecurringPattern[];\n recommendations: readonly WorkGraphTrailRecommendation[];\n trails: readonly WorkGraphTrail[];\n}): WorkGraphMirror {\n const { coverage, generatedAt, patterns, recommendations, trails } = input;\n const topTrail = [...trails].sort((a, b) => b.impact_score - a.impact_score)[0];\n const topPattern = [...patterns].sort((a, b) => b.recurrence_count - a.recurrence_count)[0];\n const decisionCount = trailsForType(trails, \"decision\").length;\n const artifactCount = trailsForType(trails, \"artifact\").length;\n const blockerCount = trailsForType(trails, \"blocker\").length;\n const sourceGapCount = coverage.missing.length;\n const headline = topPattern\n ? topPattern.title\n : topTrail\n ? `${topTrail.title} is the clearest work trail`\n : \"Your work is leaving an operating trail\";\n const primaryClaimRefs = topTrail?.evidence_refs ?? [];\n const claims: WorkGraphMirrorClaim[] = [\n {\n id: \"mirror:trail-count\",\n text: `${trails.length} trails were detected across ${coverage.connected.length} connected source${coverage.connected.length === 1 ? \"\" : \"s\"}.`,\n evidence_refs: trails.flatMap((trail) => trail.evidence_refs).slice(0, 6),\n confidence: trails.length > 0 ? 0.82 : 0.55,\n },\n {\n id: \"mirror:decision-artifact-balance\",\n text: `${decisionCount} decision trail${decisionCount === 1 ? \"\" : \"s\"} and ${artifactCount} artifact trail${artifactCount === 1 ? \"\" : \"s\"} were found.`,\n evidence_refs: trails\n .filter((trail) => trail.subject_entity_type === \"decision\" || trail.subject_entity_type === \"artifact\")\n .flatMap((trail) => trail.evidence_refs)\n .slice(0, 6),\n confidence: 0.78,\n },\n {\n id: \"mirror:missing-sources\",\n text: sourceGapCount > 0\n ? `${sourceGapCount} source gap${sourceGapCount === 1 ? \"\" : \"s\"} still limit attribution depth.`\n : \"The connected sources are enough for a first operating profile.\",\n evidence_refs: trailsForType(trails, \"source\").flatMap((trail) => trail.evidence_refs).slice(0, 4),\n confidence: sourceGapCount > 0 ? 0.76 : 0.66,\n },\n ];\n const body = [\n `OrgX found ${trails.length} evidence trail${trails.length === 1 ? \"\" : \"s\"} across ${coverage.connected.join(\", \") || \"local sources\"}.`,\n `The strongest signal is ${topPattern ? topPattern.title.toLowerCase() : topTrail?.title ?? \"still forming\"}.`,\n blockerCount > 0\n ? `${blockerCount} blocker trail${blockerCount === 1 ? \"\" : \"s\"} need promotion into owner-visible work.`\n : \"The healthiest trails already connect evidence to action.\",\n recommendations[0]\n ? `The next durable move is: ${recommendations[0].title}.`\n : \"The next move is to inspect the highest-confidence trail before publishing it.\",\n ].join(\" \");\n\n return {\n headline,\n body,\n lens: \"all\",\n claims,\n ...(topTrail ? { primary_trail_id: topTrail.id } : {}),\n generated_at: generatedAt,\n };\n}\n\nexport function buildTensionMetrics(input: {\n coverage: WorkGraphSourceCoverage;\n patterns: readonly WorkGraphRecurringPattern[];\n trails: readonly WorkGraphTrail[];\n}): WorkGraphTensionMetric[] {\n const { coverage, patterns, trails } = input;\n const decisionTrails = trailsForType(trails, \"decision\");\n const blockerTrails = trailsForType(trails, \"blocker\");\n const artifactTrails = trailsForType(trails, \"artifact\");\n const missingSourceTrails = trailsForType(trails, \"source\");\n const topReady = trails.filter((trail) => trail.impact_score >= 70 && trail.confidence >= 0.75);\n\n return [\n {\n id: \"tension:work-leaks\",\n label: \"work leaks\",\n value: String(patterns.filter((pattern) => pattern.valence === \"leak\" || pattern.valence === \"risk\").length),\n tone: patterns.some((pattern) => pattern.severity === \"critical\" || pattern.severity === \"high\") ? \"danger\" : \"warning\",\n trail_ids: patterns.flatMap((pattern) => pattern.affected_trail_ids).slice(0, 8),\n evidence_refs: trails.flatMap((trail) => trail.evidence_refs).slice(0, 8),\n explanation: \"Patterns where evidence exists but ownership, source coverage, or writeback is incomplete.\",\n },\n {\n id: \"tension:decisions-decaying\",\n label: \"decisions decaying\",\n value: String(decisionTrails.filter((trail) => trail.state === \"inferred\" || trail.state === \"missing_evidence\").length),\n tone: decisionTrails.length > 0 && !coverage.orgxMcpCalled ? \"danger\" : \"muted\",\n trail_ids: decisionTrails.map((trail) => trail.id),\n evidence_refs: decisionTrails.flatMap((trail) => trail.evidence_refs).slice(0, 8),\n explanation: \"Decision trails that have not been promoted into durable OrgX records.\",\n },\n {\n id: \"tension:artifacts-orphaned\",\n label: \"artifacts orphaned\",\n value: String(artifactTrails.filter((trail) => trail.state !== \"verified\").length),\n tone: artifactTrails.some((trail) => trail.shape === \"artifact_heavy_decision_light\") ? \"warning\" : \"muted\",\n trail_ids: artifactTrails.map((trail) => trail.id),\n evidence_refs: artifactTrails.flatMap((trail) => trail.evidence_refs).slice(0, 8),\n explanation: \"Artifacts that exist without complete decision, verification, or owner context.\",\n },\n {\n id: \"tension:sources-missing\",\n label: \"sources missing\",\n value: String(coverage.missing.length),\n tone: coverage.missing.length > 0 ? \"warning\" : \"good\",\n trail_ids: missingSourceTrails.map((trail) => trail.id),\n evidence_refs: missingSourceTrails.flatMap((trail) => trail.evidence_refs).slice(0, 6),\n explanation: \"Disconnected coordination or proof sources that limit attribution confidence.\",\n },\n {\n id: \"tension:launch-ready\",\n label: \"launch ready\",\n value: String(topReady.length),\n tone: topReady.length > 0 && blockerTrails.length === 0 ? \"good\" : \"muted\",\n trail_ids: topReady.map((trail) => trail.id).slice(0, 6),\n evidence_refs: topReady.flatMap((trail) => trail.evidence_refs).slice(0, 8),\n explanation: \"High-confidence trails that can become initiatives, decisions, artifacts, or owner-visible follow-ups.\",\n },\n ];\n}\n\nfunction countFindingsByType(\n findings: readonly WorkGraphFinding[],\n): Partial<Record<WorkGraphFindingType, number>> {\n const counts: Partial<Record<WorkGraphFindingType, number>> = {};\n for (const finding of findings) {\n counts[finding.type] = (counts[finding.type] ?? 0) + 1;\n }\n return Object.fromEntries(\n Object.entries(counts).sort(([left], [right]) => left.localeCompare(right)),\n ) as Partial<Record<WorkGraphFindingType, number>>;\n}\n\nexport function buildWorkGraphFingerprint(input: {\n connectedSources: readonly string[];\n findings: readonly WorkGraphFinding[];\n kickoffs: readonly WorkGraphKickoffCandidate[];\n missingSources: readonly string[];\n recurringPatterns: readonly WorkGraphRecurringPattern[];\n trails: readonly WorkGraphTrail[];\n workspace: WorkGraphWorkspaceRef;\n}): { fingerprint: string; basis: WorkGraphFingerprintBasis; hydration: WorkGraphSignupHydration } {\n const sourceClients = sortedUnique(input.findings.map((finding) => finding.source_client));\n const patternHashes = input.findings\n .map((finding) =>\n shortHash({\n type: finding.type,\n title: normalizeFingerprintText(finding.title),\n summary: normalizeFingerprintText(finding.summary),\n source_client: finding.source_client,\n }),\n )\n .sort();\n const kickoffHashes = input.kickoffs\n .map((kickoff) =>\n shortHash({\n title: normalizeFingerprintText(kickoff.title),\n summary: normalizeFingerprintText(kickoff.summary),\n priority: kickoff.priority,\n }),\n )\n .sort();\n const trailShapeHashes = input.trails\n .map((trail) =>\n shortHash({\n kind: trail.kind,\n subject_entity_type: trail.subject_entity_type,\n state: trail.state,\n valence: trail.valence,\n shape: trail.shape,\n title: normalizeFingerprintText(trail.title),\n }),\n )\n .sort();\n const recurringPatternHashes = input.recurringPatterns\n .map((pattern) =>\n shortHash({\n pattern_type: pattern.pattern_type,\n severity: pattern.severity,\n title: normalizeFingerprintText(pattern.title),\n recurrence_count: pattern.recurrence_count,\n }),\n )\n .sort();\n\n const basis: WorkGraphFingerprintBasis = {\n schema_version: WORK_GRAPH_SCHEMA_VERSION,\n fingerprint_version: WORK_GRAPH_FINGERPRINT_VERSION,\n workspace_hash: shortHash({\n id: normalizeFingerprintText(input.workspace.id),\n name: normalizeFingerprintText(input.workspace.name),\n }),\n source_clients: sourceClients,\n connected_source_hashes: sortedUnique(\n input.connectedSources.map((source) => shortHash(normalizeFingerprintText(source))),\n ),\n missing_source_hashes: sortedUnique(\n input.missingSources.map((source) => shortHash(normalizeFingerprintText(source))),\n ),\n finding_type_counts: countFindingsByType(input.findings),\n pattern_hashes: patternHashes,\n trail_shape_hashes: trailShapeHashes,\n recurring_pattern_hashes: recurringPatternHashes,\n kickoff_hashes: kickoffHashes,\n raw_transcripts_included: false,\n };\n const fingerprint = `wgf_${hashJson(basis).slice(0, 24)}`;\n\n return {\n fingerprint,\n basis,\n hydration: {\n strategy: \"work_graph_fingerprint_claim\",\n hydration_key: `orgx:work-graph:${fingerprint}`,\n eligible: input.findings.length > 0,\n notes: [\n \"Use this fingerprint to claim the pre-signup Work Graph after account creation.\",\n \"The fingerprint is derived from normalized patterns, source coverage, and kickoff shapes, not raw transcripts.\",\n ],\n },\n };\n}\n\nexport function buildSessionReconciliationReport(\n input: BuildSessionReconciliationReportInput,\n): SessionReconciliationReport {\n const clientExtractions = input.clientExtractions ?? [];\n if (input.imports.length === 0 && clientExtractions.length === 0) {\n throw new Error(\"At least one source import or AI-client extraction is required to build a Work Graph report.\");\n }\n\n const generatedAt = input.generatedAt ?? new Date().toISOString();\n const clientExtractionSummaries = summarizeClientExtractions(clientExtractions);\n const connectedSources = sortedUnique([\n ...(input.connectedSources ?? input.imports.map((source) => source.sourceLabel)),\n ...clientExtractionSummaries.map((summary) => summary.source_label),\n ]);\n const missingSources = input.missingSources ?? [];\n const coverage = buildCoverage(input.imports, connectedSources, missingSources, clientExtractions);\n const events = [...buildWorkGraphEvents(input.imports), ...buildClientExtractionEvents(clientExtractions)];\n const findings = [...buildWorkGraphFindings(input.imports), ...buildClientExtractionFindings(clientExtractions)];\n const autoMissed = buildMissedOpportunities(coverage, findings);\n const extractedMissed = findings.filter((finding) => finding.type === \"missed_orchestration_opportunity\");\n const missed = [...extractedMissed, ...autoMissed].filter((finding, index, all) =>\n all.findIndex((candidate) => candidate.evidence_ref === finding.evidence_ref) === index\n );\n const allFindings = [...findings, ...autoMissed];\n const trails = buildWorkGraphTrails(allFindings, generatedAt);\n const recurringPatterns = buildRecurringPatterns(coverage, allFindings, trails);\n const opportunityScore = scoreOpportunity(coverage, allFindings);\n const initiativeKickoffs = buildKickoffs(allFindings, missed, opportunityScore);\n const recommendations = buildTrailRecommendations(recurringPatterns, trails);\n const mirror = buildWorkGraphMirror({\n coverage,\n generatedAt,\n patterns: recurringPatterns,\n recommendations,\n trails,\n });\n const tensionMetrics = buildTensionMetrics({\n coverage,\n patterns: recurringPatterns,\n trails,\n });\n const fingerprint = buildWorkGraphFingerprint({\n connectedSources,\n findings: allFindings,\n kickoffs: initiativeKickoffs,\n missingSources,\n recurringPatterns,\n trails,\n workspace: input.workspace,\n });\n const reportSeed = {\n generatedAt,\n clientExtractions: clientExtractions.map((extraction, index) => ({\n extractionId: normalizeClientExtractionId(extraction, index),\n findingHash: hashJson(extraction.findings),\n })),\n imports: input.imports.map((source) => ({\n sourceId: source.sourceId,\n textHash: hashJson(source.text),\n })),\n workspace: input.workspace,\n };\n const reportHash = hashJson(reportSeed);\n const sessionId = input.sessionId ?? `work-graph-${reportHash.slice(0, 16)}`;\n\n return {\n schema_version: WORK_GRAPH_SCHEMA_VERSION,\n report_id: reportHash.slice(0, 24),\n idempotency_key: `work-graph:${sessionId}:${reportHash.slice(0, 16)}`,\n work_graph_fingerprint: fingerprint.fingerprint,\n fingerprint_version: WORK_GRAPH_FINGERPRINT_VERSION,\n fingerprint_basis: fingerprint.basis,\n signup_hydration: fingerprint.hydration,\n generated_at: generatedAt,\n source_client: \"wizard\",\n session_id: sessionId,\n workspace: input.workspace,\n extraction_protocol: buildWorkGraphExtractionProtocol(),\n client_extractions: clientExtractionSummaries,\n source_coverage: coverage,\n final_state: inferFinalState(allFindings),\n events,\n findings: allFindings,\n missed_orchestration_opportunities: missed,\n trails,\n recurring_patterns: recurringPatterns,\n recommendations,\n mirror,\n tension_metrics: tensionMetrics,\n opportunity_score: opportunityScore,\n initiative_kickoffs: initiativeKickoffs,\n redaction_level: \"summary_only\",\n raw_transcripts_sent: false,\n };\n}\n\nexport function renderWorkGraphExtractionProtocolMarkdown(\n protocol: WorkGraphExtractionProtocol = buildWorkGraphExtractionProtocol(),\n): string {\n const lines: string[] = [];\n lines.push(\"# OrgX Work Graph AI-Client Extraction Schema\");\n lines.push(\"\");\n lines.push(`Schema version: ${protocol.schema_version}`);\n lines.push(`Mode: ${protocol.mode}`);\n lines.push(\"\");\n lines.push(\"## Prompt\");\n lines.push(\"\");\n lines.push(protocol.prompt);\n lines.push(\"\");\n lines.push(\"## Objective\");\n lines.push(\"\");\n lines.push(protocol.schema.objective);\n lines.push(\"\");\n lines.push(\"## Search Lenses\");\n lines.push(\"\");\n for (const lens of protocol.schema.source_search_strategy) {\n lines.push(`- ${lens.lens}: ${lens.query} Return when: ${lens.return_when}`);\n }\n lines.push(\"\");\n lines.push(\"## Quality Bar\");\n lines.push(\"\");\n for (const item of protocol.schema.quality_bar) {\n lines.push(`- ${item}`);\n }\n lines.push(\"\");\n lines.push(\"## Reject As Noise\");\n lines.push(\"\");\n for (const item of protocol.schema.reject_as_noise) {\n lines.push(`- ${item}`);\n }\n lines.push(\"\");\n lines.push(\"## Required JSON Shape\");\n lines.push(\"\");\n lines.push(\"```json\");\n lines.push(JSON.stringify(protocol.schema.required_output, null, 2));\n lines.push(\"```\");\n\n return lines.join(\"\\n\");\n}\n\nexport function renderWorkGraphMarkdown(report: SessionReconciliationReport): string {\n const lines: string[] = [];\n lines.push(\"# OrgX Work Graph Reconciliation\");\n lines.push(\"\");\n lines.push(`Generated: ${report.generated_at}`);\n lines.push(`Workspace: ${report.workspace.name} (${report.workspace.id})`);\n lines.push(`Report ID: ${report.report_id}`);\n lines.push(`Work graph fingerprint: ${report.work_graph_fingerprint}`);\n lines.push(`Hydration key: ${report.signup_hydration.hydration_key}`);\n lines.push(`Final state: ${report.final_state}`);\n lines.push(\"\");\n lines.push(\"## AI-Client Search Protocol\");\n lines.push(\"\");\n lines.push(`Schema: ${report.extraction_protocol.schema_version}`);\n lines.push(report.extraction_protocol.prompt);\n lines.push(\"\");\n lines.push(\"Search lenses:\");\n for (const lens of report.extraction_protocol.schema.source_search_strategy) {\n lines.push(`- ${lens.lens}: ${lens.return_when}`);\n }\n lines.push(\"\");\n lines.push(\"## Client Extractions\");\n lines.push(\"\");\n if (report.client_extractions.length === 0) {\n lines.push(\"- No structured AI-client extraction files were provided; fallback local session import was used.\");\n } else {\n for (const extraction of report.client_extractions) {\n lines.push(`- ${extraction.source_label}: ${extraction.finding_count} findings, ${extraction.query_count} queries, ${extraction.searched_source_count} source groups, confidence ${extraction.confidence}`);\n }\n }\n lines.push(\"\");\n lines.push(\"## Opportunity Score\");\n lines.push(\"\");\n lines.push(`Overall: ${report.opportunity_score.overall}/100`);\n lines.push(`Value potential: ${report.opportunity_score.value_potential}/100`);\n lines.push(`Evidence quality: ${report.opportunity_score.evidence_quality}/100`);\n lines.push(`Urgency: ${report.opportunity_score.urgency}/100`);\n lines.push(`Owner clarity: ${report.opportunity_score.owner_clarity}/100`);\n lines.push(`Automation potential: ${report.opportunity_score.automation_potential}/100`);\n lines.push(`OrgX fit: ${report.opportunity_score.orgx_fit}/100`);\n lines.push(\"\");\n lines.push(\"## Source Coverage\");\n lines.push(\"\");\n lines.push(`Connected: ${report.source_coverage.connected.join(\", \") || \"none\"}`);\n lines.push(`Missing: ${report.source_coverage.missing.join(\", \") || \"none\"}`);\n lines.push(`MCP observed: ${report.source_coverage.mcpObserved ? \"yes\" : \"no\"}`);\n lines.push(`OrgX observed: ${report.source_coverage.orgxObserved ? \"yes\" : \"no\"}`);\n lines.push(`OrgX MCP called: ${report.source_coverage.orgxMcpCalled ? \"yes\" : \"no\"}`);\n lines.push(\"\");\n lines.push(\"## Mirror\");\n lines.push(\"\");\n lines.push(`### ${report.mirror.headline}`);\n lines.push(\"\");\n lines.push(report.mirror.body);\n lines.push(\"\");\n for (const claim of report.mirror.claims) {\n lines.push(`- ${claim.text} (${claim.evidence_refs.join(\", \") || \"no evidence refs\"})`);\n }\n lines.push(\"\");\n lines.push(\"## Live Tension\");\n lines.push(\"\");\n for (const metric of report.tension_metrics) {\n lines.push(`- ${metric.value} ${metric.label}: ${metric.explanation}`);\n }\n lines.push(\"\");\n lines.push(\"## Work Graph Trails\");\n lines.push(\"\");\n for (const trail of report.trails.slice(0, 12)) {\n lines.push(`- [${trail.kind}] ${trail.title} — ${trail.state}, ${trail.valence}, ${trail.shape} (${trail.evidence_refs.join(\", \")})`);\n }\n lines.push(\"\");\n lines.push(\"## Recurring Patterns\");\n lines.push(\"\");\n if (report.recurring_patterns.length === 0) {\n lines.push(\"- No recurring patterns detected yet.\");\n } else {\n for (const pattern of report.recurring_patterns) {\n lines.push(`- [${pattern.severity}] ${pattern.title}: ${pattern.root_cause_hypothesis}`);\n }\n }\n lines.push(\"\");\n lines.push(\"## Top Findings\");\n lines.push(\"\");\n for (const finding of report.findings.slice(0, 12)) {\n lines.push(`- [${finding.type}] ${finding.title} (${finding.evidence_ref})`);\n }\n lines.push(\"\");\n lines.push(\"## Missed Orchestration\");\n lines.push(\"\");\n if (report.missed_orchestration_opportunities.length === 0) {\n lines.push(\"- No missed orchestration opportunities detected.\");\n } else {\n for (const finding of report.missed_orchestration_opportunities) {\n lines.push(`- ${finding.title}: ${finding.summary}`);\n }\n }\n lines.push(\"\");\n lines.push(\"## Initiative Kickoffs\");\n lines.push(\"\");\n for (const kickoff of report.initiative_kickoffs) {\n lines.push(`- [${kickoff.priority}] ${kickoff.title}: ${kickoff.summary}`);\n }\n lines.push(\"\");\n lines.push(\"## Eject Bay Recommendations\");\n lines.push(\"\");\n for (const recommendation of report.recommendations) {\n lines.push(`- [${recommendation.priority}] ${recommendation.title}: ${recommendation.summary}`);\n }\n lines.push(\"\");\n lines.push(\"## Signup Hydration\");\n lines.push(\"\");\n lines.push(`- Strategy: ${report.signup_hydration.strategy}`);\n lines.push(`- Eligible: ${report.signup_hydration.eligible ? \"yes\" : \"no\"}`);\n for (const note of report.signup_hydration.notes) {\n lines.push(`- ${note}`);\n }\n lines.push(\"\");\n lines.push(\"## Privacy\");\n lines.push(\"\");\n lines.push(\"- Raw transcripts were not sent.\");\n lines.push(\"- This report contains summaries, hashes, and evidence refs only.\");\n\n return lines.join(\"\\n\");\n}\n","import { copyFileSync, existsSync, mkdirSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport {\n CLAUDE_DIR,\n CODEX_CONFIG_PATH,\n CODEX_DIR,\n ORGX_WIZARD_CONFIG_HOME,\n} from \"../constants.js\";\nimport { isRecord, parseJsonObject, readTextIfExists, writeJsonFile, writeTextFile } from \"./fs.js\";\n\nconst HOOK_MARKER = \"orgx-session-hook.mjs\";\nconst HOOK_EVENTS = [\"SessionStart\", \"UserPromptSubmit\", \"PreToolUse\", \"PostToolUse\", \"PermissionRequest\", \"Stop\"] as const;\nconst CLAUDE_HOOK_EVENTS = [\"SessionStart\", \"UserPromptSubmit\", \"PreToolUse\", \"PostToolUse\", \"SubagentStop\", \"Stop\", \"SessionEnd\"] as const;\n\nexport type RuntimeHookTarget = \"codex\" | \"claude-code\";\n\nexport interface RuntimeHookPaths {\n claudeSettingsPath: string;\n codexConfigPath: string;\n codexHooksPath: string;\n hookScriptPath: string;\n outboxPath: string;\n}\n\nexport interface RuntimeHookInspection {\n paths: RuntimeHookPaths;\n installed: {\n claudeCode: boolean;\n codex: boolean;\n hookScript: boolean;\n };\n codex: {\n configExists: boolean;\n hooksEnabled: boolean;\n hasNotify: boolean;\n notifyPreserved: boolean;\n };\n outboxEvents: number;\n}\n\nexport interface RuntimeHookInstallResult extends RuntimeHookInspection {\n changed: {\n claudeCode: boolean;\n codex: boolean;\n codexConfig: boolean;\n hookScript: boolean;\n };\n backups: string[];\n}\n\nexport interface RuntimeHookOptions {\n claudeSettingsPath?: string;\n codexConfigPath?: string;\n codexHooksPath?: string;\n hookScriptPath?: string;\n now?: Date;\n outboxPath?: string;\n}\n\nfunction defaultPaths(options: RuntimeHookOptions = {}): RuntimeHookPaths {\n const hookDir = join(ORGX_WIZARD_CONFIG_HOME, \"hooks\");\n return {\n claudeSettingsPath: options.claudeSettingsPath ?? join(CLAUDE_DIR, \"settings.json\"),\n codexConfigPath: options.codexConfigPath ?? CODEX_CONFIG_PATH ?? join(CODEX_DIR, \"config.toml\"),\n codexHooksPath: options.codexHooksPath ?? join(CODEX_DIR, \"hooks.json\"),\n hookScriptPath: options.hookScriptPath ?? join(hookDir, HOOK_MARKER),\n outboxPath: options.outboxPath ?? join(hookDir, \"events.jsonl\"),\n };\n}\n\nfunction countJsonlLines(path: string): number {\n const raw = readTextIfExists(path);\n if (!raw) return 0;\n return raw.split(/\\r?\\n/).filter((line) => line.trim().length > 0).length;\n}\n\nfunction backupPath(path: string, now: Date): string {\n const timestamp = now.toISOString().replace(/[:.]/g, \"-\");\n return `${path}.bak.${timestamp}`;\n}\n\nfunction backupExisting(path: string, now: Date): string | null {\n if (!existsSync(path)) return null;\n const backup = backupPath(path, now);\n copyFileSync(path, backup);\n return backup;\n}\n\nfunction hasOrgxHook(raw: string | null): boolean {\n return Boolean(raw?.includes(HOOK_MARKER));\n}\n\nfunction codexHooksEnabled(raw: string | null): boolean {\n return Boolean(raw && /^\\s*codex_hooks\\s*=\\s*true\\s*$/m.test(raw));\n}\n\nfunction codexHasNotify(raw: string | null): boolean {\n return Boolean(raw && /^\\s*notify\\s*=/m.test(raw));\n}\n\nexport function buildRuntimeHookScriptContent(): string {\n return `#!/usr/bin/env node\nimport { appendFileSync, mkdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nfunction parseArgs(argv) {\n const args = {};\n for (const arg of argv) {\n if (!arg.startsWith(\"--\")) continue;\n const [key, ...rest] = arg.slice(2).split(\"=\");\n args[key] = rest.length > 0 ? rest.join(\"=\") : \"true\";\n }\n return args;\n}\n\nfunction pickString(...values) {\n for (const value of values) {\n if (typeof value !== \"string\") continue;\n const trimmed = value.trim();\n if (trimmed) return trimmed;\n }\n return undefined;\n}\n\nasync function readStdin() {\n const chunks = [];\n for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction parseJson(value) {\n try {\n const parsed = JSON.parse(value || \"{}\");\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nfunction summarize(payload) {\n const toolName = pickString(payload.tool_name, payload.toolName, payload.tool?.name, payload.name);\n const prompt = pickString(payload.prompt);\n return {\n tool_name: toolName,\n prompt_chars: prompt ? prompt.length : undefined,\n payload_keys: Object.keys(payload).slice(0, 40),\n };\n}\n\nconst args = parseArgs(process.argv.slice(2));\nconst raw = await readStdin();\nconst payload = parseJson(raw);\nconst outbox = pickString(\n process.env.ORGX_WIZARD_HOOK_OUTBOX,\n args.outbox,\n join(homedir(), \".config\", \"useorgx\", \"wizard\", \"hooks\", \"events.jsonl\")\n);\nconst event = pickString(args.event, payload.hook_event_name, payload.hookEventName, payload.event, payload.eventName, \"unknown\");\nconst sourceClient = pickString(args.source_client, args[\"source-client\"], \"unknown\");\n\nconst record = {\n schema_version: \"2026-05-07\",\n source: \"orgx_wizard_runtime_hook\",\n source_client: sourceClient,\n event,\n session_id: pickString(payload.session_id, payload.sessionId, payload.conversation_id, payload.conversationId),\n turn_id: pickString(payload.turn_id, payload.turnId),\n cwd: pickString(payload.cwd, payload.working_directory, payload.workspace, process.cwd()),\n transcript_path: pickString(payload.transcript_path, payload.transcriptPath),\n timestamp: new Date().toISOString(),\n summary: summarize(payload),\n};\n\ntry {\n mkdirSync(dirname(outbox), { recursive: true, mode: 0o700 });\n appendFileSync(outbox, JSON.stringify(record) + \"\\\\n\", { encoding: \"utf8\", mode: 0o600 });\n} catch {\n // Hooks must never break the user's agent runtime.\n}\n\nprocess.exit(0);\n`;\n}\n\nfunction buildHookCommand(params: {\n event: string;\n hookScriptPath: string;\n outboxPath: string;\n sourceClient: RuntimeHookTarget;\n}): string {\n return [\n \"node\",\n JSON.stringify(params.hookScriptPath),\n `--event=${params.event}`,\n `--source_client=${params.sourceClient}`,\n `--outbox=${params.outboxPath}`,\n ].join(\" \");\n}\n\nfunction mergeCodexHooks(raw: string | null, paths: RuntimeHookPaths): { changed: boolean; value: Record<string, unknown> } {\n const value = parseJsonObject(raw);\n const hooks = isRecord(value.hooks) ? value.hooks : {};\n let changed = false;\n\n for (const event of HOOK_EVENTS) {\n const existing = Array.isArray(hooks[event]) ? hooks[event] as Array<unknown> : [];\n const command = buildHookCommand({\n event,\n hookScriptPath: paths.hookScriptPath,\n outboxPath: paths.outboxPath,\n sourceClient: \"codex\",\n });\n const already = existing.some((entry) =>\n isRecord(entry) && typeof entry.command === \"string\" && entry.command.includes(HOOK_MARKER)\n );\n if (!already) {\n hooks[event] = [...existing, { command }];\n changed = true;\n }\n }\n\n value.hooks = hooks;\n return { changed: changed || !raw, value };\n}\n\nfunction mergeClaudeHooks(raw: string | null, paths: RuntimeHookPaths): { changed: boolean; value: Record<string, unknown> } {\n const value = parseJsonObject(raw);\n const hooksRoot = isRecord(value.hooks) ? value.hooks : {};\n let changed = false;\n\n for (const event of CLAUDE_HOOK_EVENTS) {\n const list = Array.isArray(hooksRoot[event]) ? hooksRoot[event] as Array<Record<string, unknown>> : [];\n const matcher = event === \"PreToolUse\" || event === \"PostToolUse\" ? \"Bash|Write|Edit|MultiEdit|mcp__.*\" : \"\";\n const command = buildHookCommand({\n event,\n hookScriptPath: paths.hookScriptPath,\n outboxPath: paths.outboxPath,\n sourceClient: \"claude-code\",\n });\n let rule = list.find((entry) => isRecord(entry) && entry.matcher === matcher);\n if (!rule) {\n rule = { matcher, hooks: [] };\n list.push(rule);\n changed = true;\n }\n\n const hooks = Array.isArray(rule.hooks) ? rule.hooks as Array<Record<string, unknown>> : [];\n const already = hooks.some((entry) =>\n isRecord(entry) &&\n entry.type === \"command\" &&\n typeof entry.command === \"string\" &&\n entry.command.includes(HOOK_MARKER)\n );\n if (!already) {\n hooks.push({ type: \"command\", command });\n rule.hooks = hooks;\n changed = true;\n }\n hooksRoot[event] = list;\n }\n\n value.hooks = hooksRoot;\n return { changed: changed || !raw, value };\n}\n\nfunction ensureCodexHooksFeature(raw: string | null): { changed: boolean; value: string } {\n const current = raw ?? \"\";\n if (codexHooksEnabled(current)) {\n return { changed: false, value: current };\n }\n\n if (/^\\s*codex_hooks\\s*=\\s*false\\s*$/m.test(current)) {\n return {\n changed: true,\n value: current.replace(/^\\s*codex_hooks\\s*=\\s*false\\s*$/m, \"codex_hooks = true\"),\n };\n }\n\n if (/^\\s*\\[features\\]\\s*$/m.test(current)) {\n return {\n changed: true,\n value: current.replace(/^(\\s*\\[features\\]\\s*)$/m, \"$1\\ncodex_hooks = true\"),\n };\n }\n\n const suffix = current.trimEnd().length > 0 ? \"\\n\\n\" : \"\";\n return {\n changed: true,\n value: `${current.trimEnd()}${suffix}[features]\\ncodex_hooks = true\\n`,\n };\n}\n\nexport function inspectRuntimeHooks(options: RuntimeHookOptions = {}): RuntimeHookInspection {\n const paths = defaultPaths(options);\n const codexConfigRaw = readTextIfExists(paths.codexConfigPath);\n const codexHooksRaw = readTextIfExists(paths.codexHooksPath);\n const claudeSettingsRaw = readTextIfExists(paths.claudeSettingsPath);\n return {\n paths,\n installed: {\n claudeCode: hasOrgxHook(claudeSettingsRaw),\n codex: hasOrgxHook(codexHooksRaw),\n hookScript: existsSync(paths.hookScriptPath),\n },\n codex: {\n configExists: Boolean(codexConfigRaw),\n hooksEnabled: codexHooksEnabled(codexConfigRaw),\n hasNotify: codexHasNotify(codexConfigRaw),\n notifyPreserved: !codexHasNotify(codexConfigRaw) || !hasOrgxHook(codexConfigRaw),\n },\n outboxEvents: countJsonlLines(paths.outboxPath),\n };\n}\n\nexport function installRuntimeHooks(\n targets: readonly RuntimeHookTarget[],\n options: RuntimeHookOptions = {},\n): RuntimeHookInstallResult {\n const now = options.now ?? new Date();\n const paths = defaultPaths(options);\n const backups: string[] = [];\n const changed = {\n claudeCode: false,\n codex: false,\n codexConfig: false,\n hookScript: false,\n };\n\n mkdirSync(dirname(paths.hookScriptPath), { recursive: true, mode: 0o700 });\n const scriptContent = buildRuntimeHookScriptContent();\n if (readTextIfExists(paths.hookScriptPath) !== scriptContent) {\n const backup = backupExisting(paths.hookScriptPath, now);\n if (backup) backups.push(backup);\n writeTextFile(paths.hookScriptPath, scriptContent, { mode: 0o700 });\n changed.hookScript = true;\n }\n\n if (targets.includes(\"codex\")) {\n const rawConfig = readTextIfExists(paths.codexConfigPath);\n const nextConfig = ensureCodexHooksFeature(rawConfig);\n if (nextConfig.changed) {\n const backup = backupExisting(paths.codexConfigPath, now);\n if (backup) backups.push(backup);\n writeTextFile(paths.codexConfigPath, nextConfig.value, { mode: 0o600 });\n changed.codexConfig = true;\n }\n\n const rawHooks = readTextIfExists(paths.codexHooksPath);\n const nextHooks = mergeCodexHooks(rawHooks, paths);\n if (nextHooks.changed) {\n const backup = backupExisting(paths.codexHooksPath, now);\n if (backup) backups.push(backup);\n writeJsonFile(paths.codexHooksPath, nextHooks.value, { mode: 0o600 });\n changed.codex = true;\n }\n }\n\n if (targets.includes(\"claude-code\")) {\n const rawSettings = readTextIfExists(paths.claudeSettingsPath);\n const nextSettings = mergeClaudeHooks(rawSettings, paths);\n if (nextSettings.changed) {\n const backup = backupExisting(paths.claudeSettingsPath, now);\n if (backup) backups.push(backup);\n writeJsonFile(paths.claudeSettingsPath, nextSettings.value, { mode: 0o600 });\n changed.claudeCode = true;\n }\n }\n\n return {\n ...inspectRuntimeHooks(options),\n changed,\n backups,\n };\n}\n\nexport function parseRuntimeHookTargets(value?: string): RuntimeHookTarget[] {\n if (!value?.trim()) return [\"codex\", \"claude-code\"];\n const requested = value.split(\",\").map((item) => item.trim().toLowerCase()).filter(Boolean);\n const expanded = requested.includes(\"all\") ? [\"codex\", \"claude-code\"] : requested;\n const normalized = expanded.map((target) => {\n if (target === \"claude\" || target === \"claude_code\") return \"claude-code\";\n return target;\n });\n const invalid = normalized.filter((target) => target !== \"codex\" && target !== \"claude-code\");\n if (invalid.length > 0) {\n throw new Error(`Unsupported hook target: ${invalid.join(\", \")}. Use codex, claude-code, or all.`);\n }\n return [...new Set(normalized)] as RuntimeHookTarget[];\n}\n\nexport function runtimeHookPathsForHome(home = homedir()): RuntimeHookPaths {\n const configHome = process.env.XDG_CONFIG_HOME?.trim() || join(home, \".config\");\n const hookDir = join(configHome, \"useorgx\", \"wizard\", \"hooks\");\n return {\n claudeSettingsPath: join(home, \".claude\", \"settings.json\"),\n codexConfigPath: join(home, \".codex\", \"config.toml\"),\n codexHooksPath: join(home, \".codex\", \"hooks.json\"),\n hookScriptPath: join(hookDir, HOOK_MARKER),\n outboxPath: join(hookDir, \"events.jsonl\"),\n };\n}\n","import ora, { type Ora } from \"ora\";\nimport pc from \"picocolors\";\n\nconst frames = [\"[ ]\", \"[= ]\", \"[== ]\", \"[=== ]\", \"[ ===]\", \"[ ==]\", \"[ =]\"];\n\nexport function createOrgxSpinner(text: string): Ora {\n return ora({\n text: pc.cyan(text),\n spinner: {\n interval: 90,\n frames,\n },\n });\n}\n\n"],"mappings":";;;AAAA,YAAY,WAAW;AACvB,SAAS,aAAAA,kBAAiB;AAC1B,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,OAAOC,SAAQ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olve","hostname","resolve","text","isNonEmptyString","spawnSync","spawnSync","text","text","parseResponseBody","text","existsSync","mkdirSync","readFileSync","readdirSync","statSync","writeFileSync","dirname","join","existsSync","dirname","dirname","existsSync","createHash","existsSync","join","createHash","join","existsSync","extension","encodeRepoPath","basename","buildContentsUrl","resolveGitHubError","fetchDirectoryEntries","join","existsSync","statSync","readFileSync","mkdirSync","dirname","writeFileSync","readdirSync","resolve","inspection","parseResponseBody","text","formatHttpError","requireOrgxAuth","parse","text","parseResponseBody","formatHttpError","requireOrgxAuth","text","text","existsSync","readdirSync","readFileSync","statSync","basename","join","relative","text","existsSync","readdirSync","join","statSync","readFileSync","relative","basename","createHash","createHash","parseResponseBody","text","formatHttpError","createHash","clampScore","createHash","text","includesAny","existsSync","mkdirSync","homedir","dirname","join","join","existsSync","mkdirSync","dirname","pc","text","pc","readFileSync","text","pc","spawnSync","pc","resolve","text","handoff","spinner","doctor","assessment","verification"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/banner.ts","../src/constants.ts","../src/lib/browser-auth.ts","../src/lib/fs.ts","../src/surfaces/openclaw-config.ts","../src/lib/auth-store.ts","../src/lib/auth.ts","../src/lib/local-auth-server.ts","../src/lib/pkce.ts","../src/lib/oauth-client.ts","../src/lib/wizard-state.ts","../src/surfaces/names.ts","../src/lib/agent-roster.ts","../src/lib/openclaw-health.ts","../src/lib/hosted-mcp-health.ts","../src/lib/hosted-mcp-tool-check.ts","../src/lib/npm-registry-health.ts","../src/lib/workspaces.ts","../src/lib/workspace-connectivity.ts","../src/lib/plugins.ts","../src/surfaces/mcp-config.ts","../src/surfaces/detection.ts","../src/lib/skills.ts","../src/surfaces/registry.ts","../src/lib/continuity.ts","../src/lib/initiatives.ts","../src/lib/setup-workspace.ts","../src/lib/founder-preset.ts","../src/lib/mutation-output.ts","../src/lib/setup-verification.ts","../src/lib/telemetry-events.ts","../src/lib/telemetry.ts","../src/lib/intents.ts","../src/lib/intent-render.ts","../src/lib/daily-brief-onboarding.ts","../src/lib/ai-session-import.ts","../src/lib/self-audit.ts","../src/lib/work-graph.ts","../src/lib/work-graph-publish.ts","../src/lib/work-graph-hook-events.ts","../src/lib/runtime-hooks.ts","../src/spinner.ts"],"sourcesContent":["import * as clack from \"@clack/prompts\";\nimport { spawnSync } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { hostname } from \"node:os\";\nimport { resolve } from \"node:path\";\nimport { Command } from \"commander\";\nimport pc from \"picocolors\";\n\ndeclare const __PKG_VERSION__: string;\n\nimport { renderBanner } from \"./banner.js\";\nimport { DEFAULT_ORGX_BASE_URL, ORGX_WIZARD_AUTH_PATH } from \"./constants.js\";\nimport {\n acknowledgeBrowserPairing,\n openBrowser,\n startBrowserPairing,\n waitForBrowserPairing,\n} from \"./lib/browser-auth.js\";\nimport {\n checkOrgxAuth,\n normalizeOrgxBaseUrl,\n resolveOrgxAuth,\n verifyOrgxAuth,\n type OrgxAuthCheckResult,\n} from \"./lib/auth.js\";\nimport { clearWizardAuth, writeWizardAuth } from \"./lib/auth-store.js\";\nimport { startPkceLogin } from \"./lib/oauth-client.js\";\nimport {\n AGENT_ROSTER_DOMAINS,\n configureAgentRoster,\n ensureDefaultAgentRoster,\n listAgentRosterProfiles,\n type AgentRosterAssignment,\n} from \"./lib/agent-roster.js\";\nimport { persistContinuityDefaults } from \"./lib/continuity.js\";\nimport { runFounderPreset, type FounderPresetResult } from \"./lib/founder-preset.js\";\nimport {\n FIRST_VALUE_INITIATIVE_TITLE,\n ensureFirstValueInitiative,\n ensureOnboardingTask,\n type FirstValueInitiativeResult,\n} from \"./lib/initiatives.js\";\nimport {\n countPluginReportChanges,\n installOrgxPlugins,\n listOrgxPluginStatuses,\n uninstallOrgxPlugins,\n type OrgxPluginMutationReport,\n type OrgxPluginStatus,\n} from \"./lib/plugins.js\";\nimport {\n addSkillExtension,\n getSkillStatus,\n installOrgxSkills,\n listSkillExtensions,\n setSkillExtensionEnabled,\n type SkillsInstallReport,\n type SkillExtension,\n type SkillExtensionWrite,\n} from \"./lib/skills.js\";\nimport { summarizeMutationResults } from \"./lib/mutation-output.js\";\nimport {\n HOSTED_MCP_OUTAGE_TITLE,\n getSetupVerificationHeadline,\n summarizeSetupVerification,\n} from \"./lib/setup-verification.js\";\nimport {\n buildAgentRosterTelemetryProperties,\n buildDoctorTelemetryProperties,\n buildFirstValueInitiativeTelemetryProperties,\n buildFounderDemoTelemetryProperties,\n buildOnboardingTaskTelemetryProperties,\n buildWorkspaceSetupTelemetryProperties,\n} from \"./lib/telemetry-events.js\";\nimport { trackWizardTelemetry } from \"./lib/telemetry.js\";\nimport {\n clearWizardState,\n getOrCreateWizardInstallationId,\n hasSetupPromptSkip,\n readWizardState,\n recordSetupPromptSkip,\n type WizardAgentRosterRecord,\n type WizardFirstValueInitiativeRecord,\n} from \"./lib/wizard-state.js\";\nimport {\n createWorkspace,\n getCurrentWorkspace,\n listWorkspaces,\n setDefaultWorkspace,\n type OrgxWorkspace,\n} from \"./lib/workspaces.js\";\nimport {\n buildIntentHandoffUrl,\n createIntent,\n updateIntent,\n type AgentSlug,\n type Intent,\n} from \"./lib/intents.js\";\nimport {\n DEFAULT_HOTKEYS,\n detectRenderCapabilities,\n dim as renderDim,\n isInteractive,\n normalizeHotkey,\n renderHotkeyBar,\n renderPlanPreview,\n renderRoutingLine,\n resolveConfidenceDecimal,\n type IntentAction,\n} from \"./lib/intent-render.js\";\nimport { runWorkspaceSetup, type WorkspaceSetupResult } from \"./lib/setup-workspace.js\";\nimport { runDailyBriefOnboarding } from \"./lib/daily-brief-onboarding.js\";\nimport {\n loadAiSessionImports,\n parseAiSessionSources,\n} from \"./lib/ai-session-import.js\";\nimport {\n buildSelfAuditPlan,\n createAuditArtifact,\n createAuditFollowUpTask,\n createInitiativeFromAuditPlan,\n renderSelfAuditMarkdown,\n type AuditScores,\n type FounderLoopImport,\n} from \"./lib/self-audit.js\";\nimport {\n buildNativeAiClientExtractions,\n buildWorkGraphExtractionProtocol,\n buildSessionReconciliationReport,\n renderWorkGraphExtractionProtocolMarkdown,\n renderWorkGraphMarkdown,\n type WorkGraphClientExtraction,\n type WorkGraphOpportunityScore,\n} from \"./lib/work-graph.js\";\nimport {\n publishWorkGraphEvents,\n publishWorkGraphReport,\n} from \"./lib/work-graph-publish.js\";\nimport {\n buildWorkGraphHookReplayPatch,\n readRuntimeHookOutbox,\n} from \"./lib/work-graph-hook-events.js\";\nimport {\n inspectRuntimeHooks,\n installRuntimeHooks,\n parseRuntimeHookTargets,\n type RuntimeHookInspection,\n} from \"./lib/runtime-hooks.js\";\nimport { createOrgxSpinner } from \"./spinner.js\";\nimport { detectSurface } from \"./surfaces/detection.js\";\nimport {\n assessDoctorReport,\n addMcpSurface,\n addSurface,\n listSurfaceStatuses,\n removeMcpSurface,\n removeSurface,\n runDoctor,\n setupDetectedSurfaces,\n type SurfaceMutationResult,\n type SurfaceStatus,\n} from \"./surfaces/registry.js\";\nimport { isRecord, writeJsonFile, writeTextFile } from \"./lib/fs.js\";\n\nconst ICON = {\n ok: pc.green(\"✓\"),\n err: pc.red(\"✗\"),\n warn: pc.yellow(\"!\"),\n skip: pc.dim(\"·\"),\n} as const;\n\n/**\n * Returns the right command prefix based on how the wizard was invoked.\n * When run via `npx @useorgx/wizard`, `orgx-wizard` won't be in PATH — hints\n * should use the npx form so users can copy-paste them directly.\n */\nfunction getCmd(): string {\n const argv1 = process.argv[1] ?? \"\";\n return argv1.includes(\"_npx\") || argv1.includes(\"/.npm/\") || argv1.includes(\"/npm/_npx\")\n ? \"npx @useorgx/wizard\"\n : \"orgx-wizard\";\n}\n\nfunction formatAuthSource(source: OrgxAuthCheckResult[\"source\"]): string {\n switch (source) {\n case \"environment\":\n return \"env ORGX_API_KEY\";\n case \"wizard-store\":\n return \"wizard auth store\";\n case \"openclaw-config-file\":\n return \"openclaw config\";\n default:\n return \"not configured\";\n }\n}\n\nfunction formatPluginTargetLabel(target: OrgxPluginStatus[\"target\"]): string {\n switch (target) {\n case \"cursor\":\n return \"Cursor plugin\";\n case \"claude\":\n return \"Claude Code\";\n case \"codex\":\n return \"Codex\";\n case \"openclaw\":\n return \"OpenClaw\";\n }\n}\n\nfunction printSurfaceTable(statuses: SurfaceStatus[]): void {\n for (const status of statuses) {\n const icon = status.configured ? ICON.ok : status.detected ? ICON.warn : ICON.skip;\n const state = status.configured\n ? pc.green(\"configured\")\n : status.detected\n ? pc.yellow(\"detected\")\n : pc.dim(\"not found\");\n const mode = pc.dim(status.mode === \"automated\" ? \"auto \" : \"manual\");\n console.log(` ${icon} ${pc.bold(status.name.padEnd(10))} ${mode} ${state}`);\n if (status.mode === \"manual\") {\n console.log(` ${pc.dim(status.summary)}`);\n }\n }\n}\n\nfunction printPluginStatusReport(statuses: OrgxPluginStatus[]): void {\n for (const status of statuses) {\n const icon = status.installed ? ICON.ok : status.available ? ICON.warn : ICON.skip;\n const state = status.installed\n ? pc.green(\"installed\")\n : status.available\n ? pc.yellow(\"available\")\n : pc.dim(\"not found\");\n console.log(\n ` ${icon} ${pc.bold(formatPluginTargetLabel(status.target).padEnd(12))} ${state} ${pc.dim(status.message)}`,\n );\n }\n}\n\nfunction printMutationResults(results: SurfaceMutationResult[]): void {\n for (const result of summarizeMutationResults(results)) {\n const icon = result.state === \"updated\" ? ICON.ok : ICON.skip;\n const state = result.state === \"updated\" ? pc.green(\"updated \") : pc.dim(\"unchanged\");\n console.log(` ${icon} ${pc.bold(result.name.padEnd(10))} ${state} ${pc.dim(result.message)}`);\n }\n}\n\nfunction printSurfaceSummary(results: SurfaceMutationResult[]): void {\n const summarized = summarizeMutationResults(results);\n const updated = summarized.filter((r) => r.state === \"updated\");\n if (updated.length === 0) {\n console.log(\n ` ${ICON.skip} ${pc.dim(`${summarized.length} surface${summarized.length === 1 ? \"\" : \"s\"} already configured`)}`,\n );\n return;\n }\n for (const result of summarized) {\n const icon = result.state === \"updated\" ? ICON.ok : ICON.skip;\n const state = result.state === \"updated\" ? pc.green(\"updated \") : pc.dim(\"unchanged\");\n console.log(` ${icon} ${pc.bold(result.name.padEnd(10))} ${state} ${pc.dim(result.message)}`);\n }\n}\n\nfunction printPluginMutationReport(report: OrgxPluginMutationReport): void {\n for (const result of report.results) {\n const icon = result.changed ? ICON.ok : ICON.skip;\n const state = result.changed ? pc.green(\"updated \") : pc.dim(\"unchanged\");\n console.log(\n ` ${icon} ${pc.bold(formatPluginTargetLabel(result.target).padEnd(12))} ${state} ${pc.dim(result.message)}`,\n );\n }\n}\n\ninterface AuditCommandOptions {\n attachToInitiative?: string;\n attachArtifact?: boolean;\n artifactUrl?: string;\n claudeProjectsDir?: string;\n codexSessionsDir?: string;\n createInitiative?: boolean;\n dryRun?: boolean;\n entityId?: string;\n entityType?: \"project\" | \"initiative\" | \"milestone\" | \"task\" | \"decision\";\n extraction?: string[];\n from?: string;\n input?: string;\n json?: boolean;\n milestoneId?: string;\n outputDir?: string;\n publicShare?: boolean;\n publish?: boolean;\n sourceLabel?: string;\n sessionDays?: string;\n sessionLimit?: string;\n workspaceId?: string;\n workspaceName?: string;\n workstreamId?: string;\n writeFollowUp?: boolean;\n yes?: boolean;\n}\n\ntype WorkGraphCommandOptions = AuditCommandOptions;\n\ninterface HooksCommandOptions {\n fingerprint?: string;\n json?: boolean;\n limit?: string;\n outbox?: string;\n targets?: string;\n yes?: boolean;\n}\n\ninterface WorkGraphExtractionSchemaCommandOptions {\n json?: boolean;\n output?: string;\n}\n\nfunction formatScoreLine(scores: AuditScores): string {\n return Object.entries(scores)\n .map(([dimension, score]) => `${dimension}=${score}`)\n .join(\" \");\n}\n\nfunction formatWorkGraphScoreLine(score: WorkGraphOpportunityScore): string {\n return [\n `overall=${score.overall}`,\n `value=${score.value_potential}`,\n `evidence=${score.evidence_quality}`,\n `urgency=${score.urgency}`,\n `owner=${score.owner_clarity}`,\n `automation=${score.automation_potential}`,\n `orgx_fit=${score.orgx_fit}`,\n ].join(\" \");\n}\n\nfunction printRuntimeHookInspection(report: RuntimeHookInspection): void {\n console.log(` ${report.installed.hookScript ? ICON.ok : ICON.warn} ${pc.bold(\"hook script \")} ${report.installed.hookScript ? pc.green(\"installed\") : pc.yellow(\"missing\")} ${pc.dim(report.paths.hookScriptPath)}`);\n console.log(` ${report.installed.codex ? ICON.ok : ICON.warn} ${pc.bold(\"Codex \")} ${report.installed.codex ? pc.green(\"installed\") : pc.yellow(\"missing\")} ${pc.dim(report.paths.codexHooksPath)}`);\n console.log(` ${report.codex.hooksEnabled ? ICON.ok : ICON.warn} ${pc.bold(\"Codex flag \")} ${report.codex.hooksEnabled ? pc.green(\"enabled\") : pc.yellow(\"not enabled\")} ${pc.dim(report.paths.codexConfigPath)}`);\n console.log(` ${report.codex.notifyPreserved ? ICON.ok : ICON.warn} ${pc.bold(\"notify \")} ${report.codex.notifyPreserved ? pc.green(\"preserved\") : pc.yellow(\"check config\")} ${pc.dim(report.codex.hasNotify ? \"existing notify detected\" : \"no notify entry\")}`);\n console.log(` ${report.installed.claudeCode ? ICON.ok : ICON.warn} ${pc.bold(\"Claude Code \")} ${report.installed.claudeCode ? pc.green(\"installed\") : pc.yellow(\"missing\")} ${pc.dim(report.paths.claudeSettingsPath)}`);\n console.log(` ${ICON.skip} ${pc.bold(\"outbox \")} ${pc.dim(`${report.outboxEvents} event${report.outboxEvents === 1 ? \"\" : \"s\"} at ${report.paths.outboxPath}`)}`);\n}\n\nfunction requireHookReplayApproval(options: HooksCommandOptions, interactive: boolean): Promise<boolean> | boolean {\n if (options.yes) return true;\n if (!interactive) {\n throw new Error(\"Replaying Work Graph hook events requires --yes in non-interactive mode.\");\n }\n\n return clack.confirm({\n message: \"Replay passive hook events into this claimed Work Graph profile?\",\n }).then((value) => {\n if (clack.isCancel(value) || value !== true) {\n clack.cancel(\"Hook replay cancelled.\");\n return false;\n }\n return true;\n });\n}\n\nfunction parsePositiveInt(value: string | undefined, fallback: number): number {\n if (!value?.trim()) return fallback;\n const parsed = Number.parseInt(value.trim(), 10);\n if (!Number.isFinite(parsed) || parsed < 1) {\n throw new Error(`Expected a positive integer, got ${value}`);\n }\n return parsed;\n}\n\nasync function runHookReplayCommand(options: HooksCommandOptions): Promise<void> {\n const fingerprint = options.fingerprint?.trim();\n if (!fingerprint) {\n throw new Error(\"Missing --fingerprint <wgf_...> for hook event replay.\");\n }\n\n const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);\n const paths = inspectRuntimeHooks().paths;\n const outboxPath = resolve(options.outbox?.trim() || paths.outboxPath);\n const readResult = readRuntimeHookOutbox(outboxPath, parsePositiveInt(options.limit, 200));\n const replay = buildWorkGraphHookReplayPatch(readResult);\n\n if (replay.records === 0) {\n if (options.json) {\n console.log(JSON.stringify({ ok: true, published: false, reason: \"empty_outbox\", ...replay }, null, 2));\n return;\n }\n console.log(` ${ICON.skip} ${pc.bold(\"outbox \")} ${pc.dim(`no hook events found at ${outboxPath}`)}`);\n return;\n }\n\n const approved = await requireHookReplayApproval(options, interactive);\n if (!approved) return;\n\n const result = await publishWorkGraphEvents(fingerprint, replay.patch);\n if (!result.ok) process.exitCode = 1;\n\n await safeTrackWizardTelemetry(\"hooks_replay_ran\", {\n command: \"hooks replay\",\n fingerprint,\n records: String(replay.records),\n sources: replay.sources.join(\",\"),\n status: String(result.status),\n });\n\n if (options.json) {\n console.log(JSON.stringify({ ...replay, published: result }, null, 2));\n return;\n }\n\n console.log(` ${result.ok ? ICON.ok : ICON.warn} ${pc.bold(\"replayed \")} ${replay.records} hook event${replay.records === 1 ? \"\" : \"s\"} ${pc.dim(`status ${result.status}`)}`);\n console.log(` ${ICON.skip} ${pc.bold(\"sources \")} ${pc.dim(replay.sources.join(\", \") || \"none\")}`);\n console.log(` ${ICON.skip} ${pc.bold(\"evidence \")} ${pc.dim(`${replay.evidenceRefs} public-summary ref${replay.evidenceRefs === 1 ? \"\" : \"s\"}`)}`);\n}\n\nfunction readAuditInput(options: AuditCommandOptions, interactive: boolean): Promise<string> | string {\n if (options.input?.trim()) {\n return readFileSync(resolve(options.input.trim()), \"utf8\");\n }\n\n if (!process.stdin.isTTY) {\n return readFileSync(0, \"utf8\");\n }\n\n if (!interactive) {\n throw new Error(\"Audit input is required. Pass --input <file> or pipe text into wizard audit.\");\n }\n\n return textPrompt({\n message: \"Paste a short AI-session summary, decision log, or founder context excerpt\",\n placeholder: \"Decision: Founder Loop first. Artifact: proof ledger attached. Next action: ...\",\n validate: (value) => value?.trim().length ? undefined : \"Audit context is required.\",\n }).then((value) => {\n if (clack.isCancel(value) || typeof value !== \"string\") {\n clack.cancel(\"Audit cancelled.\");\n return \"\";\n }\n return value;\n });\n}\n\nfunction parsePositiveInteger(value: string | undefined, fallback: number, label: string): number {\n if (!value?.trim()) return fallback;\n\n const parsed = Number.parseInt(value.trim(), 10);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(`${label} must be a positive integer.`);\n }\n\n return parsed;\n}\n\nfunction collectPathOption(value: string, previous: string[] = []): string[] {\n return [\n ...previous,\n ...value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean),\n ];\n}\n\nfunction parseClientExtractionFile(path: string): WorkGraphClientExtraction {\n const resolvedPath = resolve(path);\n const parsed = JSON.parse(readFileSync(resolvedPath, \"utf8\")) as unknown;\n if (!isRecord(parsed)) {\n throw new Error(`AI-client extraction must be a JSON object: ${resolvedPath}`);\n }\n if (!Array.isArray(parsed.findings)) {\n throw new Error(`AI-client extraction must include findings[]: ${resolvedPath}`);\n }\n if (typeof parsed.source_client !== \"string\" || !parsed.source_client.trim()) {\n throw new Error(`AI-client extraction must include source_client: ${resolvedPath}`);\n }\n\n return parsed as unknown as WorkGraphClientExtraction;\n}\n\nfunction readClientExtractions(options: WorkGraphCommandOptions): WorkGraphClientExtraction[] {\n return (options.extraction ?? []).map(parseClientExtractionFile);\n}\n\nasync function readAuditImports(\n options: AuditCommandOptions,\n interactive: boolean,\n): Promise<{\n connectedSources: string[];\n imports: FounderLoopImport[];\n missingSources: string[];\n}> {\n const sources = parseAiSessionSources(options.from);\n const imports: FounderLoopImport[] = [];\n const connectedSources: string[] = [];\n const missingSources: string[] = [];\n\n if (sources.length > 0) {\n const imported = loadAiSessionImports({\n ...(options.claudeProjectsDir?.trim() ? { claudeProjectsDir: resolve(options.claudeProjectsDir.trim()) } : {}),\n ...(options.codexSessionsDir?.trim() ? { codexSessionsDir: resolve(options.codexSessionsDir.trim()) } : {}),\n limitPerSource: parsePositiveInteger(options.sessionLimit, 3, \"--session-limit\"),\n sinceDays: parsePositiveInteger(options.sessionDays, 30, \"--session-days\"),\n sources,\n });\n imports.push(...imported.imports);\n connectedSources.push(...imported.connectedSources);\n missingSources.push(...imported.missingSources);\n }\n\n const shouldReadManualInput = Boolean(options.input?.trim()) || sources.length === 0 || !process.stdin.isTTY;\n if (shouldReadManualInput) {\n const text = (await readAuditInput(options, interactive)).trim();\n if (text) {\n imports.push({\n sourceId: \"wizard-audit-input\",\n sourceLabel: options.sourceLabel?.trim() || \"Wizard audit input\",\n text,\n });\n connectedSources.push(options.sourceLabel?.trim() || \"Manual AI-session import\");\n }\n }\n\n if (imports.length === 0) {\n const sourceHint = sources.length > 0\n ? ` No audit-relevant lines were found in ${sources.join(\", \")} sessions.`\n : \"\";\n throw new Error(`Audit input is required.${sourceHint} Pass --input <file>, pipe text, or use --from codex|claude|all.`);\n }\n\n return {\n connectedSources,\n imports,\n missingSources,\n };\n}\n\nasync function readWorkGraphInputs(\n options: WorkGraphCommandOptions,\n interactive: boolean,\n): Promise<{\n clientExtractions: WorkGraphClientExtraction[];\n connectedSources: string[];\n imports: FounderLoopImport[];\n missingSources: string[];\n}> {\n const clientExtractions = readClientExtractions(options);\n const shouldReadSessionImports = Boolean(\n options.from?.trim() ||\n options.input?.trim() ||\n clientExtractions.length === 0 ||\n (!process.stdin.isTTY && clientExtractions.length === 0),\n );\n\n if (!shouldReadSessionImports) {\n return {\n clientExtractions,\n connectedSources: [],\n imports: [],\n missingSources: [],\n };\n }\n\n let auditImports: Awaited<ReturnType<typeof readAuditImports>>;\n try {\n auditImports = await readAuditImports(options, interactive);\n } catch (error) {\n if (clientExtractions.length === 0) throw error;\n const message = error instanceof Error ? error.message : String(error);\n auditImports = {\n connectedSources: [],\n imports: [],\n missingSources: [`fallback session import: ${message}`],\n };\n }\n return {\n clientExtractions,\n connectedSources: auditImports.connectedSources,\n imports: auditImports.imports,\n missingSources: auditImports.missingSources,\n };\n}\n\nfunction requireWriteApproval(options: AuditCommandOptions, interactive: boolean): Promise<boolean> | boolean {\n const wantsWrite = Boolean(options.createInitiative || options.attachToInitiative || options.writeFollowUp);\n if (!wantsWrite || options.yes || options.dryRun) return true;\n\n if (!interactive) {\n throw new Error(\"Write flags require --yes in non-interactive mode.\");\n }\n\n return clack.confirm({\n message: \"Approve OrgX writes for this audit run?\",\n }).then((value) => {\n if (clack.isCancel(value) || value !== true) {\n clack.cancel(\"Audit writeback cancelled.\");\n return false;\n }\n return true;\n });\n}\n\nfunction requireWorkGraphPublishApproval(options: WorkGraphCommandOptions, interactive: boolean): Promise<boolean> | boolean {\n const wantsPublish = Boolean(options.publish || options.publicShare);\n if (!wantsPublish || options.yes || options.dryRun) return true;\n\n if (!interactive) {\n throw new Error(\"Publishing a Work Graph requires --yes in non-interactive mode.\");\n }\n\n return clack.confirm({\n message: \"Publish this Work Graph to OrgX and create a shareable profile?\",\n }).then((value) => {\n if (clack.isCancel(value) || value !== true) {\n clack.cancel(\"Work Graph publish cancelled.\");\n return false;\n }\n return true;\n });\n}\n\nasync function resolveAuditWorkspace(\n options: AuditCommandOptions,\n): Promise<{ id: string; name: string }> {\n const explicitId = options.workspaceId?.trim();\n const explicitName = options.workspaceName?.trim();\n if (explicitId || explicitName) {\n return {\n id: explicitId || \"manual-workspace\",\n name: explicitName || explicitId || \"Manual workspace\",\n };\n }\n\n try {\n const workspace = await getCurrentWorkspace();\n if (workspace) {\n return {\n id: workspace.id,\n name: workspace.name,\n };\n }\n } catch {\n // Local-only audits should still work without OrgX auth. The failed current\n // workspace lookup becomes visible through the missing source finding.\n }\n\n return {\n id: \"local-workspace\",\n name: \"Local workspace\",\n };\n}\n\nasync function runAuditCommand(options: AuditCommandOptions): Promise<void> {\n const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);\n const auditImports = await readAuditImports(options, interactive);\n\n const workspace = await resolveAuditWorkspace(options);\n const plan = buildSelfAuditPlan({\n connectedSources: [\n ...auditImports.connectedSources,\n ...(workspace.id === \"local-workspace\" ? [] : [\"OrgX workspace\"]),\n ],\n generatedAt: new Date().toISOString(),\n imports: auditImports.imports,\n missingSources: [\n ...(workspace.id === \"local-workspace\" ? [\"OrgX workspace auth\"] : []),\n ...auditImports.missingSources,\n ],\n workspace,\n });\n const markdown = renderSelfAuditMarkdown(plan);\n const outputDir = resolve(options.outputDir?.trim() || \".orgx/audits\");\n const timestamp = plan.generated_at.replace(/[:.]/g, \"-\");\n const jsonPath = resolve(outputDir, `ai-native-self-audit-${timestamp}.json`);\n const markdownPath = resolve(outputDir, `ai-native-self-audit-${timestamp}.md`);\n\n writeJsonFile(jsonPath, plan);\n writeTextFile(markdownPath, markdown);\n\n if (options.json) {\n console.log(JSON.stringify({ jsonPath, markdownPath, scores: plan.scores }, null, 2));\n } else {\n console.log(` ${ICON.ok} ${pc.green(\"audit generated\")} ${pc.dim(markdownPath)}`);\n console.log(` ${ICON.ok} ${pc.green(\"scores \")} ${pc.dim(formatScoreLine(plan.scores))}`);\n const belowTarget = plan.self_critique.filter((item) => !item.passed);\n if (belowTarget.length === 0) {\n console.log(` ${ICON.ok} ${pc.green(\"score gate \")} ${pc.dim(\"all dimensions at 95+\")}`);\n } else {\n console.log(` ${ICON.warn} ${pc.yellow(\"score gate \")} ${pc.dim(`${belowTarget.length} dimension${belowTarget.length === 1 ? \"\" : \"s\"} below 95`)}`);\n }\n }\n\n const approved = await requireWriteApproval(options, interactive);\n if (!approved) return;\n\n let targetInitiativeId = options.attachToInitiative?.trim() || \"\";\n if (options.createInitiative) {\n const initiative = await createInitiativeFromAuditPlan({\n dryRun: Boolean(options.dryRun),\n plan,\n });\n targetInitiativeId = initiative.id;\n console.log(` ${ICON.ok} ${pc.green(\"initiative \")} ${pc.bold(initiative.title)} ${pc.dim(initiative.id)}`);\n }\n\n if (targetInitiativeId && (options.attachToInitiative || options.createInitiative)) {\n const artifact = await createAuditArtifact({\n dryRun: Boolean(options.dryRun),\n initiativeId: targetInitiativeId,\n markdown,\n plan,\n });\n console.log(` ${ICON.ok} ${pc.green(\"artifact \")} ${pc.bold(artifact.title)} ${pc.dim(artifact.id)}`);\n }\n\n if (options.writeFollowUp) {\n if (!targetInitiativeId) {\n throw new Error(\"--write-follow-up requires --attach-to-initiative <id> or --create-initiative.\");\n }\n const followUp = await createAuditFollowUpTask({\n dryRun: Boolean(options.dryRun),\n initiativeId: targetInitiativeId,\n ...(options.milestoneId?.trim() ? { milestoneId: options.milestoneId.trim() } : {}),\n plan,\n ...(options.workstreamId?.trim() ? { workstreamId: options.workstreamId.trim() } : {}),\n });\n console.log(` ${ICON.ok} ${pc.green(\"follow-up \")} ${pc.bold(followUp.title)} ${pc.dim(followUp.id)}`);\n }\n}\n\nfunction runWorkGraphExtractionSchemaCommand(options: WorkGraphExtractionSchemaCommandOptions): void {\n const protocol = buildWorkGraphExtractionProtocol();\n const outputPath = options.output?.trim() ? resolve(options.output.trim()) : \"\";\n if (outputPath) {\n if (options.json) {\n writeJsonFile(outputPath, protocol);\n } else {\n writeTextFile(outputPath, renderWorkGraphExtractionProtocolMarkdown(protocol));\n }\n }\n\n if (options.json) {\n console.log(JSON.stringify(protocol, null, 2));\n return;\n }\n\n const markdown = renderWorkGraphExtractionProtocolMarkdown(protocol);\n console.log(markdown);\n}\n\nasync function runWorkGraphCommand(\n options: WorkGraphCommandOptions,\n defaults: { from?: string } = {},\n): Promise<void> {\n const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);\n const commandOptions = {\n ...options,\n ...(options.from?.trim() ? {} : defaults.from ? { from: defaults.from } : {}),\n };\n const auditInputs = await readWorkGraphInputs(commandOptions, interactive);\n const workspace = await resolveAuditWorkspace(commandOptions);\n const generatedAt = new Date().toISOString();\n const nativeClientExtractions = buildNativeAiClientExtractions(\n auditInputs.imports,\n generatedAt,\n );\n const clientExtractions = [\n ...auditInputs.clientExtractions,\n ...nativeClientExtractions,\n ];\n const report = buildSessionReconciliationReport({\n clientExtractions,\n connectedSources: [\n ...auditInputs.connectedSources,\n ...(workspace.id === \"local-workspace\" ? [] : [\"OrgX workspace\"]),\n ],\n imports: auditInputs.imports,\n missingSources: [\n ...(workspace.id === \"local-workspace\" ? [\"OrgX workspace auth\"] : []),\n ...auditInputs.missingSources,\n ],\n generatedAt,\n workspace,\n });\n const markdown = renderWorkGraphMarkdown(report);\n const outputDir = resolve(commandOptions.outputDir?.trim() || \".orgx/work-graph\");\n const timestamp = report.generated_at.replace(/[:.]/g, \"-\");\n const jsonPath = resolve(outputDir, `work-graph-report-${timestamp}.json`);\n const markdownPath = resolve(outputDir, `work-graph-report-${timestamp}.md`);\n\n writeJsonFile(jsonPath, report);\n writeTextFile(markdownPath, markdown);\n\n let published:\n | {\n ok: boolean;\n status: number;\n publicUrl?: string;\n reviewUrl?: string;\n }\n | null = null;\n const shouldPublish = Boolean(commandOptions.publish || commandOptions.publicShare);\n if (shouldPublish) {\n const approved = await requireWorkGraphPublishApproval(commandOptions, interactive);\n if (approved) {\n if (commandOptions.dryRun) {\n published = { ok: true, status: 0 };\n } else {\n const publishResult = await publishWorkGraphReport(report, {\n ...(commandOptions.artifactUrl?.trim() ? { artifactUrl: commandOptions.artifactUrl.trim() } : {}),\n attachArtifact: Boolean(commandOptions.attachArtifact || commandOptions.attachToInitiative),\n ...(commandOptions.entityId?.trim() ? { entityId: commandOptions.entityId.trim() } : {}),\n ...(commandOptions.entityType ? { entityType: commandOptions.entityType } : {}),\n ...(commandOptions.attachToInitiative?.trim() ? { initiativeId: commandOptions.attachToInitiative.trim() } : {}),\n publicShare: Boolean(commandOptions.publicShare || commandOptions.publish),\n ...(workspace.id !== \"local-workspace\" ? { workspaceId: workspace.id } : {}),\n });\n if (!publishResult.ok) {\n throw new Error(`Work Graph publish failed with HTTP ${publishResult.status}: ${JSON.stringify(publishResult.data)}`);\n }\n const body = isRecord(publishResult.data) ? publishResult.data : {};\n const publicShare = isRecord(body.public_share) ? body.public_share : null;\n const publicUrl = typeof publicShare?.url === \"string\"\n ? `${normalizeOrgxBaseUrl(process.env.ORGX_BASE_URL || DEFAULT_ORGX_BASE_URL)}${publicShare.url}`\n : undefined;\n const readout = isRecord(body.public_readout) ? body.public_readout : null;\n published = {\n ok: true,\n status: publishResult.status,\n ...(publicUrl ? { publicUrl } : {}),\n ...(typeof readout?.review_url === \"string\" ? { reviewUrl: readout.review_url } : {}),\n };\n }\n }\n }\n\n if (commandOptions.json) {\n console.log(JSON.stringify({\n jsonPath,\n markdownPath,\n reportId: report.report_id,\n workGraphFingerprint: report.work_graph_fingerprint,\n hydrationKey: report.signup_hydration.hydration_key,\n finalState: report.final_state,\n opportunityScore: report.opportunity_score,\n executionQuality: report.execution_quality,\n impactProjection: report.impact_projection,\n missedOrchestration: report.missed_orchestration_opportunities.length,\n clientExtractionCount: report.client_extractions.length,\n kickoffCount: report.initiative_kickoffs.length,\n trailCount: report.trails.length,\n recurringPatternCount: report.recurring_patterns.length,\n attributionCount: report.attribution_spine.review.pending_count,\n topTrail: report.mirror.primary_trail_id ?? null,\n mirrorHeadline: report.mirror.headline,\n published,\n }, null, 2));\n return;\n }\n\n console.log(` ${ICON.ok} ${pc.green(\"work graph \")} ${pc.dim(markdownPath)}`);\n console.log(` ${ICON.ok} ${pc.green(\"report id \")} ${pc.dim(report.report_id)}`);\n console.log(` ${ICON.ok} ${pc.green(\"fingerprint \")} ${pc.dim(report.work_graph_fingerprint)}`);\n console.log(` ${ICON.ok} ${pc.green(\"state \")} ${pc.dim(report.final_state)}`);\n console.log(` ${ICON.ok} ${pc.green(\"extractions \")} ${pc.dim(String(report.client_extractions.length))}`);\n console.log(` ${ICON.ok} ${pc.green(\"score \")} ${pc.dim(formatWorkGraphScoreLine(report.opportunity_score))}`);\n console.log(` ${ICON.ok} ${pc.green(\"quality \")} ${pc.dim(`${report.execution_quality.overall}/100 · coverage ${report.source_coverage.coverage_score ?? 0}/100`)}`);\n console.log(` ${ICON.ok} ${pc.green(\"impact \")} ${pc.dim(`${report.impact_projection.time_saved_hours_per_week}h/week · +${report.impact_projection.acceleration_percent}% acceleration · ~$${report.impact_projection.estimated_monthly_value_usd.toLocaleString(\"en-US\")}/month`)}`);\n const missed = report.missed_orchestration_opportunities.length;\n const missedColor = missed > 0 ? pc.yellow : pc.green;\n console.log(` ${missed > 0 ? ICON.warn : ICON.ok} ${missedColor(\"missed \")} ${pc.dim(`${missed} orchestration opportunit${missed === 1 ? \"y\" : \"ies\"}`)}`);\n console.log(` ${ICON.ok} ${pc.green(\"trails \")} ${pc.dim(`${report.trails.length} trail${report.trails.length === 1 ? \"\" : \"s\"} · ${report.recurring_patterns.length} recurring pattern${report.recurring_patterns.length === 1 ? \"\" : \"s\"}`)}`);\n console.log(` ${ICON.skip} ${pc.bold(\"mirror \")} ${report.mirror.headline}`);\n for (const metric of report.tension_metrics.slice(0, 4)) {\n const tone = metric.tone === \"danger\" ? pc.red : metric.tone === \"warning\" ? pc.yellow : metric.tone === \"good\" ? pc.green : pc.dim;\n console.log(` ${ICON.skip} ${tone(`${metric.value} ${metric.label}`)} ${pc.dim(metric.explanation)}`);\n }\n for (const kickoff of report.initiative_kickoffs) {\n console.log(` ${ICON.skip} ${pc.bold(kickoff.priority.padEnd(3))} ${kickoff.title}`);\n }\n console.log(` ${ICON.ok} ${pc.green(\"attribution \")} ${pc.dim(`${report.attribution_spine.review.pending_count} nodes · ${report.attribution_spine.source_events.length} source events`)}`);\n if (published?.publicUrl) {\n console.log(` ${ICON.ok} ${pc.green(\"profile \")} ${pc.bold(published.publicUrl)}`);\n }\n}\n\nasync function printPluginStatusSection(): Promise<OrgxPluginStatus[]> {\n const spinner = createOrgxSpinner(\"Checking OrgX companion plugin status\");\n spinner.start();\n const statuses = await listOrgxPluginStatuses();\n spinner.succeed(\"OrgX companion plugin status checked\");\n console.log(\"\");\n console.log(pc.dim(\" plugins\"));\n printPluginStatusReport(statuses);\n return statuses;\n}\n\nasync function checkPluginStatusesCompact(): Promise<OrgxPluginStatus[]> {\n const spinner = createOrgxSpinner(\"Checking OrgX companion plugin status\");\n spinner.start();\n const statuses = await listOrgxPluginStatuses();\n const installable = statuses.filter((s) => s.available && !s.installed);\n const installed = statuses.filter((s) => s.installed).length;\n if (installable.length === 0) {\n spinner.succeed(`Plugins ready (${installed} installed)`);\n return statuses;\n }\n spinner.succeed(\"OrgX companion plugin status checked\");\n console.log(\"\");\n console.log(pc.dim(\" plugins\"));\n printPluginStatusReport(statuses);\n return statuses;\n}\n\nfunction printSkillInstallReport(report: SkillsInstallReport): void {\n for (const write of report.writes) {\n const icon = write.skipped ? ICON.warn : write.changed ? ICON.ok : ICON.skip;\n const state = write.skipped ? pc.yellow(\"skipped \") : write.changed ? pc.green(\"updated \") : pc.dim(\"unchanged\");\n console.log(` ${icon} ${pc.bold(write.label.padEnd(10))} ${state}`);\n if (write.reason) {\n console.log(` ${pc.dim(write.reason)}`);\n }\n }\n\n for (const pack of report.packs) {\n const changedCount = pack.files.filter((f) => f.changed).length;\n const skippedCount = pack.files.filter((f) => f.skipped).length;\n const icon = skippedCount > 0 ? ICON.warn : changedCount > 0 ? ICON.ok : ICON.skip;\n const state = skippedCount > 0\n ? pc.yellow(`${skippedCount} skipped `)\n : changedCount > 0\n ? pc.green(`${changedCount} updated `)\n : pc.dim(\"unchanged\");\n console.log(` ${icon} ${pc.bold(pack.name.padEnd(10))} ${state} ${pc.dim(`${pack.files.length} files`)}`);\n for (const file of pack.files.filter((entry) => entry.skipped && entry.reason)) {\n console.log(` ${pc.dim(`${file.label}: ${file.reason}`)}`);\n }\n }\n\n for (const note of report.notes) {\n console.log(` ${ICON.skip} ${pc.dim(note)}`);\n }\n}\n\nfunction countSkillReportChanges(report: SkillsInstallReport): number {\n const writeChanges = report.writes.filter((write) => write.changed && !write.skipped).length;\n const packChanges = report.packs.reduce(\n (count, pack) => count + pack.files.filter((file) => file.changed && !file.skipped).length,\n 0,\n );\n return writeChanges + packChanges;\n}\n\nfunction printSkillExtensions(extensions: readonly SkillExtension[]): void {\n if (extensions.length === 0) {\n console.log(` ${ICON.skip} ${pc.dim(\"no skill extensions yet\")}`);\n return;\n }\n\n for (const extension of extensions) {\n const icon = extension.enabled ? ICON.ok : ICON.skip;\n const state = extension.enabled ? pc.green(\"enabled \") : pc.dim(\"disabled \");\n console.log(\n ` ${icon} ${pc.bold(extension.id.padEnd(24))} ${state} ${pc.dim(extension.path)}`,\n );\n }\n}\n\nfunction printSkillExtensionWrite(result: SkillExtensionWrite): void {\n const action = result.created ? \"created\" : result.changed ? \"updated\" : \"unchanged\";\n const color = result.created || result.changed ? pc.green : pc.dim;\n console.log(\n ` ${result.created || result.changed ? ICON.ok : ICON.skip} ${pc.bold(result.extension.id.padEnd(24))} ${color(action)}`,\n );\n console.log(` ${pc.dim(result.path)}`);\n}\n\nfunction openPathInEditor(path: string): boolean {\n const editor = process.env.EDITOR || process.env.VISUAL;\n if (!editor) {\n return false;\n }\n\n const result = spawnSync(editor, [path], {\n shell: true,\n stdio: \"inherit\",\n });\n return result.status === 0;\n}\n\nasync function safeTrackWizardTelemetry(\n event: string,\n properties: Record<string, unknown> = {},\n): Promise<void> {\n try {\n await trackWizardTelemetry(event, properties);\n } catch {\n // Telemetry should never block setup/auth flows.\n }\n}\n\nfunction printWorkspace(workspace: OrgxWorkspace): void {\n console.log(\n `${pc.bold(workspace.name)}${workspace.isDefault ? ` ${pc.green(\"(default)\")}` : \"\"}`,\n );\n console.log(` id: ${workspace.id}`);\n if (workspace.description) {\n console.log(` description: ${workspace.description}`);\n }\n if (workspace.createdAt) {\n console.log(` created: ${workspace.createdAt}`);\n }\n if (workspace.updatedAt) {\n console.log(` updated: ${workspace.updatedAt}`);\n }\n}\n\nfunction printWorkspaceList(workspaces: OrgxWorkspace[]): void {\n if (workspaces.length === 0) {\n console.log(pc.yellow(\"No workspaces found for this OrgX user.\"));\n return;\n }\n\n for (const workspace of workspaces) {\n printWorkspace(workspace);\n }\n}\n\nfunction printWorkspaceSetupResult(result: WorkspaceSetupResult): void {\n if (result.workspace) {\n const icon = result.status === \"updated\" ? ICON.ok : ICON.skip;\n console.log(` ${icon} ${pc.green(\"workspace \")} ${pc.bold(result.workspace.name)}`);\n } else {\n console.log(` ${ICON.skip} ${pc.dim(result.message)}`);\n }\n}\n\nfunction printSetupScopeNote(): void {\n console.log(pc.dim(\" setup updates your AI tools with:\"));\n console.log(` ${ICON.skip} ${pc.dim(\"MCP configs for local and cloud OrgX access\")}`);\n console.log(` ${ICON.skip} ${pc.dim(\"OrgX agent skills, rules, prompts, commands, and hooks\")}`);\n console.log(` ${ICON.skip} ${pc.dim(\"companion plugins where your editor supports them\")}`);\n}\n\nfunction printFirstValueHandoff(input: {\n initiative: FirstValueInitiativeResult;\n workspace: Pick<OrgxWorkspace, \"name\">;\n}): void {\n const cmd = getCmd();\n console.log(\"\");\n console.log(pc.bold(\"first OrgX handoff\"));\n console.log(\n ` ${input.initiative.created ? pc.green(\"created\") : pc.yellow(\"ready\")} ${pc.bold(input.initiative.initiative.title)}`,\n );\n console.log(` live: ${input.initiative.liveUrl}`);\n console.log(\n ` ${pc.dim(\"ask your AI tool:\")} ${pc.cyan(\n `Use OrgX to continue \"${input.initiative.initiative.title}\" in ${input.workspace.name}. Show the next action, then start with the onboarding task.`,\n )}`,\n );\n console.log(` ${pc.dim(\"later:\")} ${pc.cyan(`${cmd} doctor`)} ${pc.dim(\"checks tool wiring\")}`);\n}\n\nfunction firstValueRecordToResult(\n record: WizardFirstValueInitiativeRecord | undefined,\n): FirstValueInitiativeResult | null {\n if (!record) {\n return null;\n }\n\n return {\n created: false,\n initiative: {\n id: record.id,\n title: record.title,\n ...(record.summary ? { summary: record.summary } : {}),\n },\n liveUrl: record.liveUrl,\n };\n}\n\nfunction printFounderPresetResult(result: FounderPresetResult): void {\n printMutationResults(result.surfaceResults);\n console.log(\"\");\n printSkillInstallReport(result.skillReport);\n\n if (result.workspaceSetup) {\n console.log(\"\");\n printWorkspaceSetupResult(result.workspaceSetup);\n }\n\n if (result.demoInitiative) {\n console.log(\"\");\n console.log(pc.bold(\"demo initiative\"));\n console.log(\n ` ${result.demoInitiative.created ? pc.green(\"created\") : pc.yellow(\"unchanged\")} ${result.demoInitiative.initiative.title}`,\n );\n console.log(` live: ${result.demoInitiative.liveUrl}`);\n console.log(\n ` decision: ${result.demoInitiative.decision.title} ${pc.dim(`(${result.demoInitiative.decision.status ?? \"pending\"})`)}`,\n );\n console.log(\n ` artifact: ${result.demoInitiative.artifact.name}${result.demoInitiative.artifact.url ? ` ${pc.dim(result.demoInitiative.artifact.url)}` : \"\"}`,\n );\n }\n}\n\nfunction normalizePromptResult<T>(value: T | symbol): T | symbol {\n return value;\n}\n\nasync function secretPrompt(message: string): Promise<string | null> {\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n return null;\n }\n\n process.stdout.write(`${message}: `);\n\n const stdin = process.stdin;\n const stdout = process.stdout;\n const previousRawMode = stdin.isRaw === true;\n\n return await new Promise<string | null>((resolve) => {\n let value = \"\";\n\n const cleanup = (result: string | null) => {\n stdin.off(\"data\", onData);\n if (stdin.isTTY) {\n stdin.setRawMode(previousRawMode);\n }\n stdin.pause();\n stdout.write(\"\\n\");\n resolve(result);\n };\n\n const onData = (chunk: Buffer | string) => {\n const text = chunk.toString(\"utf8\");\n\n for (const char of text) {\n if (char === \"\\u0003\") {\n cleanup(null);\n return;\n }\n\n if (char === \"\\r\" || char === \"\\n\") {\n cleanup(value.trim());\n return;\n }\n\n if (char === \"\\u007f\" || char === \"\\b\") {\n value = value.slice(0, -1);\n continue;\n }\n\n if (char >= \" \") {\n value += char;\n }\n }\n };\n\n if (stdin.isTTY) {\n stdin.setRawMode(true);\n }\n stdin.resume();\n stdin.on(\"data\", onData);\n });\n}\n\nasync function selectPrompt(input: {\n initialValue?: string | undefined;\n message: string;\n options: { hint?: string; label: string; value: string }[];\n}): Promise<string | symbol> {\n const promptInput = input.initialValue\n ? { ...input, initialValue: input.initialValue }\n : { message: input.message, options: input.options };\n\n return normalizePromptResult(await clack.select<string>(promptInput));\n}\n\nasync function textPrompt(input: {\n initialValue?: string | undefined;\n message: string;\n placeholder?: string;\n validate?: (value: string | undefined) => Error | string | undefined;\n}): Promise<string | symbol> {\n const promptInput = input.initialValue\n ? { ...input, initialValue: input.initialValue }\n : {\n message: input.message,\n ...(input.placeholder ? { placeholder: input.placeholder } : {}),\n ...(input.validate ? { validate: input.validate } : {}),\n };\n\n return normalizePromptResult(await clack.text(promptInput));\n}\n\nasync function multiselectPrompt(input: {\n initialValues?: string[] | undefined;\n message: string;\n options: { disabled?: boolean; hint?: string; label: string; value: string }[];\n required?: boolean;\n}): Promise<string[] | symbol> {\n const promptInput = {\n message: `${input.message} ${pc.dim(\"Space to select, Enter to continue. Defaults are preselected.\")}`,\n options: input.options,\n ...(input.initialValues ? { initialValues: input.initialValues } : {}),\n ...(input.required !== undefined ? { required: input.required } : {}),\n };\n\n return normalizePromptResult(await clack.multiselect<string>(promptInput));\n}\n\nfunction printAgentRoster(roster: WizardAgentRosterRecord): void {\n console.log(` ${ICON.ok} ${pc.green(\"agent roster\")} ${pc.bold(`${roster.agents.length} agents`)}`);\n for (const agent of roster.agents) {\n console.log(\n ` ${pc.dim(agent.domain.padEnd(12))} ${pc.bold(agent.name)} ${pc.dim(agent.agentType)}`,\n );\n }\n}\n\nasync function promptForGuidedAgentRoster(\n workspace: OrgxWorkspace,\n): Promise<\"cancelled\" | WizardAgentRosterRecord | null> {\n const remainingAgents = listAgentRosterProfiles();\n const assignments: AgentRosterAssignment[] = [];\n\n for (const domain of AGENT_ROSTER_DOMAINS) {\n if (remainingAgents.length === 0) {\n break;\n }\n\n const defaultAgent = remainingAgents.find((agent) => agent.defaultDomain === domain);\n const choice = await selectPrompt({\n initialValue: defaultAgent?.name ?? \"skip\",\n message: `Assign an OrgX agent to the ${domain} domain`,\n options: [\n ...remainingAgents.map((agent) => ({\n value: agent.name,\n label: agent.name,\n hint: `${agent.agentType} · default ${agent.defaultDomain}`,\n })),\n { value: \"skip\", label: `Leave ${domain} unassigned`, hint: \"optional\" },\n ],\n });\n\n if (clack.isCancel(choice)) {\n clack.cancel(\"Setup cancelled.\");\n return \"cancelled\";\n }\n\n if (choice === \"skip\") {\n continue;\n }\n\n const index = remainingAgents.findIndex((agent) => agent.name === choice);\n if (index === -1) {\n continue;\n }\n\n const [selectedAgent] = remainingAgents.splice(index, 1);\n if (!selectedAgent) {\n continue;\n }\n\n assignments.push({ domain, name: selectedAgent.name });\n }\n\n if (assignments.length === 0) {\n return null;\n }\n\n return configureAgentRoster(workspace, assignments);\n}\n\nasync function verifyAndPersistAuth(\n apiKey: string,\n options: { baseUrl?: string; telemetrySource?: string },\n): Promise<{\n verification: OrgxAuthCheckResult;\n} | {\n openclawResults: SurfaceMutationResult[];\n stored: Awaited<ReturnType<typeof writeWizardAuth>>;\n verification: OrgxAuthCheckResult;\n}> {\n const trimmedKey = apiKey.trim();\n if (!trimmedKey.toLowerCase().startsWith(\"oxk_\")) {\n throw new Error(\"Expected a per-user OrgX API key that starts with oxk_.\");\n }\n\n const baseUrl = normalizeOrgxBaseUrl(options.baseUrl);\n const verification = await verifyOrgxAuth({\n apiKey: trimmedKey,\n keyPrefix: trimmedKey.slice(0, 12),\n baseUrl,\n source: \"wizard-store\",\n });\n\n if (!verification.ok) {\n return { verification };\n }\n\n const stored = await writeWizardAuth({\n apiKey: trimmedKey,\n baseUrl,\n verifiedAt: new Date().toISOString(),\n });\n await safeTrackWizardTelemetry(\"auth_completed\", {\n auth_source: options.telemetrySource ?? \"manual_api_key\",\n has_base_url: Boolean(baseUrl),\n });\n const openclawResults = detectSurface(\"openclaw\").detected\n ? await addSurface(\"openclaw\")\n : [];\n\n return { openclawResults, stored, verification };\n}\n\nasync function syncContinuityAfterAuth(seed: {\n executionMode?: \"cloud\" | \"local\" | null;\n workspaceName?: string | null;\n} = {}): Promise<void> {\n try {\n const workspace = await getCurrentWorkspace().catch(() => null);\n persistContinuityDefaults({\n ...(seed.executionMode !== undefined ? { executionMode: seed.executionMode } : {}),\n workspace,\n workspaceName: seed.workspaceName ?? workspace?.name ?? null,\n });\n } catch {\n // Auth success should not depend on workspace or continuity writes.\n }\n}\n\nfunction parseTimeoutSeconds(value: string): number {\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\"--timeout must be a positive number of seconds.\");\n }\n return parsed;\n}\n\n/**\n * Read a single keystroke from stdin in raw mode. Returns the lowercased\n * character, or null on EOF / Ctrl-C / non-TTY. Mirrors the `secretPrompt`\n * pattern used elsewhere in this file so we do not pull in an extra dep\n * for the M-P5 intent flow.\n */\nasync function readSingleKey(): Promise<string | null> {\n const stdin = process.stdin;\n if (!stdin.isTTY) return null;\n\n const previousRawMode = stdin.isRaw === true;\n return await new Promise<string | null>((resolve) => {\n const cleanup = (result: string | null) => {\n stdin.off(\"data\", onData);\n if (stdin.isTTY) {\n stdin.setRawMode(previousRawMode);\n }\n stdin.pause();\n resolve(result);\n };\n\n const onData = (chunk: Buffer | string) => {\n const text = chunk.toString(\"utf8\");\n const first = text.charAt(0);\n if (first === \"\\u0003\" || first === \"\\u0004\") {\n cleanup(null);\n return;\n }\n cleanup(first.toLowerCase());\n };\n\n if (stdin.isTTY) {\n stdin.setRawMode(true);\n }\n stdin.resume();\n stdin.on(\"data\", onData);\n });\n}\n\n/**\n * Pretty-print the classified intent: routing line, plan preview, hotkey bar.\n * Stays pure on the render side (all strings built in `intent-render.ts`); the\n * only side effects are `console.log` calls.\n */\nfunction printIntentPreview(intent: Intent, baseUrl: string): void {\n const render = detectRenderCapabilities();\n const agent: AgentSlug = intent.suggested_agent_slug ?? \"xandy\";\n const confidence = resolveConfidenceDecimal(intent.plan_preview);\n\n console.log(\"\");\n console.log(renderRoutingLine(agent, confidence, render));\n console.log(\"\");\n console.log(renderPlanPreview(intent.plan_preview, render));\n console.log(\"\");\n console.log(\n renderDim(\n ` slug ${intent.slug} handoff ${buildIntentHandoffUrl(intent.slug, { baseUrl })}`,\n render,\n ),\n );\n console.log(\"\");\n console.log(renderHotkeyBar(DEFAULT_HOTKEYS, render));\n}\n\n/**\n * Capture a first OrgX intent during `setup`. Replaces the old people-first\n * capture: instead of asking for one contact by hand, we ask the user what\n * they want OrgX to move, hand that to the classifier, and let the agent\n * draft the ICP + source the people downstream. Mirrors the Fon fixture\n * pattern in the main orgx repo (lib/execution/fixtures/fonScenario.ts).\n *\n * Contract:\n * - Requires an interactive TTY and a resolved workspace, otherwise skipped.\n * - One prompt. Blank answer = skip. Non-blank = create intent + preview.\n * - Optionally approves the intent so the /command view opens in \"ready\"\n * state instead of \"pending\".\n * - Never throws; network/auth failures return \"failed\" and print a hint.\n */\nasync function maybeCaptureSetupIntent(input: {\n interactive: boolean;\n workspace: OrgxWorkspace | null;\n}): Promise<\"skipped\" | \"captured\" | \"approved\" | \"failed\" | \"cancelled\"> {\n if (!input.interactive || !input.workspace) {\n return \"skipped\";\n }\n if (hasSetupPromptSkip(input.workspace.id, \"setup_intent\")) {\n return \"skipped\";\n }\n\n const prompt = await textPrompt({\n message: \"In one line, what do you want OrgX to move first? (blank to skip — you can start from the dashboard)\",\n placeholder: \"e.g. open a warm-intro loop to 50 design-led SaaS founders\",\n validate: (value) => {\n const trimmed = (value ?? \"\").trim();\n if (!trimmed) return undefined;\n if (trimmed.length > 4_000) return \"Keep it under 4,000 characters.\";\n return undefined;\n },\n });\n if (clack.isCancel(prompt)) {\n return \"cancelled\";\n }\n const intentText = typeof prompt === \"string\" ? prompt.trim() : \"\";\n if (!intentText) {\n recordSetupPromptSkip({\n promptKey: \"setup_intent\",\n workspaceId: input.workspace.id,\n workspaceName: input.workspace.name,\n });\n return \"skipped\";\n }\n\n const spinner = createOrgxSpinner(\"Routing\");\n spinner.start();\n\n let intent: Intent;\n try {\n intent = await createIntent({\n workspace_id: input.workspace.id,\n text: intentText,\n });\n spinner.stop();\n } catch (error) {\n spinner.fail(\"Could not classify intent.\");\n const message = error instanceof Error ? error.message : String(error);\n console.log(` ${ICON.warn} ${pc.yellow(\"intent\")} ${pc.dim(message)}`);\n return \"failed\";\n }\n\n const auth = await resolveOrgxAuth().catch(() => null);\n const baseUrl = auth?.baseUrl ?? DEFAULT_ORGX_BASE_URL;\n\n printIntentPreview(intent, baseUrl);\n\n const approveChoice = await clack.confirm({\n message: \"Approve this plan and hand off to OrgX?\",\n initialValue: true,\n });\n if (clack.isCancel(approveChoice)) {\n return \"cancelled\";\n }\n\n if (approveChoice) {\n const approveSpinner = createOrgxSpinner(\"Approving\");\n approveSpinner.start();\n try {\n await updateIntent(intent.id, { status: \"approved\" });\n approveSpinner.stop();\n } catch (error) {\n approveSpinner.fail(\"Approve failed.\");\n const message = error instanceof Error ? error.message : String(error);\n console.log(` ${ICON.warn} ${pc.yellow(\"intent\")} ${pc.dim(message)}`);\n return \"failed\";\n }\n const handoff = buildIntentHandoffUrl(intent.slug, { baseUrl });\n console.log(` ${ICON.ok} ${pc.green(\"intent\")} ${pc.dim(`approved · ${handoff}`)}`);\n return \"approved\";\n }\n\n const handoff = buildIntentHandoffUrl(intent.slug, { baseUrl });\n console.log(` ${ICON.skip} ${pc.dim(`intent pending · ${handoff}`)}`);\n return \"captured\";\n}\n\nasync function runIntentCommand(options: {\n initialText?: string;\n workspaceId?: string;\n jsonOutput?: boolean;\n}): Promise<void> {\n const interactive = isInteractive();\n\n // Step 1 — collect the intent text. In an interactive TTY we use clack's\n // text prompt (same styling as the rest of the wizard); non-TTY invocations\n // must pass the intent as arguments so the command stays pipeable.\n let intentText = options.initialText?.trim() ?? \"\";\n if (!intentText) {\n if (!interactive) {\n console.error(\n pc.red(\"Intent text is required when running non-interactively.\"),\n );\n console.error(\n pc.dim(\" Example: orgx-wizard intent \\\"launch partner outreach campaign\\\"\"),\n );\n process.exitCode = 1;\n return;\n }\n const prompt = await textPrompt({\n message: \"What do you want to move?\",\n placeholder: \"e.g. launch partner outreach campaign\",\n validate: (value) => {\n const trimmed = (value ?? \"\").trim();\n if (!trimmed) return \"Intent text cannot be empty.\";\n if (trimmed.length > 4_000) return \"Intent text exceeds 4,000 characters.\";\n return undefined;\n },\n });\n if (clack.isCancel(prompt) || typeof prompt !== \"string\") {\n console.log(pc.dim(\"Cancelled.\"));\n return;\n }\n intentText = prompt.trim();\n }\n\n // Step 2 — resolve the workspace. The intent API insists on a workspace id;\n // we default to the current workspace so the happy path is `orgx-wizard\n // intent \"...\"` with no extra flags.\n let workspaceId = options.workspaceId ?? \"\";\n let workspaceName: string | null = null;\n let workspaceBaseUrl: string | null = null;\n if (!workspaceId) {\n const loadLabel = \"Loading current OrgX workspace\";\n const spinner = interactive ? createOrgxSpinner(loadLabel) : null;\n if (spinner) spinner.start();\n else console.log(pc.dim(`${loadLabel}...`));\n try {\n const current = await getCurrentWorkspace();\n if (!current) {\n if (spinner) spinner.fail(\"No OrgX workspace is configured.\");\n else console.error(pc.red(\"No OrgX workspace is configured.\"));\n console.log(\n pc.dim(\" Run `orgx-wizard workspace create <name>` or pass --workspace <id>.\"),\n );\n process.exitCode = 1;\n return;\n }\n workspaceId = current.id;\n workspaceName = current.name;\n if (spinner) spinner.stop();\n } catch (error) {\n if (spinner) spinner.fail(\"Failed to load current workspace.\");\n console.error(\n pc.red(error instanceof Error ? error.message : String(error)),\n );\n process.exitCode = 1;\n return;\n }\n }\n\n // Step 3 — classify. The spinner in interactive mode shows the spec's\n // \"⠋ Classifying intent…\" affordance; non-interactive runs print a single\n // status line so CI logs stay readable.\n const classifyLabel = \"Routing\";\n const classifySpinner = interactive\n ? createOrgxSpinner(classifyLabel)\n : null;\n if (classifySpinner) classifySpinner.start();\n else console.log(pc.dim(`${classifyLabel}...`));\n\n let intent: Intent;\n try {\n intent = await createIntent({ workspace_id: workspaceId, text: intentText });\n if (classifySpinner) classifySpinner.stop();\n } catch (error) {\n if (classifySpinner) classifySpinner.fail(\"Classification failed.\");\n console.error(\n pc.red(error instanceof Error ? error.message : String(error)),\n );\n process.exitCode = 1;\n return;\n }\n\n // Resolve the OrgX base URL for handoff links. We prefer the auth-resolved\n // URL so environment overrides (ORGX_BASE_URL, wizard auth store) take\n // precedence over the public default.\n const auth = await resolveOrgxAuth().catch(() => null);\n const baseUrl = auth?.baseUrl ?? DEFAULT_ORGX_BASE_URL;\n workspaceBaseUrl = baseUrl;\n\n if (options.jsonOutput) {\n const payload = {\n intent,\n handoff_url: buildIntentHandoffUrl(intent.slug, { baseUrl }),\n workspace: workspaceName ? { id: workspaceId, name: workspaceName } : { id: workspaceId },\n };\n console.log(JSON.stringify(payload, null, 2));\n return;\n }\n\n // Step 4 — render the preview block.\n printIntentPreview(intent, baseUrl);\n console.log(\"\");\n\n // Step 5 — hotkey bar. In non-interactive mode we exit after rendering so\n // scripts can parse stdout; interactive mode waits for a single keypress.\n if (!interactive) {\n console.log(\n pc.dim(\n `Run \\`orgx-wizard intent --workspace ${workspaceId}\\` interactively to approve, edit, or archive.`,\n ),\n );\n return;\n }\n\n let action: IntentAction | null = null;\n while (action === null) {\n const key = await readSingleKey();\n if (!key) {\n action = \"quit\";\n break;\n }\n action = normalizeHotkey(key);\n if (action === null) {\n console.log(\n pc.dim(` Unrecognized key. Press a, e, x, or q.`),\n );\n }\n }\n\n switch (action) {\n case \"approve\": {\n const approveLabel = \"Approving\";\n const spinner = interactive ? createOrgxSpinner(approveLabel) : null;\n if (spinner) spinner.start();\n try {\n await updateIntent(intent.id, { status: \"approved\" });\n if (spinner) spinner.stop();\n } catch (error) {\n if (spinner) spinner.fail(\"Approve failed.\");\n console.error(\n pc.red(error instanceof Error ? error.message : String(error)),\n );\n process.exitCode = 1;\n return;\n }\n const handoff = buildIntentHandoffUrl(intent.slug, { baseUrl: workspaceBaseUrl ?? baseUrl });\n console.log(\"\");\n console.log(`${pc.green(\"✓\")} Approved · ${handoff}`);\n return;\n }\n case \"edit\": {\n const handoff = buildIntentHandoffUrl(intent.slug, { baseUrl: workspaceBaseUrl ?? baseUrl });\n console.log(\"\");\n console.log(`${pc.yellow(\"✎\")} Opening ${handoff}`);\n const result = openBrowser(handoff);\n if (!result.ok) {\n console.log(pc.dim(` Could not launch browser: ${result.error}`));\n console.log(pc.dim(` Visit ${handoff} to finish editing.`));\n }\n return;\n }\n case \"archive\": {\n const archiveLabel = \"Archiving\";\n const spinner = interactive ? createOrgxSpinner(archiveLabel) : null;\n if (spinner) spinner.start();\n try {\n await updateIntent(intent.id, { status: \"archived\" });\n if (spinner) spinner.stop();\n } catch (error) {\n if (spinner) spinner.fail(\"Archive failed.\");\n console.error(\n pc.red(error instanceof Error ? error.message : String(error)),\n );\n process.exitCode = 1;\n return;\n }\n console.log(\"\");\n console.log(`${pc.red(\"✕\")} Archived · intent will not be executed.`);\n return;\n }\n case \"quit\":\n default: {\n console.log(\"\");\n console.log(pc.dim(\" Exited without saving. Intent remains pending.\"));\n console.log(\n pc.dim(\n ` Resume at ${buildIntentHandoffUrl(intent.slug, { baseUrl: workspaceBaseUrl ?? baseUrl })}`,\n ),\n );\n return;\n }\n }\n}\n\nasync function maybeConfigureOptionalWorkspaceAddOns(input: {\n initiativeId?: string;\n interactive: boolean;\n telemetry?: {\n command: string;\n preset?: string;\n };\n workspace: OrgxWorkspace | null;\n}): Promise<\"cancelled\" | \"configured\" | \"skipped\"> {\n if (!input.interactive || !input.workspace) {\n return \"skipped\";\n }\n\n const existingState = readWizardState();\n const providedInitiativeId = input.initiativeId?.trim();\n const storedDemoInitiative = existingState?.demoInitiative?.workspaceId === input.workspace.id\n ? existingState.demoInitiative\n : undefined;\n const storedFirstValueInitiative =\n existingState?.firstValueInitiative?.workspaceId === input.workspace.id\n ? existingState.firstValueInitiative\n : undefined;\n let effectiveInitiativeId = providedInitiativeId\n || storedDemoInitiative?.id\n || storedFirstValueInitiative?.id;\n let firstValueInitiative = providedInitiativeId || storedDemoInitiative\n ? null\n : firstValueRecordToResult(storedFirstValueInitiative);\n const firstInitiativeSkipped = hasSetupPromptSkip(\n input.workspace.id,\n \"first_initiative\",\n );\n\n if (!effectiveInitiativeId && !firstInitiativeSkipped) {\n const firstInitiativeChoice = await selectPrompt({\n initialValue: \"yes\",\n message: `Create your first OrgX initiative in ${input.workspace.name}?`,\n options: [\n {\n value: \"yes\",\n label: \"Create first initiative\",\n hint: \"recommended; gives setup a live next step\",\n },\n { value: \"no\", label: \"Skip initiative creation\" },\n ],\n });\n if (clack.isCancel(firstInitiativeChoice)) {\n clack.cancel(\"Setup cancelled.\");\n return \"cancelled\";\n }\n\n if (firstInitiativeChoice === \"yes\") {\n const title = await textPrompt({\n initialValue: FIRST_VALUE_INITIATIVE_TITLE,\n message: \"What should OrgX help you move forward first?\",\n validate: (value) => {\n if (!value || value.trim().length === 0) {\n return \"Enter an initiative title.\";\n }\n return undefined;\n },\n });\n if (clack.isCancel(title)) {\n clack.cancel(\"Setup cancelled.\");\n return \"cancelled\";\n }\n\n const spinner = createOrgxSpinner(\"Creating your first OrgX initiative and live handoff\");\n spinner.start();\n try {\n firstValueInitiative = await ensureFirstValueInitiative(input.workspace, {\n title: String(title),\n });\n spinner.succeed(\n firstValueInitiative.created\n ? \"First OrgX initiative created\"\n : \"First OrgX initiative ready\",\n );\n effectiveInitiativeId = firstValueInitiative.initiative.id;\n await safeTrackWizardTelemetry(\n \"first_value_initiative_ready\",\n buildFirstValueInitiativeTelemetryProperties(\n firstValueInitiative,\n {\n command: input.telemetry?.command ?? \"setup\",\n ...(input.telemetry?.preset ? { preset: input.telemetry.preset } : {}),\n },\n ),\n );\n } catch (error) {\n spinner.fail(\"First OrgX initiative was not created\");\n const message = error instanceof Error ? error.message : String(error);\n console.log(` ${ICON.warn} ${pc.yellow(\"initiative\")} ${pc.dim(message)}`);\n }\n } else if (firstInitiativeChoice === \"no\") {\n recordSetupPromptSkip({\n promptKey: \"first_initiative\",\n workspaceId: input.workspace.id,\n workspaceName: input.workspace.name,\n });\n }\n }\n\n const hasOnboardingTask = existingState?.onboardingTask?.workspaceId === input.workspace.id;\n const onboardingTaskSkipped = hasSetupPromptSkip(\n input.workspace.id,\n \"onboarding_task\",\n );\n if (!hasOnboardingTask && effectiveInitiativeId && !onboardingTaskSkipped) {\n let shouldCreateOnboardingTask = firstValueInitiative !== null;\n if (!shouldCreateOnboardingTask) {\n const onboardingChoice = await selectPrompt({\n initialValue: \"yes\",\n message: `Create a starter onboarding task for ${input.workspace.name}?`,\n options: [\n { value: \"yes\", label: \"Create onboarding task\", hint: \"recommended\" },\n { value: \"no\", label: \"Skip task creation\" },\n ],\n });\n if (clack.isCancel(onboardingChoice)) {\n clack.cancel(\"Setup cancelled.\");\n return \"cancelled\";\n }\n shouldCreateOnboardingTask = onboardingChoice === \"yes\";\n if (onboardingChoice === \"no\") {\n recordSetupPromptSkip({\n promptKey: \"onboarding_task\",\n workspaceId: input.workspace.id,\n workspaceName: input.workspace.name,\n });\n }\n }\n\n if (shouldCreateOnboardingTask) {\n const spinner = createOrgxSpinner(\"Creating onboarding workstream and starter task\");\n spinner.start();\n try {\n const task = await ensureOnboardingTask(input.workspace, {\n initiativeId: effectiveInitiativeId,\n });\n spinner.succeed(\"Onboarding workstream and starter task ready\");\n console.log(` ${ICON.ok} ${pc.green(\"onboarding\")} ${pc.bold(task.title)}`);\n await safeTrackWizardTelemetry(\n \"onboarding_task_created\",\n buildOnboardingTaskTelemetryProperties(\n {\n created: true,\n hasInitiative: true,\n task,\n },\n {\n command: input.telemetry?.command ?? \"setup\",\n ...(input.telemetry?.preset ? { preset: input.telemetry.preset } : {}),\n },\n ),\n );\n } catch (error) {\n spinner.fail(\"Onboarding task was not created\");\n const message = error instanceof Error ? error.message : String(error);\n console.log(` ${ICON.warn} ${pc.yellow(\"onboarding\")} ${pc.dim(message)}`);\n }\n }\n }\n\n if (firstValueInitiative) {\n printFirstValueHandoff({\n initiative: firstValueInitiative,\n workspace: input.workspace,\n });\n }\n\n const refreshedState = readWizardState();\n const hasAgentRoster = refreshedState?.agentRoster?.workspaceId === input.workspace.id;\n const agentRosterSkipped = hasSetupPromptSkip(input.workspace.id, \"agent_roster\");\n if (!hasAgentRoster && !agentRosterSkipped) {\n const rosterChoice = await selectPrompt({\n initialValue: \"default\",\n message: `Set up an OrgX agent roster for ${input.workspace.name}?`,\n options: [\n { value: \"default\", label: \"Install the full default roster\", hint: \"recommended\" },\n { value: \"guided\", label: \"Choose agents and domains\" },\n { value: \"no\", label: \"Skip roster setup\" },\n ],\n });\n if (clack.isCancel(rosterChoice)) {\n clack.cancel(\"Setup cancelled.\");\n return \"cancelled\";\n }\n if (rosterChoice === \"guided\") {\n const roster = await promptForGuidedAgentRoster(input.workspace);\n if (roster === \"cancelled\") {\n return \"cancelled\";\n }\n if (roster) {\n printAgentRoster(roster);\n await safeTrackWizardTelemetry(\n \"agent_roster_configured\",\n buildAgentRosterTelemetryProperties(\n {\n roster,\n strategy: \"guided\",\n },\n {\n command: input.telemetry?.command ?? \"setup\",\n ...(input.telemetry?.preset ? { preset: input.telemetry.preset } : {}),\n },\n ),\n );\n } else {\n console.log(` ${ICON.skip} ${pc.dim(\"agent roster skipped\")} ${pc.dim(\"(no agents selected)\")}`);\n recordSetupPromptSkip({\n promptKey: \"agent_roster\",\n workspaceId: input.workspace.id,\n workspaceName: input.workspace.name,\n });\n }\n } else if (rosterChoice === \"default\") {\n const roster = ensureDefaultAgentRoster(input.workspace);\n printAgentRoster(roster);\n await safeTrackWizardTelemetry(\n \"agent_roster_configured\",\n buildAgentRosterTelemetryProperties(\n {\n roster,\n strategy: \"default\",\n },\n {\n command: input.telemetry?.command ?? \"setup\",\n ...(input.telemetry?.preset ? { preset: input.telemetry.preset } : {}),\n },\n ),\n );\n } else if (rosterChoice === \"no\") {\n recordSetupPromptSkip({\n promptKey: \"agent_roster\",\n workspaceId: input.workspace.id,\n workspaceName: input.workspace.name,\n });\n }\n }\n\n return \"configured\";\n}\n\nasync function promptOptionalCompanionPluginTargets(input: {\n interactive: boolean;\n statuses?: OrgxPluginStatus[];\n}): Promise<\"cancelled\" | OrgxPluginStatus[\"target\"][]> {\n if (!input.interactive) {\n return [];\n }\n\n let statuses = input.statuses;\n if (!statuses) {\n const spinner = createOrgxSpinner(\"Checking optional OrgX companion plugin status\");\n spinner.start();\n statuses = await listOrgxPluginStatuses();\n spinner.succeed(\"Optional OrgX companion plugin status checked\");\n }\n const installable = statuses.filter((status) => status.available && !status.installed);\n if (installable.length === 0) {\n return [];\n }\n\n const selection = await multiselectPrompt({\n initialValues: installable.map((status) => status.target),\n message: \"Install OrgX companion plugins into your detected AI tools?\",\n options: installable.map((status) => ({\n value: status.target,\n label: `Install ${formatPluginTargetLabel(status.target)}`,\n hint: status.message,\n })),\n required: false,\n });\n\n if (clack.isCancel(selection)) {\n clack.cancel(\"Setup cancelled.\");\n return \"cancelled\";\n }\n\n return selection as OrgxPluginStatus[\"target\"][];\n}\n\nfunction printPluginSkillOwnershipNote(targets: readonly OrgxPluginStatus[\"target\"][]): void {\n if (!targets.some((target) => target === \"cursor\" || target === \"claude\" || target === \"codex\")) {\n return;\n }\n\n console.log(\n ` ${ICON.skip} ${pc.dim(\n \"Cursor, Claude Code, and Codex companion plugins carry their own OrgX skills, rules, MCP config, commands, hooks, and agent prompts. Use 'wizard skills add' only for standalone rules or skills when those plugins are not in play.\",\n )}`,\n );\n}\n\nasync function installSelectedCompanionPlugins(input: {\n targets: readonly OrgxPluginStatus[\"target\"][];\n telemetry?: {\n command: string;\n preset?: string;\n };\n}): Promise<\"configured\" | \"skipped\"> {\n if (input.targets.length === 0) {\n return \"skipped\";\n }\n\n const spinner = createOrgxSpinner(\"Installing OrgX companion plugins\");\n spinner.start();\n const report = await installOrgxPlugins({ targets: input.targets });\n spinner.succeed(\"OrgX companion plugins processed\");\n printPluginMutationReport(report);\n printPluginSkillOwnershipNote(input.targets);\n\n await safeTrackWizardTelemetry(\"plugins_installed\", {\n changed_count: countPluginReportChanges(report),\n command: input.telemetry?.command ?? \"setup\",\n ...(input.telemetry?.preset ? { preset: input.telemetry.preset } : {}),\n requested_target_count: input.targets.length,\n target_count: report.results.length,\n });\n\n return countPluginReportChanges(report) > 0 ? \"configured\" : \"skipped\";\n}\n\nasync function maybeInstallOptionalCompanionPlugins(input: {\n interactive: boolean;\n statuses?: OrgxPluginStatus[];\n telemetry?: {\n command: string;\n preset?: string;\n };\n}): Promise<\"cancelled\" | \"configured\" | \"skipped\"> {\n const selection = await promptOptionalCompanionPluginTargets({\n interactive: input.interactive,\n ...(input.statuses ? { statuses: input.statuses } : {}),\n });\n if (selection === \"cancelled\") {\n return \"cancelled\";\n }\n\n return await installSelectedCompanionPlugins({\n targets: selection,\n ...(input.telemetry ? { telemetry: input.telemetry } : {}),\n });\n}\n\n\nfunction printAuthStatus(status: OrgxAuthCheckResult): void {\n if (!status.configured) {\n console.log(` ${ICON.warn} ${pc.yellow(\"not paired\")} run ${pc.cyan(`${getCmd()} auth login`)} to pair this terminal`);\n return;\n }\n\n const icon = status.ok ? ICON.ok : ICON.err;\n const state = status.ok ? pc.green(\"paired \") : status.skipped ? pc.yellow(\"skipped \") : pc.red(\"invalid \");\n const via = pc.dim(formatAuthSource(status.source));\n console.log(` ${icon} ${state} ${pc.bold(status.keyPrefix ?? \"unknown\")} ${via}`);\n if (!status.ok && status.error) {\n console.log(` ${pc.red(status.error)}`);\n }\n}\n\nfunction printDoctorReport(\n report: Awaited<ReturnType<typeof runDoctor>>,\n assessment: ReturnType<typeof assessDoctorReport>,\n): void {\n const verification = summarizeSetupVerification(assessment);\n // — Surfaces —\n console.log(pc.dim(\" surfaces\"));\n printSurfaceTable(report.surfaces);\n\n // — Account —\n console.log(\"\");\n console.log(pc.dim(\" account\"));\n printAuthStatus(report.auth);\n\n // — Services —\n console.log(\"\");\n console.log(pc.dim(\" services\"));\n\n // Hosted MCP\n const mcp = report.hostedMcp;\n {\n const icon = mcp.skipped ? ICON.skip : mcp.ok ? ICON.ok : ICON.err;\n const label = pc.dim(\"cloud mcp \".padEnd(14));\n const state = mcp.skipped ? pc.dim(\"skipped\") : mcp.ok ? pc.green(\"reachable\") : pc.red(\"unreachable\");\n const tail = !mcp.ok && !mcp.skipped && mcp.error ? ` ${pc.dim(mcp.error)}` : \"\";\n console.log(` ${icon} ${label} ${state}${tail}`);\n }\n\n // Tool call\n const tool = report.hostedMcpTool;\n {\n const icon = tool.skipped ? ICON.skip : tool.ok ? ICON.ok : ICON.err;\n const label = pc.dim(\"tool call \".padEnd(14));\n const state = tool.skipped ? pc.dim(\"skipped\") : tool.ok ? pc.green(\"authenticated\") : pc.red(\"failed\");\n const tail = !tool.ok && !tool.skipped && tool.error ? ` ${pc.dim(tool.error)}` : \"\";\n console.log(` ${icon} ${label} ${state}${tail}`);\n }\n\n // Workspace\n const ws = report.workspace;\n {\n const icon = !ws.configured ? ICON.skip : ws.ok ? ICON.ok : ICON.err;\n const label = pc.dim(\"workspace \".padEnd(14));\n const state = !ws.configured\n ? pc.dim(\"not configured\")\n : ws.ok && ws.workspace\n ? pc.green(ws.workspace.name)\n : pc.red(`unreachable${ws.error ? `: ${ws.error}` : \"\"}`);\n console.log(` ${icon} ${label} ${state}`);\n }\n\n // OpenClaw\n const openclaw = report.openclaw;\n {\n const icon = openclaw.skipped ? ICON.skip : openclaw.ok ? ICON.ok : ICON.err;\n const label = pc.dim(\"openclaw \".padEnd(14));\n const state = openclaw.skipped\n ? pc.dim(\"not installed\")\n : openclaw.ok\n ? pc.green(`healthy${openclaw.method && openclaw.method !== \"none\" ? ` (${openclaw.method})` : \"\"}`)\n : pc.red(`unhealthy${openclaw.error ? `: ${openclaw.error}` : \"\"}`);\n console.log(` ${icon} ${label} ${state}`);\n }\n\n // — Summary —\n console.log(\"\");\n const configuredCount = report.surfaces.filter((s) => s.configured).length;\n if (assessment.issues.length === 0) {\n console.log(` ${ICON.ok} ${pc.green(\"All systems ready.\")}`);\n if (!report.auth.configured) {\n console.log(`\\n ${pc.dim(\"→\")} ${pc.cyan(`${getCmd()} auth login`)} ${pc.dim(\"to connect your account\")}`);\n } else {\n console.log(` ${pc.dim(\"→\")} ${pc.dim(`OrgX is active across ${configuredCount} editor${configuredCount !== 1 ? \"s\" : \"\"}`)}`);\n }\n } else {\n const headlineText = getSetupVerificationHeadline(verification);\n const headline = verification.status === \"error\"\n ? `${ICON.err} ${pc.red(headlineText)}`\n : `${ICON.warn} ${pc.yellow(headlineText)}`;\n console.log(` ${headline}`);\n for (const issue of assessment.issues) {\n const degradedHostedMcpIssue =\n verification.hostedMcpDegraded && issue.title === HOSTED_MCP_OUTAGE_TITLE;\n const label = degradedHostedMcpIssue\n ? pc.yellow(\"degr \")\n : issue.level === \"error\"\n ? pc.red(\"error\")\n : pc.yellow(\"warn \");\n console.log(`\\n ${label} ${issue.title}`);\n console.log(` ${pc.dim(\"→\")} ${issue.suggestion}`);\n }\n }\n}\n\nasync function main(): Promise<void> {\n const program = new Command();\n program\n .name(\"orgx-wizard\")\n .description(\"Add OrgX MCP configs, skills/rules, and companion plugins to your local AI tools.\")\n .showHelpAfterError();\n\n const pkgVersion = typeof __PKG_VERSION__ !== \"undefined\" ? __PKG_VERSION__ : undefined;\n program.version(pkgVersion ?? \"unknown\", \"-V, --version\");\n\n program.hook(\"preAction\", (_thisCommand, actionCommand) => {\n if (Boolean(actionCommand.optsWithGlobals().json)) return;\n console.log(renderBanner(pkgVersion));\n });\n\n program\n .command(\"setup\")\n .description(\"Add OrgX MCP configs, skills/rules, and companion plugins to detected tools.\")\n .option(\"--preset <name>\", \"run a setup bundle (currently: founder)\")\n .option(\"--workspace\", \"choose or change the default workspace during setup\")\n .option(\"--daily-brief\", \"configure Daily Brief even if setup already handled it\")\n .option(\"--skip-daily-brief\", \"skip Daily Brief prompts and remember the skip\")\n .action(async (options: {\n dailyBrief?: boolean;\n preset?: string;\n skipDailyBrief?: boolean;\n workspace?: boolean;\n }) => {\n const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);\n if (options.dailyBrief && options.skipDailyBrief) {\n throw new Error(\"Use either --daily-brief or --skip-daily-brief, not both.\");\n }\n await safeTrackWizardTelemetry(\"wizard_started\", {\n command: \"setup\",\n interactive,\n preset: options.preset ?? \"standard\",\n });\n printSetupScopeNote();\n console.log(\"\");\n\n if (options.preset) {\n if (options.preset !== \"founder\") {\n throw new Error(`Unknown setup preset '${options.preset}'. Supported presets: founder.`);\n }\n\n const founderPluginTargets = await promptOptionalCompanionPluginTargets({\n interactive,\n });\n if (founderPluginTargets === \"cancelled\") {\n return;\n }\n\n const spinner = createOrgxSpinner(\"Running founder setup preset\");\n spinner.start();\n const presetResult = await runFounderPreset(\n {\n cancel: clack.cancel,\n isCancel: clack.isCancel,\n select: selectPrompt,\n text: textPrompt,\n },\n {\n interactive,\n pluginTargets: founderPluginTargets,\n },\n );\n\n if (\"status\" in presetResult) {\n spinner.stop();\n if (presetResult.status === \"cancelled\") {\n return;\n }\n printWorkspaceSetupResult(presetResult);\n return;\n }\n\n spinner.succeed(\"Founder setup preset complete\");\n printFounderPresetResult(presetResult);\n await safeTrackWizardTelemetry(\"mcp_injected\", {\n changed_count: presetResult.surfaceResults.filter((result) => result.changed).length,\n preset: \"founder\",\n surface_count: presetResult.surfaceResults.length,\n });\n await safeTrackWizardTelemetry(\"skills_installed\", {\n changed_count: countSkillReportChanges(presetResult.skillReport),\n pack_count: presetResult.skillReport.packs.length,\n preset: \"founder\",\n write_count: presetResult.skillReport.writes.length,\n });\n if (presetResult.workspaceSetup) {\n await safeTrackWizardTelemetry(\n \"workspace_bootstrapped\",\n buildWorkspaceSetupTelemetryProperties(presetResult.workspaceSetup, {\n command: \"setup\",\n interactive,\n preset: \"founder\",\n }),\n );\n }\n if (presetResult.demoInitiative) {\n await safeTrackWizardTelemetry(\n \"founder_demo_ready\",\n buildFounderDemoTelemetryProperties(presetResult.demoInitiative, {\n command: \"setup\",\n preset: \"founder\",\n }),\n );\n }\n\n const addOnResult = await maybeConfigureOptionalWorkspaceAddOns({\n interactive,\n telemetry: { command: \"setup\", preset: \"founder\" },\n workspace: presetResult.workspace,\n ...(presetResult.demoInitiative\n ? { initiativeId: presetResult.demoInitiative.initiative.id }\n : {}),\n });\n if (addOnResult === \"cancelled\") {\n return;\n }\n\n await installSelectedCompanionPlugins({\n telemetry: { command: \"setup\", preset: \"founder\" },\n targets: founderPluginTargets,\n });\n\n console.log(\"\");\n const doctor = await runDoctor();\n const assessment = assessDoctorReport(doctor);\n const verification = summarizeSetupVerification(assessment);\n await safeTrackWizardTelemetry(\n \"setup_verified\",\n buildDoctorTelemetryProperties(doctor, assessment, verification, {\n command: \"setup\",\n preset: \"founder\",\n }),\n );\n printDoctorReport(doctor, assessment);\n if (verification.status === \"error\") {\n process.exitCode = 1;\n }\n return;\n }\n\n const spinner = createOrgxSpinner(\"Configuring detected OrgX surfaces\");\n spinner.start();\n const results = await setupDetectedSurfaces();\n spinner.succeed(\"Detected surfaces configured\");\n printSurfaceSummary(results);\n const pluginStatuses = await checkPluginStatusesCompact();\n await safeTrackWizardTelemetry(\"mcp_injected\", {\n changed_count: results.filter((result) => result.changed).length,\n preset: \"standard\",\n surface_count: results.length,\n });\n\n const wasAlreadyPaired = (await resolveOrgxAuth()) !== null;\n let resolvedAuth = await resolveOrgxAuth();\n if (!resolvedAuth) {\n console.log(\"\");\n if (interactive) {\n const choice = await selectPrompt({\n message: \"Pair this terminal with your OrgX account to finish setup\",\n options: [\n { value: \"login\", label: \"Open browser to pair\", hint: \"recommended\" },\n { value: \"skip\", label: \"Skip for now\", hint: `run \\`${getCmd()} auth login\\` later` },\n ],\n });\n if (clack.isCancel(choice)) {\n clack.cancel(\"Setup cancelled.\");\n return;\n }\n if (choice === \"login\") {\n const loginOk = await runBrowserLogin({ telemetrySource: \"browser_pairing\" });\n if (!loginOk) {\n // Pairing failed — show clean next steps, don't dump the full doctor\n console.log(`\\n ${pc.dim(\"→\")} ${pc.cyan(`${getCmd()} auth login`)} ${pc.dim(\"to start a fresh browser pairing\")}`);\n console.log(` ${pc.dim(\"→\")} ${pc.cyan(`${getCmd()} auth login --api-key`)} ${pc.dim(\"to paste a key directly\")}`);\n return;\n }\n resolvedAuth = await resolveOrgxAuth();\n } else {\n // User skipped\n console.log(`\\n ${pc.dim(\"→\")} ${pc.cyan(`${getCmd()} auth login`)} ${pc.dim(\"to pair when ready\")}`);\n return;\n }\n } else {\n console.log(\n ` ${ICON.warn} ${pc.yellow(\"Terminal not paired.\")} Run ${pc.cyan(`${getCmd()} auth login`)} to pair it.`,\n );\n return;\n }\n }\n\n if (resolvedAuth) {\n console.log(\"\");\n const workspaceSetup = await runWorkspaceSetup(\n {\n createWorkspace,\n getCurrentWorkspace,\n listWorkspaces,\n setDefaultWorkspace,\n },\n {\n cancel: clack.cancel,\n isCancel: clack.isCancel,\n select: selectPrompt,\n text: textPrompt,\n },\n {\n interactive,\n skipIfConfigured: !options.workspace,\n },\n );\n if (workspaceSetup.status === \"cancelled\") {\n return;\n }\n if (workspaceSetup.status === \"reauth_requested\") {\n console.log(\"\");\n console.log(\n ` ${ICON.warn} ${pc.yellow(\"workspace\")} ${pc.dim(\"API key authenticated but returned 0 workspaces — likely an identity mismatch.\")}`,\n );\n console.log(` ${pc.cyan(`${getCmd()} auth login`)} ${pc.dim(\"→ re-link via OAuth, then rerun\")} ${pc.cyan(`${getCmd()} setup`)}`);\n await safeTrackWizardTelemetry(\n \"workspace_bootstrapped\",\n buildWorkspaceSetupTelemetryProperties(workspaceSetup, {\n command: \"setup\",\n interactive,\n preset: \"standard\",\n }),\n );\n return;\n }\n await safeTrackWizardTelemetry(\n \"workspace_bootstrapped\",\n buildWorkspaceSetupTelemetryProperties(workspaceSetup, {\n command: \"setup\",\n interactive,\n preset: \"standard\",\n }),\n );\n const resolvedWorkspace = workspaceSetup.workspace ?? await getCurrentWorkspace().catch(() => null);\n if (resolvedWorkspace) {\n persistContinuityDefaults({ workspace: resolvedWorkspace });\n }\n if (workspaceSetup.workspace) {\n console.log(` ${ICON.ok} ${pc.green(\"workspace \")} ${pc.bold(workspaceSetup.workspace.name)}`);\n }\n\n // Daily Brief + Trust Loop onboarding. Idempotent locally and\n // server-side: repeat setup runs do not re-ask unless --daily-brief is\n // passed.\n const briefResult = await runDailyBriefOnboarding({\n force: Boolean(options.dailyBrief),\n interactive,\n skip: Boolean(options.skipDailyBrief),\n workspace: resolvedWorkspace,\n prompts: {\n cancel: clack.cancel,\n isCancel: clack.isCancel,\n text: textPrompt,\n select: selectPrompt,\n confirm: clack.confirm,\n },\n });\n if (briefResult.status === \"cancelled\") {\n console.log(` ${ICON.skip} ${pc.dim(briefResult.message)}`);\n } else if (briefResult.status === \"skipped_user\") {\n console.log(` ${ICON.skip} ${pc.dim(briefResult.message)}`);\n } else if (briefResult.status === \"completed\") {\n console.log(` ${ICON.ok} ${pc.green(\"daily brief\")} ${pc.dim(briefResult.message)}`);\n } else if (briefResult.status === \"failed\") {\n console.log(` ${ICON.warn} ${pc.yellow(\"daily brief\")} ${pc.dim(briefResult.message)}`);\n }\n\n // Intent capture — the orgx canonical entry point. One free-text line\n // gets classified into an agent + plan (ICP draft, first-wave, etc).\n // The agent sources people from the ICP downstream; we do not ask the\n // user to type contacts by hand.\n const intentResult = await maybeCaptureSetupIntent({\n interactive,\n workspace: resolvedWorkspace,\n });\n if (intentResult === \"cancelled\") {\n return;\n }\n\n const addOnResult = await maybeConfigureOptionalWorkspaceAddOns({\n interactive,\n telemetry: { command: \"setup\", preset: \"standard\" },\n workspace: resolvedWorkspace,\n });\n if (addOnResult === \"cancelled\") {\n return;\n }\n\n const pluginInstallResult = await maybeInstallOptionalCompanionPlugins({\n interactive,\n statuses: pluginStatuses,\n telemetry: { command: \"setup\", preset: \"standard\" },\n });\n if (pluginInstallResult === \"cancelled\") {\n return;\n }\n }\n\n // Compact final status — surfaces already shown above, just give the bottom line\n const doctor = await runDoctor();\n const assessment = assessDoctorReport(doctor);\n const verification = summarizeSetupVerification(assessment);\n await safeTrackWizardTelemetry(\n \"setup_verified\",\n buildDoctorTelemetryProperties(doctor, assessment, verification, {\n command: \"setup\",\n preset: \"standard\",\n }),\n );\n const configuredCount = doctor.surfaces.filter((s) => s.configured).length;\n console.log(\"\");\n if (assessment.issues.length === 0) {\n console.log(` ${ICON.ok} ${pc.green(\"You're all set.\")} ${pc.dim(`OrgX is active across ${configuredCount} editor${configuredCount !== 1 ? \"s\" : \"\"}`)}`);\n if (wasAlreadyPaired) {\n console.log(\n ` ${pc.dim(\"→\")} ${pc.dim(\"If you opened the browser onboarding, click\")} ${pc.cyan(\"I've already paired\")} ${pc.dim(\"to continue.\")}`,\n );\n }\n } else {\n // Something needs attention — show full report\n printDoctorReport(doctor, assessment);\n if (verification.status === \"error\") {\n process.exitCode = 1;\n }\n }\n });\n\n async function runPkceLogin(opts: {\n open?: boolean;\n telemetrySource?: string;\n timeout?: number;\n } = {}): Promise<boolean> {\n const spinner = createOrgxSpinner(\"Starting OrgX OAuth login\");\n spinner.start();\n\n try {\n const pkceResult = await startPkceLogin({\n timeoutMs: (opts.timeout ?? 600) * 1_000,\n onAuthorizeUrl: (url) => {\n spinner.succeed(\"Authorization ready\");\n console.log(`\\n ${pc.dim(\"Open this URL to authorize:\")}`);\n console.log(` ${pc.cyan(url)}\\n`);\n if (opts.open !== false) {\n const openResult = openBrowser(url);\n if (!openResult.ok && openResult.error) {\n console.log(pc.yellow(`Browser open failed: ${openResult.error}`));\n }\n }\n spinner.start();\n spinner.text = \"Waiting for browser authorization...\";\n },\n });\n\n spinner.text = \"Verifying token...\";\n const baseUrl = normalizeOrgxBaseUrl(DEFAULT_ORGX_BASE_URL);\n const verification = await verifyOrgxAuth({\n apiKey: pkceResult.accessToken,\n keyPrefix: pkceResult.accessToken.slice(0, 12),\n baseUrl,\n source: \"wizard-store\",\n });\n\n if (!verification.ok) {\n spinner.fail(\"OAuth token verification failed\");\n console.log(` ${pc.red(verification.error ?? `HTTP ${verification.status ?? \"error\"}`)}`);\n console.log(` ${pc.dim(\"If this persists, try: wizard auth set-key <oxk_...>\")}`);\n return false;\n }\n\n const stored = await writeWizardAuth({\n apiKey: pkceResult.accessToken,\n baseUrl,\n verifiedAt: new Date().toISOString(),\n source: \"pkce\",\n ...(pkceResult.refreshToken !== undefined ? { refreshToken: pkceResult.refreshToken } : {}),\n oauthClientId: pkceResult.clientId,\n });\n\n await safeTrackWizardTelemetry(\"auth_completed\", {\n auth_source: opts.telemetrySource ?? \"pkce\",\n has_base_url: false,\n });\n\n const openclawResults = detectSurface(\"openclaw\").detected\n ? await addSurface(\"openclaw\")\n : [];\n\n spinner.succeed(\"OrgX account paired\");\n await syncContinuityAfterAuth();\n console.log(` ${ICON.ok} ${pc.green(\"paired \")} ${pc.bold(stored.keyPrefix)} ${pc.dim(\"browser sign-in\")}`);\n\n if (openclawResults.length > 0) {\n console.log(\"\");\n printMutationResults(openclawResults);\n }\n\n return true;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n spinner.fail(\"OAuth login failed\");\n console.log(` ${pc.red(message)}`);\n return false;\n }\n }\n\n function shortPairingId(pairingId: string): string {\n return pairingId.length > 13\n ? `${pairingId.slice(0, 8)}...${pairingId.slice(-4)}`\n : pairingId;\n }\n\n function formatPairingExpiry(expiresAt: string): string {\n const remainingMs = Date.parse(expiresAt) - Date.now();\n if (!Number.isFinite(remainingMs) || remainingMs <= 0) return \"expired\";\n const minutes = Math.ceil(remainingMs / 60_000);\n return minutes <= 1 ? \"<1m\" : `${minutes}m`;\n }\n\n async function runBrowserLogin(opts: {\n baseUrl?: string;\n deviceName?: string;\n open?: boolean;\n telemetrySource?: string;\n timeout?: number;\n } = {}): Promise<boolean> {\n const installationId = getOrCreateWizardInstallationId();\n const deviceName = opts.deviceName ?? hostname();\n const spinner = createOrgxSpinner(\"Starting OrgX browser pairing\");\n spinner.start();\n\n try {\n const pairing = await startBrowserPairing({\n installationId,\n baseUrl: opts.baseUrl,\n deviceName,\n platform: process.platform,\n });\n spinner.succeed(\"Browser pairing ready\");\n\n console.log(`\\n ${pc.dim(\"Open this URL to approve terminal pairing:\")}`);\n console.log(` ${pc.cyan(pairing.connectUrl)}\\n`);\n console.log(\n ` ${pc.dim(\"session \")} ${pc.bold(shortPairingId(pairing.pairingId))} ${pc.dim(\"device\")} ${pc.bold(deviceName)} ${pc.dim(\"expires\")} ${pc.bold(formatPairingExpiry(pairing.expiresAt))}\\n`\n );\n if (opts.open !== false) {\n const openResult = openBrowser(pairing.connectUrl);\n if (!openResult.ok && openResult.error) {\n console.log(pc.yellow(`Browser open failed: ${openResult.error}`));\n }\n }\n\n spinner.start();\n spinner.text = \"Waiting for browser approval...\";\n const ready = await waitForBrowserPairing({\n baseUrl: opts.baseUrl,\n pairingId: pairing.pairingId,\n pollIntervalMs: pairing.pollIntervalMs,\n pollToken: pairing.pollToken,\n timeoutMs: (opts.timeout ?? 600) * 1000,\n });\n\n spinner.text = \"Verifying paired account...\";\n const result = await verifyAndPersistAuth(ready.key!, {\n ...(opts.baseUrl !== undefined ? { baseUrl: opts.baseUrl } : {}),\n ...(opts.telemetrySource ? { telemetrySource: opts.telemetrySource } : {}),\n });\n\n if (!(\"stored\" in result)) {\n spinner.fail(\"Pairing completed but OrgX rejected the key\");\n console.log(` ${pc.red(result.verification.error ?? `HTTP ${result.verification.status ?? \"error\"}`)}`);\n console.log(` ${pc.dim(\"The browser flow finished, but OrgX rejected the key. Try again or check your account at useorgx.com.\")}`);\n return false;\n }\n\n let ackConfirmed = false;\n try {\n await acknowledgeBrowserPairing({\n baseUrl: opts.baseUrl,\n pairingId: pairing.pairingId,\n pollToken: pairing.pollToken,\n });\n ackConfirmed = true;\n } catch (error: unknown) {\n console.log(pc.dim(`Pairing ack failed: ${error instanceof Error ? error.message : String(error)}`));\n }\n\n spinner.succeed(\"OrgX account paired\");\n await syncContinuityAfterAuth({\n executionMode: ready.executionMode,\n workspaceName: ready.workspaceName,\n });\n\n console.log(` ${ICON.ok} ${pc.green(\"paired \")} ${pc.bold(result.stored.keyPrefix ?? result.verification.keyPrefix ?? \"unknown\")} ${pc.dim(\"wizard auth store\")}`);\n if (ready.workspaceName) {\n console.log(` ${ICON.ok} ${pc.green(\"workspace \")} ${pc.bold(ready.workspaceName)}`);\n }\n console.log(` ${ackConfirmed ? ICON.ok : ICON.warn} ${ackConfirmed ? pc.green(\"ack \") : pc.yellow(\"ack \")} ${pc.bold(ackConfirmed ? \"terminal confirmed\" : \"browser delivery pending\")} ${pc.dim(shortPairingId(pairing.pairingId))}`);\n\n if (result.openclawResults.length > 0) {\n console.log(\"\");\n printMutationResults(result.openclawResults);\n }\n\n return true;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n spinner.fail(\"Browser pairing failed\");\n console.log(` ${pc.red(message)}`);\n return false;\n }\n }\n\n const auth = program.command(\"auth\").description(\"Pair this terminal with an OrgX account.\");\n\n auth\n .command(\"status\")\n .description(\"Show which OrgX account this terminal is paired with.\")\n .action(async () => {\n const spinner = createOrgxSpinner(\"Checking OrgX auth\");\n spinner.start();\n const status = await checkOrgxAuth();\n spinner.stop();\n console.log(pc.dim(\" account\"));\n printAuthStatus(status);\n });\n\n auth\n .command(\"login\")\n .description(\"Open the browser pairing flow and store a scoped OrgX key for this terminal.\")\n .option(\"--api-key <key>\", \"Bypass browser auth and verify this OrgX API key directly.\")\n .option(\"--base-url <url>\", \"OrgX base URL (for OpenClaw pairing fallback).\")\n .option(\"--device-name <name>\", \"Device name shown during OpenClaw pairing.\")\n .option(\"--no-open\", \"Do not automatically open the browser auth URL.\")\n .option(\"--pairing\", \"Force the terminal pairing fallback instead of browser sign-in.\")\n .option(\"--timeout <seconds>\", \"How long to wait for browser auth before giving up.\", parseTimeoutSeconds, 600)\n .action(async (options: { apiKey?: string; baseUrl?: string; deviceName?: string; open?: boolean; pairing?: boolean; timeout: number }) => {\n // Direct key path — CI / blocked browser fallback\n if (options.apiKey) {\n const spinner = createOrgxSpinner(\"Verifying OrgX API key\");\n spinner.start();\n const result = await verifyAndPersistAuth(options.apiKey, {\n ...options,\n telemetrySource: \"manual_api_key\",\n });\n\n if (!(\"stored\" in result)) {\n spinner.fail(\"OrgX API key verification failed\");\n printAuthStatus(result.verification);\n return;\n }\n\n spinner.succeed(\"OrgX account paired\");\n await syncContinuityAfterAuth();\n console.log(` ${ICON.ok} ${pc.green(\"paired \")} ${pc.bold(result.stored.keyPrefix ?? result.verification.keyPrefix ?? \"unknown\")} ${pc.dim(\"wizard auth store\")}`);\n\n if (result.openclawResults.length > 0) {\n console.log(\"\");\n printMutationResults(result.openclawResults);\n }\n return;\n }\n\n // Force OpenClaw pairing when explicitly requested\n if (options.pairing) {\n await runBrowserLogin({\n ...(options.baseUrl !== undefined ? { baseUrl: options.baseUrl } : {}),\n ...(options.deviceName !== undefined ? { deviceName: options.deviceName } : {}),\n ...(options.open !== undefined ? { open: options.open } : {}),\n telemetrySource: \"browser_pairing\",\n timeout: options.timeout,\n });\n return;\n }\n\n // Default: OAuth PKCE (works without OpenClaw), fall back to OpenClaw pairing\n const pkceOk = await runPkceLogin({\n ...(options.open !== undefined ? { open: options.open } : {}),\n telemetrySource: \"pkce\",\n timeout: options.timeout,\n });\n\n if (!pkceOk) {\n console.log(pc.dim(\"\\n Browser sign-in did not finish. Opening the terminal pairing fallback...\"));\n await runBrowserLogin({\n ...(options.baseUrl !== undefined ? { baseUrl: options.baseUrl } : {}),\n ...(options.deviceName !== undefined ? { deviceName: options.deviceName } : {}),\n ...(options.open !== undefined ? { open: options.open } : {}),\n telemetrySource: \"browser_pairing_fallback\",\n timeout: options.timeout,\n });\n }\n });\n\n auth\n .command(\"set-key\")\n .description(\"Verify and persist a per-user OrgX API key for the wizard.\")\n .argument(\"<apiKey>\", \"per-user OrgX API key (oxk_...)\")\n .option(\"--base-url <url>\", \"OrgX base URL\")\n .action(async (apiKey: string, options: { baseUrl?: string }) => {\n const spinner = createOrgxSpinner(\"Verifying OrgX API key\");\n spinner.start();\n const result = await verifyAndPersistAuth(apiKey, {\n ...options,\n telemetrySource: \"manual_api_key\",\n });\n\n if (!(\"stored\" in result)) {\n spinner.fail(\"OrgX API key verification failed\");\n printAuthStatus(result.verification);\n return;\n }\n\n spinner.succeed(\"OrgX account paired\");\n await syncContinuityAfterAuth();\n console.log(` ${ICON.ok} ${pc.green(\"paired \")} ${pc.bold(result.stored.keyPrefix ?? result.verification.keyPrefix ?? \"unknown\")} ${pc.dim(\"wizard auth store\")}`);\n\n if (result.openclawResults.length > 0) {\n console.log(\"\");\n printMutationResults(result.openclawResults);\n }\n });\n\n auth\n .command(\"clear\")\n .description(\"Remove the wizard-local saved OrgX API key.\")\n .action(async () => {\n const removed = await clearWizardAuth();\n if (removed) {\n console.log(pc.green(\"Removed the wizard-local OrgX API key.\"));\n } else {\n console.log(pc.yellow(\"No wizard-local OrgX API key was stored.\"));\n }\n\n const resolved = await resolveOrgxAuth();\n if (resolved) {\n console.log(\n `Effective OrgX auth still resolves from ${formatAuthSource(resolved.source)} (${resolved.keyPrefix}).`,\n );\n }\n });\n\n program\n .command(\"uninstall\")\n .description(\"Remove OrgX-managed MCP tool configs, companion plugins, auth, and wizard state from this machine.\")\n .option(\"--keep-auth\", \"Keep the wizard-local saved OrgX API key.\")\n .option(\"--keep-state\", \"Keep wizard-local setup state.\")\n .option(\"--skip-plugins\", \"Skip companion plugin and legacy Cursor rules removal.\")\n .option(\"--skip-surfaces\", \"Skip MCP tool config removal.\")\n .action(async (options: {\n keepAuth?: boolean;\n keepState?: boolean;\n skipPlugins?: boolean;\n skipSurfaces?: boolean;\n }) => {\n await safeTrackWizardTelemetry(\"wizard_uninstalled\", {\n keep_auth: Boolean(options.keepAuth),\n keep_state: Boolean(options.keepState),\n skip_plugins: Boolean(options.skipPlugins),\n skip_surfaces: Boolean(options.skipSurfaces),\n });\n\n console.log(pc.bold(\"Removing OrgX wizard-managed configuration\"));\n\n if (options.skipSurfaces) {\n console.log(` ${ICON.skip} ${pc.bold(\"surfaces\".padEnd(10))} ${pc.dim(\"skipped\")}`);\n } else {\n console.log(\"\");\n console.log(pc.dim(\" surfaces\"));\n const surfaceResults = removeSurface([\"all\"]);\n printMutationResults(surfaceResults);\n }\n\n if (options.skipPlugins) {\n console.log(` ${ICON.skip} ${pc.bold(\"plugins\".padEnd(12))} ${pc.dim(\"skipped\")}`);\n } else {\n console.log(\"\");\n console.log(pc.dim(\" plugins\"));\n const spinner = createOrgxSpinner(\"Removing OrgX companion plugins and legacy Cursor rules\");\n spinner.start();\n const pluginReport = await uninstallOrgxPlugins({ targets: [\"all\"] });\n spinner.succeed(\"OrgX companion plugins and legacy Cursor rules processed\");\n printPluginMutationReport(pluginReport);\n }\n\n console.log(\"\");\n if (options.keepAuth) {\n console.log(` ${ICON.skip} ${pc.bold(\"auth\".padEnd(12))} ${pc.dim(\"kept\")}`);\n } else {\n const removedAuth = await clearWizardAuth();\n const state = removedAuth ? pc.green(\"updated \") : pc.dim(\"unchanged\");\n const message = removedAuth\n ? \"Removed the wizard-local OrgX API key.\"\n : \"No wizard-local OrgX API key was stored.\";\n console.log(` ${removedAuth ? ICON.ok : ICON.skip} ${pc.bold(\"auth\".padEnd(12))} ${state} ${pc.dim(message)}`);\n }\n\n if (options.keepState) {\n console.log(` ${ICON.skip} ${pc.bold(\"state\".padEnd(12))} ${pc.dim(\"kept\")}`);\n } else {\n const removedState = clearWizardState();\n const state = removedState ? pc.green(\"updated \") : pc.dim(\"unchanged\");\n const message = removedState\n ? \"Removed wizard-local setup state.\"\n : \"No wizard-local setup state was stored.\";\n console.log(` ${removedState ? ICON.ok : ICON.skip} ${pc.bold(\"state\".padEnd(12))} ${state} ${pc.dim(message)}`);\n }\n });\n\n const surface = program.command(\"surface\").description(\"Manage supported OrgX surfaces.\");\n\n surface\n .command(\"list\")\n .description(\"Show supported surfaces and their current status.\")\n .action(() => {\n printSurfaceTable(listSurfaceStatuses());\n });\n\n surface\n .command(\"add\")\n .description(\"Patch one surface or all automated surfaces.\")\n .argument(\"<names...>\", \"surface names or 'all'\")\n .action(async (names: string[]) => {\n const results = await addSurface(names as Parameters<typeof addSurface>[0]);\n printMutationResults(results);\n });\n\n surface\n .command(\"remove\")\n .description(\"Remove OrgX-managed config from one surface or all automated surfaces.\")\n .argument(\"<names...>\", \"surface names or 'all'\")\n .action((names: string[]) => {\n const results = removeSurface(names as Parameters<typeof removeSurface>[0]);\n printMutationResults(results);\n });\n\n const mcp = program\n .command(\"mcp\")\n .description(\"Add or remove OrgX MCP config entries in Claude, Cursor, Codex, VS Code, Windsurf, and Zed.\");\n\n mcp\n .command(\"add\")\n .description(\"Add OrgX MCP entries to one tool config or all supported MCP tool configs.\")\n .argument(\"[surfaces...]\", \"claude, cursor, codex, vscode, windsurf, zed, or all\", [\"all\"])\n .action(async (names: string[]) => {\n const results = await addMcpSurface(names as Parameters<typeof addMcpSurface>[0]);\n printMutationResults(results);\n });\n\n mcp\n .command(\"remove\")\n .description(\"Remove OrgX MCP entries from one tool config or all supported MCP tool configs.\")\n .argument(\"[surfaces...]\", \"claude, cursor, codex, vscode, windsurf, zed, or all\", [\"all\"])\n .action((names: string[]) => {\n const results = removeMcpSurface(names as Parameters<typeof removeMcpSurface>[0]);\n printMutationResults(results);\n });\n\n const plugins = program\n .command(\"plugins\")\n .description(\"Install or remove OrgX companion plugins in Cursor, Claude Code, Codex, and OpenClaw.\");\n\n plugins\n .command(\"list\")\n .description(\"Show companion plugin availability and install status in your tools.\")\n .action(async () => {\n const spinner = createOrgxSpinner(\"Checking OrgX companion plugin status\");\n spinner.start();\n const statuses = await listOrgxPluginStatuses();\n spinner.succeed(\"OrgX companion plugin status checked\");\n printPluginStatusReport(statuses);\n });\n\n plugins\n .command(\"add\")\n .description(\"Install OrgX companion plugins into Cursor, Claude Code, Codex, and OpenClaw.\")\n .argument(\"[targets...]\", \"cursor, claude, codex, openclaw, or all\", [\"all\"])\n .action(async (targets: string[]) => {\n const spinner = createOrgxSpinner(\"Installing OrgX companion plugins\");\n spinner.start();\n const report = await installOrgxPlugins({ targets });\n spinner.succeed(\"OrgX companion plugins processed\");\n printPluginMutationReport(report);\n printPluginSkillOwnershipNote(report.results.map((result) => result.target));\n await safeTrackWizardTelemetry(\"plugins_installed\", {\n changed_count: countPluginReportChanges(report),\n command: \"plugins:add\",\n requested_target_count: targets.length,\n target_count: report.results.length,\n });\n });\n\n plugins\n .command(\"remove\")\n .description(\"Uninstall managed OrgX companion plugins and legacy managed Cursor rules from Cursor, Claude Code, Codex, and OpenClaw.\")\n .argument(\"[targets...]\", \"cursor, claude, codex, openclaw, or all\", [\"all\"])\n .action(async (targets: string[]) => {\n const spinner = createOrgxSpinner(\"Removing OrgX companion plugins and legacy Cursor rules\");\n spinner.start();\n const report = await uninstallOrgxPlugins({ targets });\n spinner.succeed(\"OrgX companion plugins and legacy Cursor rules processed\");\n printPluginMutationReport(report);\n await safeTrackWizardTelemetry(\"plugins_removed\", {\n changed_count: countPluginReportChanges(report),\n command: \"plugins:remove\",\n requested_target_count: targets.length,\n target_count: report.results.length,\n });\n });\n\n const workspace = program\n .command(\"workspace\")\n .description(\"Inspect and create OrgX workspaces.\");\n\n workspace\n .command(\"current\")\n .description(\"Show the current OrgX workspace.\")\n .action(async () => {\n const spinner = createOrgxSpinner(\"Loading current OrgX workspace\");\n spinner.start();\n const current = await getCurrentWorkspace();\n spinner.stop();\n\n if (!current) {\n console.log(pc.yellow(\"No OrgX workspaces found for the current user.\"));\n return;\n }\n\n printWorkspace(current);\n });\n\n workspace\n .command(\"list\")\n .description(\"List OrgX workspaces accessible with the current API key.\")\n .action(async () => {\n const spinner = createOrgxSpinner(\"Loading OrgX workspaces\");\n spinner.start();\n const workspaces = await listWorkspaces();\n spinner.stop();\n printWorkspaceList(workspaces);\n });\n\n workspace\n .command(\"create\")\n .description(\"Create a new OrgX workspace.\")\n .argument(\"<name>\", \"workspace name\")\n .option(\"--description <text>\", \"workspace description\")\n .action(async (name: string, options: { description?: string }) => {\n const spinner = createOrgxSpinner(\"Creating OrgX workspace\");\n spinner.start();\n const created = await createWorkspace(\n {\n name,\n ...(options.description ? { description: options.description } : {}),\n },\n );\n spinner.succeed(\"OrgX workspace created\");\n if (created.isDefault) {\n persistContinuityDefaults({ workspace: created });\n }\n printWorkspace(created);\n if (!created.isDefault) {\n console.log(\"\");\n console.log(pc.dim(`Run \\`wizard workspace set-default ${created.id}\\` to promote it.`));\n }\n });\n\n workspace\n .command(\"set-default\")\n .description(\"Set the default OrgX workspace.\")\n .argument(\"<id>\", \"workspace id\")\n .action(async (id: string) => {\n const spinner = createOrgxSpinner(\"Updating default OrgX workspace\");\n spinner.start();\n const result = await setDefaultWorkspace({ id });\n spinner.succeed(\n result.changed ? \"Default OrgX workspace updated\" : \"OrgX workspace already set as default\",\n );\n persistContinuityDefaults({ workspace: result.workspace });\n printWorkspace(result.workspace);\n });\n\n program\n .command(\"intent\")\n .description(\n \"Capture an intent, preview the classified agent + plan, and approve or hand off to the browser.\",\n )\n .argument(\"[text...]\", \"intent text (quotes optional)\")\n .option(\"--workspace <id>\", \"workspace id override; defaults to the current workspace\")\n .option(\"--json\", \"emit a JSON summary instead of the box-drawn preview\")\n .action(async (textParts: string[], options: { workspace?: string; json?: boolean }) => {\n const initialText = textParts.join(\" \").trim();\n const workspaceId = options.workspace?.trim() ?? \"\";\n await runIntentCommand({\n ...(initialText ? { initialText } : {}),\n ...(workspaceId ? { workspaceId } : {}),\n jsonOutput: Boolean(options.json),\n });\n });\n\n program\n .command(\"audit\")\n .description(\"Run the AI-native Founder Loop self-audit from pasted or file-based AI-session context.\")\n .option(\"--input <path>\", \"AI-session transcript or summary file; stdin is used when piped\")\n .option(\"--from <sources>\", \"auto-import recent local AI sessions: codex, claude, or all\")\n .option(\"--session-limit <count>\", \"max recent sessions to import per selected source\", \"3\")\n .option(\"--session-days <days>\", \"lookback window for local AI-session imports\", \"30\")\n .option(\"--codex-sessions-dir <path>\", \"override Codex sessions directory for audit import\")\n .option(\"--claude-projects-dir <path>\", \"override Claude projects directory for audit import\")\n .option(\"--source-label <label>\", \"label for the imported AI-session source\")\n .option(\"--workspace-id <id>\", \"workspace id override; defaults to the current OrgX workspace when authenticated\")\n .option(\"--workspace-name <name>\", \"workspace name override for local-only audits\")\n .option(\"--output-dir <path>\", \"directory for generated audit JSON and Markdown\", \".orgx/audits\")\n .option(\"--attach-to-initiative <id>\", \"attach the generated audit artifact to an existing OrgX initiative\")\n .option(\"--create-initiative\", \"create an OrgX initiative from the generated audit plan\")\n .option(\"--write-follow-up\", \"create one approval-gated OrgX follow-up task from the audit recommendation\")\n .option(\"--workstream-id <id>\", \"optional workstream id for the generated follow-up task\")\n .option(\"--milestone-id <id>\", \"optional milestone id for the generated follow-up task\")\n .option(\"--dry-run\", \"exercise OrgX write paths without sending writes\")\n .option(\"--yes\", \"approve OrgX write flags in non-interactive mode\")\n .option(\"--json\", \"emit a JSON command summary\")\n .action(async (options: AuditCommandOptions) => {\n await safeTrackWizardTelemetry(\"audit_started\", {\n attach_to_initiative: Boolean(options.attachToInitiative),\n command: \"audit\",\n create_initiative: Boolean(options.createInitiative),\n dry_run: Boolean(options.dryRun),\n write_follow_up: Boolean(options.writeFollowUp),\n });\n await runAuditCommand(options);\n });\n\n const workGraph = program\n .command(\"work-graph\")\n .description(\"Build a redacted OrgX Work Graph report from AI-client, Slack, MCP, or manual context.\");\n\n workGraph\n .command(\"extraction-schema\")\n .description(\"Print the AI-client search schema used to extract Work Graph Trails from sessions and logs.\")\n .option(\"--output <path>\", \"write the schema prompt to a file\")\n .option(\"--json\", \"emit the protocol as JSON instead of Markdown\")\n .action(async (options: WorkGraphExtractionSchemaCommandOptions) => {\n await safeTrackWizardTelemetry(\"work_graph_extraction_schema_started\", {\n command: \"work-graph extraction-schema\",\n json: Boolean(options.json),\n });\n runWorkGraphExtractionSchemaCommand(options);\n });\n\n workGraph\n .command(\"preview\")\n .description(\"Preview the live Work Graph opportunity map without writing to OrgX.\")\n .option(\"--input <path>\", \"source transcript or summary file; stdin is used when piped\")\n .option(\"--extraction <path>\", \"structured AI-client extraction JSON; repeat or comma-separate for multiple clients\", collectPathOption, [])\n .option(\"--from <sources>\", \"auto-import recent local AI sessions: codex, claude, or all\")\n .option(\"--session-limit <count>\", \"max recent sessions to import per selected source\", \"3\")\n .option(\"--session-days <days>\", \"lookback window for local AI-session imports\", \"30\")\n .option(\"--codex-sessions-dir <path>\", \"override Codex sessions directory for import\")\n .option(\"--claude-projects-dir <path>\", \"override Claude projects directory for import\")\n .option(\"--source-label <label>\", \"label for the imported manual source\")\n .option(\"--workspace-id <id>\", \"workspace id override; defaults to the current OrgX workspace when authenticated\")\n .option(\"--workspace-name <name>\", \"workspace name override for local-only previews\")\n .option(\"--output-dir <path>\", \"directory for generated Work Graph JSON and Markdown\", \".orgx/work-graph\")\n .option(\"--json\", \"emit a JSON command summary\")\n .action(async (options: WorkGraphCommandOptions) => {\n await safeTrackWizardTelemetry(\"work_graph_preview_started\", {\n command: \"work-graph preview\",\n from: options.from ?? \"manual\",\n });\n await runWorkGraphCommand(options);\n });\n\n workGraph\n .command(\"profile\")\n .description(\"Build a local OrgX Profile with Work Graph Trails, Mirror, tensions, and launch recommendations.\")\n .option(\"--input <path>\", \"source transcript or summary file; stdin is used when piped\")\n .option(\"--extraction <path>\", \"structured AI-client extraction JSON; repeat or comma-separate for multiple clients\", collectPathOption, [])\n .option(\"--from <sources>\", \"auto-import recent local AI sessions: codex, claude, or all\")\n .option(\"--session-limit <count>\", \"max recent sessions to import per selected source\", \"5\")\n .option(\"--session-days <days>\", \"lookback window for local AI-session imports\", \"30\")\n .option(\"--codex-sessions-dir <path>\", \"override Codex sessions directory for import\")\n .option(\"--claude-projects-dir <path>\", \"override Claude projects directory for import\")\n .option(\"--source-label <label>\", \"label for the imported manual source\")\n .option(\"--workspace-id <id>\", \"workspace id override; defaults to the current OrgX workspace when authenticated\")\n .option(\"--workspace-name <name>\", \"workspace name override for local-only profiles\")\n .option(\"--output-dir <path>\", \"directory for generated Work Graph JSON and Markdown\", \".orgx/work-graph\")\n .option(\"--publish\", \"publish the generated OrgX Profile to OrgX and return a shareable URL\")\n .option(\"--public-share\", \"create a public redacted /work-graph/<token> share when publishing\")\n .option(\"--attach-artifact\", \"attach the report as an OrgX artifact when an initiative/entity is provided\")\n .option(\"--attach-to-initiative <id>\", \"attach the report to an existing OrgX initiative\")\n .option(\"--entity-type <type>\", \"entity type for artifact attachment: project, initiative, milestone, task, decision\")\n .option(\"--entity-id <id>\", \"entity id for artifact attachment\")\n .option(\"--artifact-url <url>\", \"override the artifact URL stored in OrgX\")\n .option(\"--yes\", \"approve publish/write prompts in non-interactive mode\")\n .option(\"--json\", \"emit a JSON command summary\")\n .action(async (options: WorkGraphCommandOptions) => {\n await safeTrackWizardTelemetry(\"work_graph_profile_started\", {\n command: \"work-graph profile\",\n from: options.from ?? \"manual\",\n });\n await runWorkGraphCommand(options);\n });\n\n const sessions = program\n .command(\"sessions\")\n .description(\"Inspect and reconcile local AI sessions into OrgX-ready Work Graph reports.\");\n\n sessions\n .command(\"reconcile\")\n .description(\"Backfill recent Codex and Claude sessions into a redacted Work Graph report.\")\n .option(\"--extraction <path>\", \"structured AI-client extraction JSON; repeat or comma-separate for multiple clients\", collectPathOption, [])\n .option(\"--from <sources>\", \"auto-import recent local AI sessions: codex, claude, or all\", \"all\")\n .option(\"--session-limit <count>\", \"max recent sessions to import per selected source\", \"5\")\n .option(\"--session-days <days>\", \"lookback window for local AI-session imports\", \"7\")\n .option(\"--codex-sessions-dir <path>\", \"override Codex sessions directory for import\")\n .option(\"--claude-projects-dir <path>\", \"override Claude projects directory for import\")\n .option(\"--workspace-id <id>\", \"workspace id override; defaults to the current OrgX workspace when authenticated\")\n .option(\"--workspace-name <name>\", \"workspace name override for local-only reconciliation\")\n .option(\"--output-dir <path>\", \"directory for generated Work Graph JSON and Markdown\", \".orgx/work-graph\")\n .option(\"--publish\", \"publish the generated OrgX Profile to OrgX and return a shareable URL\")\n .option(\"--public-share\", \"create a public redacted /work-graph/<token> share when publishing\")\n .option(\"--attach-artifact\", \"attach the report as an OrgX artifact when an initiative/entity is provided\")\n .option(\"--attach-to-initiative <id>\", \"attach the report to an existing OrgX initiative\")\n .option(\"--entity-type <type>\", \"entity type for artifact attachment: project, initiative, milestone, task, decision\")\n .option(\"--entity-id <id>\", \"entity id for artifact attachment\")\n .option(\"--artifact-url <url>\", \"override the artifact URL stored in OrgX\")\n .option(\"--yes\", \"approve publish/write prompts in non-interactive mode\")\n .option(\"--json\", \"emit a JSON command summary\")\n .action(async (options: WorkGraphCommandOptions) => {\n await safeTrackWizardTelemetry(\"sessions_reconcile_started\", {\n command: \"sessions reconcile\",\n from: options.from ?? \"all\",\n });\n await runWorkGraphCommand(options, { from: \"all\" });\n });\n\n const hooks = program\n .command(\"hooks\")\n .description(\"Inspect or install passive OrgX runtime hooks for local agent clients.\");\n\n hooks\n .command(\"doctor\")\n .description(\"Show Codex and Claude Code runtime hook wiring status.\")\n .option(\"--json\", \"emit a JSON command summary\")\n .action(async (options: HooksCommandOptions) => {\n const report = inspectRuntimeHooks();\n await safeTrackWizardTelemetry(\"hooks_doctor_ran\", {\n command: \"hooks doctor\",\n codex_installed: report.installed.codex,\n claude_code_installed: report.installed.claudeCode,\n hook_script_installed: report.installed.hookScript,\n });\n if (options.json) {\n console.log(JSON.stringify(report, null, 2));\n return;\n }\n printRuntimeHookInspection(report);\n });\n\n hooks\n .command(\"install\")\n .description(\"Install passive OrgX runtime hooks for Codex and/or Claude Code.\")\n .option(\"--targets <targets>\", \"comma-separated targets: codex, claude-code, or all\", \"all\")\n .option(\"--json\", \"emit a JSON command summary\")\n .action(async (options: HooksCommandOptions) => {\n const targets = parseRuntimeHookTargets(options.targets);\n const result = installRuntimeHooks(targets);\n await safeTrackWizardTelemetry(\"hooks_install_ran\", {\n command: \"hooks install\",\n targets: targets.join(\",\"),\n codex_changed: result.changed.codex,\n claude_code_changed: result.changed.claudeCode,\n });\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n printRuntimeHookInspection(result);\n if (result.backups.length > 0) {\n console.log(\"\");\n console.log(pc.dim(\" backups\"));\n for (const backup of result.backups) {\n console.log(` ${ICON.skip} ${pc.dim(backup)}`);\n }\n }\n });\n\n hooks\n .command(\"replay\")\n .description(\"Replay passive hook outbox events into a claimed Work Graph profile.\")\n .requiredOption(\"--fingerprint <fingerprint>\", \"target Work Graph fingerprint, for example wgf_0123...\")\n .option(\"--outbox <path>\", \"runtime hook JSONL outbox path\")\n .option(\"--limit <count>\", \"maximum recent hook events to replay\", \"200\")\n .option(\"--yes\", \"approve publishing hook evidence without prompting\")\n .option(\"--json\", \"emit a JSON command summary\")\n .action(async (options: HooksCommandOptions) => {\n await runHookReplayCommand(options);\n });\n\n program\n .command(\"doctor\")\n .description(\"Verify local OrgX surface config and optional remote setup status.\")\n .action(async () => {\n const spinner = createOrgxSpinner(\"Running OrgX health check\");\n spinner.start();\n const report = await runDoctor();\n spinner.stop();\n const assessment = assessDoctorReport(report);\n const verification = summarizeSetupVerification(assessment);\n await safeTrackWizardTelemetry(\n \"doctor_ran\",\n buildDoctorTelemetryProperties(report, assessment, verification, {\n command: \"doctor\",\n }),\n );\n printDoctorReport(report, assessment);\n if (verification.status === \"error\") {\n process.exitCode = 1;\n }\n });\n\n const skills = program\n .command(\"skills\")\n .description(\"Install OrgX skills and rules into supported local tools.\");\n\n skills\n .command(\"add\")\n .description(\"Write standalone OrgX Cursor rules and Claude skills, skipping tool surfaces already owned by companion plugins.\")\n .argument(\"[packs...]\", \"skill pack names or 'all'\", [\"all\"])\n .option(\"--force\", \"Overwrite generated skill files even when manual edits are detected.\")\n .action(async (packs: string[], options: { force?: boolean }) => {\n const pluginTargets = (await listOrgxPluginStatuses())\n .filter((status) => status.installed)\n .map((status) => status.target);\n const spinner = createOrgxSpinner(\"Installing OrgX skills/rules into tools\");\n spinner.start();\n const report = await installOrgxSkills({\n force: options.force === true,\n pluginTargets,\n skillNames: packs,\n });\n spinner.succeed(\"OrgX skills/rules installed into tools\");\n printSkillInstallReport(report);\n await safeTrackWizardTelemetry(\"skills_installed\", {\n changed_count: countSkillReportChanges(report),\n command: \"skills:add\",\n pack_count: report.packs.length,\n plugin_managed_target_count: pluginTargets.length,\n requested_pack_count: packs.length,\n skill_extension_count: report.extensions.length,\n write_count: report.writes.length,\n });\n });\n\n skills\n .command(\"sync\")\n .description(\"Recompose installed OrgX skills/rules from core skills plus local extensions.\")\n .argument(\"[packs...]\", \"skill pack names or 'all'\", [\"all\"])\n .option(\"--force\", \"Overwrite generated skill files even when manual edits are detected.\")\n .action(async (packs: string[], options: { force?: boolean }) => {\n const pluginTargets = (await listOrgxPluginStatuses())\n .filter((status) => status.installed)\n .map((status) => status.target);\n const spinner = createOrgxSpinner(\"Syncing OrgX skills/rules and extensions into tools\");\n spinner.start();\n const report = await installOrgxSkills({\n force: options.force === true,\n pluginTargets,\n skillNames: packs,\n });\n spinner.succeed(\"OrgX skills/rules synced into tools\");\n printSkillInstallReport(report);\n await safeTrackWizardTelemetry(\"skills_synced\", {\n changed_count: countSkillReportChanges(report),\n command: \"skills:sync\",\n pack_count: report.packs.length,\n plugin_managed_target_count: pluginTargets.length,\n requested_pack_count: packs.length,\n skill_extension_count: report.extensions.length,\n write_count: report.writes.length,\n });\n });\n\n skills\n .command(\"status\")\n .description(\"Show installed skill/rule tracking and local skill extensions.\")\n .action(async () => {\n const report = getSkillStatus();\n console.log(pc.dim(\" extensions\"));\n printSkillExtensions(report.extensions);\n console.log(\"\");\n console.log(pc.dim(\" generated files\"));\n if (report.trackedFiles.length === 0) {\n console.log(` ${ICON.skip} ${pc.dim(\"no generated skill files tracked yet\")}`);\n } else {\n for (const file of report.trackedFiles) {\n console.log(` ${ICON.ok} ${pc.bold(file.skillId.padEnd(24))} ${pc.dim(file.path)}`);\n }\n }\n });\n\n const skillExtensions = skills\n .command(\"extensions\")\n .description(\"Create, edit, and sync user extensions appended after OrgX core skills.\");\n\n skillExtensions\n .command(\"list\")\n .description(\"List local OrgX skill extensions.\")\n .action(() => {\n printSkillExtensions(listSkillExtensions());\n });\n\n skillExtensions\n .command(\"add\")\n .description(\"Create a local extension file for an OrgX skill.\")\n .argument(\"<skill>\", \"Skill id, for example orgx, cursor-rules, or morning-briefing\")\n .option(\"--scope <scope>\", \"Extension scope: user, workspace, or project.\", \"user\")\n .option(\"--title <title>\", \"Extension title.\")\n .option(\"--content <content>\", \"Initial extension body content.\")\n .option(\"--overwrite\", \"Overwrite an existing extension file.\")\n .action((skill: string, options: {\n content?: string;\n overwrite?: boolean;\n scope?: \"user\" | \"workspace\" | \"project\";\n title?: string;\n }) => {\n const result = addSkillExtension({\n overwrite: options.overwrite === true,\n skillId: skill,\n ...(options.content !== undefined ? { content: options.content } : {}),\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n ...(options.title !== undefined ? { title: options.title } : {}),\n });\n printSkillExtensionWrite(result);\n console.log(\n ` ${ICON.skip} ${pc.dim(`Run ${getCmd()} skills sync to apply it to configured tools.`)}`,\n );\n });\n\n skillExtensions\n .command(\"edit\")\n .description(\"Create if needed, then open a local OrgX skill extension in $EDITOR.\")\n .argument(\"<skill>\", \"Skill id, for example orgx, cursor-rules, or morning-briefing\")\n .option(\"--scope <scope>\", \"Extension scope: user, workspace, or project.\", \"user\")\n .action((skill: string, options: { scope?: \"user\" | \"workspace\" | \"project\" }) => {\n const result = addSkillExtension({\n skillId: skill,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n });\n printSkillExtensionWrite(result);\n if (!openPathInEditor(result.path)) {\n console.log(\n ` ${ICON.warn} ${pc.yellow(\"editor not opened\")} ${pc.dim(`Set EDITOR or edit ${result.path}`)}`,\n );\n }\n console.log(\n ` ${ICON.skip} ${pc.dim(`Run ${getCmd()} skills sync to apply it to configured tools.`)}`,\n );\n });\n\n skillExtensions\n .command(\"enable\")\n .description(\"Enable a local OrgX skill extension.\")\n .argument(\"<skill>\", \"Skill id, for example orgx, cursor-rules, or morning-briefing\")\n .option(\"--scope <scope>\", \"Extension scope: user, workspace, or project.\", \"user\")\n .action((skill: string, options: { scope?: \"user\" | \"workspace\" | \"project\" }) => {\n const result = setSkillExtensionEnabled({\n enabled: true,\n skillId: skill,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n });\n printSkillExtensionWrite(result);\n console.log(\n ` ${ICON.skip} ${pc.dim(`Run ${getCmd()} skills sync to apply it to configured tools.`)}`,\n );\n });\n\n skillExtensions\n .command(\"disable\")\n .description(\"Disable a local OrgX skill extension without deleting it.\")\n .argument(\"<skill>\", \"Skill id, for example orgx, cursor-rules, or morning-briefing\")\n .option(\"--scope <scope>\", \"Extension scope: user, workspace, or project.\", \"user\")\n .action((skill: string, options: { scope?: \"user\" | \"workspace\" | \"project\" }) => {\n const result = setSkillExtensionEnabled({\n enabled: false,\n skillId: skill,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n });\n printSkillExtensionWrite(result);\n console.log(\n ` ${ICON.skip} ${pc.dim(`Run ${getCmd()} skills sync to apply it to configured tools.`)}`,\n );\n });\n\n await program.parseAsync(process.argv);\n}\n\nmain().catch((error) => {\n console.error(pc.red(error instanceof Error ? error.message : String(error)));\n process.exitCode = 1;\n});\n","import pc from \"picocolors\";\n\nexport function renderBanner(version?: string): string {\n const lines = [\n \" ____ ____ _______ __\",\n \" / __ \\\\/ __ \\\\ / ____/ |/ /\",\n \"/ / / / /_/ // / __ | / \",\n \"/ /_/ / _, _// /_/ // | \",\n \"\\\\____/_/ |_| \\\\____//_/|_| \",\n ];\n\n const art = lines.map((line) => pc.cyan(line)).join(\"\\n\");\n const tag = version ? ` ${pc.dim(`v${version}`)}` : \"\";\n return `${art}${tag}`;\n}\n\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const ORGX_HOSTED_MCP_KEY = \"orgx\";\nexport const ORGX_LOCAL_MCP_KEY = \"orgx-openclaw\";\nexport const ORGX_HOSTED_MCP_URL = \"https://mcp.useorgx.com/mcp\";\nexport const ORGX_HOSTED_MCP_HEALTH_URL = \"https://mcp.useorgx.com/health\";\nexport const ORGX_HOSTED_OAUTH_BASE_URL = \"https://mcp.useorgx.com\";\nexport const ORGX_HOSTED_OAUTH_AUTHORIZE_URL = `${ORGX_HOSTED_OAUTH_BASE_URL}/authorize`;\nexport const ORGX_HOSTED_OAUTH_TOKEN_URL = `${ORGX_HOSTED_OAUTH_BASE_URL}/token`;\nexport const ORGX_HOSTED_OAUTH_REGISTER_URL = `${ORGX_HOSTED_OAUTH_BASE_URL}/register`;\nexport const ORGX_WIZARD_NPM_PACKAGE_NAME = \"@useorgx/wizard\";\nexport const NPM_REGISTRY_BASE_URL = \"https://registry.npmjs.org\";\nexport const DEFAULT_OPENCLAW_GATEWAY_PORT = 18_789;\nexport const DEFAULT_ORGX_BASE_URL =\n process.env.ORGX_BASE_URL?.trim() || \"https://useorgx.com\";\nexport const ORGX_WIZARD_OAUTH_CALLBACK_HOST = \"127.0.0.1\";\nexport const ORGX_WIZARD_OAUTH_CALLBACK_PATH = \"/oauth/callback\";\nexport const ORGX_WIZARD_OAUTH_PREFERRED_PORT = 6_274;\nexport const ORGX_WIZARD_OAUTH_SCOPES = [\n \"decisions:read\",\n \"decisions:write\",\n \"agents:read\",\n \"agents:write\",\n \"initiatives:read\",\n \"initiatives:write\",\n \"memory:read\",\n \"offline_access\",\n] as const;\nexport const ORGX_WIZARD_OAUTH_SCOPE = ORGX_WIZARD_OAUTH_SCOPES.join(\" \");\n\nconst HOME = homedir();\nconst APPDATA = process.env.APPDATA?.trim();\nconst LOCAL_APPDATA = process.env.LOCALAPPDATA?.trim();\nconst XDG_CONFIG_HOME =\n process.env.XDG_CONFIG_HOME?.trim() || join(HOME, \".config\");\nexport const ORGX_WIZARD_CONFIG_HOME =\n process.env.ORGX_WIZARD_CONFIG_HOME?.trim() ||\n join(XDG_CONFIG_HOME, \"useorgx\", \"wizard\");\nexport const ORGX_WIZARD_AUTH_PATH = join(ORGX_WIZARD_CONFIG_HOME, \"auth.json\");\nexport const ORGX_WIZARD_STATE_PATH = join(ORGX_WIZARD_CONFIG_HOME, \"state.json\");\nexport const ORGX_SKILL_EXTENSIONS_DIR = join(ORGX_WIZARD_CONFIG_HOME, \"skill-extensions\");\nexport const ORGX_WIZARD_KEYTAR_SERVICE = \"@useorgx/wizard\";\nexport const ORGX_WIZARD_KEYTAR_ACCOUNT = \"orgx-api-key\";\n\nfunction normalizeOrgxApiBaseUrl(baseUrl: string): string {\n const normalized = baseUrl.replace(/\\/+$/, \"\");\n if (/\\/api(\\/|$)/.test(normalized)) {\n return normalized;\n }\n return `${normalized}/api`;\n}\n\nconst ORGX_API_BASE_URL = normalizeOrgxApiBaseUrl(DEFAULT_ORGX_BASE_URL);\nexport const ORGX_SETUP_STATUS_URL = `${ORGX_API_BASE_URL}/setup/status`;\nexport const ORGX_AUTH_VERIFY_URL = `${ORGX_API_BASE_URL}/auth/verify`;\nexport const ORGX_CLIENT_SYNC_URL = `${ORGX_API_BASE_URL}/client/sync`;\n\nfunction uniquePaths(paths: Array<string | undefined>): string[] {\n return [...new Set(paths.filter((path): path is string => Boolean(path)))];\n}\n\nexport const CLAUDE_DIR = join(HOME, \".claude\");\nexport const CURSOR_DIR = join(HOME, \".cursor\");\nexport const CODEX_DIR = join(HOME, \".codex\");\nexport const OPENCLAW_DIR = join(HOME, \".openclaw\");\nexport const AGENTS_DIR = join(HOME, \".agents\");\nexport const CLAUDE_PROJECTS_DIR = join(CLAUDE_DIR, \"projects\");\nexport const CODEX_SESSIONS_DIR = join(CODEX_DIR, \"sessions\");\nexport const CLAUDE_SKILLS_DIR = join(CLAUDE_DIR, \"skills\");\nexport const CLAUDE_ORGX_SKILL_DIR = join(CLAUDE_SKILLS_DIR, \"orgx\");\nexport const CLAUDE_ORGX_SKILL_PATH = join(CLAUDE_ORGX_SKILL_DIR, \"SKILL.md\");\nexport const CURSOR_RULES_DIR = join(CURSOR_DIR, \"rules\");\nexport const CURSOR_ORGX_RULE_PATH = join(CURSOR_RULES_DIR, \"orgx.md\");\nexport const CURSOR_PLUGINS_DIR = join(CURSOR_DIR, \"plugins\", \"local\");\nexport const CURSOR_ORGX_PLUGIN_DIR = join(CURSOR_PLUGINS_DIR, \"cursor-plugin\");\nexport const CODEX_PLUGINS_DIR = join(CODEX_DIR, \"plugins\");\nexport const CODEX_ORGX_PLUGIN_DIR = join(CODEX_PLUGINS_DIR, \"orgx-codex-plugin\");\nexport const CODEX_MARKETPLACE_DIR = join(AGENTS_DIR, \"plugins\");\nexport const CODEX_MARKETPLACE_PATH = join(CODEX_MARKETPLACE_DIR, \"marketplace.json\");\nexport const CLAUDE_MANAGED_MARKETPLACE_DIR = join(\n ORGX_WIZARD_CONFIG_HOME,\n \"plugins\",\n \"claude-marketplace\",\n);\nexport const CLAUDE_MANAGED_MARKETPLACE_MANIFEST_PATH = join(\n CLAUDE_MANAGED_MARKETPLACE_DIR,\n \".claude-plugin\",\n \"marketplace.json\",\n);\nexport const CLAUDE_MANAGED_PLUGIN_DIR = join(\n CLAUDE_MANAGED_MARKETPLACE_DIR,\n \"plugins\",\n \"orgx-claude-code-plugin\",\n);\n\nexport const CLAUDE_MCP_PATHS = uniquePaths([join(CLAUDE_DIR, \"mcp.json\")]);\nexport const CURSOR_MCP_PATHS = uniquePaths([join(CURSOR_DIR, \"mcp.json\")]);\nexport const CODEX_CONFIG_PATHS = uniquePaths([join(CODEX_DIR, \"config.toml\")]);\nexport const OPENCLAW_CONFIG_PATHS = uniquePaths([\n join(OPENCLAW_DIR, \"openclaw.json\"),\n]);\n\nexport const CLAUDE_MCP_PATH = CLAUDE_MCP_PATHS[0];\nexport const CURSOR_MCP_PATH = CURSOR_MCP_PATHS[0];\nexport const CODEX_CONFIG_PATH = CODEX_CONFIG_PATHS[0];\nexport const OPENCLAW_CONFIG_PATH = OPENCLAW_CONFIG_PATHS[0];\n\nexport const CLAUDE_INSTALL_PATHS = uniquePaths([CLAUDE_DIR]);\nexport const CURSOR_INSTALL_PATHS = uniquePaths([CURSOR_DIR]);\nexport const CODEX_INSTALL_PATHS = uniquePaths([CODEX_DIR]);\nexport const OPENCLAW_INSTALL_PATHS = uniquePaths([OPENCLAW_DIR]);\n\nexport const VSCODE_MCP_PATHS = uniquePaths([\n join(HOME, \"Library\", \"Application Support\", \"Code\", \"User\", \"mcp.json\"),\n join(XDG_CONFIG_HOME, \"Code\", \"User\", \"mcp.json\"),\n APPDATA ? join(APPDATA, \"Code\", \"User\", \"mcp.json\") : undefined,\n]);\nexport const VSCODE_INSTALL_PATHS = uniquePaths([\n join(HOME, \"Library\", \"Application Support\", \"Code\", \"User\"),\n join(XDG_CONFIG_HOME, \"Code\", \"User\"),\n APPDATA ? join(APPDATA, \"Code\", \"User\") : undefined,\n LOCAL_APPDATA ? join(LOCAL_APPDATA, \"Programs\", \"Microsoft VS Code\") : undefined,\n]);\n\nexport const WINDSURF_MCP_PATHS = uniquePaths([\n join(HOME, \".codeium\", \"windsurf\", \"mcp_config.json\"),\n]);\nexport const WINDSURF_INSTALL_PATHS = uniquePaths([\n join(HOME, \".codeium\", \"windsurf\"),\n LOCAL_APPDATA ? join(LOCAL_APPDATA, \"Programs\", \"Windsurf\") : undefined,\n]);\n\nexport const ZED_SETTINGS_PATHS = uniquePaths([\n join(HOME, \"Library\", \"Application Support\", \"Zed\", \"settings.json\"),\n join(XDG_CONFIG_HOME, \"zed\", \"settings.json\"),\n APPDATA ? join(APPDATA, \"Zed\", \"settings.json\") : undefined,\n]);\nexport const ZED_INSTALL_PATHS = uniquePaths([\n join(HOME, \"Library\", \"Application Support\", \"Zed\"),\n join(XDG_CONFIG_HOME, \"zed\"),\n APPDATA ? join(APPDATA, \"Zed\") : undefined,\n LOCAL_APPDATA ? join(LOCAL_APPDATA, \"Programs\", \"Zed\") : undefined,\n]);\n\nexport const CHATGPT_APP_PATHS = uniquePaths([\n join(HOME, \"Library\", \"Application Support\", \"OpenAI\"),\n join(HOME, \"Library\", \"Application Support\", \"com.openai.chat\"),\n join(XDG_CONFIG_HOME, \"OpenAI\"),\n join(XDG_CONFIG_HOME, \"openai\"),\n APPDATA ? join(APPDATA, \"OpenAI\") : undefined,\n LOCAL_APPDATA ? join(LOCAL_APPDATA, \"OpenAI\") : undefined,\n]);\n","import { spawnSync } from \"node:child_process\";\n\nimport { buildOrgxApiUrl, normalizeOrgxBaseUrl } from \"./auth.js\";\nimport { isRecord } from \"./fs.js\";\n\nexport type PairingStatus =\n | \"pending\"\n | \"authorized\"\n | \"ready\"\n | \"consumed\"\n | \"expired\"\n | \"cancelled\"\n | \"failed\";\n\nexport interface BrowserPairingStartResult {\n pairingId: string;\n pollToken: string;\n connectUrl: string;\n expiresAt: string;\n pollIntervalMs: number;\n}\n\nexport interface BrowserPairingPollResult {\n pairingId: string;\n status: PairingStatus;\n expiresAt: string;\n workspaceName: string | null;\n keyPrefix: string | null;\n executionMode: \"cloud\" | \"local\" | null;\n errorCode: string | null;\n errorMessage: string | null;\n key?: string;\n}\n\nexport interface BrowserPairingOpenResult {\n ok: boolean;\n error?: string;\n}\n\ninterface FetchJsonOptions {\n body?: string | undefined;\n fetchImpl?: typeof fetch | undefined;\n method: string;\n url: string;\n}\n\nfunction asString(value: unknown): string | null {\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : null;\n}\n\nfunction parseJsonBody(text: string): unknown {\n if (!text) return null;\n\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nasync function fetchJson<T>({\n url,\n method,\n body,\n fetchImpl = fetch,\n}: FetchJsonOptions): Promise<T> {\n const response = await fetchImpl(url, {\n method,\n headers: {\n Accept: \"application/json\",\n ...(body ? { \"Content-Type\": \"application/json\" } : {}),\n },\n ...(body ? { body } : {}),\n signal: AbortSignal.timeout(7_000),\n });\n\n const payload = parseJsonBody(await response.text());\n\n if (!response.ok) {\n const errorMessage = isRecord(payload)\n ? asString(payload.error) ?? asString(payload.message)\n : typeof payload === \"string\"\n ? payload\n : null;\n throw new Error(errorMessage ?? `HTTP ${response.status}`);\n }\n\n if (isRecord(payload) && payload.ok === true && \"data\" in payload) {\n return payload.data as T;\n }\n\n return payload as T;\n}\n\nconst UNROUTABLE_HOSTNAMES = new Set([\"0.0.0.0\", \"::\", \"[::]\"]);\n\nexport function sanitizeConnectUrl(connectUrl: string, baseUrl?: string): string {\n try {\n const parsed = new URL(connectUrl);\n if (UNROUTABLE_HOSTNAMES.has(parsed.hostname)) {\n const base = new URL(normalizeOrgxBaseUrl(baseUrl));\n parsed.protocol = base.protocol;\n parsed.hostname = base.hostname;\n parsed.port = base.port;\n }\n return parsed.toString();\n } catch {\n return connectUrl;\n }\n}\n\nfunction parsePairingStartResult(value: unknown): BrowserPairingStartResult {\n if (!isRecord(value)) {\n throw new Error(\"OrgX pairing start returned an invalid response.\");\n }\n\n const pairingId = asString(value.pairingId);\n const pollToken = asString(value.pollToken);\n const connectUrl = asString(value.connectUrl);\n const expiresAt = asString(value.expiresAt);\n const pollIntervalMs = typeof value.pollIntervalMs === \"number\"\n ? value.pollIntervalMs\n : Number.NaN;\n\n if (!pairingId || !pollToken || !connectUrl || !expiresAt || !Number.isFinite(pollIntervalMs)) {\n throw new Error(\"OrgX pairing start returned an incomplete response.\");\n }\n\n return { pairingId, pollToken, connectUrl, expiresAt, pollIntervalMs };\n}\n\nfunction parsePairingPollResult(value: unknown): BrowserPairingPollResult {\n if (!isRecord(value)) {\n throw new Error(\"OrgX pairing poll returned an invalid response.\");\n }\n\n const pairingId = asString(value.pairingId);\n const status = asString(value.status) as PairingStatus | null;\n const expiresAt = asString(value.expiresAt);\n\n if (!pairingId || !status || !expiresAt) {\n throw new Error(\"OrgX pairing poll returned an incomplete response.\");\n }\n\n return {\n pairingId,\n status,\n expiresAt,\n workspaceName: asString(value.workspaceName),\n keyPrefix: asString(value.keyPrefix),\n executionMode: value.executionMode === \"cloud\" || value.executionMode === \"local\"\n ? value.executionMode\n : null,\n errorCode: asString(value.errorCode),\n errorMessage: asString(value.errorMessage),\n ...(asString(value.key) ? { key: asString(value.key)! } : {}),\n };\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport async function startBrowserPairing(\n options: {\n baseUrl?: string | undefined;\n deviceName?: string | undefined;\n installationId: string;\n platform?: string | undefined;\n },\n fetchImpl?: typeof fetch,\n): Promise<BrowserPairingStartResult> {\n const data = await fetchJson<unknown>({\n url: buildOrgxApiUrl(\"/plugin/openclaw/pairings\", options.baseUrl),\n method: \"POST\",\n body: JSON.stringify({\n installationId: options.installationId,\n clientType: 'orgx-wizard',\n ...(options.deviceName ? { deviceName: options.deviceName } : {}),\n ...(options.platform ? { platform: options.platform } : {}),\n }),\n fetchImpl,\n });\n\n const result = parsePairingStartResult(data);\n return {\n ...result,\n connectUrl: sanitizeConnectUrl(result.connectUrl, options.baseUrl),\n };\n}\n\nexport async function pollBrowserPairing(\n options: {\n baseUrl?: string | undefined;\n pairingId: string;\n pollToken: string;\n },\n fetchImpl?: typeof fetch,\n): Promise<BrowserPairingPollResult> {\n const baseUrl = normalizeOrgxBaseUrl(options.baseUrl);\n const url = new URL(buildOrgxApiUrl(`/plugin/openclaw/pairings/${options.pairingId}`, baseUrl));\n url.searchParams.set(\"pollToken\", options.pollToken);\n\n const data = await fetchJson<unknown>({\n url: url.toString(),\n method: \"GET\",\n fetchImpl,\n });\n\n return parsePairingPollResult(data);\n}\n\nexport async function waitForBrowserPairing(\n options: {\n baseUrl?: string | undefined;\n pairingId: string;\n pollIntervalMs?: number | undefined;\n pollToken: string;\n timeoutMs?: number | undefined;\n },\n fetchImpl?: typeof fetch,\n): Promise<BrowserPairingPollResult> {\n const timeoutMs = options.timeoutMs ?? 10 * 60_000;\n const pollIntervalMs = options.pollIntervalMs ?? 1_500;\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() <= deadline) {\n const result = await pollBrowserPairing(\n {\n baseUrl: options.baseUrl,\n pairingId: options.pairingId,\n pollToken: options.pollToken,\n },\n fetchImpl,\n );\n\n if (result.status === \"ready\") {\n if (!result.key) {\n throw new Error(\"OrgX pairing completed without returning an API key.\");\n }\n return result;\n }\n\n if (result.status === \"failed\") {\n throw new Error(result.errorMessage ?? \"OrgX pairing failed.\");\n }\n\n if (result.status === \"expired\") {\n throw new Error(\"OrgX pairing expired before it was approved.\");\n }\n\n if (result.status === \"cancelled\") {\n throw new Error(\"OrgX pairing was cancelled in the browser.\");\n }\n\n if (result.status === \"consumed\") {\n throw new Error(\"OrgX pairing was already consumed by another client.\");\n }\n\n await sleep(Math.min(5_000, Math.max(350, pollIntervalMs)));\n }\n\n throw new Error(\n `Timed out waiting for OrgX pairing after ${Math.round(timeoutMs / 1000)} seconds.`,\n );\n}\n\nexport async function acknowledgeBrowserPairing(\n options: {\n baseUrl?: string | undefined;\n pairingId: string;\n pollToken: string;\n },\n fetchImpl?: typeof fetch,\n): Promise<void> {\n await fetchJson<unknown>({\n url: buildOrgxApiUrl(`/plugin/openclaw/pairings/${options.pairingId}/ack`, options.baseUrl),\n method: \"POST\",\n body: JSON.stringify({ pollToken: options.pollToken }),\n fetchImpl,\n });\n}\n\nexport function openBrowser(url: string): BrowserPairingOpenResult {\n const platform = process.platform;\n const result = platform === \"darwin\"\n ? spawnSync(\"open\", [url], { stdio: \"ignore\" })\n : platform === \"win32\"\n ? spawnSync(\"cmd\", [\"/c\", \"start\", \"\", url], { stdio: \"ignore\" })\n : spawnSync(\"xdg-open\", [url], { stdio: \"ignore\" });\n\n if (result.error) {\n return { ok: false, error: result.error.message };\n }\n\n if (typeof result.status === \"number\" && result.status !== 0) {\n return { ok: false, error: `Browser open command exited with code ${result.status}.` };\n }\n\n return { ok: true };\n}\n","import {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport function fileExists(path: string): boolean {\n return existsSync(path);\n}\n\nexport function readTextIfExists(path: string): string | null {\n if (!existsSync(path)) return null;\n\n try {\n if (!statSync(path).isFile()) {\n return null;\n }\n\n return readFileSync(path, \"utf8\");\n } catch (error) {\n const code = typeof error === \"object\" && error && \"code\" in error\n ? String(error.code)\n : undefined;\n\n if (code === \"ENOENT\" || code === \"ENOTDIR\" || code === \"EISDIR\") {\n return null;\n }\n\n throw error;\n }\n}\n\nexport function writeTextFile(\n path: string,\n content: string,\n options: { mode?: number } = {},\n): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, content, {\n encoding: \"utf8\",\n ...(options.mode === undefined ? {} : { mode: options.mode }),\n });\n\n if (options.mode !== undefined) {\n chmodSync(path, options.mode);\n }\n}\n\nexport function writeJsonFile(\n path: string,\n value: unknown,\n options: { mode?: number } = {},\n): void {\n writeTextFile(path, `${JSON.stringify(value, null, 2)}\\n`, options);\n}\n\nexport function deleteFileIfExists(path: string): boolean {\n if (!existsSync(path)) return false;\n\n try {\n if (!statSync(path).isFile()) {\n return false;\n }\n\n unlinkSync(path);\n return true;\n } catch (error) {\n const code = typeof error === \"object\" && error && \"code\" in error\n ? String(error.code)\n : undefined;\n\n if (code === \"ENOENT\" || code === \"ENOTDIR\" || code === \"EISDIR\") {\n return false;\n }\n\n throw error;\n }\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nexport function parseJsonObject(input: string | null): Record<string, unknown> {\n if (!input) return {};\n\n try {\n const parsed = JSON.parse(input);\n return isRecord(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nexport function readObject(\n value: unknown,\n fallback: Record<string, unknown> = {},\n): Record<string, unknown> {\n return isRecord(value) ? value : fallback;\n}\n","import {\n DEFAULT_OPENCLAW_GATEWAY_PORT,\n DEFAULT_ORGX_BASE_URL,\n} from \"../constants.js\";\nimport { isRecord, parseJsonObject, readObject } from \"../lib/fs.js\";\n\ntype JsonObject = Record<string, unknown>;\n\nexport interface OpenClawInspection {\n configured: boolean;\n installed: boolean;\n pluginKey: \"orgx\" | \"openclaw-plugin\" | null;\n details: string[];\n}\n\nexport interface OpenClawAuthConfig {\n apiKey: string;\n baseUrl: string;\n pluginKey: \"orgx\" | \"openclaw-plugin\" | null;\n enabled: boolean;\n}\n\nexport interface OpenClawOrgxDefaultsInput {\n apiKey?: string;\n baseUrl?: string;\n}\n\nfunction cleanupEmptyObjects(value: JsonObject): void {\n for (const [key, child] of Object.entries(value)) {\n if (!isRecord(child)) continue;\n cleanupEmptyObjects(child);\n if (Object.keys(child).length === 0) {\n delete value[key];\n }\n }\n}\n\nexport function readOpenClawGatewayPort(raw: unknown): number {\n const isValidPort = (value: number): boolean =>\n Number.isFinite(value) && value >= 1 && value <= 65_535;\n\n const root = isRecord(raw) ? raw : {};\n const gateway = readObject(root.gateway);\n const port = gateway.port;\n\n if (typeof port === \"number\" && isValidPort(port)) {\n return Math.floor(port);\n }\n\n if (typeof port === \"string\") {\n const parsed = Number.parseInt(port, 10);\n if (isValidPort(parsed)) {\n return parsed;\n }\n }\n\n return DEFAULT_OPENCLAW_GATEWAY_PORT;\n}\n\nexport function buildLocalMcpUrl(raw: unknown): string {\n return `http://127.0.0.1:${readOpenClawGatewayPort(raw)}/orgx/mcp`;\n}\n\nfunction resolvePluginKey(entries: JsonObject): \"orgx\" | \"openclaw-plugin\" {\n if (isRecord(entries[\"openclaw-plugin\"])) {\n return \"openclaw-plugin\";\n }\n\n if (isRecord(entries.orgx)) {\n return \"orgx\";\n }\n\n return \"orgx\";\n}\n\nexport function readOpenClawAuth(input: string | null): OpenClawAuthConfig {\n const current = parseJsonObject(input);\n const plugins = readObject(current.plugins);\n const entries = readObject(plugins.entries);\n const pluginKey = isRecord(entries[\"openclaw-plugin\"])\n ? \"openclaw-plugin\"\n : isRecord(entries.orgx)\n ? \"orgx\"\n : null;\n const entry = pluginKey ? readObject(entries[pluginKey]) : {};\n const config = readObject(entry.config);\n\n return {\n apiKey: typeof config.apiKey === \"string\" ? config.apiKey.trim() : \"\",\n baseUrl:\n typeof config.baseUrl === \"string\" && config.baseUrl.trim().length > 0\n ? config.baseUrl.trim()\n : DEFAULT_ORGX_BASE_URL,\n pluginKey,\n enabled: entry.enabled !== false,\n };\n}\n\nexport function patchOpenClawConfig(\n input: string | null,\n auth: OpenClawOrgxDefaultsInput = {},\n): string {\n const current = parseJsonObject(input);\n const plugins = readObject(current.plugins);\n const entries = readObject(plugins.entries);\n const pluginKey = resolvePluginKey(entries);\n const entry = readObject(entries[pluginKey]);\n const config = readObject(entry.config);\n const apiKey =\n typeof auth.apiKey === \"string\" && auth.apiKey.trim().length > 0\n ? auth.apiKey.trim()\n : typeof config.apiKey === \"string\" && config.apiKey.trim().length > 0\n ? config.apiKey.trim()\n : undefined;\n const baseUrl =\n typeof auth.baseUrl === \"string\" && auth.baseUrl.trim().length > 0\n ? auth.baseUrl.trim()\n : typeof config.baseUrl === \"string\" && config.baseUrl.trim().length > 0\n ? config.baseUrl.trim()\n : DEFAULT_ORGX_BASE_URL;\n\n entries[pluginKey] = {\n ...entry,\n enabled: true,\n config: {\n ...config,\n ...(apiKey ? { apiKey } : {}),\n baseUrl,\n dashboardEnabled:\n typeof config.dashboardEnabled === \"boolean\"\n ? config.dashboardEnabled\n : true,\n autoInstallAgentSuiteOnConnect:\n typeof config.autoInstallAgentSuiteOnConnect === \"boolean\"\n ? config.autoInstallAgentSuiteOnConnect\n : true,\n autoConfigureMcpClientsOnConnect:\n typeof config.autoConfigureMcpClientsOnConnect === \"boolean\"\n ? config.autoConfigureMcpClientsOnConnect\n : true,\n },\n };\n\n plugins.entries = entries;\n current.plugins = plugins;\n\n return `${JSON.stringify(current, null, 2)}\\n`;\n}\n\nexport function removeOpenClawConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const plugins = readObject(current.plugins);\n const entries = readObject(plugins.entries);\n\n for (const key of [\"openclaw-plugin\", \"orgx\"]) {\n const entry = readObject(entries[key]);\n if (!Object.keys(entry).length) continue;\n const config = readObject(entry.config);\n delete config.baseUrl;\n delete config.dashboardEnabled;\n delete config.autoInstallAgentSuiteOnConnect;\n delete config.autoConfigureMcpClientsOnConnect;\n if (Object.keys(config).length > 0) {\n entry.config = config;\n } else {\n delete entry.config;\n }\n entries[key] = entry;\n }\n\n plugins.entries = entries;\n current.plugins = plugins;\n cleanupEmptyObjects(current);\n\n return `${JSON.stringify(current, null, 2)}\\n`;\n}\n\nexport function inspectOpenClawConfig(input: string | null): OpenClawInspection {\n const current = parseJsonObject(input);\n const plugins = readObject(current.plugins);\n const entries = readObject(plugins.entries);\n const installs = readObject(plugins.installs);\n const pluginKey = isRecord(entries[\"openclaw-plugin\"])\n ? \"openclaw-plugin\"\n : isRecord(entries.orgx)\n ? \"orgx\"\n : null;\n const entry = pluginKey ? readObject(entries[pluginKey]) : {};\n const config = readObject(entry.config);\n const installed =\n pluginKey !== null ||\n isRecord(installs[\"openclaw-plugin\"]) ||\n isRecord(installs.orgx);\n const configured =\n installed &&\n entry.enabled === true &&\n (typeof config.baseUrl === \"string\" ||\n typeof config.autoInstallAgentSuiteOnConnect === \"boolean\" ||\n typeof config.autoConfigureMcpClientsOnConnect === \"boolean\");\n\n return {\n configured,\n installed,\n pluginKey,\n details: [\n `plugin key: ${pluginKey ?? \"missing\"}`,\n `enabled: ${entry.enabled === true ? \"yes\" : \"no\"}`,\n `gateway port: ${readOpenClawGatewayPort(current)}`,\n ],\n };\n}\n","import {\n ORGX_WIZARD_AUTH_PATH,\n ORGX_WIZARD_KEYTAR_ACCOUNT,\n ORGX_WIZARD_KEYTAR_SERVICE,\n} from \"../constants.js\";\nimport {\n deleteFileIfExists,\n parseJsonObject,\n readTextIfExists,\n writeJsonFile,\n} from \"./fs.js\";\n\nexport type WizardAuthStorage = \"file\" | \"keytar\";\nexport type WizardAuthSource = \"manual\" | \"pkce\";\n\nexport interface WizardAuthRecord {\n apiKey: string;\n keyPrefix: string;\n baseUrl: string;\n source: WizardAuthSource;\n storage: WizardAuthStorage;\n verifiedAt: string;\n /** Present when source is \"pkce\" — used to silently refresh access_token. */\n refreshToken?: string;\n /** OAuth client_id used to obtain this token (needed for refresh). */\n oauthClientId?: string;\n}\n\nexport interface WizardAuthMetadata {\n baseUrl: string;\n keyPrefix: string;\n source: WizardAuthSource;\n storage: WizardAuthStorage;\n verifiedAt: string;\n}\n\nexport interface WizardSecretStore {\n deletePassword(service: string, account: string): Promise<boolean>;\n getPassword(service: string, account: string): Promise<string | null>;\n setPassword(service: string, account: string, password: string): Promise<void>;\n}\n\ninterface StoredWizardAuthRecord {\n apiKey?: string;\n baseUrl: string;\n keyPrefix: string;\n source?: WizardAuthSource;\n storage: WizardAuthStorage;\n verifiedAt: string;\n refreshToken?: string;\n oauthClientId?: string;\n}\n\ninterface WizardAuthStoreOptions {\n preferSecureStorage?: boolean;\n secretStore?: WizardSecretStore | null;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\nexport function extractKeyPrefix(apiKey: string): string {\n return apiKey.trim().slice(0, 12);\n}\n\nfunction parseStoredWizardAuthRecord(raw: string | null): StoredWizardAuthRecord | null {\n const parsed = parseJsonObject(raw);\n\n if (\n !isNonEmptyString(parsed.keyPrefix) ||\n !isNonEmptyString(parsed.baseUrl) ||\n !isNonEmptyString(parsed.verifiedAt)\n ) {\n return null;\n }\n\n const storage = parsed.storage === \"keytar\" ? \"keytar\" : \"file\";\n const source: WizardAuthSource = parsed.source === \"pkce\" ? \"pkce\" : \"manual\";\n\n return {\n baseUrl: parsed.baseUrl.trim(),\n ...(isNonEmptyString(parsed.apiKey) ? { apiKey: parsed.apiKey.trim() } : {}),\n keyPrefix: parsed.keyPrefix.trim(),\n source,\n storage,\n verifiedAt: parsed.verifiedAt.trim(),\n ...(isNonEmptyString(parsed.refreshToken) ? { refreshToken: parsed.refreshToken.trim() } : {}),\n ...(isNonEmptyString(parsed.oauthClientId) ? { oauthClientId: parsed.oauthClientId.trim() } : {}),\n };\n}\n\nasync function loadDefaultSecretStore(): Promise<WizardSecretStore | null> {\n if (process.env.ORGX_WIZARD_DISABLE_KEYTAR === \"1\") {\n return null;\n }\n\n try {\n const imported = await import(\"keytar\");\n const candidate = (\n \"default\" in imported && imported.default ? imported.default : imported\n ) as Partial<WizardSecretStore>;\n\n if (\n typeof candidate.getPassword === \"function\" &&\n typeof candidate.setPassword === \"function\" &&\n typeof candidate.deletePassword === \"function\"\n ) {\n return candidate as WizardSecretStore;\n }\n } catch {\n return null;\n }\n\n return null;\n}\n\nasync function resolveSecretStore(\n options: WizardAuthStoreOptions,\n): Promise<WizardSecretStore | null> {\n if (options.secretStore !== undefined) {\n return options.secretStore;\n }\n\n return loadDefaultSecretStore();\n}\n\nfunction buildStoredRecord(\n value: WizardAuthRecord,\n): StoredWizardAuthRecord {\n return {\n ...(value.storage === \"file\" ? { apiKey: value.apiKey } : {}),\n baseUrl: value.baseUrl,\n keyPrefix: value.keyPrefix,\n source: value.source,\n storage: value.storage,\n verifiedAt: value.verifiedAt,\n ...(value.refreshToken ? { refreshToken: value.refreshToken } : {}),\n ...(value.oauthClientId ? { oauthClientId: value.oauthClientId } : {}),\n };\n}\n\nexport function readWizardAuthMetadata(\n authPath: string = ORGX_WIZARD_AUTH_PATH,\n): WizardAuthMetadata | null {\n const stored = parseStoredWizardAuthRecord(readTextIfExists(authPath));\n if (!stored) {\n return null;\n }\n\n return {\n baseUrl: stored.baseUrl,\n keyPrefix: stored.keyPrefix,\n source: stored.source ?? \"manual\",\n storage: stored.storage,\n verifiedAt: stored.verifiedAt,\n };\n}\n\nexport async function readWizardAuth(\n authPath: string = ORGX_WIZARD_AUTH_PATH,\n options: WizardAuthStoreOptions = {},\n): Promise<WizardAuthRecord | null> {\n const stored = parseStoredWizardAuthRecord(readTextIfExists(authPath));\n if (!stored) {\n return null;\n }\n\n const source: WizardAuthSource = stored.source ?? \"manual\";\n\n const apiKeyFromFile =\n stored.storage === \"file\" && isNonEmptyString(stored.apiKey)\n ? stored.apiKey.trim()\n : null;\n\n if (apiKeyFromFile) {\n return {\n apiKey: apiKeyFromFile,\n baseUrl: stored.baseUrl,\n keyPrefix: stored.keyPrefix,\n source,\n storage: \"file\",\n verifiedAt: stored.verifiedAt,\n ...(stored.refreshToken ? { refreshToken: stored.refreshToken } : {}),\n ...(stored.oauthClientId ? { oauthClientId: stored.oauthClientId } : {}),\n };\n }\n\n if (stored.storage !== \"keytar\") {\n return null;\n }\n\n const secretStore = await resolveSecretStore(options);\n if (!secretStore) {\n return null;\n }\n\n const apiKey = await secretStore.getPassword(\n ORGX_WIZARD_KEYTAR_SERVICE,\n ORGX_WIZARD_KEYTAR_ACCOUNT,\n );\n\n if (!isNonEmptyString(apiKey)) {\n return null;\n }\n\n return {\n apiKey: apiKey.trim(),\n baseUrl: stored.baseUrl,\n keyPrefix: stored.keyPrefix,\n source,\n storage: \"keytar\",\n verifiedAt: stored.verifiedAt,\n ...(stored.refreshToken ? { refreshToken: stored.refreshToken } : {}),\n ...(stored.oauthClientId ? { oauthClientId: stored.oauthClientId } : {}),\n };\n}\n\nexport async function writeWizardAuth(\n value: {\n apiKey: string;\n baseUrl: string;\n keyPrefix?: string;\n verifiedAt: string;\n source?: WizardAuthSource;\n refreshToken?: string;\n oauthClientId?: string;\n },\n authPath: string = ORGX_WIZARD_AUTH_PATH,\n options: WizardAuthStoreOptions = {},\n): Promise<WizardAuthRecord> {\n const secretStore = options.preferSecureStorage === false\n ? null\n : await resolveSecretStore(options);\n\n const record: WizardAuthRecord = {\n apiKey: value.apiKey.trim(),\n keyPrefix: value.keyPrefix?.trim() || extractKeyPrefix(value.apiKey),\n baseUrl: value.baseUrl.trim(),\n source: value.source ?? \"manual\",\n storage: secretStore ? \"keytar\" : \"file\",\n verifiedAt: value.verifiedAt.trim(),\n ...(value.refreshToken ? { refreshToken: value.refreshToken } : {}),\n ...(value.oauthClientId ? { oauthClientId: value.oauthClientId } : {}),\n };\n\n if (secretStore) {\n await secretStore.setPassword(\n ORGX_WIZARD_KEYTAR_SERVICE,\n ORGX_WIZARD_KEYTAR_ACCOUNT,\n record.apiKey,\n );\n }\n\n writeJsonFile(authPath, buildStoredRecord(record), { mode: 0o600 });\n return record;\n}\n\nexport async function clearWizardAuth(\n authPath: string = ORGX_WIZARD_AUTH_PATH,\n options: WizardAuthStoreOptions = {},\n): Promise<boolean> {\n const secretStore = await resolveSecretStore(options);\n const secretRemoved = secretStore\n ? await secretStore.deletePassword(\n ORGX_WIZARD_KEYTAR_SERVICE,\n ORGX_WIZARD_KEYTAR_ACCOUNT,\n )\n : false;\n const fileRemoved = deleteFileIfExists(authPath);\n return secretRemoved || fileRemoved;\n}\n","import {\n DEFAULT_ORGX_BASE_URL,\n OPENCLAW_CONFIG_PATH,\n ORGX_WIZARD_AUTH_PATH,\n} from \"../constants.js\";\nimport { readOpenClawAuth } from \"../surfaces/openclaw-config.js\";\nimport { readTextIfExists } from \"./fs.js\";\nimport {\n extractKeyPrefix,\n readWizardAuth,\n readWizardAuthMetadata,\n} from \"./auth-store.js\";\n\nexport type OrgxAuthSource =\n | \"environment\"\n | \"wizard-store\"\n | \"openclaw-config-file\";\n\nexport interface ResolvedOrgxAuth {\n apiKey: string;\n keyPrefix: string;\n baseUrl: string;\n source: OrgxAuthSource;\n path?: string;\n verifiedAt?: string;\n}\n\nexport interface OrgxAuthCheckResult {\n configured: boolean;\n ok: boolean;\n skipped: boolean;\n source: OrgxAuthSource | \"none\";\n keyPrefix?: string;\n baseUrl?: string;\n path?: string;\n verifiedAt?: string;\n status?: number;\n url?: string;\n error?: string;\n data?: unknown;\n}\n\nexport interface ResolveOrgxAuthOptions {\n authPath?: string;\n openclawConfigPath?: string;\n}\n\nexport interface OrgxAuthHint {\n keyPrefix: string;\n baseUrl: string;\n source: OrgxAuthSource;\n path?: string;\n verifiedAt?: string;\n}\n\nfunction normalizeHost(value: string): string {\n return value.trim().toLowerCase().replace(/^\\[|\\]$/g, \"\");\n}\n\nfunction isLoopbackHostname(hostname: string): boolean {\n const normalized = normalizeHost(hostname);\n return normalized === \"localhost\" || normalized === \"127.0.0.1\" || normalized === \"::1\";\n}\n\nexport function normalizeOrgxBaseUrl(raw?: string): string {\n const candidate = raw?.trim() || DEFAULT_ORGX_BASE_URL;\n\n try {\n const parsed = new URL(candidate);\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n return DEFAULT_ORGX_BASE_URL;\n }\n\n if (parsed.username || parsed.password) {\n return DEFAULT_ORGX_BASE_URL;\n }\n\n if (parsed.protocol === \"http:\" && !isLoopbackHostname(parsed.hostname)) {\n return DEFAULT_ORGX_BASE_URL;\n }\n\n parsed.search = \"\";\n parsed.hash = \"\";\n parsed.pathname = parsed.pathname.replace(/\\/api\\/?$/, \"\").replace(/\\/+$/, \"\");\n return parsed.toString().replace(/\\/+$/, \"\");\n } catch {\n return DEFAULT_ORGX_BASE_URL;\n }\n}\n\nexport function buildOrgxApiUrl(path: string, baseUrl?: string): string {\n const parsedBase = new URL(normalizeOrgxBaseUrl(baseUrl));\n const normalizedBase = parsedBase.toString().replace(/\\/+$/, \"\");\n const apiBase = normalizedBase.endsWith(\"/api\") ? normalizedBase : `${normalizedBase}/api`;\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n return `${apiBase}${normalizedPath}`;\n}\n\nfunction withResolvedBaseUrl(baseUrl: string, envBaseUrl?: string): string {\n return normalizeOrgxBaseUrl(envBaseUrl?.trim() || baseUrl);\n}\n\nfunction buildResolvedAuth(\n apiKey: string,\n baseUrl: string,\n source: OrgxAuthSource,\n extras: Pick<ResolvedOrgxAuth, \"path\" | \"verifiedAt\"> = {},\n): ResolvedOrgxAuth {\n return {\n apiKey: apiKey.trim(),\n keyPrefix: extractKeyPrefix(apiKey),\n baseUrl,\n source,\n ...(extras.path ? { path: extras.path } : {}),\n ...(extras.verifiedAt ? { verifiedAt: extras.verifiedAt } : {}),\n };\n}\n\nfunction buildAuthHint(\n keyPrefix: string,\n baseUrl: string,\n source: OrgxAuthSource,\n extras: Pick<OrgxAuthHint, \"path\" | \"verifiedAt\"> = {},\n): OrgxAuthHint {\n return {\n keyPrefix: keyPrefix.trim(),\n baseUrl,\n source,\n ...(extras.path ? { path: extras.path } : {}),\n ...(extras.verifiedAt ? { verifiedAt: extras.verifiedAt } : {}),\n };\n}\n\nexport function peekResolvedOrgxAuth(\n options: ResolveOrgxAuthOptions = {},\n): OrgxAuthHint | null {\n const envApiKey = process.env.ORGX_API_KEY?.trim();\n const envBaseUrl = process.env.ORGX_BASE_URL?.trim();\n if (envApiKey) {\n return buildAuthHint(\n extractKeyPrefix(envApiKey),\n withResolvedBaseUrl(DEFAULT_ORGX_BASE_URL, envBaseUrl),\n \"environment\",\n );\n }\n\n const authPath = options.authPath ?? ORGX_WIZARD_AUTH_PATH;\n const stored = readWizardAuthMetadata(authPath);\n if (stored) {\n return buildAuthHint(\n stored.keyPrefix,\n withResolvedBaseUrl(stored.baseUrl, envBaseUrl),\n \"wizard-store\",\n {\n path: authPath,\n verifiedAt: stored.verifiedAt,\n },\n );\n }\n\n const openclawConfigPath = options.openclawConfigPath ?? OPENCLAW_CONFIG_PATH;\n const openclawAuth = readOpenClawAuth(\n openclawConfigPath ? readTextIfExists(openclawConfigPath) : null,\n );\n if (openclawAuth.apiKey && openclawConfigPath) {\n return buildAuthHint(\n extractKeyPrefix(openclawAuth.apiKey),\n withResolvedBaseUrl(openclawAuth.baseUrl || DEFAULT_ORGX_BASE_URL, envBaseUrl),\n \"openclaw-config-file\",\n { path: openclawConfigPath },\n );\n }\n\n return null;\n}\n\nexport async function resolveOrgxAuth(\n options: ResolveOrgxAuthOptions = {},\n): Promise<ResolvedOrgxAuth | null> {\n const envApiKey = process.env.ORGX_API_KEY?.trim();\n const envBaseUrl = process.env.ORGX_BASE_URL?.trim();\n if (envApiKey) {\n return buildResolvedAuth(\n envApiKey,\n withResolvedBaseUrl(DEFAULT_ORGX_BASE_URL, envBaseUrl),\n \"environment\",\n );\n }\n\n const authPath = options.authPath ?? ORGX_WIZARD_AUTH_PATH;\n const stored = await readWizardAuth(authPath);\n if (stored) {\n return buildResolvedAuth(\n stored.apiKey,\n withResolvedBaseUrl(stored.baseUrl, envBaseUrl),\n \"wizard-store\",\n {\n path: authPath,\n verifiedAt: stored.verifiedAt,\n },\n );\n }\n\n const openclawConfigPath = options.openclawConfigPath ?? OPENCLAW_CONFIG_PATH;\n const openclawAuth = readOpenClawAuth(\n openclawConfigPath ? readTextIfExists(openclawConfigPath) : null,\n );\n if (openclawAuth.apiKey && openclawConfigPath) {\n return buildResolvedAuth(\n openclawAuth.apiKey,\n withResolvedBaseUrl(openclawAuth.baseUrl || DEFAULT_ORGX_BASE_URL, envBaseUrl),\n \"openclaw-config-file\",\n { path: openclawConfigPath },\n );\n }\n\n return null;\n}\n\nasync function parseResponseBody(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nexport async function verifyOrgxAuth(\n auth: Pick<ResolvedOrgxAuth, \"apiKey\" | \"baseUrl\" | \"source\" | \"keyPrefix\"> & {\n path?: string;\n verifiedAt?: string;\n },\n): Promise<OrgxAuthCheckResult> {\n const url = buildOrgxApiUrl(\"/client/sync\", auth.baseUrl);\n\n try {\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: \"{}\",\n signal: AbortSignal.timeout(7_000),\n });\n\n const data = await parseResponseBody(response);\n\n return {\n configured: true,\n ok: response.ok,\n skipped: false,\n source: auth.source,\n keyPrefix: auth.keyPrefix,\n baseUrl: auth.baseUrl,\n ...(auth.path ? { path: auth.path } : {}),\n ...(auth.verifiedAt ? { verifiedAt: auth.verifiedAt } : {}),\n status: response.status,\n url,\n data,\n ...(response.ok ? {} : { error: `HTTP ${response.status}` }),\n };\n } catch (error) {\n return {\n configured: true,\n ok: false,\n skipped: false,\n source: auth.source,\n keyPrefix: auth.keyPrefix,\n baseUrl: auth.baseUrl,\n ...(auth.path ? { path: auth.path } : {}),\n ...(auth.verifiedAt ? { verifiedAt: auth.verifiedAt } : {}),\n url,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport async function checkOrgxAuth(\n options: ResolveOrgxAuthOptions = {},\n): Promise<OrgxAuthCheckResult> {\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n return {\n configured: false,\n ok: false,\n skipped: true,\n source: \"none\",\n error: \"No OrgX account connected. Run `orgx-wizard auth login` to connect.\",\n url: buildOrgxApiUrl(\"/client/sync\", DEFAULT_ORGX_BASE_URL),\n };\n }\n\n return verifyOrgxAuth(auth);\n}\n\nexport function describeSetupStatusScope(): string {\n return \"The setup-status endpoint is still service-key-only and uses ORGX_SERVICE_KEY.\";\n}\n","import { createServer } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\n\nexport interface OAuthCallbackResult {\n code: string;\n state: string;\n}\n\nexport interface LocalAuthServerOptions {\n /** Preferred port; falls back through preferredPort+1..+9 until one binds. */\n preferredPort: number;\n /** Expected state value — rejects callbacks with mismatched state. */\n expectedState: string;\n /** Milliseconds to wait before timing out. Default: 5 minutes. */\n timeoutMs?: number;\n /** Path to listen on. Default: /oauth/callback */\n callbackPath?: string;\n /** HTML to show in the browser on success. */\n successHtml?: string;\n /** HTML to show in the browser on error. */\n errorHtml?: string;\n}\n\nconst DEFAULT_SUCCESS_HTML = `<!DOCTYPE html>\n<html>\n<head><title>OrgX connected</title>\n<style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#f9fafb}\n.card{text-align:center;padding:2rem;max-width:400px}\nh1{font-size:1.5rem;color:#111}p{color:#555;margin-top:.5rem}</style>\n</head>\n<body><div class=\"card\">\n<h1>&#10003; Connected to OrgX</h1>\n<p>You can close this tab and return to your terminal.</p>\n</div></body></html>`;\n\nconst DEFAULT_ERROR_HTML = `<!DOCTYPE html>\n<html>\n<head><title>OrgX auth error</title>\n<style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#fef2f2}\n.card{text-align:center;padding:2rem;max-width:400px}\nh1{font-size:1.5rem;color:#b91c1c}p{color:#555;margin-top:.5rem}</style>\n</head>\n<body><div class=\"card\">\n<h1>&#10007; Authentication failed</h1>\n<p>Return to your terminal and try again.</p>\n</div></body></html>`;\n\nfunction tryListen(port: number, hostname: string): Promise<ReturnType<typeof createServer>> {\n return new Promise((resolve, reject) => {\n const server = createServer();\n server.once(\"error\", reject);\n server.listen(port, hostname, () => {\n server.removeListener(\"error\", reject);\n resolve(server);\n });\n });\n}\n\nasync function bindServer(\n preferredPort: number,\n hostname: string,\n): Promise<{ server: ReturnType<typeof createServer>; port: number }> {\n // Port 0 lets the OS pick a free port — read the actual port back from address()\n if (preferredPort === 0) {\n const server = await tryListen(0, hostname);\n const port = (server.address() as AddressInfo).port;\n return { server, port };\n }\n\n for (let offset = 0; offset < 10; offset++) {\n const port = preferredPort + offset;\n try {\n const server = await tryListen(port, hostname);\n return { server, port };\n } catch {\n // port busy — try next\n }\n }\n throw new Error(\n `Could not bind local auth server: ports ${preferredPort}–${preferredPort + 9} are all in use.`,\n );\n}\n\n/**\n * Starts a local HTTP server that waits for a single OAuth callback redirect,\n * validates the state parameter, and returns the authorization code.\n *\n * Returns the bound port so callers can build the redirect_uri before opening\n * the browser.\n */\nexport async function startLocalAuthServer(\n options: LocalAuthServerOptions,\n): Promise<{ port: number; result: Promise<OAuthCallbackResult> }> {\n const hostname = \"127.0.0.1\";\n const callbackPath = options.callbackPath ?? \"/oauth/callback\";\n const timeoutMs = options.timeoutMs ?? 5 * 60_000;\n const successHtml = options.successHtml ?? DEFAULT_SUCCESS_HTML;\n const errorHtml = options.errorHtml ?? DEFAULT_ERROR_HTML;\n\n const { server, port } = await bindServer(options.preferredPort, hostname);\n\n const result = new Promise<OAuthCallbackResult>((resolve, reject) => {\n const timer = setTimeout(() => {\n server.close();\n reject(new Error(\"Timed out waiting for browser authorization.\"));\n }, timeoutMs);\n\n server.on(\"request\", (req, res) => {\n if (!req.url) {\n res.writeHead(400).end(errorHtml);\n return;\n }\n\n const url = new URL(req.url, `http://${hostname}:${port}`);\n\n if (url.pathname !== callbackPath) {\n res.writeHead(404).end(\"Not found\");\n return;\n }\n\n const error = url.searchParams.get(\"error\");\n const errorDescription = url.searchParams.get(\"error_description\");\n\n if (error) {\n res.writeHead(400, { \"Content-Type\": \"text/html\" }).end(errorHtml);\n clearTimeout(timer);\n server.close();\n reject(new Error(errorDescription ?? error));\n return;\n }\n\n const code = url.searchParams.get(\"code\");\n const state = url.searchParams.get(\"state\");\n\n if (!code || !state) {\n res.writeHead(400, { \"Content-Type\": \"text/html\" }).end(errorHtml);\n clearTimeout(timer);\n server.close();\n reject(new Error(\"Missing code or state in callback.\"));\n return;\n }\n\n if (state !== options.expectedState) {\n res.writeHead(400, { \"Content-Type\": \"text/html\" }).end(errorHtml);\n clearTimeout(timer);\n server.close();\n reject(new Error(\"State mismatch — possible CSRF. Retry auth.\"));\n return;\n }\n\n res.writeHead(200, { \"Content-Type\": \"text/html\" }).end(successHtml);\n clearTimeout(timer);\n server.close();\n resolve({ code, state });\n });\n });\n\n return { port, result };\n}\n\nexport function buildRedirectUri(port: number, callbackPath = \"/oauth/callback\"): string {\n return `http://127.0.0.1:${port}${callbackPath}`;\n}\n\n/** Returns the actual port the server is listening on (useful if OS assigned it). */\nexport function getServerPort(server: ReturnType<typeof createServer>): number {\n return (server.address() as AddressInfo).port;\n}\n","import { createHash, randomBytes } from \"node:crypto\";\n\nexport interface PkceChallenge {\n codeVerifier: string;\n codeChallenge: string;\n codeChallengeMethod: \"S256\";\n}\n\n/**\n * Generates a PKCE code_verifier and S256 code_challenge per RFC 7636.\n * Uses 32 random bytes → 43-char base64url string (within the 43–128 char spec range).\n */\nexport function generatePkce(): PkceChallenge {\n const codeVerifier = randomBytes(32).toString(\"base64url\");\n const codeChallenge = createHash(\"sha256\")\n .update(codeVerifier)\n .digest(\"base64url\");\n return { codeVerifier, codeChallenge, codeChallengeMethod: \"S256\" };\n}\n\nexport function generateState(): string {\n return randomBytes(16).toString(\"base64url\");\n}\n\nexport interface AuthorizeUrlOptions {\n authorizeEndpoint: string;\n clientId: string;\n redirectUri: string;\n scope: string;\n codeChallenge: string;\n codeChallengeMethod: \"S256\" | \"plain\";\n state: string;\n}\n\nexport function buildAuthorizeUrl(options: AuthorizeUrlOptions): string {\n const url = new URL(options.authorizeEndpoint);\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"client_id\", options.clientId);\n url.searchParams.set(\"redirect_uri\", options.redirectUri);\n url.searchParams.set(\"scope\", options.scope);\n url.searchParams.set(\"code_challenge\", options.codeChallenge);\n url.searchParams.set(\"code_challenge_method\", options.codeChallengeMethod);\n url.searchParams.set(\"state\", options.state);\n return url.toString();\n}\n","import {\n ORGX_HOSTED_OAUTH_AUTHORIZE_URL,\n ORGX_HOSTED_OAUTH_REGISTER_URL,\n ORGX_HOSTED_OAUTH_TOKEN_URL,\n ORGX_WIZARD_OAUTH_CALLBACK_PATH,\n ORGX_WIZARD_OAUTH_PREFERRED_PORT,\n ORGX_WIZARD_OAUTH_SCOPE,\n} from \"../constants.js\";\nimport { isRecord } from \"./fs.js\";\nimport { buildRedirectUri, startLocalAuthServer } from \"./local-auth-server.js\";\nimport { buildAuthorizeUrl, generatePkce, generateState } from \"./pkce.js\";\n\nexport interface OAuthTokenResponse {\n access_token: string;\n token_type: string;\n expires_in?: number;\n refresh_token?: string;\n scope?: string;\n}\n\nexport interface RegisteredOAuthClient {\n client_id: string;\n client_secret?: string;\n}\n\nexport interface PkceLoginResult {\n accessToken: string;\n refreshToken: string | undefined;\n redirectUri: string;\n clientId: string;\n expiresIn: number | undefined;\n}\n\nasync function registerPublicClient(\n options: {\n redirectUri: string;\n fetchImpl?: typeof fetch;\n },\n): Promise<RegisteredOAuthClient> {\n const fetchImpl = options.fetchImpl ?? fetch;\n const response = await fetchImpl(ORGX_HOSTED_OAUTH_REGISTER_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n client_name: \"OrgX Wizard CLI\",\n redirect_uris: [options.redirectUri],\n token_endpoint_auth_method: \"none\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"],\n }),\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(`OAuth client registration failed (HTTP ${response.status}): ${text}`);\n }\n\n const data = await response.json();\n if (!isRecord(data) || typeof data.client_id !== \"string\") {\n throw new Error(\"OAuth registration response missing client_id.\");\n }\n\n return { client_id: data.client_id as string };\n}\n\nasync function exchangeCodeForTokens(\n options: {\n code: string;\n codeVerifier: string;\n redirectUri: string;\n clientId: string;\n fetchImpl?: typeof fetch;\n },\n): Promise<OAuthTokenResponse> {\n const fetchImpl = options.fetchImpl ?? fetch;\n const body = new URLSearchParams({\n grant_type: \"authorization_code\",\n code: options.code,\n redirect_uri: options.redirectUri,\n client_id: options.clientId,\n code_verifier: options.codeVerifier,\n });\n\n const response = await fetchImpl(ORGX_HOSTED_OAUTH_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: body.toString(),\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(`Token exchange failed (HTTP ${response.status}): ${text}`);\n }\n\n const data = await response.json();\n if (!isRecord(data) || typeof data.access_token !== \"string\") {\n throw new Error(\"Token response missing access_token.\");\n }\n\n return {\n access_token: data.access_token as string,\n token_type: typeof data.token_type === \"string\" ? data.token_type : \"Bearer\",\n ...(typeof data.expires_in === \"number\" ? { expires_in: data.expires_in } : {}),\n ...(typeof data.refresh_token === \"string\" ? { refresh_token: data.refresh_token } : {}),\n ...(typeof data.scope === \"string\" ? { scope: data.scope } : {}),\n };\n}\n\nexport async function refreshAccessToken(\n options: {\n refreshToken: string;\n clientId: string;\n fetchImpl?: typeof fetch;\n },\n): Promise<OAuthTokenResponse> {\n const fetchImpl = options.fetchImpl ?? fetch;\n const body = new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: options.refreshToken,\n client_id: options.clientId,\n });\n\n const response = await fetchImpl(ORGX_HOSTED_OAUTH_TOKEN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: body.toString(),\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(`Token refresh failed (HTTP ${response.status}): ${text}`);\n }\n\n const data = await response.json();\n if (!isRecord(data) || typeof data.access_token !== \"string\") {\n throw new Error(\"Refresh response missing access_token.\");\n }\n\n return {\n access_token: data.access_token as string,\n token_type: typeof data.token_type === \"string\" ? data.token_type : \"Bearer\",\n ...(typeof data.expires_in === \"number\" ? { expires_in: data.expires_in } : {}),\n ...(typeof data.refresh_token === \"string\" ? { refresh_token: data.refresh_token } : {}),\n };\n}\n\nexport interface StartPkceLoginOptions {\n /** Called with the URL the user should open. Return false to skip auto-open. */\n onAuthorizeUrl?: (url: string) => void;\n /** Override preferred callback port (default from constants). */\n preferredPort?: number;\n /** Override OAuth scopes. */\n scope?: string;\n /** Timeout in ms (default 5 min). */\n timeoutMs?: number;\n /** Injected fetch for testing. */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Full PKCE authorization_code flow:\n * 1. Register a public dynamic client\n * 2. Start local callback server\n * 3. Build authorize URL and open browser\n * 4. Wait for callback, validate state\n * 5. Exchange code for tokens\n *\n * Returns access_token + optional refresh_token — no OpenClaw required.\n */\nexport async function startPkceLogin(\n options: StartPkceLoginOptions = {},\n): Promise<PkceLoginResult> {\n const port = options.preferredPort ?? ORGX_WIZARD_OAUTH_PREFERRED_PORT;\n const scope = options.scope ?? ORGX_WIZARD_OAUTH_SCOPE;\n const { codeVerifier, codeChallenge, codeChallengeMethod } = generatePkce();\n const state = generateState();\n\n // Start local server first so we know the actual bound port\n const serverOpts = {\n preferredPort: port,\n expectedState: state,\n callbackPath: ORGX_WIZARD_OAUTH_CALLBACK_PATH,\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n };\n const { port: boundPort, result: callbackPromise } = await startLocalAuthServer(serverOpts);\n\n const redirectUri = buildRedirectUri(boundPort, ORGX_WIZARD_OAUTH_CALLBACK_PATH);\n\n const clientOpts = {\n redirectUri,\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n };\n const client = await registerPublicClient(clientOpts);\n\n const authorizeUrl = buildAuthorizeUrl({\n authorizeEndpoint: ORGX_HOSTED_OAUTH_AUTHORIZE_URL,\n clientId: client.client_id,\n redirectUri,\n scope,\n codeChallenge,\n codeChallengeMethod,\n state,\n });\n\n options.onAuthorizeUrl?.(authorizeUrl);\n\n const { code } = await callbackPromise;\n\n const exchangeOpts = {\n code,\n codeVerifier,\n redirectUri,\n clientId: client.client_id,\n ...(options.fetchImpl !== undefined ? { fetchImpl: options.fetchImpl } : {}),\n };\n const tokens = await exchangeCodeForTokens(exchangeOpts);\n\n return {\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token,\n redirectUri,\n clientId: client.client_id,\n expiresIn: tokens.expires_in,\n };\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { ORGX_WIZARD_STATE_PATH } from \"../constants.js\";\nimport { deleteFileIfExists, parseJsonObject, readTextIfExists, writeJsonFile } from \"./fs.js\";\nimport { SURFACE_NAMES, type SurfaceName } from \"../surfaces/names.js\";\n\nexport interface WizardContinuityDefaults {\n executionMode?: \"cloud\" | \"local\";\n reviewSurface?: SurfaceName;\n workspaceId?: string;\n workspaceName?: string;\n}\n\nexport interface WizardDemoInitiativeRecord {\n createdAt: string;\n artifactId?: string;\n artifactName?: string;\n artifactType?: string;\n artifactUrl?: string;\n decisionId?: string;\n decisionStatus?: string;\n decisionTitle?: string;\n id: string;\n liveUrl: string;\n title: string;\n workspaceId?: string;\n workspaceName?: string;\n}\n\nexport interface WizardFirstValueInitiativeRecord {\n createdAt: string;\n id: string;\n liveUrl: string;\n summary?: string;\n title: string;\n workspaceId?: string;\n workspaceName?: string;\n}\n\nexport interface WizardOnboardingTaskRecord {\n createdAt: string;\n id: string;\n initiativeId?: string;\n status?: string;\n title: string;\n workstreamId?: string;\n workspaceId?: string;\n workspaceName?: string;\n}\n\nexport interface WizardAgentRosterEntry {\n agentType: string;\n domain: string;\n name: string;\n}\n\nexport interface WizardAgentRosterRecord {\n agents: WizardAgentRosterEntry[];\n configuredAt: string;\n workspaceId?: string;\n workspaceName?: string;\n}\n\nexport interface WizardSkillFileRecord {\n contentSha256: string;\n coreSha256?: string;\n path: string;\n skillId: string;\n updatedAt: string;\n}\n\nexport interface WizardSkillFilesRecord {\n files: WizardSkillFileRecord[];\n updatedAt: string;\n}\n\n/**\n * People-first capture idempotency record — keyed by workspace id so the\n * wizard does not re-prompt Wave 3b capture on every run. Mirrors the\n * pattern the Daily Brief uses server-side (`onboardingCompletedAt`). This\n * local record is authoritative while the server endpoints are still\n * landing (Wave 2).\n */\nexport interface WizardPeopleFirstCaptureEntry {\n workspaceId: string;\n completedAt: string;\n personId?: string;\n templatePersona?: string;\n /** True when the server endpoints were not live at capture time and the\n * payload was staged to `~/.orgx-wizard/pending-people.json`. */\n stagedLocally?: boolean;\n}\n\nexport interface WizardPeopleFirstCaptureRecord {\n updatedAt: string;\n entries: WizardPeopleFirstCaptureEntry[];\n}\n\nexport type WizardDailyBriefOnboardingStatus = \"completed\" | \"skipped\";\n\nexport interface WizardDailyBriefOnboardingEntry {\n workspaceId: string;\n status: WizardDailyBriefOnboardingStatus;\n completedAt?: string;\n skippedAt?: string;\n workspaceName?: string;\n}\n\nexport interface WizardDailyBriefOnboardingRecord {\n updatedAt: string;\n entries: WizardDailyBriefOnboardingEntry[];\n}\n\nexport type WizardSetupPromptKey =\n | \"first_initiative\"\n | \"onboarding_task\"\n | \"agent_roster\"\n | \"setup_intent\";\n\nexport interface WizardSetupPromptDecisionEntry {\n promptKey: WizardSetupPromptKey;\n skippedAt: string;\n status: \"skipped\";\n workspaceId: string;\n workspaceName?: string;\n}\n\nexport interface WizardSetupPromptDecisionsRecord {\n updatedAt: string;\n entries: WizardSetupPromptDecisionEntry[];\n}\n\nexport interface WizardStateRecord {\n continuity?: WizardContinuityDefaults;\n installationId: string;\n agentRoster?: WizardAgentRosterRecord;\n demoInitiative?: WizardDemoInitiativeRecord;\n firstValueInitiative?: WizardFirstValueInitiativeRecord;\n onboardingTask?: WizardOnboardingTaskRecord;\n skillFiles?: WizardSkillFilesRecord;\n peopleFirstCapture?: WizardPeopleFirstCaptureRecord;\n dailyBriefOnboarding?: WizardDailyBriefOnboardingRecord;\n setupPromptDecisions?: WizardSetupPromptDecisionsRecord;\n createdAt: string;\n updatedAt: string;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\nfunction isSurfaceName(value: unknown): value is SurfaceName {\n return typeof value === \"string\" && SURFACE_NAMES.includes(value as SurfaceName);\n}\n\nfunction parseContinuityDefaults(value: unknown): WizardContinuityDefaults | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n const parsed: WizardContinuityDefaults = {};\n\n if (record.executionMode === \"cloud\" || record.executionMode === \"local\") {\n parsed.executionMode = record.executionMode;\n }\n\n if (isSurfaceName(record.reviewSurface)) {\n parsed.reviewSurface = record.reviewSurface;\n }\n\n if (isNonEmptyString(record.workspaceId)) {\n parsed.workspaceId = record.workspaceId.trim();\n }\n\n if (isNonEmptyString(record.workspaceName)) {\n parsed.workspaceName = record.workspaceName.trim();\n }\n\n return Object.keys(parsed).length > 0 ? parsed : undefined;\n}\n\nfunction parseDemoInitiative(value: unknown): WizardDemoInitiativeRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.id) ||\n !isNonEmptyString(record.title) ||\n !isNonEmptyString(record.liveUrl) ||\n !isNonEmptyString(record.createdAt)\n ) {\n return undefined;\n }\n\n return {\n createdAt: record.createdAt.trim(),\n ...(isNonEmptyString(record.artifactId)\n ? { artifactId: record.artifactId.trim() }\n : {}),\n ...(isNonEmptyString(record.artifactName)\n ? { artifactName: record.artifactName.trim() }\n : {}),\n ...(isNonEmptyString(record.artifactType)\n ? { artifactType: record.artifactType.trim() }\n : {}),\n ...(isNonEmptyString(record.artifactUrl)\n ? { artifactUrl: record.artifactUrl.trim() }\n : {}),\n ...(isNonEmptyString(record.decisionId)\n ? { decisionId: record.decisionId.trim() }\n : {}),\n ...(isNonEmptyString(record.decisionStatus)\n ? { decisionStatus: record.decisionStatus.trim() }\n : {}),\n ...(isNonEmptyString(record.decisionTitle)\n ? { decisionTitle: record.decisionTitle.trim() }\n : {}),\n id: record.id.trim(),\n liveUrl: record.liveUrl.trim(),\n title: record.title.trim(),\n ...(isNonEmptyString(record.workspaceId)\n ? { workspaceId: record.workspaceId.trim() }\n : {}),\n ...(isNonEmptyString(record.workspaceName)\n ? { workspaceName: record.workspaceName.trim() }\n : {}),\n };\n}\n\nfunction parseFirstValueInitiative(\n value: unknown,\n): WizardFirstValueInitiativeRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.id) ||\n !isNonEmptyString(record.title) ||\n !isNonEmptyString(record.liveUrl) ||\n !isNonEmptyString(record.createdAt)\n ) {\n return undefined;\n }\n\n return {\n createdAt: record.createdAt.trim(),\n id: record.id.trim(),\n liveUrl: record.liveUrl.trim(),\n ...(isNonEmptyString(record.summary) ? { summary: record.summary.trim() } : {}),\n title: record.title.trim(),\n ...(isNonEmptyString(record.workspaceId)\n ? { workspaceId: record.workspaceId.trim() }\n : {}),\n ...(isNonEmptyString(record.workspaceName)\n ? { workspaceName: record.workspaceName.trim() }\n : {}),\n };\n}\n\nfunction parseOnboardingTask(value: unknown): WizardOnboardingTaskRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.id) ||\n !isNonEmptyString(record.title) ||\n !isNonEmptyString(record.createdAt)\n ) {\n return undefined;\n }\n\n return {\n createdAt: record.createdAt.trim(),\n id: record.id.trim(),\n ...(isNonEmptyString(record.initiativeId)\n ? { initiativeId: record.initiativeId.trim() }\n : {}),\n ...(isNonEmptyString(record.status)\n ? { status: record.status.trim() }\n : {}),\n title: record.title.trim(),\n ...(isNonEmptyString(record.workstreamId)\n ? { workstreamId: record.workstreamId.trim() }\n : {}),\n ...(isNonEmptyString(record.workspaceId)\n ? { workspaceId: record.workspaceId.trim() }\n : {}),\n ...(isNonEmptyString(record.workspaceName)\n ? { workspaceName: record.workspaceName.trim() }\n : {}),\n };\n}\n\nfunction parseAgentRosterEntry(value: unknown): WizardAgentRosterEntry | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.agentType) ||\n !isNonEmptyString(record.domain) ||\n !isNonEmptyString(record.name)\n ) {\n return undefined;\n }\n\n return {\n agentType: record.agentType.trim(),\n domain: record.domain.trim(),\n name: record.name.trim(),\n };\n}\n\nfunction parseAgentRoster(value: unknown): WizardAgentRosterRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (!isNonEmptyString(record.configuredAt) || !Array.isArray(record.agents)) {\n return undefined;\n }\n\n const agents = record.agents\n .map((entry) => parseAgentRosterEntry(entry))\n .filter((entry): entry is WizardAgentRosterEntry => Boolean(entry));\n if (agents.length === 0) {\n return undefined;\n }\n\n return {\n agents,\n configuredAt: record.configuredAt.trim(),\n ...(isNonEmptyString(record.workspaceId)\n ? { workspaceId: record.workspaceId.trim() }\n : {}),\n ...(isNonEmptyString(record.workspaceName)\n ? { workspaceName: record.workspaceName.trim() }\n : {}),\n };\n}\n\nfunction parseSkillFileRecord(value: unknown): WizardSkillFileRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.path) ||\n !isNonEmptyString(record.skillId) ||\n !isNonEmptyString(record.contentSha256) ||\n !isNonEmptyString(record.updatedAt)\n ) {\n return undefined;\n }\n\n return {\n contentSha256: record.contentSha256.trim(),\n path: record.path.trim(),\n skillId: record.skillId.trim(),\n updatedAt: record.updatedAt.trim(),\n ...(isNonEmptyString(record.coreSha256)\n ? { coreSha256: record.coreSha256.trim() }\n : {}),\n };\n}\n\nfunction parseSkillFiles(value: unknown): WizardSkillFilesRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (!isNonEmptyString(record.updatedAt) || !Array.isArray(record.files)) {\n return undefined;\n }\n\n const files = record.files\n .map((entry) => parseSkillFileRecord(entry))\n .filter((entry): entry is WizardSkillFileRecord => Boolean(entry));\n if (files.length === 0) {\n return undefined;\n }\n\n return {\n files,\n updatedAt: record.updatedAt.trim(),\n };\n}\n\nfunction parsePeopleFirstCaptureEntry(\n value: unknown,\n): WizardPeopleFirstCaptureEntry | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.workspaceId) ||\n !isNonEmptyString(record.completedAt)\n ) {\n return undefined;\n }\n return {\n workspaceId: record.workspaceId.trim(),\n completedAt: record.completedAt.trim(),\n ...(isNonEmptyString(record.personId) ? { personId: record.personId.trim() } : {}),\n ...(isNonEmptyString(record.templatePersona)\n ? { templatePersona: record.templatePersona.trim() }\n : {}),\n ...(record.stagedLocally === true ? { stagedLocally: true } : {}),\n };\n}\n\nfunction parsePeopleFirstCapture(\n value: unknown,\n): WizardPeopleFirstCaptureRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n const record = value as Record<string, unknown>;\n if (!isNonEmptyString(record.updatedAt) || !Array.isArray(record.entries)) {\n return undefined;\n }\n const entries = record.entries\n .map((entry) => parsePeopleFirstCaptureEntry(entry))\n .filter(\n (entry): entry is WizardPeopleFirstCaptureEntry => Boolean(entry),\n );\n if (entries.length === 0) return undefined;\n return {\n updatedAt: record.updatedAt.trim(),\n entries,\n };\n}\n\nfunction parseDailyBriefOnboardingEntry(\n value: unknown,\n): WizardDailyBriefOnboardingEntry | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n const status = record.status;\n if (\n !isNonEmptyString(record.workspaceId) ||\n (status !== \"completed\" && status !== \"skipped\")\n ) {\n return undefined;\n }\n\n const completedAt = isNonEmptyString(record.completedAt)\n ? record.completedAt.trim()\n : undefined;\n const skippedAt = isNonEmptyString(record.skippedAt)\n ? record.skippedAt.trim()\n : undefined;\n\n if (status === \"completed\" && !completedAt) return undefined;\n if (status === \"skipped\" && !skippedAt) return undefined;\n\n return {\n workspaceId: record.workspaceId.trim(),\n status,\n ...(completedAt ? { completedAt } : {}),\n ...(skippedAt ? { skippedAt } : {}),\n ...(isNonEmptyString(record.workspaceName)\n ? { workspaceName: record.workspaceName.trim() }\n : {}),\n };\n}\n\nfunction parseDailyBriefOnboarding(\n value: unknown,\n): WizardDailyBriefOnboardingRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (!isNonEmptyString(record.updatedAt) || !Array.isArray(record.entries)) {\n return undefined;\n }\n\n const entries = record.entries\n .map((entry) => parseDailyBriefOnboardingEntry(entry))\n .filter(\n (entry): entry is WizardDailyBriefOnboardingEntry => Boolean(entry),\n );\n if (entries.length === 0) return undefined;\n\n return {\n updatedAt: record.updatedAt.trim(),\n entries,\n };\n}\n\nfunction isSetupPromptKey(value: unknown): value is WizardSetupPromptKey {\n return (\n value === \"first_initiative\" ||\n value === \"onboarding_task\" ||\n value === \"agent_roster\" ||\n value === \"setup_intent\"\n );\n}\n\nfunction parseSetupPromptDecisionEntry(\n value: unknown,\n): WizardSetupPromptDecisionEntry | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (\n !isNonEmptyString(record.workspaceId) ||\n !isSetupPromptKey(record.promptKey) ||\n record.status !== \"skipped\" ||\n !isNonEmptyString(record.skippedAt)\n ) {\n return undefined;\n }\n\n return {\n promptKey: record.promptKey,\n skippedAt: record.skippedAt.trim(),\n status: \"skipped\",\n workspaceId: record.workspaceId.trim(),\n ...(isNonEmptyString(record.workspaceName)\n ? { workspaceName: record.workspaceName.trim() }\n : {}),\n };\n}\n\nfunction parseSetupPromptDecisions(\n value: unknown,\n): WizardSetupPromptDecisionsRecord | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n\n const record = value as Record<string, unknown>;\n if (!isNonEmptyString(record.updatedAt) || !Array.isArray(record.entries)) {\n return undefined;\n }\n\n const entries = record.entries\n .map((entry) => parseSetupPromptDecisionEntry(entry))\n .filter(\n (entry): entry is WizardSetupPromptDecisionEntry => Boolean(entry),\n );\n if (entries.length === 0) return undefined;\n\n return {\n updatedAt: record.updatedAt.trim(),\n entries,\n };\n}\n\nfunction createWizardState(now = new Date().toISOString()): WizardStateRecord {\n return {\n installationId: `wizard-${randomUUID()}`,\n createdAt: now,\n updatedAt: now,\n };\n}\n\nfunction sanitizeWizardStateRecord(record: WizardStateRecord): WizardStateRecord {\n const continuity = parseContinuityDefaults(record.continuity);\n const agentRoster = parseAgentRoster(record.agentRoster);\n const demoInitiative = parseDemoInitiative(record.demoInitiative);\n const firstValueInitiative = parseFirstValueInitiative(record.firstValueInitiative);\n const onboardingTask = parseOnboardingTask(record.onboardingTask);\n const skillFiles = parseSkillFiles(record.skillFiles);\n const peopleFirstCapture = parsePeopleFirstCapture(record.peopleFirstCapture);\n const dailyBriefOnboarding = parseDailyBriefOnboarding(record.dailyBriefOnboarding);\n const setupPromptDecisions = parseSetupPromptDecisions(record.setupPromptDecisions);\n\n return {\n installationId: record.installationId.trim(),\n createdAt: record.createdAt.trim(),\n updatedAt: record.updatedAt.trim(),\n ...(continuity ? { continuity } : {}),\n ...(agentRoster ? { agentRoster } : {}),\n ...(demoInitiative ? { demoInitiative } : {}),\n ...(firstValueInitiative ? { firstValueInitiative } : {}),\n ...(onboardingTask ? { onboardingTask } : {}),\n ...(skillFiles ? { skillFiles } : {}),\n ...(peopleFirstCapture ? { peopleFirstCapture } : {}),\n ...(dailyBriefOnboarding ? { dailyBriefOnboarding } : {}),\n ...(setupPromptDecisions ? { setupPromptDecisions } : {}),\n };\n}\n\nexport function readWizardState(\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardStateRecord | null {\n const parsed = parseJsonObject(readTextIfExists(statePath));\n\n if (\n !isNonEmptyString(parsed.installationId) ||\n !isNonEmptyString(parsed.createdAt) ||\n !isNonEmptyString(parsed.updatedAt)\n ) {\n return null;\n }\n\n const state: WizardStateRecord = {\n installationId: parsed.installationId.trim(),\n createdAt: parsed.createdAt.trim(),\n updatedAt: parsed.updatedAt.trim(),\n };\n const continuity = parseContinuityDefaults(parsed.continuity);\n if (continuity !== undefined) state.continuity = continuity;\n const agentRoster = parseAgentRoster(parsed.agentRoster);\n if (agentRoster !== undefined) state.agentRoster = agentRoster;\n const demoInitiative = parseDemoInitiative(parsed.demoInitiative);\n if (demoInitiative !== undefined) state.demoInitiative = demoInitiative;\n const firstValueInitiative = parseFirstValueInitiative(parsed.firstValueInitiative);\n if (firstValueInitiative !== undefined) {\n state.firstValueInitiative = firstValueInitiative;\n }\n const onboardingTask = parseOnboardingTask(parsed.onboardingTask);\n if (onboardingTask !== undefined) state.onboardingTask = onboardingTask;\n const skillFiles = parseSkillFiles(parsed.skillFiles);\n if (skillFiles !== undefined) state.skillFiles = skillFiles;\n const peopleFirstCapture = parsePeopleFirstCapture(parsed.peopleFirstCapture);\n if (peopleFirstCapture !== undefined) state.peopleFirstCapture = peopleFirstCapture;\n const dailyBriefOnboarding = parseDailyBriefOnboarding(parsed.dailyBriefOnboarding);\n if (dailyBriefOnboarding !== undefined) {\n state.dailyBriefOnboarding = dailyBriefOnboarding;\n }\n const setupPromptDecisions = parseSetupPromptDecisions(parsed.setupPromptDecisions);\n if (setupPromptDecisions !== undefined) {\n state.setupPromptDecisions = setupPromptDecisions;\n }\n return state;\n}\n\n/**\n * Idempotency helpers for people-first capture. `hasCompleted` is called\n * before prompting; `recordCompletion` is called after a successful capture\n * (server-backed or local-fallback) so subsequent wizard runs skip.\n */\nexport function hasPeopleFirstCaptureCompleted(\n workspaceId: string,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): boolean {\n const state = readWizardState(statePath);\n if (!state?.peopleFirstCapture) return false;\n return state.peopleFirstCapture.entries.some(\n (entry) => entry.workspaceId === workspaceId,\n );\n}\n\nexport function recordPeopleFirstCaptureCompletion(\n entry: WizardPeopleFirstCaptureEntry,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardStateRecord {\n return updateWizardState((current) => {\n const existingEntries = current.peopleFirstCapture?.entries ?? [];\n const withoutExisting = existingEntries.filter(\n (e) => e.workspaceId !== entry.workspaceId,\n );\n return {\n ...current,\n peopleFirstCapture: {\n updatedAt: new Date().toISOString(),\n entries: [...withoutExisting, entry],\n },\n };\n }, statePath);\n}\n\nexport function getDailyBriefOnboardingDecision(\n workspaceId: string,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardDailyBriefOnboardingEntry | null {\n const state = readWizardState(statePath);\n return state?.dailyBriefOnboarding?.entries.find(\n (entry) => entry.workspaceId === workspaceId,\n ) ?? null;\n}\n\nexport function hasDailyBriefOnboardingDecision(\n workspaceId: string,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): boolean {\n return getDailyBriefOnboardingDecision(workspaceId, statePath) !== null;\n}\n\nexport function recordDailyBriefOnboardingDecision(\n entry: WizardDailyBriefOnboardingEntry,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardStateRecord {\n return updateWizardState((current) => {\n const existingEntries = current.dailyBriefOnboarding?.entries ?? [];\n const withoutExisting = existingEntries.filter(\n (e) => e.workspaceId !== entry.workspaceId,\n );\n return {\n ...current,\n dailyBriefOnboarding: {\n updatedAt: new Date().toISOString(),\n entries: [...withoutExisting, entry],\n },\n };\n }, statePath);\n}\n\nexport function getSetupPromptDecision(\n workspaceId: string,\n promptKey: WizardSetupPromptKey,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardSetupPromptDecisionEntry | null {\n const state = readWizardState(statePath);\n return (\n state?.setupPromptDecisions?.entries.find(\n (entry) =>\n entry.workspaceId === workspaceId && entry.promptKey === promptKey,\n ) ?? null\n );\n}\n\nexport function hasSetupPromptSkip(\n workspaceId: string,\n promptKey: WizardSetupPromptKey,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): boolean {\n return getSetupPromptDecision(workspaceId, promptKey, statePath) !== null;\n}\n\nexport function recordSetupPromptSkip(\n entry: {\n promptKey: WizardSetupPromptKey;\n skippedAt?: string;\n workspaceId: string;\n workspaceName?: string;\n },\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardStateRecord {\n return updateWizardState((current) => {\n const existingEntries = current.setupPromptDecisions?.entries ?? [];\n const withoutExisting = existingEntries.filter(\n (existing) =>\n !(\n existing.workspaceId === entry.workspaceId &&\n existing.promptKey === entry.promptKey\n ),\n );\n return {\n ...current,\n setupPromptDecisions: {\n updatedAt: new Date().toISOString(),\n entries: [\n ...withoutExisting,\n {\n promptKey: entry.promptKey,\n skippedAt: entry.skippedAt ?? new Date().toISOString(),\n status: \"skipped\",\n workspaceId: entry.workspaceId,\n ...(entry.workspaceName ? { workspaceName: entry.workspaceName } : {}),\n },\n ],\n },\n };\n }, statePath);\n}\n\nexport function writeWizardState(\n value: WizardStateRecord,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardStateRecord {\n const record = sanitizeWizardStateRecord(value);\n writeJsonFile(statePath, record, { mode: 0o600 });\n return record;\n}\n\nexport function updateWizardState(\n updater: (current: WizardStateRecord) => WizardStateRecord,\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): WizardStateRecord {\n const current = readWizardState(statePath) ?? createWizardState();\n const next = updater(current);\n const sanitized = sanitizeWizardStateRecord({\n ...next,\n installationId: next.installationId || current.installationId,\n createdAt: next.createdAt || current.createdAt,\n updatedAt: new Date().toISOString(),\n });\n writeJsonFile(statePath, sanitized, { mode: 0o600 });\n return sanitized;\n}\n\nexport function getOrCreateWizardInstallationId(\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): string {\n const existing = readWizardState(statePath);\n if (existing) {\n return existing.installationId;\n }\n\n const record = createWizardState();\n writeWizardState(record, statePath);\n return record.installationId;\n}\n\nexport function clearWizardState(\n statePath: string = ORGX_WIZARD_STATE_PATH,\n): boolean {\n return deleteFileIfExists(statePath);\n}\n","export const SURFACE_NAMES = [\n \"claude\",\n \"cursor\",\n \"codex\",\n \"openclaw\",\n \"vscode\",\n \"windsurf\",\n \"zed\",\n \"chatgpt\",\n] as const;\n\nexport type SurfaceName = (typeof SURFACE_NAMES)[number];\nexport type SurfaceMode = \"automated\" | \"manual\";\n\nexport const AUTOMATED_SURFACE_NAMES = [\n \"claude\",\n \"cursor\",\n \"codex\",\n \"openclaw\",\n \"vscode\",\n \"windsurf\",\n \"zed\",\n] as const satisfies readonly SurfaceName[];\n\nexport const MCP_SURFACE_NAMES = [\n \"claude\",\n \"cursor\",\n \"codex\",\n \"vscode\",\n \"windsurf\",\n \"zed\",\n] as const;\n","import type { OrgxWorkspace } from \"./workspaces.js\";\nimport {\n readWizardState,\n updateWizardState,\n type WizardAgentRosterEntry,\n type WizardAgentRosterRecord,\n} from \"./wizard-state.js\";\n\nexport interface AgentRosterProfile {\n agentType: string;\n defaultDomain: string;\n name: string;\n}\n\nexport interface AgentRosterAssignment {\n domain: string;\n name: string;\n}\n\nexport const AGENT_ROSTER_PROFILES: AgentRosterProfile[] = [\n { agentType: \"orchestrator-agent\", defaultDomain: \"orchestrator\", name: \"Xandy\" },\n { agentType: \"product-agent\", defaultDomain: \"product\", name: \"Pace\" },\n { agentType: \"engineering-agent\", defaultDomain: \"engineering\", name: \"Eli\" },\n { agentType: \"marketing-agent\", defaultDomain: \"marketing\", name: \"Mark\" },\n { agentType: \"sales-agent\", defaultDomain: \"sales\", name: \"Sage\" },\n { agentType: \"operations-agent\", defaultDomain: \"operations\", name: \"Orion\" },\n { agentType: \"design-agent\", defaultDomain: \"design\", name: \"Dana\" },\n];\n\nexport const AGENT_ROSTER_DOMAINS = AGENT_ROSTER_PROFILES.map((profile) => profile.defaultDomain);\n\nexport const DEFAULT_AGENT_ROSTER: WizardAgentRosterEntry[] = AGENT_ROSTER_PROFILES.map(\n ({ agentType, defaultDomain, name }) => ({\n agentType,\n domain: defaultDomain,\n name,\n }),\n);\n\nfunction findAgentRosterProfile(name: string): AgentRosterProfile | undefined {\n return AGENT_ROSTER_PROFILES.find((profile) => profile.name === name);\n}\n\nexport function listAgentRosterProfiles(): AgentRosterProfile[] {\n return AGENT_ROSTER_PROFILES.map((profile) => ({ ...profile }));\n}\n\nexport function buildAgentRosterEntries(\n assignments: AgentRosterAssignment[],\n): WizardAgentRosterEntry[] {\n const seenNames = new Set<string>();\n\n return assignments.map((assignment) => {\n const name = assignment.name.trim();\n const domain = assignment.domain.trim();\n if (domain.length === 0) {\n throw new Error(\"OrgX agent roster domains must be non-empty.\");\n }\n\n const profile = findAgentRosterProfile(name);\n if (!profile) {\n throw new Error(`Unknown OrgX agent '${assignment.name}'.`);\n }\n\n if (seenNames.has(profile.name)) {\n throw new Error(`OrgX agent '${profile.name}' can only be assigned once.`);\n }\n seenNames.add(profile.name);\n\n return {\n agentType: profile.agentType,\n domain,\n name: profile.name,\n };\n });\n}\n\nfunction toAgentRosterRecord(\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n agents: WizardAgentRosterEntry[],\n): WizardAgentRosterRecord {\n return {\n agents: agents.map((agent) => ({ ...agent })),\n configuredAt: new Date().toISOString(),\n workspaceId: workspace.id,\n workspaceName: workspace.name,\n };\n}\n\nexport function configureAgentRoster(\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n assignments: AgentRosterAssignment[],\n options: { statePath?: string } = {},\n): WizardAgentRosterRecord {\n const agents = buildAgentRosterEntries(assignments);\n if (agents.length === 0) {\n throw new Error(\"Select at least one OrgX agent before saving the roster.\");\n }\n\n const roster = toAgentRosterRecord(workspace, agents);\n updateWizardState(\n (current) => ({\n ...current,\n agentRoster: roster,\n }),\n options.statePath,\n );\n return roster;\n}\n\nexport function ensureDefaultAgentRoster(\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n options: { statePath?: string } = {},\n): WizardAgentRosterRecord {\n const existing = readWizardState(options.statePath)?.agentRoster;\n if (existing?.workspaceId === workspace.id && existing.agents.length > 0) {\n return existing;\n }\n\n const roster = toAgentRosterRecord(workspace, DEFAULT_AGENT_ROSTER);\n updateWizardState(\n (current) => ({\n ...current,\n agentRoster: roster,\n }),\n options.statePath,\n );\n return roster;\n}\n","import { spawnSync } from \"node:child_process\";\n\nimport { readTextIfExists } from \"./fs.js\";\nimport { readOpenClawGatewayPort } from \"../surfaces/openclaw-config.js\";\n\nexport interface OpenClawHealthCheck {\n ok: boolean;\n skipped: boolean;\n method: \"cli\" | \"http\" | \"none\";\n url?: string;\n details: string[];\n error?: string;\n}\n\nfunction trimOutput(value: string | null | undefined): string | undefined {\n const next = value?.trim();\n return next ? next : undefined;\n}\n\nexport async function checkOpenClawHealth(\n configPath?: string,\n): Promise<OpenClawHealthCheck> {\n const rawConfig = configPath ? readTextIfExists(configPath) : null;\n const port = readOpenClawGatewayPort(rawConfig);\n const url = `http://127.0.0.1:${port}/orgx/live`;\n\n const cli = spawnSync(\"openclaw\", [\"gateway\", \"status\"], {\n encoding: \"utf8\",\n timeout: 5_000,\n });\n\n if (!cli.error) {\n const stdout = trimOutput(cli.stdout);\n const stderr = trimOutput(cli.stderr);\n const details = [`gateway port: ${port}`];\n if (stdout) details.push(`cli: ${stdout}`);\n if (stderr) details.push(`cli stderr: ${stderr}`);\n\n if (cli.status === 0) {\n return {\n ok: true,\n skipped: false,\n method: \"cli\",\n url,\n details,\n };\n }\n }\n\n try {\n const response = await fetch(url, {\n redirect: \"manual\",\n signal: AbortSignal.timeout(5_000),\n });\n\n if (response.ok || (response.status >= 300 && response.status < 400)) {\n return {\n ok: true,\n skipped: false,\n method: \"http\",\n url,\n details: [`gateway port: ${port}`, `http status: ${response.status}`],\n };\n }\n\n return {\n ok: false,\n skipped: false,\n method: \"http\",\n url,\n error: `HTTP ${response.status}`,\n details: [`gateway port: ${port}`, `http status: ${response.status}`],\n };\n } catch (error) {\n const cliError = cli.error instanceof Error ? cli.error.message : undefined;\n return {\n ok: false,\n skipped: false,\n method: cliError ? \"none\" : \"http\",\n url,\n error: error instanceof Error ? error.message : String(error),\n details: [\n `gateway port: ${port}`,\n ...(cliError ? [`openclaw cli unavailable: ${cliError}`] : []),\n ],\n };\n }\n}\n","import { ORGX_HOSTED_MCP_HEALTH_URL } from \"../constants.js\";\n\nexport interface HostedMcpHealthCheck {\n ok: boolean;\n skipped: boolean;\n status?: number;\n url: string;\n body?: string;\n error?: string;\n details: string[];\n}\n\nfunction trimBody(value: string): string | undefined {\n const next = value.trim();\n if (!next) return undefined;\n return next.length > 120 ? `${next.slice(0, 117)}...` : next;\n}\n\nexport async function checkHostedMcpHealth(): Promise<HostedMcpHealthCheck> {\n try {\n const response = await fetch(ORGX_HOSTED_MCP_HEALTH_URL, {\n method: \"GET\",\n signal: AbortSignal.timeout(5_000),\n });\n const text = await response.text();\n const body = trimBody(text);\n\n return {\n ok: response.ok,\n skipped: false,\n status: response.status,\n url: ORGX_HOSTED_MCP_HEALTH_URL,\n ...(body ? { body } : {}),\n ...(response.ok ? {} : { error: `HTTP ${response.status}` }),\n details: [\n `http status: ${response.status}`,\n ...(body ? [`body: ${body}`] : []),\n ],\n };\n } catch (error) {\n return {\n ok: false,\n skipped: false,\n url: ORGX_HOSTED_MCP_HEALTH_URL,\n error: error instanceof Error ? error.message : String(error),\n details: [],\n };\n }\n}\n","import { ORGX_HOSTED_MCP_URL } from \"../constants.js\";\nimport {\n resolveOrgxAuth,\n type OrgxAuthSource,\n type ResolveOrgxAuthOptions,\n} from \"./auth.js\";\n\nconst DEFAULT_TOOL_NAME = \"get_setup_status\";\n\nexport interface HostedMcpToolCheck {\n configured: boolean;\n ok: boolean;\n skipped: boolean;\n source: OrgxAuthSource | \"none\";\n toolName: string;\n url: string;\n baseUrl?: string;\n initializeStatus?: number;\n callStatus?: number;\n error?: string;\n details: string[];\n response?: unknown;\n}\n\nexport async function checkHostedMcpToolAccess(\n options: ResolveOrgxAuthOptions = {},\n toolName = DEFAULT_TOOL_NAME,\n): Promise<HostedMcpToolCheck> {\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n return {\n configured: false,\n ok: false,\n skipped: true,\n source: \"none\",\n toolName,\n url: ORGX_HOSTED_MCP_URL,\n error: \"No OrgX API key configured; hosted MCP tool verification skipped.\",\n details: [],\n };\n }\n\n return {\n configured: true,\n ok: false,\n skipped: true,\n source: auth.source,\n toolName,\n url: ORGX_HOSTED_MCP_URL,\n baseUrl: auth.baseUrl,\n error: \"Hosted OrgX MCP uses OAuth; API-key tool verification is skipped.\",\n details: [\n `auth source: ${auth.source}`,\n \"Hosted OrgX MCP connectors complete OAuth during client setup, so the wizard cannot preflight tools with an oxk_ API key.\",\n ],\n };\n}\n","import {\n NPM_REGISTRY_BASE_URL,\n ORGX_WIZARD_NPM_PACKAGE_NAME,\n} from \"../constants.js\";\nimport { isRecord } from \"./fs.js\";\n\nexport interface NpmRegistryCheck {\n ok: boolean;\n skipped: boolean;\n reachable: boolean;\n published: boolean;\n url: string;\n packageName: string;\n version?: string;\n error?: string;\n details: string[];\n}\n\nfunction resolvePackageUrl(packageName: string): string {\n return `${NPM_REGISTRY_BASE_URL}/${encodeURIComponent(packageName)}`;\n}\n\nfunction getLatestVersion(payload: unknown): string | undefined {\n if (!isRecord(payload) || !isRecord(payload[\"dist-tags\"])) {\n return undefined;\n }\n\n const latest = payload[\"dist-tags\"].latest;\n return typeof latest === \"string\" && latest.trim().length > 0 ? latest : undefined;\n}\n\nexport async function checkNpmRegistryHealth(\n packageName: string = ORGX_WIZARD_NPM_PACKAGE_NAME,\n): Promise<NpmRegistryCheck> {\n const url = resolvePackageUrl(packageName);\n\n try {\n const response = await fetch(url, {\n method: \"GET\",\n headers: { Accept: \"application/json\" },\n signal: AbortSignal.timeout(7_000),\n });\n\n const text = await response.text();\n let payload: unknown = text;\n try {\n payload = text.length > 0 ? JSON.parse(text) : null;\n } catch {\n payload = text;\n }\n\n if (response.ok) {\n const version = getLatestVersion(payload);\n return {\n ok: true,\n skipped: false,\n reachable: true,\n published: true,\n url,\n packageName,\n ...(version ? { version } : {}),\n details: [\n `http status: ${response.status}`,\n ...(version ? [`latest version: ${version}`] : [\"latest version: unavailable\"]),\n ],\n };\n }\n\n if (response.status === 404) {\n return {\n ok: true,\n skipped: false,\n reachable: true,\n published: false,\n url,\n packageName,\n error: `${packageName} is not published on npm yet.`,\n details: [`http status: ${response.status}`],\n };\n }\n\n return {\n ok: false,\n skipped: false,\n reachable: false,\n published: false,\n url,\n packageName,\n error: `npm registry returned HTTP ${response.status}`,\n details: [`http status: ${response.status}`],\n };\n } catch (error) {\n return {\n ok: false,\n skipped: false,\n reachable: false,\n published: false,\n url,\n packageName,\n error: error instanceof Error ? error.message : String(error),\n details: [],\n };\n }\n}\n","import { buildOrgxApiUrl, resolveOrgxAuth, type ResolveOrgxAuthOptions } from \"./auth.js\";\nimport { isRecord } from \"./fs.js\";\n\nexport interface OrgxWorkspace {\n id: string;\n name: string;\n description?: string;\n isDefault: boolean;\n createdAt?: string;\n updatedAt?: string;\n}\n\nexport interface CreateWorkspaceInput {\n name: string;\n description?: string;\n}\n\nexport interface SetDefaultWorkspaceInput {\n id: string;\n}\n\nexport interface OrgxWorkspaceClientOptions extends ResolveOrgxAuthOptions {}\n\nasync function requireOrgxAuth(options: OrgxWorkspaceClientOptions = {}) {\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n throw new Error(\n \"No OrgX API key configured. Run `wizard auth login` or `wizard auth set-key <oxk_...>` first.\",\n );\n }\n\n return auth;\n}\n\nasync function parseResponseBody(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction parseWorkspace(value: unknown): OrgxWorkspace | null {\n if (!isRecord(value)) return null;\n\n const id = typeof value.id === \"string\" ? value.id : null;\n const name = typeof value.name === \"string\" ? value.name : null;\n if (!id || !name) return null;\n\n return {\n id,\n name,\n ...(typeof value.description === \"string\" && value.description.trim().length > 0\n ? { description: value.description }\n : {}),\n isDefault: value.is_default === true,\n ...(typeof value.created_at === \"string\" ? { createdAt: value.created_at } : {}),\n ...(typeof value.updated_at === \"string\" ? { updatedAt: value.updated_at } : {}),\n };\n}\n\nfunction sortWorkspaces(workspaces: OrgxWorkspace[]): OrgxWorkspace[] {\n return [...workspaces].sort((left, right) => {\n if (left.isDefault !== right.isDefault) {\n return left.isDefault ? -1 : 1;\n }\n\n const nameCompare = left.name.localeCompare(right.name);\n if (nameCompare !== 0) {\n return nameCompare;\n }\n\n return left.id.localeCompare(right.id);\n });\n}\n\nfunction parseWorkspaceList(payload: unknown): OrgxWorkspace[] {\n if (!isRecord(payload) || !Array.isArray(payload.data)) {\n return [];\n }\n\n return sortWorkspaces(payload.data.map(parseWorkspace).filter((item): item is OrgxWorkspace => item !== null));\n}\n\nfunction parseWorkspaceResponse(payload: unknown): OrgxWorkspace | null {\n if (!isRecord(payload)) return null;\n return parseWorkspace(payload.data);\n}\n\nfunction parseCurrentWorkspaceResponse(payload: unknown): OrgxWorkspace | null {\n if (!isRecord(payload)) return null;\n\n const id = typeof payload.id === \"string\" ? payload.id : null;\n const name = typeof payload.name === \"string\" ? payload.name : null;\n if (!id || !name) return null;\n\n return {\n id,\n name,\n isDefault: true,\n ...(typeof payload.createdAt === \"string\" ? { createdAt: payload.createdAt } : {}),\n };\n}\n\nfunction buildRequestHeaders(apiKey: string): Record<string, string> {\n return {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n}\n\nfunction formatHttpError(status: number, body: unknown): string {\n if (typeof body === \"string\" && body.trim().length > 0) {\n return `HTTP ${status}: ${body}`;\n }\n\n if (isRecord(body) && typeof body.error === \"string\" && body.error.trim().length > 0) {\n return `HTTP ${status}: ${body.error}`;\n }\n\n return `HTTP ${status}`;\n}\n\nexport async function listWorkspaces(\n options: OrgxWorkspaceClientOptions = {},\n): Promise<OrgxWorkspace[]> {\n const auth = await requireOrgxAuth(options);\n const url = buildOrgxApiUrl(\"/entities?type=workspace&limit=100\", auth.baseUrl);\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n },\n signal: AbortSignal.timeout(7_000),\n });\n const body = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new Error(`Failed to list workspaces. ${formatHttpError(response.status, body)}`);\n }\n\n return parseWorkspaceList(body);\n}\n\nexport async function getCurrentWorkspace(\n options: OrgxWorkspaceClientOptions = {},\n): Promise<OrgxWorkspace | null> {\n const auth = await requireOrgxAuth(options);\n const url = buildOrgxApiUrl(\"/v1/workspaces/current\", auth.baseUrl);\n const response = await fetch(url, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n },\n signal: AbortSignal.timeout(7_000),\n });\n const body = await parseResponseBody(response);\n\n if (response.ok) {\n const workspace = parseCurrentWorkspaceResponse(body);\n if (!workspace) {\n throw new Error(\"OrgX returned an unexpected current workspace payload.\");\n }\n return workspace;\n }\n\n if (response.status === 401 || response.status === 404) {\n const workspaces = await listWorkspaces(options);\n return workspaces[0] ?? null;\n }\n\n throw new Error(`Failed to load current workspace. ${formatHttpError(response.status, body)}`);\n}\n\nexport async function createWorkspace(\n input: CreateWorkspaceInput,\n options: OrgxWorkspaceClientOptions = {},\n): Promise<OrgxWorkspace> {\n const name = input.name.trim();\n if (!name) {\n throw new Error(\"Workspace name is required.\");\n }\n\n const auth = await requireOrgxAuth(options);\n const url = buildOrgxApiUrl(\"/entities\", auth.baseUrl);\n const payload = {\n type: \"workspace\",\n name,\n ...(input.description?.trim()\n ? { description: input.description.trim() }\n : {}),\n };\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: buildRequestHeaders(auth.apiKey),\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(7_000),\n });\n const body = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new Error(`Failed to create workspace. ${formatHttpError(response.status, body)}`);\n }\n\n const workspace = parseWorkspaceResponse(body);\n if (!workspace) {\n throw new Error(\"OrgX returned an unexpected workspace payload.\");\n }\n\n return workspace;\n}\n\nasync function updateWorkspace(\n input: SetDefaultWorkspaceInput,\n patch: Record<string, unknown>,\n options: OrgxWorkspaceClientOptions = {},\n): Promise<OrgxWorkspace> {\n const auth = await requireOrgxAuth(options);\n const url = buildOrgxApiUrl(\"/entities\", auth.baseUrl);\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: buildRequestHeaders(auth.apiKey),\n body: JSON.stringify({\n type: \"workspace\",\n id: input.id,\n ...patch,\n }),\n signal: AbortSignal.timeout(7_000),\n });\n const body = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new Error(`Failed to update workspace. ${formatHttpError(response.status, body)}`);\n }\n\n const workspace = parseWorkspaceResponse(body);\n if (!workspace) {\n throw new Error(\"OrgX returned an unexpected workspace update payload.\");\n }\n\n return workspace;\n}\n\nexport async function setDefaultWorkspace(\n input: SetDefaultWorkspaceInput,\n options: OrgxWorkspaceClientOptions = {},\n): Promise<{ changed: boolean; workspace: OrgxWorkspace }> {\n const workspaceId = input.id.trim();\n if (!workspaceId) {\n throw new Error(\"Workspace id is required.\");\n }\n\n const workspaces = await listWorkspaces(options);\n const target = workspaces.find((workspace) => workspace.id === workspaceId);\n if (!target) {\n throw new Error(`Workspace ${workspaceId} was not found in the current OrgX account.`);\n }\n\n if (target.isDefault) {\n return {\n changed: false,\n workspace: target,\n };\n }\n\n const currentDefault = workspaces.find((workspace) => workspace.isDefault);\n if (currentDefault) {\n await updateWorkspace({ id: currentDefault.id }, { is_default: false }, options);\n }\n\n try {\n const updated = await updateWorkspace({ id: workspaceId }, { is_default: true }, options);\n return {\n changed: true,\n workspace: updated,\n };\n } catch (error) {\n if (currentDefault) {\n try {\n await updateWorkspace({ id: currentDefault.id }, { is_default: true }, options);\n } catch {\n // Preserve the original failure while best-effort restoring the prior default.\n }\n }\n throw error;\n }\n}\n","import {\n resolveOrgxAuth,\n type OrgxAuthSource,\n type ResolveOrgxAuthOptions,\n} from \"./auth.js\";\nimport { getCurrentWorkspace, type OrgxWorkspace } from \"./workspaces.js\";\n\nexport interface WorkspaceConnectivityCheck {\n configured: boolean;\n ok: boolean;\n skipped: boolean;\n source: OrgxAuthSource | \"none\";\n baseUrl?: string;\n workspace?: OrgxWorkspace;\n error?: string;\n details: string[];\n}\n\nexport async function checkWorkspaceConnectivity(\n options: ResolveOrgxAuthOptions = {},\n): Promise<WorkspaceConnectivityCheck> {\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n return {\n configured: false,\n ok: false,\n skipped: true,\n source: \"none\",\n error: \"No OrgX API key configured; workspace connectivity check skipped.\",\n details: [],\n };\n }\n\n try {\n const workspace = await getCurrentWorkspace(options);\n if (!workspace) {\n return {\n configured: true,\n ok: false,\n skipped: false,\n source: auth.source,\n baseUrl: auth.baseUrl,\n error: \"OrgX auth resolved, but no accessible workspace was returned.\",\n details: [],\n };\n }\n\n return {\n configured: true,\n ok: true,\n skipped: false,\n source: auth.source,\n baseUrl: auth.baseUrl,\n workspace,\n details: [\n `workspace id: ${workspace.id}`,\n ...(workspace.isDefault ? [\"workspace is marked as default\"] : []),\n ],\n };\n } catch (error) {\n return {\n configured: true,\n ok: false,\n skipped: false,\n source: auth.source,\n baseUrl: auth.baseUrl,\n error: error instanceof Error ? error.message : String(error),\n details: [],\n };\n }\n}\n","import { spawn } from \"node:child_process\";\nimport {\n existsSync,\n mkdirSync,\n mkdtempSync,\n readFileSync,\n readdirSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join, relative } from \"node:path\";\n\nimport {\n CLAUDE_MANAGED_MARKETPLACE_DIR,\n CLAUDE_MANAGED_MARKETPLACE_MANIFEST_PATH,\n CLAUDE_MANAGED_PLUGIN_DIR,\n CODEX_MARKETPLACE_PATH,\n CODEX_ORGX_PLUGIN_DIR,\n CURSOR_DIR,\n CURSOR_MCP_PATH,\n CURSOR_ORGX_PLUGIN_DIR,\n CURSOR_ORGX_RULE_PATH,\n NPM_REGISTRY_BASE_URL,\n} from \"../constants.js\";\nimport { inspectCursorMcpConfig } from \"../surfaces/mcp-config.js\";\nimport { detectSurface } from \"../surfaces/detection.js\";\nimport { CURSOR_RULES_CONTENT } from \"./skills.js\";\nimport { deleteFileIfExists, parseJsonObject, readObject, readTextIfExists } from \"./fs.js\";\n\nexport const DEFAULT_ORGX_PLUGIN_TARGETS = [\"cursor\", \"claude\", \"codex\", \"openclaw\"] as const;\n\nexport type OrgxPluginTarget = typeof DEFAULT_ORGX_PLUGIN_TARGETS[number];\n\nexport interface OrgxPluginStatus {\n target: OrgxPluginTarget;\n available: boolean;\n installed: boolean;\n message: string;\n}\n\nexport interface OrgxPluginMutation {\n target: OrgxPluginTarget;\n changed: boolean;\n message: string;\n}\n\nexport interface OrgxPluginMutationReport {\n results: OrgxPluginMutation[];\n}\n\nexport interface PluginCommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n errorCode?: string;\n}\n\nexport type PluginCommandRunner = (\n command: string,\n args: readonly string[],\n) => Promise<PluginCommandResult>;\n\nexport interface OrgxPluginPaths {\n claudeMarketplaceDir: string;\n claudeMarketplaceManifestPath: string;\n claudePluginDir: string;\n codexMarketplacePath: string;\n codexPluginDir: string;\n cursorPluginDir: string;\n cursorRulePath: string;\n}\n\nexport interface ListOrgxPluginStatusesOptions {\n commandRunner?: PluginCommandRunner;\n paths?: Partial<OrgxPluginPaths>;\n}\n\nexport interface InstallOrgxPluginsOptions {\n targets?: readonly string[];\n commandRunner?: PluginCommandRunner;\n fetchImpl?: typeof fetch;\n paths?: Partial<OrgxPluginPaths>;\n}\n\nexport interface UninstallOrgxPluginsOptions {\n targets?: readonly string[];\n commandRunner?: PluginCommandRunner;\n paths?: Partial<OrgxPluginPaths>;\n}\n\ninterface RepoDirectoryEntry {\n name: string;\n path: string;\n type: \"dir\" | \"file\";\n download_url: string | null;\n}\n\ninterface RemoteRepoFile {\n localPath: string;\n path: string;\n sourceUrl: string;\n}\n\ninterface RepoSyncSpec {\n owner: string;\n repo: string;\n ref: string;\n include: Array<{ localPath: string; remotePath: string }>;\n}\n\nconst ORGX_PLUGIN_GITHUB_OWNER = \"useorgx\";\nconst ORGX_PLUGIN_GITHUB_REF = \"main\";\nconst ORGX_CLAUDE_PLUGIN_NAME = \"orgx-claude-code-plugin\";\nconst ORGX_CLAUDE_MARKETPLACE_NAME = \"orgx-local\";\nconst ORGX_CODEX_PLUGIN_NAME = \"orgx-codex-plugin\";\nconst ORGX_CURSOR_PLUGIN_NAME = \"cursor-plugin\";\nconst ORGX_OPENCLAW_PLUGIN_ID = \"orgx\";\nconst ORGX_OPENCLAW_PLUGIN_PACKAGE_NAME = \"@useorgx/openclaw-plugin\";\n\nconst CLAUDE_PLUGIN_SYNC_SPEC: RepoSyncSpec = {\n owner: ORGX_PLUGIN_GITHUB_OWNER,\n repo: ORGX_CLAUDE_PLUGIN_NAME,\n ref: ORGX_PLUGIN_GITHUB_REF,\n include: [\n { localPath: \".claude-plugin\", remotePath: \".claude-plugin\" },\n { localPath: \"agents\", remotePath: \"agents\" },\n { localPath: \"commands\", remotePath: \"commands\" },\n { localPath: \"hooks\", remotePath: \"hooks\" },\n { localPath: \"lib\", remotePath: \"lib\" },\n { localPath: \"scripts\", remotePath: \"scripts\" },\n { localPath: \"skills\", remotePath: \"skills\" },\n ],\n};\n\nconst CODEX_PLUGIN_SYNC_SPEC: RepoSyncSpec = {\n owner: ORGX_PLUGIN_GITHUB_OWNER,\n repo: ORGX_CODEX_PLUGIN_NAME,\n ref: ORGX_PLUGIN_GITHUB_REF,\n include: [\n { localPath: \".codex-plugin\", remotePath: \".codex-plugin\" },\n { localPath: \".mcp.json\", remotePath: \".mcp.json\" },\n { localPath: \"assets\", remotePath: \"assets\" },\n { localPath: \"skills\", remotePath: \"skills\" },\n ],\n};\n\nconst CURSOR_PLUGIN_SYNC_SPEC: RepoSyncSpec = {\n owner: ORGX_PLUGIN_GITHUB_OWNER,\n repo: ORGX_CURSOR_PLUGIN_NAME,\n ref: ORGX_PLUGIN_GITHUB_REF,\n include: [\n { localPath: \".cursor-plugin\", remotePath: \".cursor-plugin\" },\n { localPath: \".mcp.json\", remotePath: \".mcp.json\" },\n { localPath: \"agents\", remotePath: \"agents\" },\n { localPath: \"assets\", remotePath: \"assets\" },\n { localPath: \"commands\", remotePath: \"commands\" },\n { localPath: \"hooks\", remotePath: \"hooks\" },\n { localPath: \"rules\", remotePath: \"rules\" },\n { localPath: \"scripts\", remotePath: \"scripts\" },\n { localPath: \"skills\", remotePath: \"skills\" },\n ],\n};\n\nfunction defaultPluginPaths(): OrgxPluginPaths {\n return {\n claudeMarketplaceDir: CLAUDE_MANAGED_MARKETPLACE_DIR,\n claudeMarketplaceManifestPath: CLAUDE_MANAGED_MARKETPLACE_MANIFEST_PATH,\n claudePluginDir: CLAUDE_MANAGED_PLUGIN_DIR,\n codexMarketplacePath: CODEX_MARKETPLACE_PATH,\n codexPluginDir: CODEX_ORGX_PLUGIN_DIR,\n cursorPluginDir: CURSOR_ORGX_PLUGIN_DIR,\n cursorRulePath: CURSOR_ORGX_RULE_PATH,\n };\n}\n\nfunction resolvePluginPaths(paths: Partial<OrgxPluginPaths> = {}): OrgxPluginPaths {\n return {\n ...defaultPluginPaths(),\n ...paths,\n };\n}\n\nfunction isRepoDirectoryEntry(value: unknown): value is RepoDirectoryEntry {\n if (!value || typeof value !== \"object\") return false;\n\n const entry = value as Partial<RepoDirectoryEntry>;\n const hasType = entry.type === \"file\" || entry.type === \"dir\";\n return typeof entry.name === \"string\" && typeof entry.path === \"string\" && hasType;\n}\n\nfunction encodeRepoPath(value: string): string {\n return value\n .split(\"/\")\n .filter((segment) => segment.length > 0)\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n}\n\nfunction isLikelyRepoFilePath(path: string): boolean {\n const basename = path.split(\"/\").pop() ?? path;\n return basename.includes(\".\") && !/^\\.[^./]+$/.test(basename);\n}\n\nfunction buildContentsUrl(spec: RepoSyncSpec, path: string): string {\n const encodedPath = encodeRepoPath(path);\n return `https://api.github.com/repos/${spec.owner}/${spec.repo}/contents/${encodedPath}?ref=${encodeURIComponent(spec.ref)}`;\n}\n\nfunction resolveGitHubError(spec: RepoSyncSpec, status: number, path: string): string {\n const repoName = `${spec.owner}/${spec.repo}`;\n if (status === 404) {\n return `Could not find '${path}' in ${repoName}.`;\n }\n\n return `GitHub returned HTTP ${status} while loading '${path}' from ${repoName}.`;\n}\n\nasync function fetchDirectoryEntries(\n spec: RepoSyncSpec,\n path: string,\n fetchImpl: typeof fetch,\n): Promise<RepoDirectoryEntry[]> {\n const response = await fetchImpl(buildContentsUrl(spec, path), {\n headers: {\n Accept: \"application/vnd.github+json\",\n },\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n throw new Error(resolveGitHubError(spec, response.status, path));\n }\n\n const data = await response.json();\n if (!Array.isArray(data)) {\n throw new Error(`Expected '${path}' to be a directory in ${spec.owner}/${spec.repo}.`);\n }\n\n return data\n .filter(isRepoDirectoryEntry)\n .sort((left, right) => left.path.localeCompare(right.path));\n}\n\nasync function fetchRepoFile(\n spec: RepoSyncSpec,\n path: string,\n fetchImpl: typeof fetch,\n): Promise<RepoDirectoryEntry> {\n const response = await fetchImpl(buildContentsUrl(spec, path), {\n headers: {\n Accept: \"application/vnd.github+json\",\n },\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n throw new Error(resolveGitHubError(spec, response.status, path));\n }\n\n const data = await response.json();\n if (!isRepoDirectoryEntry(data) || data.type !== \"file\" || typeof data.download_url !== \"string\") {\n throw new Error(`Expected '${path}' to be a file in ${spec.owner}/${spec.repo}.`);\n }\n\n return data;\n}\n\nasync function listRemoteRepoFiles(\n spec: RepoSyncSpec,\n path: string,\n localPath: string,\n fetchImpl: typeof fetch,\n): Promise<RemoteRepoFile[]> {\n const files: RemoteRepoFile[] = [];\n\n if (isLikelyRepoFilePath(path) && !path.endsWith(\"/\")) {\n const file = await fetchRepoFile(spec, path, fetchImpl);\n files.push({\n localPath,\n path: file.path,\n sourceUrl: file.download_url ?? \"\",\n });\n return files;\n }\n\n const entries = await fetchDirectoryEntries(spec, path, fetchImpl);\n for (const entry of entries) {\n if (entry.type === \"dir\") {\n files.push(\n ...await listRemoteRepoFiles(\n spec,\n entry.path,\n join(localPath, entry.name),\n fetchImpl,\n ),\n );\n continue;\n }\n\n if (!entry.download_url) {\n throw new Error(`GitHub did not provide a download URL for '${entry.path}'.`);\n }\n\n files.push({\n localPath: join(localPath, entry.name),\n path: entry.path,\n sourceUrl: entry.download_url,\n });\n }\n\n return files;\n}\n\nasync function collectRemoteRepoFiles(spec: RepoSyncSpec, fetchImpl: typeof fetch): Promise<RemoteRepoFile[]> {\n const files: RemoteRepoFile[] = [];\n for (const entry of spec.include) {\n const isFile = isLikelyRepoFilePath(entry.remotePath) && !entry.remotePath.endsWith(\"/\");\n if (isFile) {\n const file = await fetchRepoFile(spec, entry.remotePath, fetchImpl);\n files.push({\n localPath: entry.localPath,\n path: file.path,\n sourceUrl: file.download_url ?? \"\",\n });\n continue;\n }\n\n files.push(...await listRemoteRepoFiles(spec, entry.remotePath, entry.localPath, fetchImpl));\n }\n\n return files.sort((left, right) => left.localPath.localeCompare(right.localPath));\n}\n\nasync function fetchRemoteBytes(sourceUrl: string, fetchImpl: typeof fetch): Promise<Buffer> {\n const response = await fetchImpl(sourceUrl, {\n headers: {\n Accept: \"application/octet-stream\",\n },\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n throw new Error(`GitHub returned HTTP ${response.status} while downloading ${sourceUrl}.`);\n }\n\n return Buffer.from(await response.arrayBuffer());\n}\n\nfunction readBytesIfExists(path: string): Buffer | null {\n if (!existsSync(path)) return null;\n\n try {\n if (!statSync(path).isFile()) {\n return null;\n }\n return readFileSync(path);\n } catch (error) {\n const code = typeof error === \"object\" && error && \"code\" in error\n ? String(error.code)\n : undefined;\n if (code === \"ENOENT\" || code === \"ENOTDIR\" || code === \"EISDIR\") {\n return null;\n }\n throw error;\n }\n}\n\nfunction writeBytesIfChanged(path: string, bytes: Buffer): boolean {\n const existing = readBytesIfExists(path);\n if (existing && Buffer.compare(existing, bytes) === 0) {\n return false;\n }\n\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, bytes);\n return true;\n}\n\nfunction removePathIfExists(path: string): boolean {\n if (!existsSync(path)) return false;\n rmSync(path, { force: true, recursive: true });\n return true;\n}\n\nfunction listRelativeFiles(root: string, base = root): string[] {\n if (!existsSync(root)) return [];\n if (!statSync(root).isDirectory()) {\n return [];\n }\n\n const files: string[] = [];\n for (const entry of readdirSync(root, { withFileTypes: true })) {\n const nextPath = join(root, entry.name);\n if (entry.isDirectory()) {\n files.push(...listRelativeFiles(nextPath, base));\n continue;\n }\n if (entry.isFile()) {\n files.push(relative(base, nextPath));\n }\n }\n return files.sort();\n}\n\nfunction pruneEmptyDirectories(root: string, current = root): boolean {\n if (!existsSync(current) || !statSync(current).isDirectory()) {\n return false;\n }\n\n let changed = false;\n for (const entry of readdirSync(current, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n changed = pruneEmptyDirectories(root, join(current, entry.name)) || changed;\n }\n\n if (current !== root && readdirSync(current).length === 0) {\n rmSync(current, { force: true, recursive: true });\n return true;\n }\n\n return changed;\n}\n\nasync function syncManagedRepoTree(\n spec: RepoSyncSpec,\n destinationRoot: string,\n fetchImpl: typeof fetch,\n): Promise<{ changed: boolean; fileCount: number }> {\n const remoteFiles = await collectRemoteRepoFiles(spec, fetchImpl);\n let changed = false;\n const expected = new Set(remoteFiles.map((file) => file.localPath));\n\n if (existsSync(destinationRoot) && !statSync(destinationRoot).isDirectory()) {\n rmSync(destinationRoot, { force: true, recursive: true });\n changed = true;\n }\n\n for (const file of listRelativeFiles(destinationRoot)) {\n if (expected.has(file)) continue;\n rmSync(join(destinationRoot, file), { force: true });\n changed = true;\n }\n changed = pruneEmptyDirectories(destinationRoot) || changed;\n\n for (const file of remoteFiles) {\n const bytes = await fetchRemoteBytes(file.sourceUrl, fetchImpl);\n if (writeBytesIfChanged(join(destinationRoot, file.localPath), bytes)) {\n changed = true;\n }\n }\n\n return { changed, fileCount: remoteFiles.length };\n}\n\nfunction serializeJson(value: unknown): string {\n return `${JSON.stringify(value, null, 2)}\\n`;\n}\n\nfunction writeJsonIfChanged(path: string, value: unknown): boolean {\n const next = serializeJson(value);\n const existing = readTextIfExists(path);\n if (existing === next) {\n return false;\n }\n\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, next, \"utf8\");\n return true;\n}\n\nfunction buildClaudeMarketplaceManifest(): Record<string, unknown> {\n return {\n $schema: \"https://anthropic.com/claude-code/marketplace.schema.json\",\n name: ORGX_CLAUDE_MARKETPLACE_NAME,\n description: \"Local OrgX plugins\",\n owner: {\n name: \"OrgX Team\",\n },\n plugins: [\n {\n name: ORGX_CLAUDE_PLUGIN_NAME,\n description: \"OrgX MCP tools and runtime telemetry hooks for Claude Code.\",\n source: `./plugins/${ORGX_CLAUDE_PLUGIN_NAME}`,\n },\n ],\n };\n}\n\nfunction buildCodexMarketplaceEntry(): Record<string, unknown> {\n return {\n name: ORGX_CODEX_PLUGIN_NAME,\n source: {\n source: \"local\",\n path: `./.codex/plugins/${ORGX_CODEX_PLUGIN_NAME}`,\n },\n policy: {\n installation: \"AVAILABLE\",\n authentication: \"ON_INSTALL\",\n },\n category: \"Productivity\",\n };\n}\n\nfunction readMarketplacePlugins(path: string): {\n document: Record<string, unknown>;\n plugins: Record<string, unknown>[];\n} {\n const document = parseJsonObject(readTextIfExists(path));\n const plugins = Array.isArray(document.plugins)\n ? document.plugins.filter((value): value is Record<string, unknown> => Boolean(value) && typeof value === \"object\" && !Array.isArray(value))\n : [];\n\n return { document, plugins };\n}\n\nfunction upsertCodexMarketplaceEntry(path: string): boolean {\n const { document, plugins } = readMarketplacePlugins(path);\n const nextEntry = buildCodexMarketplaceEntry();\n let replaced = false;\n\n const nextPlugins = plugins.map((plugin) => {\n if (plugin.name !== ORGX_CODEX_PLUGIN_NAME) {\n return plugin;\n }\n replaced = true;\n return nextEntry;\n });\n\n if (!replaced) {\n nextPlugins.push(nextEntry);\n }\n\n const nextDocument: Record<string, unknown> = {\n ...document,\n ...(document.name ? {} : { name: ORGX_CLAUDE_MARKETPLACE_NAME }),\n ...(readObject(document.interface).displayName ? {} : { interface: { displayName: \"OrgX Local\" } }),\n plugins: nextPlugins,\n };\n\n return writeJsonIfChanged(path, nextDocument);\n}\n\nfunction removeCodexMarketplaceEntry(path: string): boolean {\n if (!existsSync(path)) {\n return false;\n }\n\n const { document, plugins } = readMarketplacePlugins(path);\n const nextPlugins = plugins.filter((plugin) => plugin.name !== ORGX_CODEX_PLUGIN_NAME);\n if (nextPlugins.length === plugins.length) {\n return false;\n }\n\n if (nextPlugins.length === 0) {\n rmSync(path, { force: true });\n return true;\n }\n\n return writeJsonIfChanged(path, {\n ...document,\n plugins: nextPlugins,\n });\n}\n\nfunction codexMarketplaceHasOrgxEntry(path: string): boolean {\n const { plugins } = readMarketplacePlugins(path);\n return plugins.some((plugin) => plugin.name === ORGX_CODEX_PLUGIN_NAME);\n}\n\nfunction extractClaudePluginNames(payload: string): string[] {\n try {\n const parsed = JSON.parse(payload);\n if (!Array.isArray(parsed)) return [];\n return parsed.flatMap((entry) => {\n if (typeof entry === \"string\") return [entry];\n if (!entry || typeof entry !== \"object\") return [];\n if (typeof entry.name === \"string\") return [entry.name];\n if (typeof entry.id === \"string\") return [entry.id];\n return [];\n });\n } catch {\n return [];\n }\n}\n\nfunction extractOpenclawPluginIds(payload: string): string[] {\n try {\n const parsed = JSON.parse(payload);\n if (Array.isArray(parsed)) {\n return parsed.flatMap((entry) => {\n if (!entry || typeof entry !== \"object\") return [];\n if (typeof entry.id === \"string\") return [entry.id];\n if (typeof entry.name === \"string\") return [entry.name];\n return [];\n });\n }\n\n const root = readObject(parsed);\n const plugins = Array.isArray(root.plugins) ? root.plugins : [];\n return plugins.flatMap((entry) => {\n if (!entry || typeof entry !== \"object\") return [];\n const item = entry as Record<string, unknown>;\n if (typeof item.id === \"string\") return [item.id];\n if (typeof item.name === \"string\") return [item.name];\n return [];\n });\n } catch {\n return [];\n }\n}\n\nfunction formatCommandFailure(\n command: string,\n args: readonly string[],\n result: PluginCommandResult,\n): string {\n const detail = [result.stderr.trim(), result.stdout.trim()].find((value) => value.length > 0);\n if (result.errorCode === \"ENOENT\") {\n return `Command '${command}' is not available on PATH.`;\n }\n\n return `${command} ${args.join(\" \")} failed${result.exitCode >= 0 ? ` with exit code ${result.exitCode}` : \"\"}${detail ? `: ${detail}` : \".\"}`;\n}\n\nasync function defaultCommandRunner(command: string, args: readonly string[]): Promise<PluginCommandResult> {\n return await new Promise((resolve) => {\n const child = spawn(command, [...args], {\n env: process.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n\n child.stdout.on(\"data\", (chunk) => {\n stdout += chunk.toString();\n });\n child.stderr.on(\"data\", (chunk) => {\n stderr += chunk.toString();\n });\n\n child.on(\"error\", (error) => {\n const errorCode = typeof error === \"object\" && error && \"code\" in error\n ? String(error.code)\n : undefined;\n resolve({\n exitCode: -1,\n stdout,\n stderr,\n ...(errorCode ? { errorCode } : {}),\n });\n });\n\n child.on(\"close\", (code) => {\n resolve({\n exitCode: code ?? -1,\n stdout,\n stderr,\n });\n });\n });\n}\n\nfunction resolveCommandRunner(runner?: PluginCommandRunner): PluginCommandRunner {\n return runner ?? defaultCommandRunner;\n}\n\nasync function commandExists(command: string, runner: PluginCommandRunner): Promise<boolean> {\n const result = await runner(command, [\"--help\"]);\n return result.errorCode !== \"ENOENT\" && result.exitCode !== 127;\n}\n\nasync function getClaudeInstallState(runner: PluginCommandRunner): Promise<{ available: boolean; installed: boolean }> {\n const available = detectSurface(\"claude\").detected || await commandExists(\"claude\", runner);\n if (!available) {\n return { available: false, installed: false };\n }\n\n const result = await runner(\"claude\", [\"plugin\", \"list\", \"--json\"]);\n if (result.exitCode !== 0) {\n return { available: true, installed: false };\n }\n\n return {\n available: true,\n installed: extractClaudePluginNames(result.stdout).includes(ORGX_CLAUDE_PLUGIN_NAME),\n };\n}\n\nasync function getOpenclawInstallState(runner: PluginCommandRunner): Promise<{ available: boolean; installed: boolean }> {\n const available = detectSurface(\"openclaw\").detected || await commandExists(\"openclaw\", runner);\n if (!available) {\n return { available: false, installed: false };\n }\n\n const result = await runner(\"openclaw\", [\"plugins\", \"list\", \"--json\"]);\n if (result.exitCode !== 0) {\n return { available: true, installed: false };\n }\n\n return {\n available: true,\n installed: extractOpenclawPluginIds(result.stdout).includes(ORGX_OPENCLAW_PLUGIN_ID),\n };\n}\n\nfunction cursorPluginManifestPath(paths: OrgxPluginPaths): string {\n return join(paths.cursorPluginDir, \".cursor-plugin\", \"plugin.json\");\n}\n\nfunction cursorPluginMcpPath(paths: OrgxPluginPaths): string {\n return join(paths.cursorPluginDir, \".mcp.json\");\n}\n\nfunction isCursorPluginInstalled(paths: OrgxPluginPaths): boolean {\n return existsSync(cursorPluginManifestPath(paths)) && existsSync(cursorPluginMcpPath(paths));\n}\n\n/**\n * Distinguishes companion-plugin bundle (skills, hooks, rules in ~/.cursor/plugins/local/cursor-plugin)\n * from user-level ~/.cursor/mcp.json wiring only.\n */\nexport interface CursorToolingState {\n /** Managed bundle from `wizard plugins add cursor` (or equivalent). */\n pluginBundleInstalled: boolean;\n /** `orgx-openclaw` MCP entry in user ~/.cursor/mcp.json. */\n mcpLocalOpenclaw: boolean;\n /** Hosted `orgx` → mcp.useorgx.com in user ~/.cursor/mcp.json. */\n mcpHostedOrgx: boolean;\n}\n\nexport function getCursorToolingState(\n options: { paths?: Partial<OrgxPluginPaths>; mcpPath?: string } = {},\n): CursorToolingState {\n const paths = resolvePluginPaths(options.paths);\n const mcpFile: string = options.mcpPath ?? CURSOR_MCP_PATH ?? join(CURSOR_DIR, \"mcp.json\");\n const mcpText = readTextIfExists(mcpFile);\n const inspection = inspectCursorMcpConfig(mcpText);\n return {\n pluginBundleInstalled: isCursorPluginInstalled(paths),\n mcpLocalOpenclaw: inspection.localConfigured === true,\n mcpHostedOrgx: inspection.hostedConfigured === true,\n };\n}\n\nfunction isCursorPluginAvailable(paths: OrgxPluginPaths): boolean {\n return detectSurface(\"cursor\").detected ||\n existsSync(paths.cursorPluginDir) ||\n existsSync(dirname(paths.cursorPluginDir)) ||\n readTextIfExists(paths.cursorRulePath) !== null;\n}\n\nfunction buildCursorStatus(paths: OrgxPluginPaths): OrgxPluginStatus {\n const existingRules = readTextIfExists(paths.cursorRulePath);\n const available = isCursorPluginAvailable(paths);\n const installed = isCursorPluginInstalled(paths);\n\n if (installed) {\n return {\n target: \"cursor\",\n available: true,\n installed: true,\n message: \"Cursor OrgX plugin bundle is installed.\",\n };\n }\n\n if (existingRules === CURSOR_RULES_CONTENT) {\n return {\n target: \"cursor\",\n available: true,\n installed: false,\n message: \"Legacy Cursor OrgX rules are installed; run plugins add cursor to install the full plugin bundle.\",\n };\n }\n\n if (existingRules !== null) {\n return {\n target: \"cursor\",\n available: true,\n installed: false,\n message: \"Cursor rules file exists, but the OrgX plugin bundle is missing.\",\n };\n }\n\n return {\n target: \"cursor\",\n available,\n installed: false,\n message: available\n ? \"Cursor is available and ready for OrgX plugin install.\"\n : \"Cursor was not detected.\",\n };\n}\n\nasync function buildClaudeStatus(paths: OrgxPluginPaths, runner: PluginCommandRunner): Promise<OrgxPluginStatus> {\n const state = await getClaudeInstallState(runner);\n if (state.installed) {\n return {\n target: \"claude\",\n available: true,\n installed: true,\n message: \"Claude Code plugin is installed.\",\n };\n }\n\n if (!state.available) {\n return {\n target: \"claude\",\n available: false,\n installed: false,\n message: \"Claude Code was not detected.\",\n };\n }\n\n const marketplaceExists = existsSync(paths.claudeMarketplaceManifestPath);\n return {\n target: \"claude\",\n available: true,\n installed: false,\n message: marketplaceExists\n ? \"Claude marketplace wrapper exists, but the plugin is not installed.\"\n : \"Claude Code is available and ready for plugin install.\",\n };\n}\n\nfunction buildCodexStatus(paths: OrgxPluginPaths, runner: PluginCommandRunner): Promise<OrgxPluginStatus> {\n return (async () => {\n const available = detectSurface(\"codex\").detected || await commandExists(\"codex\", runner);\n const pluginExists = existsSync(paths.codexPluginDir);\n const marketplaceExists = codexMarketplaceHasOrgxEntry(paths.codexMarketplacePath);\n const installed = pluginExists && marketplaceExists;\n\n if (installed) {\n return {\n target: \"codex\",\n available: true,\n installed: true,\n message: \"Codex plugin files and marketplace entry are present.\",\n };\n }\n\n if (!available) {\n return {\n target: \"codex\",\n available: false,\n installed: false,\n message: \"Codex was not detected.\",\n };\n }\n\n if (pluginExists && !marketplaceExists) {\n return {\n target: \"codex\",\n available: true,\n installed: false,\n message: \"Codex plugin files exist, but the marketplace entry is missing.\",\n };\n }\n\n if (!pluginExists && marketplaceExists) {\n return {\n target: \"codex\",\n available: true,\n installed: false,\n message: \"Codex marketplace entry exists, but plugin files are missing.\",\n };\n }\n\n return {\n target: \"codex\",\n available: true,\n installed: false,\n message: \"Codex is available and ready for plugin install.\",\n };\n })();\n}\n\nasync function buildOpenclawStatus(runner: PluginCommandRunner): Promise<OrgxPluginStatus> {\n const state = await getOpenclawInstallState(runner);\n if (state.installed) {\n return {\n target: \"openclaw\",\n available: true,\n installed: true,\n message: \"OpenClaw plugin is installed.\",\n };\n }\n\n return {\n target: \"openclaw\",\n available: state.available,\n installed: false,\n message: state.available\n ? \"OpenClaw is available and ready for plugin install.\"\n : \"OpenClaw was not detected.\",\n };\n}\n\nasync function resolveOpenclawTarball(fetchImpl: typeof fetch): Promise<{ tarballUrl: string; version: string }> {\n const response = await fetchImpl(\n `${NPM_REGISTRY_BASE_URL}/${encodeURIComponent(ORGX_OPENCLAW_PLUGIN_PACKAGE_NAME)}`,\n {\n headers: {\n Accept: \"application/json\",\n },\n signal: AbortSignal.timeout(10_000),\n },\n );\n\n if (!response.ok) {\n throw new Error(\n `npm registry returned HTTP ${response.status} while resolving ${ORGX_OPENCLAW_PLUGIN_PACKAGE_NAME}.`,\n );\n }\n\n const data = await response.json() as {\n \"dist-tags\"?: Record<string, string>;\n versions?: Record<string, { dist?: { tarball?: string } }>;\n };\n const latestVersion = data[\"dist-tags\"]?.latest;\n const tarballUrl = latestVersion ? data.versions?.[latestVersion]?.dist?.tarball : undefined;\n\n if (!latestVersion || !tarballUrl) {\n throw new Error(`Could not resolve a tarball URL for ${ORGX_OPENCLAW_PLUGIN_PACKAGE_NAME}.`);\n }\n\n return {\n tarballUrl,\n version: latestVersion,\n };\n}\n\nasync function installCursorPlugin(\n paths: OrgxPluginPaths,\n fetchImpl: typeof fetch,\n): Promise<OrgxPluginMutation> {\n if (!isCursorPluginAvailable(paths)) {\n return {\n target: \"cursor\",\n changed: false,\n message: \"Cursor is not available on this machine.\",\n };\n }\n\n const syncResult = await syncManagedRepoTree(CURSOR_PLUGIN_SYNC_SPEC, paths.cursorPluginDir, fetchImpl);\n return {\n target: \"cursor\",\n changed: syncResult.changed,\n message: syncResult.changed\n ? `Synced ${syncResult.fileCount} Cursor plugin files into ${paths.cursorPluginDir}. Reload Cursor to finish loading the plugin.`\n : \"Cursor plugin bundle is already installed and up to date.\",\n };\n}\n\nasync function installClaudePlugin(\n paths: OrgxPluginPaths,\n fetchImpl: typeof fetch,\n runner: PluginCommandRunner,\n): Promise<OrgxPluginMutation> {\n const state = await getClaudeInstallState(runner);\n if (!state.available) {\n return {\n target: \"claude\",\n changed: false,\n message: \"Claude Code is not available on this machine.\",\n };\n }\n\n const syncResult = await syncManagedRepoTree(CLAUDE_PLUGIN_SYNC_SPEC, paths.claudePluginDir, fetchImpl);\n const manifestChanged = writeJsonIfChanged(\n paths.claudeMarketplaceManifestPath,\n buildClaudeMarketplaceManifest(),\n );\n\n const marketplaceAdd = await runner(\"claude\", [\"plugin\", \"marketplace\", \"add\", paths.claudeMarketplaceDir]);\n if (marketplaceAdd.exitCode !== 0) {\n throw new Error(formatCommandFailure(\"claude\", [\"plugin\", \"marketplace\", \"add\", paths.claudeMarketplaceDir], marketplaceAdd));\n }\n\n let installedChanged = false;\n if (!state.installed) {\n const install = await runner(\"claude\", [\n \"plugin\",\n \"install\",\n `${ORGX_CLAUDE_PLUGIN_NAME}@${ORGX_CLAUDE_MARKETPLACE_NAME}`,\n \"--scope\",\n \"user\",\n ]);\n if (install.exitCode !== 0) {\n throw new Error(\n formatCommandFailure(\n \"claude\",\n [\n \"plugin\",\n \"install\",\n `${ORGX_CLAUDE_PLUGIN_NAME}@${ORGX_CLAUDE_MARKETPLACE_NAME}`,\n \"--scope\",\n \"user\",\n ],\n install,\n ),\n );\n }\n installedChanged = true;\n }\n\n const changed = syncResult.changed || manifestChanged || installedChanged;\n return {\n target: \"claude\",\n changed,\n message: changed\n ? `Synced ${syncResult.fileCount} Claude plugin files and ensured the plugin is installed.`\n : \"Claude Code plugin is already installed and up to date.\",\n };\n}\n\nasync function installCodexPlugin(\n paths: OrgxPluginPaths,\n fetchImpl: typeof fetch,\n runner: PluginCommandRunner,\n): Promise<OrgxPluginMutation> {\n const available = detectSurface(\"codex\").detected || await commandExists(\"codex\", runner);\n if (!available) {\n return {\n target: \"codex\",\n changed: false,\n message: \"Codex is not available on this machine.\",\n };\n }\n\n const syncResult = await syncManagedRepoTree(CODEX_PLUGIN_SYNC_SPEC, paths.codexPluginDir, fetchImpl);\n const marketplaceChanged = upsertCodexMarketplaceEntry(paths.codexMarketplacePath);\n const changed = syncResult.changed || marketplaceChanged;\n\n return {\n target: \"codex\",\n changed,\n message: changed\n ? `Synced ${syncResult.fileCount} Codex plugin files and updated the marketplace entry.`\n : \"Codex plugin files and marketplace entry already match the managed OrgX plugin.\",\n };\n}\n\nasync function installOpenclawPlugin(\n fetchImpl: typeof fetch,\n runner: PluginCommandRunner,\n): Promise<OrgxPluginMutation> {\n const state = await getOpenclawInstallState(runner);\n if (!state.available) {\n return {\n target: \"openclaw\",\n changed: false,\n message: \"OpenClaw is not available on this machine.\",\n };\n }\n if (state.installed) {\n return {\n target: \"openclaw\",\n changed: false,\n message: \"OpenClaw plugin is already installed.\",\n };\n }\n\n const { tarballUrl, version } = await resolveOpenclawTarball(fetchImpl);\n const tarballBytes = await fetchRemoteBytes(tarballUrl, fetchImpl);\n const tempRoot = mkdtempSync(join(tmpdir(), \"orgx-wizard-openclaw-\"));\n const archivePath = join(tempRoot, `orgx-openclaw-plugin-${version}.tgz`);\n\n try {\n writeFileSync(archivePath, tarballBytes);\n const install = await runner(\"openclaw\", [\"plugins\", \"install\", archivePath]);\n if (install.exitCode !== 0) {\n throw new Error(\n formatCommandFailure(\"openclaw\", [\"plugins\", \"install\", archivePath], install),\n );\n }\n } finally {\n rmSync(tempRoot, { force: true, recursive: true });\n }\n\n return {\n target: \"openclaw\",\n changed: true,\n message: `Installed OpenClaw plugin ${ORGX_OPENCLAW_PLUGIN_ID} from ${ORGX_OPENCLAW_PLUGIN_PACKAGE_NAME}@${version}.`,\n };\n}\n\nfunction uninstallCursorPlugin(paths: OrgxPluginPaths): OrgxPluginMutation {\n const existingRules = readTextIfExists(paths.cursorRulePath);\n const removedPluginDir = removePathIfExists(paths.cursorPluginDir);\n const removedLegacyRules = existingRules === CURSOR_RULES_CONTENT\n ? deleteFileIfExists(paths.cursorRulePath)\n : false;\n const changed = removedPluginDir || removedLegacyRules;\n return {\n target: \"cursor\",\n changed,\n message: changed\n ? existingRules !== null && existingRules !== CURSOR_RULES_CONTENT\n ? \"Removed the managed Cursor OrgX plugin bundle. Existing Cursor rules differ from managed OrgX rules, so they were left in place.\"\n : \"Removed the managed Cursor OrgX plugin bundle and legacy managed Cursor rules.\"\n : existingRules !== null && existingRules !== CURSOR_RULES_CONTENT\n ? \"Cursor plugin was not installed. Existing Cursor rules differ from managed OrgX rules, so they were left in place.\"\n : \"Cursor plugin was not installed.\",\n };\n}\n\nasync function uninstallClaudePlugin(\n paths: OrgxPluginPaths,\n runner: PluginCommandRunner,\n): Promise<OrgxPluginMutation> {\n const state = await getClaudeInstallState(runner);\n let changed = false;\n\n if (state.available && state.installed) {\n const uninstall = await runner(\"claude\", [\n \"plugin\",\n \"uninstall\",\n ORGX_CLAUDE_PLUGIN_NAME,\n \"--scope\",\n \"user\",\n ]);\n if (uninstall.exitCode !== 0) {\n throw new Error(\n formatCommandFailure(\n \"claude\",\n [\"plugin\", \"uninstall\", ORGX_CLAUDE_PLUGIN_NAME, \"--scope\", \"user\"],\n uninstall,\n ),\n );\n }\n changed = true;\n }\n\n if (state.available) {\n const removeMarketplace = await runner(\"claude\", [\"plugin\", \"marketplace\", \"remove\", ORGX_CLAUDE_MARKETPLACE_NAME]);\n if (removeMarketplace.exitCode === 0) {\n changed = true;\n }\n }\n\n changed = removePathIfExists(paths.claudeMarketplaceDir) || changed;\n\n return {\n target: \"claude\",\n changed,\n message: changed\n ? \"Removed the managed Claude Code plugin and marketplace wrapper.\"\n : \"Claude Code plugin was not installed.\",\n };\n}\n\nasync function uninstallCodexPlugin(paths: OrgxPluginPaths): Promise<OrgxPluginMutation> {\n const removedPluginDir = removePathIfExists(paths.codexPluginDir);\n const removedMarketplaceEntry = removeCodexMarketplaceEntry(paths.codexMarketplacePath);\n const changed = removedPluginDir || removedMarketplaceEntry;\n\n return {\n target: \"codex\",\n changed,\n message: changed\n ? \"Removed the managed Codex plugin files and marketplace entry.\"\n : \"Codex plugin was not installed.\",\n };\n}\n\nasync function uninstallOpenclawPlugin(runner: PluginCommandRunner): Promise<OrgxPluginMutation> {\n const state = await getOpenclawInstallState(runner);\n if (!state.available || !state.installed) {\n return {\n target: \"openclaw\",\n changed: false,\n message: \"OpenClaw plugin was not installed.\",\n };\n }\n\n const uninstall = await runner(\"openclaw\", [\"plugins\", \"uninstall\", ORGX_OPENCLAW_PLUGIN_ID, \"--force\"]);\n if (uninstall.exitCode !== 0) {\n throw new Error(\n formatCommandFailure(\n \"openclaw\",\n [\"plugins\", \"uninstall\", ORGX_OPENCLAW_PLUGIN_ID, \"--force\"],\n uninstall,\n ),\n );\n }\n\n return {\n target: \"openclaw\",\n changed: true,\n message: \"Removed the managed OpenClaw plugin.\",\n };\n}\n\nexport function resolvePluginTargets(requested: readonly string[] = []): OrgxPluginTarget[] {\n if (requested.length === 0 || requested.includes(\"all\")) {\n return [...DEFAULT_ORGX_PLUGIN_TARGETS];\n }\n\n const seen = new Set<OrgxPluginTarget>();\n const normalized: OrgxPluginTarget[] = [];\n\n for (const rawTarget of requested) {\n const target = rawTarget.trim().toLowerCase();\n if (target === \"\" || target === \"all\") continue;\n if (!DEFAULT_ORGX_PLUGIN_TARGETS.includes(target as OrgxPluginTarget)) {\n throw new Error(\n `Unknown plugin target '${rawTarget}'. Supported targets: ${DEFAULT_ORGX_PLUGIN_TARGETS.join(\", \")}.`,\n );\n }\n\n const nextTarget = target as OrgxPluginTarget;\n if (seen.has(nextTarget)) continue;\n seen.add(nextTarget);\n normalized.push(nextTarget);\n }\n\n return normalized;\n}\n\nexport async function listOrgxPluginStatuses(\n options: ListOrgxPluginStatusesOptions = {},\n): Promise<OrgxPluginStatus[]> {\n const paths = resolvePluginPaths(options.paths);\n const runner = resolveCommandRunner(options.commandRunner);\n\n return await Promise.all([\n buildCursorStatus(paths),\n buildClaudeStatus(paths, runner),\n buildCodexStatus(paths, runner),\n buildOpenclawStatus(runner),\n ]);\n}\n\nexport async function installOrgxPlugins(\n options: InstallOrgxPluginsOptions = {},\n): Promise<OrgxPluginMutationReport> {\n const targets = resolvePluginTargets(options.targets ?? []);\n const fetchImpl = options.fetchImpl ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new Error(\"Global fetch is unavailable in this runtime.\");\n }\n\n const paths = resolvePluginPaths(options.paths);\n const runner = resolveCommandRunner(options.commandRunner);\n const results: OrgxPluginMutation[] = [];\n\n for (const target of targets) {\n switch (target) {\n case \"cursor\":\n results.push(await installCursorPlugin(paths, fetchImpl));\n break;\n case \"claude\":\n results.push(await installClaudePlugin(paths, fetchImpl, runner));\n break;\n case \"codex\":\n results.push(await installCodexPlugin(paths, fetchImpl, runner));\n break;\n case \"openclaw\":\n results.push(await installOpenclawPlugin(fetchImpl, runner));\n break;\n }\n }\n\n return { results };\n}\n\nexport async function uninstallOrgxPlugins(\n options: UninstallOrgxPluginsOptions = {},\n): Promise<OrgxPluginMutationReport> {\n const targets = resolvePluginTargets(options.targets ?? []);\n const paths = resolvePluginPaths(options.paths);\n const runner = resolveCommandRunner(options.commandRunner);\n const results: OrgxPluginMutation[] = [];\n\n for (const target of targets) {\n switch (target) {\n case \"cursor\":\n results.push(uninstallCursorPlugin(paths));\n break;\n case \"claude\":\n results.push(await uninstallClaudePlugin(paths, runner));\n break;\n case \"codex\":\n results.push(await uninstallCodexPlugin(paths));\n break;\n case \"openclaw\":\n results.push(await uninstallOpenclawPlugin(runner));\n break;\n }\n }\n\n return { results };\n}\n\nexport function countPluginReportChanges(report: OrgxPluginMutationReport): number {\n return report.results.filter((result) => result.changed).length;\n}\n","import * as TOML from \"@iarna/toml\";\n\nimport {\n ORGX_HOSTED_MCP_KEY,\n ORGX_HOSTED_MCP_URL,\n ORGX_LOCAL_MCP_KEY,\n} from \"../constants.js\";\nimport { isRecord, parseJsonObject, readObject } from \"../lib/fs.js\";\n\ntype JsonObject = Record<string, unknown>;\n\nexport interface McpConfigInspection {\n configured: boolean;\n hostedConfigured?: boolean;\n localConfigured?: boolean;\n details: string[];\n}\n\nfunction cloneConfigCollection(config: JsonObject, key: string): JsonObject {\n return { ...readObject(config[key]) };\n}\n\nfunction removeLegacyScopedMcpServers(servers: JsonObject): boolean {\n const scopedPrefix = `${ORGX_LOCAL_MCP_KEY}-`;\n let updated = false;\n\n for (const key of Object.keys(servers)) {\n if (key === ORGX_LOCAL_MCP_KEY) continue;\n if (!key.startsWith(scopedPrefix)) continue;\n delete servers[key];\n updated = true;\n }\n\n return updated;\n}\n\nfunction stringifyJsonConfig(config: JsonObject): string {\n return `${JSON.stringify(config, null, 2)}\\n`;\n}\n\nfunction clearStdioFields(entry: JsonObject): JsonObject {\n const next = { ...entry };\n delete next.command;\n delete next.args;\n delete next.env;\n return next;\n}\n\nfunction matchHttpEntry(value: unknown, url: string): boolean {\n if (!isRecord(value)) return false;\n return value.type === \"http\" && value.url === url;\n}\n\nfunction matchUrlEntry(value: unknown, url: string): boolean {\n if (!isRecord(value)) return false;\n return value.url === url;\n}\n\nexport function patchClaudeMcpConfig(\n input: string | null,\n localMcpUrl?: string,\n): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n const existingOrgx = readObject(servers[ORGX_HOSTED_MCP_KEY]);\n const existingLocal = readObject(servers[ORGX_LOCAL_MCP_KEY]);\n const hostedUrl = typeof existingOrgx.url === \"string\" ? existingOrgx.url : \"\";\n const hostedType = typeof existingOrgx.type === \"string\" ? existingOrgx.type : \"\";\n const shouldSetHostedOrgx =\n !isRecord(servers[ORGX_HOSTED_MCP_KEY]) ||\n (hostedUrl === localMcpUrl && hostedType === \"http\");\n\n if (shouldSetHostedOrgx) {\n servers[ORGX_HOSTED_MCP_KEY] = {\n ...existingOrgx,\n type: \"http\",\n url: ORGX_HOSTED_MCP_URL,\n description:\n typeof existingOrgx.description === \"string\" &&\n existingOrgx.description.trim().length > 0\n ? existingOrgx.description\n : \"OrgX cloud MCP (OAuth)\",\n };\n }\n\n if (localMcpUrl) {\n servers[ORGX_LOCAL_MCP_KEY] = {\n ...existingLocal,\n type: \"http\",\n url: localMcpUrl,\n description:\n typeof existingLocal.description === \"string\" &&\n existingLocal.description.trim().length > 0\n ? existingLocal.description\n : \"OrgX platform via local OpenClaw plugin (no OAuth)\",\n };\n }\n\n removeLegacyScopedMcpServers(servers);\n\n return stringifyJsonConfig({\n ...current,\n mcpServers: servers,\n });\n}\n\nexport function removeClaudeMcpConfig(\n input: string | null,\n): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n\n if (isRecord(servers[ORGX_LOCAL_MCP_KEY])) {\n delete servers[ORGX_LOCAL_MCP_KEY];\n }\n\n if (matchHttpEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL)) {\n delete servers[ORGX_HOSTED_MCP_KEY];\n }\n\n removeLegacyScopedMcpServers(servers);\n\n return stringifyJsonConfig({\n ...current,\n mcpServers: servers,\n });\n}\n\nexport function inspectClaudeMcpConfig(input: string | null): McpConfigInspection {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n const local = readObject(servers[ORGX_LOCAL_MCP_KEY]);\n const hostedConfigured = matchHttpEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL);\n const localConfigured =\n local.type === \"http\" &&\n typeof local.url === \"string\";\n const localUrl = localConfigured ? String(local.url) : \"missing\";\n\n return {\n configured: hostedConfigured && localConfigured,\n hostedConfigured,\n localConfigured,\n details: [\n `hosted orgx: ${hostedConfigured ? \"ok\" : \"missing\"}`,\n `local orgx-openclaw: ${localUrl}`,\n ],\n };\n}\n\nexport function patchCursorMcpConfig(\n input: string | null,\n localMcpUrl: string,\n): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n const existingLocal = readObject(servers[ORGX_LOCAL_MCP_KEY]);\n\n servers[ORGX_LOCAL_MCP_KEY] = {\n ...clearStdioFields(existingLocal),\n url: localMcpUrl,\n };\n\n removeLegacyScopedMcpServers(servers);\n\n return stringifyJsonConfig({\n ...current,\n mcpServers: servers,\n });\n}\n\nexport function removeCursorMcpConfig(\n input: string | null,\n): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n\n if (isRecord(servers[ORGX_LOCAL_MCP_KEY])) {\n delete servers[ORGX_LOCAL_MCP_KEY];\n }\n\n removeLegacyScopedMcpServers(servers);\n\n return stringifyJsonConfig({\n ...current,\n mcpServers: servers,\n });\n}\n\nexport function inspectCursorMcpConfig(input: string | null): McpConfigInspection {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n const local = readObject(servers[ORGX_LOCAL_MCP_KEY]);\n const localConfigured = typeof local.url === \"string\";\n const localUrl = localConfigured ? String(local.url) : \"missing\";\n const hostedConfigured = matchHttpEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL);\n\n return {\n // Back-compat: \"configured\" on Cursor historically meant the OpenClaw bridge line only.\n configured: localConfigured,\n hostedConfigured,\n localConfigured,\n details: [\n `hosted orgx: ${hostedConfigured ? \"ok\" : \"missing\"}`,\n `local orgx-openclaw: ${localUrl}`,\n ],\n };\n}\n\nexport function patchVscodeMcpConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"servers\");\n const existingHosted = readObject(servers[ORGX_HOSTED_MCP_KEY]);\n\n servers[ORGX_HOSTED_MCP_KEY] = {\n ...clearStdioFields(existingHosted),\n type: \"http\",\n url: ORGX_HOSTED_MCP_URL,\n };\n\n return stringifyJsonConfig({\n ...current,\n servers,\n });\n}\n\nexport function removeVscodeMcpConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"servers\");\n\n if (matchHttpEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL)) {\n delete servers[ORGX_HOSTED_MCP_KEY];\n }\n\n return stringifyJsonConfig({\n ...current,\n servers,\n });\n}\n\nexport function inspectVscodeMcpConfig(input: string | null): McpConfigInspection {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"servers\");\n const hostedConfigured = matchHttpEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL);\n\n return {\n configured: hostedConfigured,\n hostedConfigured,\n details: [`hosted orgx: ${hostedConfigured ? \"ok\" : \"missing\"}`],\n };\n}\n\nfunction matchServerUrlEntry(value: unknown, url: string): boolean {\n if (!isRecord(value)) return false;\n return value.serverUrl === url || value.url === url;\n}\n\nexport function patchWindsurfMcpConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n const existingHosted = readObject(servers[ORGX_HOSTED_MCP_KEY]);\n const nextEntry = clearStdioFields(existingHosted);\n\n delete nextEntry.url;\n servers[ORGX_HOSTED_MCP_KEY] = {\n ...nextEntry,\n serverUrl: ORGX_HOSTED_MCP_URL,\n };\n\n return stringifyJsonConfig({\n ...current,\n mcpServers: servers,\n });\n}\n\nexport function removeWindsurfMcpConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n\n if (matchServerUrlEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL)) {\n delete servers[ORGX_HOSTED_MCP_KEY];\n }\n\n return stringifyJsonConfig({\n ...current,\n mcpServers: servers,\n });\n}\n\nexport function inspectWindsurfMcpConfig(input: string | null): McpConfigInspection {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"mcpServers\");\n const hostedConfigured = matchServerUrlEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL);\n\n return {\n configured: hostedConfigured,\n hostedConfigured,\n details: [`hosted orgx: ${hostedConfigured ? \"ok\" : \"missing\"}`],\n };\n}\n\nexport function patchZedMcpConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"context_servers\");\n const existingHosted = readObject(servers[ORGX_HOSTED_MCP_KEY]);\n\n servers[ORGX_HOSTED_MCP_KEY] = {\n ...clearStdioFields(existingHosted),\n url: ORGX_HOSTED_MCP_URL,\n };\n\n return stringifyJsonConfig({\n ...current,\n context_servers: servers,\n });\n}\n\nexport function removeZedMcpConfig(input: string | null): string {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"context_servers\");\n\n if (matchUrlEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL)) {\n delete servers[ORGX_HOSTED_MCP_KEY];\n }\n\n return stringifyJsonConfig({\n ...current,\n context_servers: servers,\n });\n}\n\nexport function inspectZedMcpConfig(input: string | null): McpConfigInspection {\n const current = parseJsonObject(input);\n const servers = cloneConfigCollection(current, \"context_servers\");\n const hostedConfigured = matchUrlEntry(servers[ORGX_HOSTED_MCP_KEY], ORGX_HOSTED_MCP_URL);\n\n return {\n configured: hostedConfigured,\n hostedConfigured,\n details: [`hosted orgx: ${hostedConfigured ? \"ok\" : \"missing\"}`],\n };\n}\n\nfunction parseTomlDocument(input: string | null): JsonObject {\n if (!input) return {};\n\n try {\n const parsed = TOML.parse(input) as unknown;\n return isRecord(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nfunction stringifyTomlDocument(document: JsonObject): string {\n const rendered = TOML.stringify(document as TOML.JsonMap);\n return rendered.endsWith(\"\\n\") ? rendered : `${rendered}\\n`;\n}\n\nfunction upsertCodexEntry(servers: JsonObject, key: string, url: string): void {\n const current = readObject(servers[key]);\n const next: JsonObject = {\n ...current,\n url,\n };\n delete next.command;\n delete next.args;\n delete next.startup_timeout_sec;\n servers[key] = next;\n}\n\nfunction removeLegacyCodexEntries(servers: JsonObject): boolean {\n const scopedPrefix = `${ORGX_LOCAL_MCP_KEY}-`;\n let updated = false;\n\n for (const key of Object.keys(servers)) {\n if (key === ORGX_LOCAL_MCP_KEY) continue;\n if (!key.startsWith(scopedPrefix)) continue;\n delete servers[key];\n updated = true;\n }\n\n return updated;\n}\n\nexport function patchCodexConfigToml(\n input: string | null,\n localMcpUrl?: string,\n): string {\n const current = parseTomlDocument(input);\n const servers = readObject(current.mcp_servers);\n\n upsertCodexEntry(servers, ORGX_HOSTED_MCP_KEY, ORGX_HOSTED_MCP_URL);\n if (localMcpUrl) {\n upsertCodexEntry(servers, ORGX_LOCAL_MCP_KEY, localMcpUrl);\n }\n removeLegacyCodexEntries(servers);\n\n current.mcp_servers = servers;\n return stringifyTomlDocument(current);\n}\n\nexport function removeCodexConfigToml(\n input: string | null,\n): string {\n const current = parseTomlDocument(input);\n const servers = readObject(current.mcp_servers);\n const hosted = readObject(servers[ORGX_HOSTED_MCP_KEY]);\n\n if (isRecord(servers[ORGX_LOCAL_MCP_KEY])) {\n delete servers[ORGX_LOCAL_MCP_KEY];\n }\n\n if (hosted.url === ORGX_HOSTED_MCP_URL) {\n delete servers[ORGX_HOSTED_MCP_KEY];\n }\n\n removeLegacyCodexEntries(servers);\n current.mcp_servers = servers;\n\n return stringifyTomlDocument(current);\n}\n\nexport function inspectCodexConfigToml(input: string | null): McpConfigInspection {\n const current = parseTomlDocument(input);\n const servers = readObject(current.mcp_servers);\n const hosted = readObject(servers[ORGX_HOSTED_MCP_KEY]);\n const local = readObject(servers[ORGX_LOCAL_MCP_KEY]);\n const hostedConfigured = hosted.url === ORGX_HOSTED_MCP_URL;\n const localConfigured = typeof local.url === \"string\";\n\n return {\n configured: hostedConfigured && localConfigured,\n hostedConfigured,\n localConfigured,\n details: [\n `hosted orgx: ${hostedConfigured ? \"ok\" : \"missing\"}`,\n `local orgx-openclaw: ${localConfigured ? local.url : \"missing\"}`,\n ],\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nimport {\n CHATGPT_APP_PATHS,\n CLAUDE_INSTALL_PATHS,\n CLAUDE_MCP_PATHS,\n CODEX_CONFIG_PATHS,\n CODEX_INSTALL_PATHS,\n CURSOR_INSTALL_PATHS,\n CURSOR_MCP_PATHS,\n OPENCLAW_CONFIG_PATHS,\n OPENCLAW_INSTALL_PATHS,\n VSCODE_INSTALL_PATHS,\n VSCODE_MCP_PATHS,\n WINDSURF_INSTALL_PATHS,\n WINDSURF_MCP_PATHS,\n ZED_INSTALL_PATHS,\n ZED_SETTINGS_PATHS,\n} from \"../constants.js\";\nimport type { SurfaceName } from \"./names.js\";\n\nexport interface SurfaceLocator {\n configPaths: string[];\n installPaths: string[];\n}\n\nexport interface SurfaceDetection {\n detected: boolean;\n preferredPath?: string;\n existingPath?: string;\n evidence: string[];\n}\n\ntype Exists = (path: string) => boolean;\n\nconst SURFACE_LOCATORS: Record<SurfaceName, SurfaceLocator> = {\n claude: {\n configPaths: CLAUDE_MCP_PATHS,\n installPaths: CLAUDE_INSTALL_PATHS,\n },\n cursor: {\n configPaths: CURSOR_MCP_PATHS,\n installPaths: CURSOR_INSTALL_PATHS,\n },\n codex: {\n configPaths: CODEX_CONFIG_PATHS,\n installPaths: CODEX_INSTALL_PATHS,\n },\n openclaw: {\n configPaths: OPENCLAW_CONFIG_PATHS,\n installPaths: OPENCLAW_INSTALL_PATHS,\n },\n vscode: {\n configPaths: VSCODE_MCP_PATHS,\n installPaths: VSCODE_INSTALL_PATHS,\n },\n windsurf: {\n configPaths: WINDSURF_MCP_PATHS,\n installPaths: WINDSURF_INSTALL_PATHS,\n },\n zed: {\n configPaths: ZED_SETTINGS_PATHS,\n installPaths: ZED_INSTALL_PATHS,\n },\n chatgpt: {\n configPaths: [],\n installPaths: CHATGPT_APP_PATHS,\n },\n};\n\nfunction firstExistingPath(paths: string[], exists: Exists): string | undefined {\n return paths.find((path) => exists(path));\n}\n\nfunction buildFallbackInstallPaths(configPaths: string[]): string[] {\n return [...new Set(configPaths.map((path) => dirname(path)))];\n}\n\nexport function getSurfaceLocator(name: SurfaceName): SurfaceLocator {\n return SURFACE_LOCATORS[name];\n}\n\nexport function detectSurface(name: SurfaceName, exists: Exists = existsSync): SurfaceDetection {\n const locator = getSurfaceLocator(name);\n const existingConfigPath = firstExistingPath(locator.configPaths, exists);\n const preferredPath = locator.configPaths[0] ?? locator.installPaths[0];\n const installCandidates = [\n ...locator.installPaths,\n ...buildFallbackInstallPaths(locator.configPaths),\n ];\n const existingInstallPath = firstExistingPath(installCandidates, exists);\n const existingPath = existingConfigPath ?? existingInstallPath;\n const evidence: string[] = [];\n\n if (existingConfigPath) {\n evidence.push(`config found: ${existingConfigPath}`);\n }\n if (existingInstallPath && existingInstallPath !== existingConfigPath) {\n evidence.push(`install marker found: ${existingInstallPath}`);\n }\n if (!existingConfigPath && !existingInstallPath) {\n evidence.push(\"no candidate paths found on disk\");\n }\n\n const detection: SurfaceDetection = {\n detected: Boolean(existingConfigPath || existingInstallPath),\n evidence,\n };\n\n if (preferredPath) {\n detection.preferredPath = preferredPath;\n }\n if (existingPath) {\n detection.existingPath = existingPath;\n }\n\n return detection;\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, readdirSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\n\nimport {\n CLAUDE_ORGX_SKILL_PATH,\n CLAUDE_SKILLS_DIR,\n CURSOR_ORGX_RULE_PATH,\n ORGX_SKILL_EXTENSIONS_DIR,\n ORGX_WIZARD_STATE_PATH,\n} from \"../constants.js\";\nimport { readTextIfExists, writeTextFile } from \"./fs.js\";\nimport type { OrgxPluginTarget } from \"./plugins.js\";\nimport { readWizardState, updateWizardState, type WizardSkillFileRecord } from \"./wizard-state.js\";\n\nexport const DEFAULT_ORGX_SKILL_PACKS = [\n \"morning-briefing\",\n \"initiative-kickoff\",\n \"bulk-create\",\n \"nightly-recap\",\n] as const;\nexport const PLUGIN_MANAGED_SKILL_TARGETS = [\"claude\", \"codex\"] as const;\n\n// Directory entries in the useorgx/skills repo root that are not skill packs.\nconst EXCLUDED_PACK_DIRS = new Set([\".github\", \"scripts\"]);\n\nconst ORGX_SKILLS_OWNER = \"useorgx\";\nconst ORGX_SKILLS_REPO = \"skills\";\nconst ORGX_SKILLS_REF = \"main\";\nconst SKILL_EXTENSION_SCOPES = [\"user\", \"workspace\", \"project\"] as const;\nconst COMPOSED_SKILL_MARKER = \"ORGX SKILL COMPOSED v1\";\nconst EXTENSION_FRONTMATTER_DELIMITER = \"---\";\n\nexport interface ManagedFileWrite {\n label: string;\n path: string;\n changed: boolean;\n reason?: string;\n skipped?: boolean;\n sourceUrl?: string;\n}\n\nexport interface InstalledSkillPack {\n name: string;\n files: ManagedFileWrite[];\n}\n\nexport interface SkillsInstallReport {\n writes: ManagedFileWrite[];\n packs: InstalledSkillPack[];\n notes: string[];\n extensions: SkillExtension[];\n}\n\nexport interface InstallOrgxSkillsOptions {\n skillNames?: readonly string[];\n claudeSkillsDir?: string;\n claudeOrgxSkillPath?: string;\n cursorRulePath?: string;\n force?: boolean;\n fetchImpl?: typeof fetch;\n pluginTargets?: readonly string[];\n ref?: string;\n skillExtensionsDir?: string;\n statePath?: string;\n}\n\nexport interface OrgxSkillsInstallPlan {\n installClaudeSkillBootstrap: boolean;\n installClaudeSkillPacks: boolean;\n notes: string[];\n pluginManagedTargets: OrgxPluginTarget[];\n}\n\ninterface GithubDirectoryEntry {\n name: string;\n path: string;\n type: \"file\" | \"dir\";\n download_url: string | null;\n}\n\ninterface RemoteSkillFile {\n path: string;\n sourceUrl: string;\n}\n\nexport type SkillExtensionScope = \"user\" | \"workspace\" | \"project\";\n\nexport interface SkillExtension {\n content: string;\n enabled: boolean;\n id: string;\n path: string;\n scope: SkillExtensionScope;\n skillId: string;\n title: string;\n}\n\nexport interface AddSkillExtensionOptions {\n content?: string;\n extensionsDir?: string;\n overwrite?: boolean;\n scope?: SkillExtensionScope;\n skillId: string;\n title?: string;\n}\n\nexport interface SkillExtensionWrite {\n changed: boolean;\n created: boolean;\n extension: SkillExtension;\n path: string;\n}\n\nexport interface ListSkillExtensionsOptions {\n extensionsDir?: string;\n}\n\nexport interface SkillStatusReport {\n extensions: SkillExtension[];\n trackedFiles: WizardSkillFileRecord[];\n}\n\nexport interface SkillStatusOptions {\n extensionsDir?: string;\n statePath?: string;\n}\n\nexport const CURSOR_RULES_CONTENT = `# OrgX Rules\n\n- Prefer \\`workspace_id\\` on OrgX tool calls. \\`command_center_id\\` is a deprecated alias and should only be used for backwards compatibility. If both are present, they must match.\n- Treat \\`entity_action\\` with \\`force: true\\` as an escape hatch. It bypasses hierarchy and proof checks, so only use it when the user explicitly wants that behavior and say why.\n- Treat \\`scaffold_initiative continue_on_error\\` as best-effort creation. Use it only when partial scaffolds are acceptable, and follow up on any failed children.\n- Preserve \\`_context\\` when widget or app-rendering flows depend on client, conversation, session, or user metadata. Do not strip or rename it.\n- Prefer \\`list_entities\\` for pending approvals and state inspection before reaching for legacy aliases.\n- Keep hosted OrgX MCP calls distinct from local OpenClaw/plugin surfaces before mutating config or entity state.\n- Artifact proof must use durable sources: GitHub PR/commit/blob permalinks, published/public URLs, or absolute file paths / \\`file://...\\`.\n- Never use OrgX wrapper pages like \\`/live/...\\`, \\`/artifacts/...\\`, or \\`/console/...\\` as proof links. \\`preview_markdown\\` is supplemental, not proof.\n`;\n\nconst CLAUDE_ORGX_SKILL_CONTENT = `---\nname: orgx\ndescription: Use when working against the hosted OrgX MCP server for workspace-scoped planning, entity mutations, progress reporting, and decision handling.\nversion: 1.0.0\nuser-invocable: true\ntags:\n - orchestration\n - productivity\n - workspace\n---\n\n# OrgX Hosted MCP\n\nUse this skill when Claude is connected to the hosted OrgX MCP server at \\`https://mcp.useorgx.com/mcp\\`.\n\nThis skill is for the hosted OrgX tool surface, not the local OpenClaw plugin. Keep those surfaces distinct before mutating config or entity state.\n\n## Operating Rules\n\n- Prefer \\`workspace_id\\` on OrgX tools. \\`command_center_id\\` is a deprecated alias kept for compatibility.\n- Treat \\`entity_action\\` with \\`force: true\\` as a deliberate override only. It bypasses hierarchy and proof-chain checks.\n- Treat \\`scaffold_initiative continue_on_error\\` as best-effort scaffolding. Use it only when partial creation is acceptable and inspect failures afterward.\n- Preserve \\`_context\\` when widget or app rendering depends on client, conversation, session, or user metadata.\n- Prefer \\`list_entities\\` over older aliases when you need pending decisions, blockers, or entity state.\n- Artifact proof must use durable sources: GitHub PR/commit/blob permalinks, published/public URLs, or absolute file paths / \\`file://...\\`.\n- Never use OrgX wrapper pages like \\`/live/...\\`, \\`/artifacts/...\\`, or \\`/console/...\\` as proof links. \\`preview_markdown\\` is supporting context only.\n\n## Suggested Skill Packs\n\nInstall and use these packs alongside this base skill:\n\n- \\`morning-briefing\\`\n- \\`initiative-kickoff\\`\n- \\`bulk-create\\`\n- \\`nightly-recap\\`\n\n## Suggested Workflow\n\n1. Inspect state with \\`mcp__orgx__list_entities\\`, \\`mcp__orgx__get_initiative_pulse\\`, or the relevant workspace-scoped read tool.\n2. Mutate state with the narrowest tool that matches the task.\n3. When you need a hard override, explain why before using \\`force: true\\`.\n4. When you scaffold, decide up front whether \\`continue_on_error\\` is acceptable.\n5. Carry \\`_context\\` through any widget-producing flows so the UI can render and resume correctly.\n`;\n\nfunction sha256(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\");\n}\n\nfunction normalizeSkillId(value: string): string {\n const normalized = value.trim().toLowerCase();\n if (!/^[a-z0-9][a-z0-9._-]*$/.test(normalized)) {\n throw new Error(\n \"Skill id must start with a letter or number and only contain letters, numbers, '.', '_' or '-'.\",\n );\n }\n return normalized;\n}\n\nfunction normalizeSkillExtensionScope(value: string | undefined): SkillExtensionScope {\n const normalized = (value ?? \"user\").trim().toLowerCase();\n if (!SKILL_EXTENSION_SCOPES.includes(normalized as SkillExtensionScope)) {\n throw new Error(\"Skill extension scope must be one of: user, workspace, project.\");\n }\n return normalized as SkillExtensionScope;\n}\n\nfunction defaultExtensionTitle(skillId: string, scope: SkillExtensionScope): string {\n const prefix = scope === \"user\" ? \"Personal\" : scope === \"workspace\" ? \"Workspace\" : \"Project\";\n return `${prefix} ${skillId} behavior`;\n}\n\nfunction extensionFilePath(\n skillId: string,\n scope: SkillExtensionScope,\n extensionsDir = ORGX_SKILL_EXTENSIONS_DIR,\n): string {\n return join(extensionsDir, `${scope}.${skillId}.md`);\n}\n\nfunction extensionTemplate(input: {\n skillId: string;\n scope: SkillExtensionScope;\n title: string;\n content?: string;\n}): string {\n const body = input.content?.trim()\n ? input.content.trim()\n : [\n `# ${input.title}`,\n \"\",\n \"- Add your custom behavior here.\",\n \"- These instructions are appended after the OrgX-managed core skill when the wizard syncs skills.\",\n ].join(\"\\n\");\n\n return [\n EXTENSION_FRONTMATTER_DELIMITER,\n `skill: ${input.skillId}`,\n `scope: ${input.scope}`,\n \"enabled: true\",\n `title: ${input.title}`,\n EXTENSION_FRONTMATTER_DELIMITER,\n \"\",\n body,\n \"\",\n ].join(\"\\n\");\n}\n\nfunction parseFrontmatter(content: string): {\n body: string;\n data: Record<string, string>;\n} {\n if (!content.startsWith(`${EXTENSION_FRONTMATTER_DELIMITER}\\n`)) {\n return { body: content, data: {} };\n }\n\n const closeIndex = content.indexOf(`\\n${EXTENSION_FRONTMATTER_DELIMITER}\\n`, 4);\n if (closeIndex === -1) {\n return { body: content, data: {} };\n }\n\n const raw = content.slice(4, closeIndex);\n const body = content.slice(closeIndex + 5);\n const data: Record<string, string> = {};\n for (const line of raw.split(\"\\n\")) {\n const index = line.indexOf(\":\");\n if (index === -1) {\n continue;\n }\n const key = line.slice(0, index).trim();\n const value = line.slice(index + 1).trim();\n if (key) {\n data[key] = value;\n }\n }\n\n return { body, data };\n}\n\nfunction serializeFrontmatter(data: Record<string, string>, body: string): string {\n return [\n EXTENSION_FRONTMATTER_DELIMITER,\n ...Object.entries(data).map(([key, value]) => `${key}: ${value}`),\n EXTENSION_FRONTMATTER_DELIMITER,\n \"\",\n body.trimEnd(),\n \"\",\n ].join(\"\\n\");\n}\n\nfunction parseSkillExtension(path: string, content: string): SkillExtension | null {\n const fallbackId = basename(path, \".md\");\n const fallbackParts = fallbackId.split(\".\");\n const fallbackScope = normalizeSkillExtensionScope(\n SKILL_EXTENSION_SCOPES.includes(fallbackParts[0] as SkillExtensionScope)\n ? fallbackParts.shift()\n : \"user\",\n );\n const fallbackSkillId = normalizeSkillId(fallbackParts.join(\".\") || fallbackId);\n const parsed = parseFrontmatter(content);\n const skillId = normalizeSkillId(parsed.data.skill || fallbackSkillId);\n const scope = normalizeSkillExtensionScope(parsed.data.scope || fallbackScope);\n const title = parsed.data.title?.trim() || defaultExtensionTitle(skillId, scope);\n\n return {\n content: parsed.body.trim(),\n enabled: parsed.data.enabled?.trim().toLowerCase() !== \"false\",\n id: `${scope}.${skillId}`,\n path,\n scope,\n skillId,\n title,\n };\n}\n\nexport function listSkillExtensions(\n options: ListSkillExtensionsOptions = {},\n): SkillExtension[] {\n const extensionsDir = options.extensionsDir ?? ORGX_SKILL_EXTENSIONS_DIR;\n if (!existsSync(extensionsDir)) {\n return [];\n }\n\n return readdirSync(extensionsDir, { withFileTypes: true })\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".md\"))\n .map((entry) => {\n const path = join(extensionsDir, entry.name);\n const content = readTextIfExists(path);\n return content === null ? null : parseSkillExtension(path, content);\n })\n .filter((entry): entry is SkillExtension => Boolean(entry))\n .sort((left, right) => left.id.localeCompare(right.id));\n}\n\nexport function addSkillExtension(\n options: AddSkillExtensionOptions,\n): SkillExtensionWrite {\n const skillId = normalizeSkillId(options.skillId);\n const scope = normalizeSkillExtensionScope(options.scope);\n const path = extensionFilePath(skillId, scope, options.extensionsDir);\n const title = options.title?.trim() || defaultExtensionTitle(skillId, scope);\n const existing = readTextIfExists(path);\n\n if (existing !== null && options.overwrite !== true) {\n const extension = parseSkillExtension(path, existing);\n if (!extension) {\n throw new Error(`Could not parse existing skill extension at ${path}.`);\n }\n\n return {\n changed: false,\n created: false,\n extension,\n path,\n };\n }\n\n const nextContent = extensionTemplate({\n scope,\n skillId,\n title,\n ...(options.content !== undefined ? { content: options.content } : {}),\n });\n writeTextFile(path, nextContent);\n const extension = parseSkillExtension(path, nextContent);\n if (!extension) {\n throw new Error(`Could not parse newly written skill extension at ${path}.`);\n }\n\n return {\n changed: existing !== nextContent,\n created: existing === null,\n extension,\n path,\n };\n}\n\nexport function setSkillExtensionEnabled(input: {\n enabled: boolean;\n extensionsDir?: string;\n scope?: SkillExtensionScope;\n skillId: string;\n}): SkillExtensionWrite {\n const skillId = normalizeSkillId(input.skillId);\n const scope = normalizeSkillExtensionScope(input.scope);\n const path = extensionFilePath(skillId, scope, input.extensionsDir);\n const existing = readTextIfExists(path);\n if (existing === null) {\n if (!input.enabled) {\n throw new Error(`No ${scope} extension exists for ${skillId}.`);\n }\n\n return addSkillExtension({\n scope,\n skillId,\n ...(input.extensionsDir !== undefined ? { extensionsDir: input.extensionsDir } : {}),\n });\n }\n\n const parsed = parseFrontmatter(existing);\n const data = {\n skill: parsed.data.skill || skillId,\n scope: parsed.data.scope || scope,\n enabled: input.enabled ? \"true\" : \"false\",\n title: parsed.data.title || defaultExtensionTitle(skillId, scope),\n };\n const nextContent = serializeFrontmatter(data, parsed.body);\n if (nextContent !== existing) {\n writeTextFile(path, nextContent);\n }\n const extension = parseSkillExtension(path, nextContent);\n if (!extension) {\n throw new Error(`Could not parse skill extension at ${path}.`);\n }\n\n return {\n changed: nextContent !== existing,\n created: false,\n extension,\n path,\n };\n}\n\nfunction composeSkillContent(\n skillId: string,\n coreContent: string,\n extensions: readonly SkillExtension[],\n): string {\n const enabled = extensions.filter((extension) => extension.enabled && extension.skillId === skillId);\n if (enabled.length === 0) {\n return coreContent;\n }\n\n const extensionBlocks = enabled.map((extension) => [\n `<!-- extension: ${extension.id} -->`,\n extension.content.trim(),\n ].join(\"\\n\"));\n\n return [\n `<!-- ${COMPOSED_SKILL_MARKER}`,\n `skill: ${skillId}`,\n `core-sha256: ${sha256(coreContent)}`,\n \"generated: true\",\n `edit-with: orgx-wizard skills extensions edit ${skillId}`,\n \"-->\",\n `<!-- ORGX CORE BEGIN ${skillId} -->`,\n coreContent.trimEnd(),\n `<!-- ORGX CORE END ${skillId} -->`,\n \"\",\n \"<!-- ORGX USER EXTENSIONS BEGIN -->\",\n ...extensionBlocks,\n \"<!-- ORGX USER EXTENSIONS END -->\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction encodeRepoPath(value: string): string {\n return value\n .split(\"/\")\n .filter((segment) => segment.length > 0)\n .map((segment) => encodeURIComponent(segment))\n .join(\"/\");\n}\n\nfunction buildContentsUrl(path: string, ref: string): string {\n const encodedPath = encodeRepoPath(path);\n return `https://api.github.com/repos/${ORGX_SKILLS_OWNER}/${ORGX_SKILLS_REPO}/contents/${encodedPath}?ref=${encodeURIComponent(ref)}`;\n}\n\nfunction resolveGitHubError(status: number, path: string): string {\n if (status === 404) {\n return `OrgX skill pack '${path}' was not found in ${ORGX_SKILLS_OWNER}/${ORGX_SKILLS_REPO}.`;\n }\n\n return `GitHub returned HTTP ${status} while loading '${path}' from ${ORGX_SKILLS_OWNER}/${ORGX_SKILLS_REPO}.`;\n}\n\nasync function readResponseText(response: Response): Promise<string> {\n return response.text();\n}\n\nasync function fetchDirectoryEntries(\n path: string,\n fetchImpl: typeof fetch,\n ref: string,\n): Promise<GithubDirectoryEntry[]> {\n const response = await fetchImpl(buildContentsUrl(path, ref), {\n headers: {\n Accept: \"application/vnd.github+json\",\n },\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n throw new Error(resolveGitHubError(response.status, path));\n }\n\n const data = await response.json();\n if (!Array.isArray(data)) {\n throw new Error(`Expected '${path}' to be a directory in ${ORGX_SKILLS_OWNER}/${ORGX_SKILLS_REPO}.`);\n }\n\n return data\n .filter((entry): entry is GithubDirectoryEntry => {\n if (!entry || typeof entry !== \"object\") return false;\n return entry.type === \"file\" || entry.type === \"dir\";\n })\n .sort((left, right) => left.path.localeCompare(right.path));\n}\n\nasync function listRemoteSkillFiles(\n path: string,\n fetchImpl: typeof fetch,\n ref: string,\n): Promise<RemoteSkillFile[]> {\n const entries = await fetchDirectoryEntries(path, fetchImpl, ref);\n const files: RemoteSkillFile[] = [];\n\n for (const entry of entries) {\n if (entry.type === \"dir\") {\n files.push(...await listRemoteSkillFiles(entry.path, fetchImpl, ref));\n continue;\n }\n\n if (!entry.download_url) {\n throw new Error(`GitHub did not provide a download URL for '${entry.path}'.`);\n }\n\n files.push({\n path: entry.path,\n sourceUrl: entry.download_url,\n });\n }\n\n return files;\n}\n\nasync function fetchRemoteText(sourceUrl: string, fetchImpl: typeof fetch): Promise<string> {\n const response = await fetchImpl(sourceUrl, {\n headers: {\n Accept: \"text/plain\",\n },\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!response.ok) {\n throw new Error(`GitHub returned HTTP ${response.status} while downloading ${sourceUrl}.`);\n }\n\n return readResponseText(response);\n}\n\nfunction getTrackedSkillFile(\n records: readonly WizardSkillFileRecord[],\n path: string,\n): WizardSkillFileRecord | undefined {\n return records.find((record) => record.path === path);\n}\n\nfunction writeManagedFile(\n path: string,\n content: string,\n label: string,\n sourceUrl?: string,\n tracking?: {\n coreContent?: string;\n force?: boolean;\n records: readonly WizardSkillFileRecord[];\n skillId: string;\n stagedRecords: Map<string, WizardSkillFileRecord>;\n },\n): ManagedFileWrite {\n const existing = readTextIfExists(path);\n const tracked = tracking ? getTrackedSkillFile(tracking.records, path) : undefined;\n if (\n tracking &&\n existing !== null &&\n tracked &&\n sha256(existing) !== tracked.contentSha256 &&\n tracking.force !== true\n ) {\n return {\n label,\n path,\n changed: false,\n skipped: true,\n reason: \"manual edits detected; move them into a skill extension or rerun with --force\",\n ...(sourceUrl ? { sourceUrl } : {}),\n };\n }\n\n const changed = existing !== content;\n\n if (changed) {\n writeTextFile(path, content);\n }\n\n if (tracking) {\n tracking.stagedRecords.set(path, {\n contentSha256: sha256(content),\n ...(tracking.coreContent ? { coreSha256: sha256(tracking.coreContent) } : {}),\n path,\n skillId: tracking.skillId,\n updatedAt: new Date().toISOString(),\n });\n }\n\n return {\n label,\n path,\n changed,\n ...(sourceUrl ? { sourceUrl } : {}),\n };\n}\n\nexport function resolveSkillPackNames(\n requested: readonly string[] = [],\n): string[] {\n if (requested.length === 0 || requested.includes(\"all\")) {\n return [...DEFAULT_ORGX_SKILL_PACKS];\n }\n\n const seen = new Set<string>();\n const normalized: string[] = [];\n\n for (const name of requested) {\n const next = name.trim();\n if (!next || seen.has(next)) {\n continue;\n }\n seen.add(next);\n normalized.push(next);\n }\n\n return normalized;\n}\n\nexport function resolvePluginManagedSkillTargets(\n requested: readonly string[] = [],\n): OrgxPluginTarget[] {\n const seen = new Set<OrgxPluginTarget>();\n const targets: OrgxPluginTarget[] = [];\n\n for (const rawTarget of requested) {\n const target = rawTarget.trim().toLowerCase() as OrgxPluginTarget;\n if (!PLUGIN_MANAGED_SKILL_TARGETS.includes(target as typeof PLUGIN_MANAGED_SKILL_TARGETS[number])) {\n continue;\n }\n if (seen.has(target)) {\n continue;\n }\n\n seen.add(target);\n targets.push(target);\n }\n\n return targets;\n}\n\nexport function planOrgxSkillsInstall(\n pluginTargets: readonly string[] = [],\n): OrgxSkillsInstallPlan {\n const pluginManagedTargets = resolvePluginManagedSkillTargets(pluginTargets);\n const managesClaudeSkills = pluginManagedTargets.includes(\"claude\");\n const notes: string[] = [];\n\n if (managesClaudeSkills) {\n notes.push(\n \"Claude Code plugin is installed, so the wizard skipped overlapping standalone Claude OrgX skill files and Claude skill-pack sync.\",\n );\n }\n if (pluginManagedTargets.includes(\"codex\")) {\n notes.push(\n \"Codex companion plugin bundles its own OrgX skills, so `wizard skills add` only manages standalone editor assets outside Codex.\",\n );\n }\n\n return {\n installClaudeSkillBootstrap: !managesClaudeSkills,\n installClaudeSkillPacks: !managesClaudeSkills,\n notes,\n pluginManagedTargets,\n };\n}\n\nasync function fetchAvailablePackNames(\n fetchImpl: typeof fetch,\n ref: string,\n): Promise<string[]> {\n const entries = await fetchDirectoryEntries(\"\", fetchImpl, ref);\n return entries\n .filter((e) => e.type === \"dir\" && !EXCLUDED_PACK_DIRS.has(e.name))\n .map((e) => e.name);\n}\n\nasync function installSkillPack(\n skillName: string,\n claudeSkillsDir: string,\n fetchImpl: typeof fetch,\n ref: string,\n tracking: {\n extensions: readonly SkillExtension[];\n force?: boolean;\n records: readonly WizardSkillFileRecord[];\n stagedRecords: Map<string, WizardSkillFileRecord>;\n },\n): Promise<InstalledSkillPack> {\n const rootPath = skillName;\n const files = await listRemoteSkillFiles(rootPath, fetchImpl, ref);\n const writes: ManagedFileWrite[] = [];\n\n for (const file of files) {\n const coreContent = await fetchRemoteText(file.sourceUrl, fetchImpl);\n const relativePath = file.path.slice(`${rootPath}/`.length);\n const content = relativePath === \"SKILL.md\"\n ? composeSkillContent(skillName, coreContent, tracking.extensions)\n : coreContent;\n writes.push(\n writeManagedFile(\n join(claudeSkillsDir, skillName, relativePath),\n content,\n `${skillName}/${relativePath}`,\n file.sourceUrl,\n {\n coreContent,\n records: tracking.records,\n skillId: skillName,\n stagedRecords: tracking.stagedRecords,\n ...(tracking.force !== undefined ? { force: tracking.force } : {}),\n },\n ),\n );\n }\n\n return {\n name: skillName,\n files: writes,\n };\n}\n\nexport async function installOrgxSkills(\n options: InstallOrgxSkillsOptions = {},\n): Promise<SkillsInstallReport> {\n const fetchImpl = options.fetchImpl ?? globalThis.fetch;\n if (!fetchImpl) {\n throw new Error(\"Global fetch is unavailable in this runtime.\");\n }\n\n const ref = options.ref ?? ORGX_SKILLS_REF;\n const claudeSkillsDir = options.claudeSkillsDir ?? CLAUDE_SKILLS_DIR;\n const claudeOrgxSkillPath = options.claudeOrgxSkillPath ?? CLAUDE_ORGX_SKILL_PATH;\n const cursorRulePath = options.cursorRulePath ?? CURSOR_ORGX_RULE_PATH;\n const statePath = options.statePath ?? ORGX_WIZARD_STATE_PATH;\n const extensions = listSkillExtensions(\n options.skillExtensionsDir !== undefined ? { extensionsDir: options.skillExtensionsDir } : {},\n );\n const enabledExtensions = extensions.filter((extension) => extension.enabled);\n const trackedRecords = readWizardState(statePath)?.skillFiles?.files ?? [];\n const stagedRecords = new Map<string, WizardSkillFileRecord>();\n const plan = planOrgxSkillsInstall(options.pluginTargets ?? []);\n const requestedNames = options.skillNames ?? [];\n let skillNames: string[];\n if (requestedNames.length === 0 || requestedNames.includes(\"all\")) {\n try {\n skillNames = await fetchAvailablePackNames(fetchImpl, ref);\n } catch {\n skillNames = [...DEFAULT_ORGX_SKILL_PACKS];\n }\n } else {\n skillNames = resolveSkillPackNames(requestedNames);\n }\n\n const writes: ManagedFileWrite[] = [\n writeManagedFile(\n cursorRulePath,\n composeSkillContent(\"cursor-rules\", CURSOR_RULES_CONTENT, extensions),\n \"cursor-rules\",\n undefined,\n {\n coreContent: CURSOR_RULES_CONTENT,\n records: trackedRecords,\n skillId: \"cursor-rules\",\n stagedRecords,\n ...(options.force !== undefined ? { force: options.force } : {}),\n },\n ),\n ];\n if (plan.installClaudeSkillBootstrap) {\n writes.push(\n writeManagedFile(\n claudeOrgxSkillPath,\n composeSkillContent(\"orgx\", CLAUDE_ORGX_SKILL_CONTENT, extensions),\n \"claude-orgx-skill\",\n undefined,\n {\n coreContent: CLAUDE_ORGX_SKILL_CONTENT,\n records: trackedRecords,\n skillId: \"orgx\",\n stagedRecords,\n ...(options.force !== undefined ? { force: options.force } : {}),\n },\n ),\n );\n }\n\n const packs: InstalledSkillPack[] = [];\n if (plan.installClaudeSkillPacks) {\n for (const skillName of skillNames) {\n packs.push(await installSkillPack(skillName, claudeSkillsDir, fetchImpl, ref, {\n extensions,\n records: trackedRecords,\n stagedRecords,\n ...(options.force !== undefined ? { force: options.force } : {}),\n }));\n }\n }\n\n if (stagedRecords.size > 0) {\n updateWizardState((current) => {\n const previousFiles = current.skillFiles?.files ?? [];\n const nextFiles = new Map<string, WizardSkillFileRecord>();\n for (const record of previousFiles) {\n nextFiles.set(record.path, record);\n }\n for (const record of stagedRecords.values()) {\n nextFiles.set(record.path, record);\n }\n\n return {\n ...current,\n skillFiles: {\n files: [...nextFiles.values()].sort((left, right) => left.path.localeCompare(right.path)),\n updatedAt: new Date().toISOString(),\n },\n };\n }, statePath);\n }\n\n const notes = [...plan.notes];\n if (enabledExtensions.length > 0) {\n notes.push(\n `Applied ${enabledExtensions.length} enabled OrgX skill extension${enabledExtensions.length === 1 ? \"\" : \"s\"} while syncing skills/rules.`,\n );\n }\n if (\n writes.some((write) => write.skipped) ||\n packs.some((pack) => pack.files.some((file) => file.skipped))\n ) {\n notes.push(\"Some generated skill files were skipped because local manual edits were detected.\");\n }\n\n return {\n extensions,\n notes,\n writes,\n packs,\n };\n}\n\nexport function getSkillStatus(\n options: SkillStatusOptions = {},\n): SkillStatusReport {\n const state = readWizardState(options.statePath ?? ORGX_WIZARD_STATE_PATH);\n return {\n extensions: listSkillExtensions(\n options.extensionsDir !== undefined ? { extensionsDir: options.extensionsDir } : {},\n ),\n trackedFiles: state?.skillFiles?.files ?? [],\n };\n}\n","import {\n checkOrgxAuth,\n peekResolvedOrgxAuth,\n resolveOrgxAuth,\n type OrgxAuthHint,\n type OrgxAuthCheckResult,\n} from \"../lib/auth.js\";\nimport { checkOpenClawHealth, type OpenClawHealthCheck } from \"../lib/openclaw-health.js\";\nimport { checkHostedMcpHealth, type HostedMcpHealthCheck } from \"../lib/hosted-mcp-health.js\";\nimport {\n checkHostedMcpToolAccess,\n type HostedMcpToolCheck,\n} from \"../lib/hosted-mcp-tool-check.js\";\nimport { checkNpmRegistryHealth, type NpmRegistryCheck } from \"../lib/npm-registry-health.js\";\nimport {\n checkWorkspaceConnectivity,\n type WorkspaceConnectivityCheck,\n} from \"../lib/workspace-connectivity.js\";\nimport { getCursorToolingState } from \"../lib/plugins.js\";\nimport { readTextIfExists, writeTextFile } from \"../lib/fs.js\";\nimport { ORGX_HOSTED_MCP_URL } from \"../constants.js\";\nimport {\n inspectClaudeMcpConfig,\n inspectCodexConfigToml,\n inspectCursorMcpConfig,\n inspectVscodeMcpConfig,\n inspectWindsurfMcpConfig,\n inspectZedMcpConfig,\n patchClaudeMcpConfig,\n patchCodexConfigToml,\n patchCursorMcpConfig,\n patchVscodeMcpConfig,\n patchWindsurfMcpConfig,\n patchZedMcpConfig,\n removeClaudeMcpConfig,\n removeCodexConfigToml,\n removeCursorMcpConfig,\n removeVscodeMcpConfig,\n removeWindsurfMcpConfig,\n removeZedMcpConfig,\n} from \"./mcp-config.js\";\nimport {\n buildLocalMcpUrl,\n inspectOpenClawConfig,\n patchOpenClawConfig,\n removeOpenClawConfig,\n} from \"./openclaw-config.js\";\nimport {\n AUTOMATED_SURFACE_NAMES,\n MCP_SURFACE_NAMES,\n SURFACE_NAMES,\n type SurfaceMode,\n type SurfaceName,\n} from \"./names.js\";\nimport {\n detectSurface,\n getSurfaceLocator,\n type SurfaceDetection,\n} from \"./detection.js\";\n\nexport { SURFACE_NAMES } from \"./names.js\";\nexport type { SurfaceName } from \"./names.js\";\n\nexport interface SurfaceStatus {\n name: SurfaceName;\n mode: SurfaceMode;\n detected: boolean;\n configured: boolean;\n path?: string;\n details: string[];\n summary: string;\n /**\n * When `name` is \"cursor\", distinguishes MCP lines in `~/.cursor/mcp.json` from the\n * managed companion bundle under `~/.cursor/plugins/local/cursor-plugin`.\n */\n cursorIntegration?: {\n mcpLocalOpenclaw: boolean;\n mcpHostedOrgx: boolean;\n pluginBundleInstalled: boolean;\n };\n}\n\nexport interface SurfaceMutationResult {\n name: SurfaceName;\n changed: boolean;\n path?: string;\n message: string;\n}\n\ntype SurfaceSelection<T extends string> = T | \"all\" | readonly (T | \"all\")[];\n\ninterface OpenClawDependencyState {\n detected: boolean;\n configured: boolean;\n path?: string;\n url?: string;\n}\n\nconst AUTH_SETUP_HINT = \"orgx-wizard auth login\";\nconst AUTH_SET_KEY_HINT = \"orgx-wizard auth set-key\";\nconst DOCTOR_HINT = \"orgx-wizard doctor\";\n\nfunction getSurfaceMode(name: SurfaceName): SurfaceMode {\n return AUTOMATED_SURFACE_NAMES.includes(name as (typeof AUTOMATED_SURFACE_NAMES)[number])\n ? \"automated\"\n : \"manual\";\n}\n\nfunction getSurfacePath(name: SurfaceName): string | undefined {\n const detection = detectSurface(name);\n const locator = getSurfaceLocator(name);\n const existingPath = detection.existingPath;\n\n if (existingPath && locator.configPaths.includes(existingPath)) {\n return existingPath;\n }\n\n return locator.configPaths[0] ?? detection.preferredPath ?? existingPath;\n}\n\nfunction getOpenClawDependencyState(): OpenClawDependencyState {\n const detection = detectSurface(\"openclaw\");\n const path = detection.existingPath ?? detection.preferredPath;\n const raw = path ? readTextIfExists(path) : null;\n const inspection = inspectOpenClawConfig(raw);\n\n const result: OpenClawDependencyState = {\n detected: detection.detected,\n configured: inspection.configured,\n };\n\n if (path) {\n result.path = path;\n }\n\n if (detection.detected) {\n result.url = buildLocalMcpUrl(raw);\n }\n\n return result;\n}\n\nfunction automatedSurfaceStatus(\n name: Extract<\n SurfaceName,\n \"claude\" | \"cursor\" | \"codex\" | \"openclaw\" | \"vscode\" | \"windsurf\" | \"zed\"\n >,\n): SurfaceStatus {\n const detection = detectSurface(name);\n const path = detection.existingPath ?? detection.preferredPath;\n const openclaw = getOpenClawDependencyState();\n\n if (name === \"claude\") {\n const inspection = inspectClaudeMcpConfig(path ? readTextIfExists(path) : null);\n const configured = inspection.hostedConfigured === true &&\n (openclaw.detected ? inspection.localConfigured === true : true);\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured,\n ...(path ? { path } : {}),\n details: [\n ...inspection.details,\n ...(openclaw.detected\n ? [`OpenClaw bridge: ${openclaw.configured ? \"configured\" : \"detected but not configured\"}`]\n : [\"OpenClaw bridge: not detected; hosted OrgX is the only available route.\"]),\n ...detection.evidence,\n ],\n summary: configured\n ? openclaw.detected\n ? \"OrgX is connected in Claude with the local OpenClaw bridge.\"\n : \"OrgX cloud MCP is connected in Claude.\"\n : detection.detected\n ? openclaw.detected\n ? `Claude is missing either hosted OrgX or the local OpenClaw bridge (${openclaw.url ?? \"unknown\"}).`\n : \"Claude is missing the hosted OrgX MCP entry.\"\n : \"Claude config directory was not detected on disk.\",\n };\n }\n\n if (name === \"cursor\") {\n const inspection = inspectCursorMcpConfig(path ? readTextIfExists(path) : null);\n const tooling = getCursorToolingState();\n const configured = openclaw.detected && inspection.localConfigured === true;\n const mcpWired = tooling.mcpLocalOpenclaw || tooling.mcpHostedOrgx;\n const summary = (() => {\n if (!detection.detected) {\n return \"Cursor config directory was not detected on disk.\";\n }\n if (configured) {\n return tooling.pluginBundleInstalled\n ? \"OrgX is connected in Cursor through the local OpenClaw bridge; companion plugin bundle is installed.\"\n : \"OrgX is connected in Cursor through the local OpenClaw bridge; companion plugin bundle (skills, hooks, rules) is not installed.\";\n }\n if (mcpWired && !tooling.pluginBundleInstalled) {\n if (tooling.mcpHostedOrgx && !openclaw.detected) {\n return \"OrgX hosted MCP is present in Cursor mcp.json; install OpenClaw for the local bridge, or add the companion plugin bundle for the full pack.\";\n }\n return \"OrgX MCP is present in Cursor mcp.json, but the companion plugin bundle (skills, hooks, rules) is not installed.\";\n }\n if (detection.detected) {\n return openclaw.detected\n ? `Cursor is missing the local OrgX OpenClaw bridge (${openclaw.url ?? \"unknown\"}).`\n : \"Cursor is ready to wire, but OpenClaw must be installed first.\";\n }\n return \"Cursor config directory was not detected on disk.\";\n })();\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured,\n ...(path ? { path } : {}),\n cursorIntegration: tooling,\n details: [\n `companion plugin bundle: ${tooling.pluginBundleInstalled ? \"installed\" : \"not installed\"}`,\n ...inspection.details,\n ...(openclaw.detected\n ? [`OpenClaw bridge: ${openclaw.configured ? \"configured\" : \"detected but not configured\"}`]\n : [\"OpenClaw bridge: not detected; Cursor cannot use the local OrgX bridge yet.\"]),\n ...detection.evidence,\n ],\n summary,\n };\n }\n\n if (name === \"codex\") {\n const inspection = inspectCodexConfigToml(path ? readTextIfExists(path) : null);\n const configured = inspection.hostedConfigured === true &&\n (openclaw.detected ? inspection.localConfigured === true : true);\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured,\n ...(path ? { path } : {}),\n details: [\n ...inspection.details,\n ...(openclaw.detected\n ? [`OpenClaw bridge: ${openclaw.configured ? \"configured\" : \"detected but not configured\"}`]\n : [\"OpenClaw bridge: not detected; hosted OrgX is the only available route.\"]),\n ...detection.evidence,\n ],\n summary: configured\n ? openclaw.detected\n ? \"OrgX is connected in Codex with the local OpenClaw bridge.\"\n : \"OrgX cloud MCP is connected in Codex.\"\n : detection.detected\n ? openclaw.detected\n ? `Codex is missing either hosted OrgX or the local OpenClaw bridge (${openclaw.url ?? \"unknown\"}).`\n : \"Codex is missing the hosted OrgX MCP entry.\"\n : \"Codex config directory was not detected on disk.\",\n };\n }\n\n if (name === \"vscode\") {\n const inspection = inspectVscodeMcpConfig(path ? readTextIfExists(path) : null);\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured: inspection.hostedConfigured === true,\n ...(path ? { path } : {}),\n details: [...inspection.details, ...detection.evidence],\n summary: inspection.hostedConfigured\n ? \"OrgX cloud MCP is connected in VS Code.\"\n : detection.detected\n ? \"VS Code is missing the hosted OrgX MCP entry.\"\n : \"VS Code config directory was not detected on disk.\",\n };\n }\n\n if (name === \"windsurf\") {\n const inspection = inspectWindsurfMcpConfig(path ? readTextIfExists(path) : null);\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured: inspection.hostedConfigured === true,\n ...(path ? { path } : {}),\n details: [...inspection.details, ...detection.evidence],\n summary: inspection.hostedConfigured\n ? \"OrgX cloud MCP is connected in Windsurf.\"\n : detection.detected\n ? \"Windsurf is missing the hosted OrgX MCP entry.\"\n : \"Windsurf config directory was not detected on disk.\",\n };\n }\n\n if (name === \"zed\") {\n const inspection = inspectZedMcpConfig(path ? readTextIfExists(path) : null);\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured: inspection.hostedConfigured === true,\n ...(path ? { path } : {}),\n details: [...inspection.details, ...detection.evidence],\n summary: inspection.hostedConfigured\n ? \"OrgX cloud MCP is connected in Zed.\"\n : detection.detected\n ? \"Zed is missing the hosted OrgX MCP entry.\"\n : \"Zed config directory was not detected on disk.\",\n };\n }\n\n const inspection = inspectOpenClawConfig(path ? readTextIfExists(path) : null);\n return {\n name,\n mode: \"automated\",\n detected: detection.detected,\n configured: inspection.configured,\n ...(path ? { path } : {}),\n details: [...inspection.details, ...detection.evidence],\n summary: inspection.configured\n ? `OpenClaw plugin entry ${inspection.pluginKey ?? \"missing\"} is configured.`\n : inspection.installed\n ? \"OpenClaw is installed but OrgX defaults have not been written.\"\n : detection.detected\n ? \"OpenClaw support files exist but no OrgX plugin entry was found.\"\n : \"OpenClaw is not installed or no support files were found.\",\n };\n}\n\nfunction formatAuthHintSource(authHint: OrgxAuthHint): string {\n switch (authHint.source) {\n case \"environment\":\n return \"env ORGX_API_KEY\";\n case \"wizard-store\":\n return \"wizard auth store\";\n case \"openclaw-config-file\":\n return \"openclaw config\";\n }\n}\n\nexport function buildChatgptManualStatus(\n detection: SurfaceDetection,\n authHint: OrgxAuthHint | null,\n): SurfaceStatus {\n const path = detection.existingPath ?? detection.preferredPath;\n\n const details = [...detection.evidence];\n if (authHint) {\n details.push(\n `OrgX auth ready via ${formatAuthHintSource(authHint)} (${authHint.keyPrefix})`,\n );\n details.push(`Hosted connector URL: ${ORGX_HOSTED_MCP_URL}`);\n details.push(\n \"Manual step: in ChatGPT desktop developer mode, add a custom connector pointing at the hosted OrgX MCP URL.\",\n );\n details.push(\n \"ChatGPT completes OAuth during connector setup; the wizard cannot preflight hosted MCP tools with an oxk_ API key.\",\n );\n details.push(\n \"After connecting ChatGPT, run `orgx-wizard doctor` to verify hosted MCP health from this machine.\",\n );\n } else {\n details.push(\n \"OrgX auth is not configured yet. Run `orgx-wizard auth login` or `orgx-wizard auth set-key` first.\",\n );\n details.push(\n \"After auth is configured, add a custom ChatGPT developer connector pointing at the hosted OrgX MCP URL.\",\n );\n }\n\n let summary: string;\n if (!authHint) {\n summary = detection.detected\n ? \"ChatGPT is installed, but OrgX auth is not configured yet.\"\n : \"ChatGPT support files were not found; configure OrgX auth first, then add the hosted connector manually.\";\n } else {\n summary = detection.detected\n ? \"ChatGPT is installed; finish the manual developer connector setup.\"\n : \"OrgX auth is ready, but ChatGPT desktop support files were not found on disk.\";\n }\n\n return {\n name: \"chatgpt\",\n mode: \"manual\",\n detected: detection.detected,\n configured: false,\n ...(path ? { path } : {}),\n details,\n summary,\n };\n}\n\nexport function buildChatgptAddResult(\n path: string | undefined,\n authHint: OrgxAuthHint | null,\n toolCheck?: HostedMcpToolCheck,\n): SurfaceMutationResult {\n if (!authHint) {\n return {\n name: \"chatgpt\",\n changed: false,\n ...(path ? { path } : {}),\n message:\n `Run \\`${AUTH_SETUP_HINT}\\` or \\`${AUTH_SET_KEY_HINT}\\` first, then add ${ORGX_HOSTED_MCP_URL} as a custom connector in ChatGPT developer mode.`,\n };\n }\n\n if (toolCheck && !toolCheck.ok && !toolCheck.skipped) {\n const failure = toolCheck?.error ?? \"hosted MCP verification did not complete.\";\n return {\n name: \"chatgpt\",\n changed: false,\n ...(path ? { path } : {}),\n message:\n `OrgX auth is configured via ${formatAuthHintSource(authHint)}, but hosted MCP verification failed (${failure}). Fix that first, then add ${ORGX_HOSTED_MCP_URL} in ChatGPT developer mode.`,\n };\n }\n\n return {\n name: \"chatgpt\",\n changed: false,\n ...(path ? { path } : {}),\n message:\n `OrgX auth is ready via ${formatAuthHintSource(authHint)}. Add ${ORGX_HOSTED_MCP_URL} as a custom connector in ChatGPT developer mode; ChatGPT will complete the OAuth flow there. Then run \\`${DOCTOR_HINT}\\` to verify hosted MCP health from this machine.`,\n };\n}\n\nexport function buildChatgptRemoveResult(path: string | undefined): SurfaceMutationResult {\n return {\n name: \"chatgpt\",\n changed: false,\n ...(path ? { path } : {}),\n message:\n \"Remove the custom OrgX connector from ChatGPT developer mode; the wizard does not manage ChatGPT config files directly.\",\n };\n}\n\nfunction manualSurfaceStatus(name: Extract<SurfaceName, \"chatgpt\">): SurfaceStatus {\n const detection = detectSurface(name);\n\n switch (name) {\n case \"chatgpt\":\n return buildChatgptManualStatus(detection, peekResolvedOrgxAuth());\n }\n}\n\nfunction getSurfaceStatus(name: SurfaceName): SurfaceStatus {\n if (AUTOMATED_SURFACE_NAMES.includes(name as (typeof AUTOMATED_SURFACE_NAMES)[number])) {\n return automatedSurfaceStatus(\n name as Extract<\n SurfaceName,\n \"claude\" | \"cursor\" | \"codex\" | \"openclaw\" | \"vscode\" | \"windsurf\" | \"zed\"\n >,\n );\n }\n\n return manualSurfaceStatus(name as Extract<SurfaceName, \"chatgpt\">);\n}\n\nexport function listSurfaceStatuses(): SurfaceStatus[] {\n return SURFACE_NAMES.map(getSurfaceStatus);\n}\n\nfunction resolveTargets<T extends string>(\n selection: SurfaceSelection<T>,\n allTargets: readonly T[],\n): T[] {\n const values = Array.isArray(selection) ? selection : [selection];\n\n if (values.includes(\"all\")) {\n return [...allTargets];\n }\n\n return [...new Set(values)] as T[];\n}\n\nexport function resolveSurfaceSelection(\n selection: SurfaceSelection<SurfaceName>,\n): SurfaceName[] {\n return resolveTargets(selection, SURFACE_NAMES);\n}\n\nexport function resolveMcpSurfaceSelection(\n selection: SurfaceSelection<(typeof MCP_SURFACE_NAMES)[number]>,\n): Array<(typeof MCP_SURFACE_NAMES)[number]> {\n return resolveTargets(selection, MCP_SURFACE_NAMES);\n}\n\nasync function addAutomatedSurface(name: SurfaceName): Promise<SurfaceMutationResult> {\n const path = getSurfacePath(name);\n const openclaw = getOpenClawDependencyState();\n\n if (!path) {\n return {\n name,\n changed: false,\n message: `${name} has no writable config path on this platform.`,\n };\n }\n\n switch (name) {\n case \"claude\": {\n const previous = readTextIfExists(path);\n const next = patchClaudeMcpConfig(previous, openclaw.url);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: openclaw.detected\n ? \"OrgX is connected in Claude with the local OpenClaw bridge.\"\n : \"OrgX cloud MCP is connected in Claude.\",\n };\n }\n case \"cursor\": {\n if (!openclaw.detected || !openclaw.url) {\n return {\n name,\n changed: false,\n path,\n message: \"Cursor needs OpenClaw installed before OrgX can be connected locally.\",\n };\n }\n const previous = readTextIfExists(path);\n const next = patchCursorMcpConfig(previous, openclaw.url);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX is connected in Cursor through the local OpenClaw bridge.\",\n };\n }\n case \"codex\": {\n const previous = readTextIfExists(path);\n const next = patchCodexConfigToml(previous, openclaw.url);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: openclaw.detected\n ? \"OrgX is connected in Codex with the local OpenClaw bridge.\"\n : \"OrgX cloud MCP is connected in Codex.\",\n };\n }\n case \"openclaw\": {\n const previous = readTextIfExists(path);\n const auth = await resolveOrgxAuth();\n const next = patchOpenClawConfig(previous, auth ?? {});\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: auth\n ? \"OpenClaw is configured as the local OrgX bridge with the resolved OrgX auth.\"\n : \"OpenClaw is configured as the local OrgX bridge.\",\n };\n }\n case \"vscode\": {\n const previous = readTextIfExists(path);\n if (inspectVscodeMcpConfig(previous).hostedConfigured) {\n return { name, changed: false, path, message: \"OrgX cloud MCP is connected in VS Code.\" };\n }\n const next = patchVscodeMcpConfig(previous);\n writeTextFile(path, next);\n return { name, changed: true, path, message: \"OrgX cloud MCP is connected in VS Code.\" };\n }\n case \"windsurf\": {\n const previous = readTextIfExists(path);\n if (inspectWindsurfMcpConfig(previous).hostedConfigured) {\n return { name, changed: false, path, message: \"OrgX cloud MCP is connected in Windsurf.\" };\n }\n const next = patchWindsurfMcpConfig(previous);\n writeTextFile(path, next);\n return { name, changed: true, path, message: \"OrgX cloud MCP is connected in Windsurf.\" };\n }\n case \"zed\": {\n const previous = readTextIfExists(path);\n if (inspectZedMcpConfig(previous).hostedConfigured) {\n return { name, changed: false, path, message: \"OrgX cloud MCP is connected in Zed.\" };\n }\n const next = patchZedMcpConfig(previous);\n writeTextFile(path, next);\n return { name, changed: true, path, message: \"OrgX cloud MCP is connected in Zed.\" };\n }\n case \"chatgpt\": {\n const authHint = peekResolvedOrgxAuth();\n if (!authHint) {\n return buildChatgptAddResult(path, null);\n }\n return buildChatgptAddResult(path, authHint);\n }\n default:\n return {\n name,\n changed: false,\n message: `${name} is not supported by the wizard.`,\n };\n }\n}\n\nfunction removeAutomatedSurface(name: SurfaceName): SurfaceMutationResult {\n const path = getSurfacePath(name);\n\n if (!path) {\n return {\n name,\n changed: false,\n message: `${name} has no writable config path on this platform.`,\n };\n }\n\n switch (name) {\n case \"claude\": {\n const previous = readTextIfExists(path);\n const next = removeClaudeMcpConfig(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX connection was removed from Claude.\",\n };\n }\n case \"cursor\": {\n const previous = readTextIfExists(path);\n const next = removeCursorMcpConfig(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX connection was removed from Cursor.\",\n };\n }\n case \"codex\": {\n const previous = readTextIfExists(path);\n const next = removeCodexConfigToml(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX connection was removed from Codex.\",\n };\n }\n case \"openclaw\": {\n const previous = readTextIfExists(path);\n const next = removeOpenClawConfig(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OpenClaw OrgX defaults were removed.\",\n };\n }\n case \"vscode\": {\n const previous = readTextIfExists(path);\n const next = removeVscodeMcpConfig(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX connection was removed from VS Code.\",\n };\n }\n case \"windsurf\": {\n const previous = readTextIfExists(path);\n const next = removeWindsurfMcpConfig(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX connection was removed from Windsurf.\",\n };\n }\n case \"zed\": {\n const previous = readTextIfExists(path);\n const next = removeZedMcpConfig(previous);\n writeTextFile(path, next);\n return {\n name,\n changed: previous !== next,\n path,\n message: \"OrgX connection was removed from Zed.\",\n };\n }\n case \"chatgpt\":\n return buildChatgptRemoveResult(path);\n default:\n return {\n name,\n changed: false,\n message: `${name} is not supported by the wizard.`,\n };\n }\n}\n\nexport async function addSurface(\n selection: SurfaceSelection<SurfaceName>,\n): Promise<SurfaceMutationResult[]> {\n const targets = resolveSurfaceSelection(selection);\n const results: SurfaceMutationResult[] = [];\n\n for (const surface of targets) {\n results.push(await addAutomatedSurface(surface));\n }\n\n return results;\n}\n\nexport function removeSurface(selection: SurfaceSelection<SurfaceName>): SurfaceMutationResult[] {\n const targets = resolveSurfaceSelection(selection);\n return targets.map((surface) => removeAutomatedSurface(surface));\n}\n\nexport async function addMcpSurface(\n selection: SurfaceSelection<(typeof MCP_SURFACE_NAMES)[number]>,\n): Promise<SurfaceMutationResult[]> {\n const targets = resolveMcpSurfaceSelection(selection);\n const results: SurfaceMutationResult[] = [];\n\n for (const surface of targets) {\n results.push(await addAutomatedSurface(surface));\n }\n\n return results;\n}\n\nexport function removeMcpSurface(\n selection: SurfaceSelection<(typeof MCP_SURFACE_NAMES)[number]>,\n): SurfaceMutationResult[] {\n const targets = resolveMcpSurfaceSelection(selection);\n return targets.map((surface) => removeAutomatedSurface(surface));\n}\n\nexport async function setupDetectedSurfaces(): Promise<SurfaceMutationResult[]> {\n const targets = AUTOMATED_SURFACE_NAMES.filter((name) => getSurfaceStatus(name).detected);\n\n targets.sort((left, right) => {\n if (left === \"openclaw\") return -1;\n if (right === \"openclaw\") return 1;\n return 0;\n });\n\n const results: SurfaceMutationResult[] = [];\n\n for (const name of targets) {\n results.push(await addAutomatedSurface(name));\n }\n\n return results;\n}\n\nexport interface DoctorReport {\n surfaces: SurfaceStatus[];\n auth: OrgxAuthCheckResult;\n hostedMcp: HostedMcpHealthCheck;\n hostedMcpTool: HostedMcpToolCheck;\n npmRegistry: NpmRegistryCheck;\n workspace: WorkspaceConnectivityCheck;\n openclaw: OpenClawHealthCheck;\n}\n\nexport interface DoctorAssessmentIssue {\n level: \"error\" | \"warning\";\n title: string;\n suggestion: string;\n}\n\nexport interface DoctorAssessment {\n ok: boolean;\n issues: DoctorAssessmentIssue[];\n}\n\nfunction skippedOpenClawHealth(): OpenClawHealthCheck {\n return {\n ok: false,\n skipped: true,\n method: \"none\",\n error: \"OpenClaw support files were not detected; skipping gateway health check.\",\n details: [],\n };\n}\n\nexport async function runDoctor(): Promise<DoctorReport> {\n const surfaces = listSurfaceStatuses();\n const openclawSurface = surfaces.find((surface) => surface.name === \"openclaw\");\n const auth = await checkOrgxAuth();\n const hostedMcp = await checkHostedMcpHealth();\n const hostedMcpTool = await checkHostedMcpToolAccess();\n const npmRegistry = await checkNpmRegistryHealth();\n const workspace = await checkWorkspaceConnectivity();\n const openclaw = openclawSurface?.detected\n ? await checkOpenClawHealth(openclawSurface.path)\n : skippedOpenClawHealth();\n return { surfaces, auth, hostedMcp, hostedMcpTool, npmRegistry, workspace, openclaw };\n}\n\nexport function assessDoctorReport(report: DoctorReport): DoctorAssessment {\n const issues: DoctorAssessmentIssue[] = [];\n\n if (!report.hostedMcp.ok) {\n issues.push({\n level: \"error\",\n title: \"Hosted OrgX MCP is unreachable.\",\n suggestion:\n \"Retry later or verify https://mcp.useorgx.com/health. Hosted-only clients will stay broken until that endpoint recovers.\",\n });\n }\n\n if (\n report.hostedMcp.ok &&\n report.hostedMcpTool.configured &&\n !report.hostedMcpTool.ok &&\n !report.hostedMcpTool.skipped\n ) {\n issues.push({\n level: \"error\",\n title: `Hosted OrgX MCP tool verification failed (${report.hostedMcpTool.toolName}).`,\n suggestion:\n \"Re-run `wizard auth login` to refresh the per-user key, then retry `wizard doctor` to confirm the hosted MCP can initialize and execute tools.\",\n });\n }\n\n if (report.auth.configured && !report.auth.ok && !report.auth.skipped) {\n issues.push({\n level: \"error\",\n title: \"OrgX user auth could not be verified.\",\n suggestion:\n \"Run `wizard auth set-key <oxk_...>` again or correct the resolved ORGX_API_KEY / base URL before retrying.\",\n });\n }\n\n if (report.workspace.configured && !report.workspace.ok) {\n issues.push({\n level: \"error\",\n title: \"Current workspace lookup failed.\",\n suggestion:\n \"Verify the resolved OrgX base URL and that the authenticated user still has access to a workspace.\",\n });\n }\n\n if (!report.npmRegistry.reachable) {\n issues.push({\n level: \"warning\",\n title: \"npm registry is unreachable.\",\n suggestion:\n \"Check outbound network access to https://registry.npmjs.org before relying on npm-based installation flows.\",\n });\n } else if (!report.npmRegistry.published) {\n issues.push({\n level: \"warning\",\n title: `${report.npmRegistry.packageName} is not published on npm yet.`,\n suggestion:\n \"This is expected before launch. Publish the package in the release workstream before asking users to install from npm.\",\n });\n }\n\n if (!report.openclaw.skipped && !report.openclaw.ok) {\n issues.push({\n level: \"warning\",\n title: \"OpenClaw is installed but its local gateway health check failed.\",\n suggestion:\n \"Run `openclaw doctor` or `openclaw doctor --repair` before relying on local bridge clients like Cursor.\",\n });\n }\n\n const cursor = report.surfaces.find((surface) => surface.name === \"cursor\");\n const ci = cursor?.cursorIntegration;\n if (cursor?.detected && ci && (ci.mcpLocalOpenclaw || ci.mcpHostedOrgx) && !ci.pluginBundleInstalled) {\n issues.push({\n level: \"warning\",\n title: \"Cursor has OrgX MCP wiring but not the full companion plugin bundle.\",\n suggestion:\n \"Run `orgx-wizard plugins add cursor` to install the managed pack (skills, rules, hooks, commands), then reload Cursor. Skip this if you intentionally use MCP-only mode.\",\n });\n }\n\n return {\n ok: !issues.some((issue) => issue.level === \"error\"),\n issues,\n };\n}\n","import { listSurfaceStatuses, type SurfaceStatus } from \"../surfaces/registry.js\";\nimport type { SurfaceName } from \"../surfaces/names.js\";\nimport type { OrgxWorkspace } from \"./workspaces.js\";\nimport {\n updateWizardState,\n type WizardContinuityDefaults,\n type WizardStateRecord,\n} from \"./wizard-state.js\";\n\nconst REVIEW_SURFACE_ORDER: SurfaceName[] = [\n \"claude\",\n \"cursor\",\n \"codex\",\n \"vscode\",\n \"windsurf\",\n \"zed\",\n \"chatgpt\",\n];\n\nexport interface ContinuitySeed {\n executionMode?: \"cloud\" | \"local\" | null;\n statuses?: SurfaceStatus[];\n workspace?: Pick<OrgxWorkspace, \"id\" | \"name\"> | null;\n workspaceName?: string | null;\n}\n\nfunction selectReviewSurface(statuses: SurfaceStatus[]): SurfaceName | undefined {\n for (const name of REVIEW_SURFACE_ORDER) {\n const configured = statuses.find((status) => status.name === name && status.configured);\n if (configured) {\n return configured.name;\n }\n }\n\n for (const name of REVIEW_SURFACE_ORDER) {\n const detected = statuses.find((status) => status.name === name && status.detected);\n if (detected) {\n return detected.name;\n }\n }\n\n return undefined;\n}\n\nfunction inferExecutionMode(\n explicitMode: \"cloud\" | \"local\" | null | undefined,\n statuses: SurfaceStatus[],\n): \"cloud\" | \"local\" | undefined {\n if (explicitMode) {\n return explicitMode;\n }\n\n const openclaw = statuses.find((status) => status.name === \"openclaw\");\n if (openclaw?.configured || openclaw?.detected) {\n return \"local\";\n }\n\n const hostedSurface = statuses.find(\n (status) => status.name !== \"openclaw\" && (status.configured || status.detected),\n );\n\n return hostedSurface ? \"cloud\" : undefined;\n}\n\nexport function inferContinuityDefaults(seed: ContinuitySeed = {}): WizardContinuityDefaults {\n const statuses = seed.statuses ?? listSurfaceStatuses();\n const continuity: WizardContinuityDefaults = {};\n\n const reviewSurface = selectReviewSurface(statuses);\n if (reviewSurface) {\n continuity.reviewSurface = reviewSurface;\n }\n\n const executionMode = inferExecutionMode(seed.executionMode, statuses);\n if (executionMode) {\n continuity.executionMode = executionMode;\n }\n\n if (seed.workspace?.id) {\n continuity.workspaceId = seed.workspace.id;\n }\n\n const workspaceName = seed.workspace?.name ?? seed.workspaceName ?? undefined;\n if (workspaceName?.trim()) {\n continuity.workspaceName = workspaceName.trim();\n }\n\n return continuity;\n}\n\nfunction mergeContinuityDefaults(\n current: WizardContinuityDefaults | undefined,\n next: WizardContinuityDefaults,\n): WizardContinuityDefaults {\n return {\n ...(current ?? {}),\n ...next,\n };\n}\n\nexport function persistContinuityDefaults(\n seed: ContinuitySeed = {},\n statePath?: string,\n): WizardStateRecord {\n const next = inferContinuityDefaults(seed);\n\n return updateWizardState(\n (current) => ({\n ...current,\n continuity: mergeContinuityDefaults(current.continuity, next),\n }),\n statePath,\n );\n}\n","import {\n buildOrgxApiUrl,\n normalizeOrgxBaseUrl,\n resolveOrgxAuth,\n type ResolveOrgxAuthOptions,\n} from \"./auth.js\";\nimport { isRecord } from \"./fs.js\";\nimport type { OrgxWorkspace } from \"./workspaces.js\";\nimport {\n readWizardState,\n updateWizardState,\n type WizardDemoInitiativeRecord,\n type WizardFirstValueInitiativeRecord,\n type WizardOnboardingTaskRecord,\n} from \"./wizard-state.js\";\n\nconst FOUNDER_DEMO_INITIATIVE_TITLE = \"Founder Demo Initiative\";\nconst FOUNDER_DEMO_INITIATIVE_SUMMARY =\n \"Starter initiative created by @useorgx/wizard to validate workspace routing, live views, and the default OrgX skill pack.\";\nconst FOUNDER_DEMO_DECISION_TITLE = \"Approve founder demo workspace\";\nconst FOUNDER_DEMO_DECISION_SUMMARY =\n \"Initial decision created by @useorgx/wizard so the founder preset leaves the workspace with a resolved approval trail.\";\nconst FOUNDER_DEMO_DECISION_RESOLUTION =\n \"Approved automatically by @useorgx/wizard after the founder preset finished creating the live demo workspace.\";\nconst FOUNDER_DEMO_ARTIFACT_NAME = \"Founder Demo Live View\";\nconst FOUNDER_DEMO_ARTIFACT_TYPE = \"document\";\nconst FOUNDER_DEMO_ARTIFACT_DESCRIPTION =\n \"Live founder demo generated by @useorgx/wizard after workspace bootstrap completed.\";\nexport const ONBOARDING_TASK_TITLE = \"Complete OrgX onboarding\";\nexport const ONBOARDING_TASK_SUMMARY =\n \"Starter onboarding task created by @useorgx/wizard so the first workspace has a clear follow-up after setup.\";\nconst ONBOARDING_WORKSTREAM_TITLE = \"OrgX onboarding\";\nconst ONBOARDING_WORKSTREAM_SUMMARY =\n \"Starter onboarding workstream created by @useorgx/wizard so the first workspace has a home for setup follow-up tasks.\";\nexport const FIRST_VALUE_INITIATIVE_TITLE = \"Make OrgX useful on this machine\";\nexport const FIRST_VALUE_INITIATIVE_SUMMARY =\n \"First initiative created by @useorgx/wizard so setup ends with a live workspace, an onboarding workstream, and a clean handoff into the user's configured AI tools.\";\n\nexport interface OrgxInitiative {\n id: string;\n summary?: string;\n title: string;\n}\n\nexport interface OrgxDecision {\n id: string;\n status?: string;\n summary?: string;\n title: string;\n}\n\nexport interface OrgxArtifact {\n id: string;\n name: string;\n type?: string;\n url?: string;\n}\n\nexport interface OrgxTask {\n id: string;\n status?: string;\n summary?: string;\n title: string;\n}\n\ninterface OrgxWorkstream {\n id: string;\n title: string;\n}\n\nexport interface FounderDemoInitiativeResult {\n created: boolean;\n artifact: OrgxArtifact;\n decision: OrgxDecision;\n initiative: OrgxInitiative;\n liveUrl: string;\n}\n\nexport interface FirstValueInitiativeResult {\n created: boolean;\n initiative: OrgxInitiative;\n liveUrl: string;\n}\n\ninterface InitiativeClientOptions extends ResolveOrgxAuthOptions {\n statePath?: string;\n}\n\nfunction parseResponseBody(text: string): unknown {\n if (!text) {\n return null;\n }\n\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction formatHttpError(status: number, body: unknown): string {\n if (typeof body === \"string\" && body.trim().length > 0) {\n return `HTTP ${status}: ${body}`;\n }\n\n if (isRecord(body) && typeof body.error === \"string\" && body.error.trim().length > 0) {\n return `HTTP ${status}: ${body.error}`;\n }\n\n return `HTTP ${status}`;\n}\n\nfunction extractEntity(payload: unknown): Record<string, unknown> {\n const entity = isRecord(payload) && isRecord(payload.data) ? payload.data : payload;\n if (!isRecord(entity)) {\n throw new Error(\"OrgX returned an unexpected entity payload.\");\n }\n\n return entity;\n}\n\nfunction parseInitiative(payload: unknown): OrgxInitiative {\n const entity = extractEntity(payload);\n\n const id = typeof entity.id === \"string\" ? entity.id.trim() : \"\";\n const title = typeof entity.title === \"string\"\n ? entity.title.trim()\n : typeof entity.name === \"string\"\n ? entity.name.trim()\n : \"\";\n\n if (!id || !title) {\n throw new Error(\"OrgX returned an incomplete initiative payload.\");\n }\n\n return {\n id,\n title,\n ...(typeof entity.summary === \"string\" && entity.summary.trim().length > 0\n ? { summary: entity.summary.trim() }\n : {}),\n };\n}\n\nfunction parseDecision(payload: unknown): OrgxDecision {\n const entity = extractEntity(payload);\n const id = typeof entity.id === \"string\" ? entity.id.trim() : \"\";\n const title = typeof entity.title === \"string\"\n ? entity.title.trim()\n : typeof entity.name === \"string\"\n ? entity.name.trim()\n : \"\";\n\n if (!id || !title) {\n throw new Error(\"OrgX returned an incomplete decision payload.\");\n }\n\n return {\n id,\n title,\n ...(typeof entity.status === \"string\" && entity.status.trim().length > 0\n ? { status: entity.status.trim() }\n : {}),\n ...(typeof entity.summary === \"string\" && entity.summary.trim().length > 0\n ? { summary: entity.summary.trim() }\n : {}),\n };\n}\n\nfunction parseArtifact(payload: unknown): OrgxArtifact {\n const entity = extractEntity(payload);\n const id = typeof entity.id === \"string\" ? entity.id.trim() : \"\";\n const name = typeof entity.name === \"string\"\n ? entity.name.trim()\n : typeof entity.title === \"string\"\n ? entity.title.trim()\n : \"\";\n const type = typeof entity.artifact_type === \"string\"\n ? entity.artifact_type.trim()\n : typeof entity.type === \"string\"\n ? entity.type.trim()\n : \"\";\n const url = typeof entity.external_url === \"string\"\n ? entity.external_url.trim()\n : typeof entity.url === \"string\"\n ? entity.url.trim()\n : \"\";\n\n if (!id || !name) {\n throw new Error(\"OrgX returned an incomplete artifact payload.\");\n }\n\n return {\n id,\n name,\n ...(type ? { type } : {}),\n ...(url ? { url } : {}),\n };\n}\n\nfunction parseTask(payload: unknown): OrgxTask {\n const entity = extractEntity(payload);\n const id = typeof entity.id === \"string\" ? entity.id.trim() : \"\";\n const title = typeof entity.title === \"string\"\n ? entity.title.trim()\n : typeof entity.name === \"string\"\n ? entity.name.trim()\n : \"\";\n\n if (!id || !title) {\n throw new Error(\"OrgX returned an incomplete task payload.\");\n }\n\n return {\n id,\n title,\n ...(typeof entity.status === \"string\" && entity.status.trim().length > 0\n ? { status: entity.status.trim() }\n : {}),\n ...(typeof entity.summary === \"string\" && entity.summary.trim().length > 0\n ? { summary: entity.summary.trim() }\n : {}),\n };\n}\n\nfunction parseWorkstream(payload: unknown): OrgxWorkstream {\n const entity = extractEntity(payload);\n const id = typeof entity.id === \"string\" ? entity.id.trim() : \"\";\n const title = typeof entity.title === \"string\"\n ? entity.title.trim()\n : typeof entity.name === \"string\"\n ? entity.name.trim()\n : \"\";\n\n if (!id || !title) {\n throw new Error(\"OrgX returned an incomplete workstream payload.\");\n }\n\n return { id, title };\n}\n\nfunction toDemoInitiativeRecord(\n artifact: OrgxArtifact,\n decision: OrgxDecision,\n initiative: OrgxInitiative,\n liveUrl: string,\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n): WizardDemoInitiativeRecord {\n return {\n createdAt: new Date().toISOString(),\n artifactId: artifact.id,\n artifactName: artifact.name,\n ...(artifact.type ? { artifactType: artifact.type } : {}),\n ...(artifact.url ? { artifactUrl: artifact.url } : {}),\n decisionId: decision.id,\n ...(decision.status ? { decisionStatus: decision.status } : {}),\n decisionTitle: decision.title,\n id: initiative.id,\n liveUrl,\n title: initiative.title,\n workspaceId: workspace.id,\n workspaceName: workspace.name,\n };\n}\n\nfunction toOnboardingTaskRecord(\n task: OrgxTask,\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n options: {\n initiativeId?: string;\n workstreamId?: string;\n } = {},\n): WizardOnboardingTaskRecord {\n return {\n createdAt: new Date().toISOString(),\n id: task.id,\n ...(options.initiativeId ? { initiativeId: options.initiativeId } : {}),\n ...(task.status ? { status: task.status } : {}),\n title: task.title,\n ...(options.workstreamId ? { workstreamId: options.workstreamId } : {}),\n workspaceId: workspace.id,\n workspaceName: workspace.name,\n };\n}\n\nfunction toFirstValueInitiativeRecord(\n initiative: OrgxInitiative,\n liveUrl: string,\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n): WizardFirstValueInitiativeRecord {\n return {\n createdAt: new Date().toISOString(),\n id: initiative.id,\n liveUrl,\n ...(initiative.summary ? { summary: initiative.summary } : {}),\n title: initiative.title,\n workspaceId: workspace.id,\n workspaceName: workspace.name,\n };\n}\n\nasync function requireOrgxAuth(options: InitiativeClientOptions = {}) {\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n throw new Error(\n \"No OrgX API key configured. Run `wizard auth login` or `wizard auth set-key <oxk_...>` first.\",\n );\n }\n\n return auth;\n}\n\nasync function createEntity<T>(\n type: string,\n body: Record<string, unknown>,\n parse: (payload: unknown) => T,\n options: InitiativeClientOptions = {},\n): Promise<T> {\n const auth = await requireOrgxAuth(options);\n const response = await fetch(buildOrgxApiUrl(\"/entities\", auth.baseUrl), {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n type,\n ...body,\n }),\n signal: AbortSignal.timeout(7_000),\n });\n\n const responseBody = parseResponseBody(await response.text());\n if (!response.ok) {\n throw new Error(`Failed to create ${type}. ${formatHttpError(response.status, responseBody)}`);\n }\n\n return parse(responseBody);\n}\n\nasync function updateEntity<T>(\n type: string,\n id: string,\n body: Record<string, unknown>,\n parse: (payload: unknown) => T,\n options: InitiativeClientOptions = {},\n): Promise<T> {\n const auth = await requireOrgxAuth(options);\n const response = await fetch(buildOrgxApiUrl(\"/entities\", auth.baseUrl), {\n method: \"PATCH\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n type,\n id,\n ...body,\n }),\n signal: AbortSignal.timeout(7_000),\n });\n\n const responseBody = parseResponseBody(await response.text());\n if (!response.ok) {\n throw new Error(`Failed to update ${type}. ${formatHttpError(response.status, responseBody)}`);\n }\n\n return parse(responseBody);\n}\n\nfunction buildLiveUrl(baseUrl: string, initiativeId: string): string {\n const parsed = new URL(normalizeOrgxBaseUrl(baseUrl));\n parsed.pathname = `/live/${initiativeId}`;\n parsed.search = \"\";\n parsed.hash = \"\";\n return parsed.toString();\n}\n\nasync function createFounderDemoDecision(\n initiative: OrgxInitiative,\n workspaceId: string,\n options: InitiativeClientOptions = {},\n): Promise<OrgxDecision> {\n return createEntity(\n \"decision\",\n {\n initiative_id: initiative.id,\n summary: FOUNDER_DEMO_DECISION_SUMMARY,\n title: FOUNDER_DEMO_DECISION_TITLE,\n workspace_id: workspaceId,\n },\n parseDecision,\n options,\n );\n}\n\nasync function approveFounderDemoDecision(\n decisionId: string,\n options: InitiativeClientOptions = {},\n): Promise<OrgxDecision> {\n return updateEntity(\n \"decision\",\n decisionId,\n {\n resolution_summary: FOUNDER_DEMO_DECISION_RESOLUTION,\n status: \"approved\",\n },\n parseDecision,\n options,\n );\n}\n\nasync function createFounderDemoArtifact(\n initiative: OrgxInitiative,\n liveUrl: string,\n workspaceId: string,\n options: InitiativeClientOptions = {},\n): Promise<OrgxArtifact> {\n return createEntity(\n \"artifact\",\n {\n artifact_type: FOUNDER_DEMO_ARTIFACT_TYPE,\n description: FOUNDER_DEMO_ARTIFACT_DESCRIPTION,\n entity_id: initiative.id,\n entity_type: \"initiative\",\n external_url: liveUrl,\n initiative_id: initiative.id,\n name: FOUNDER_DEMO_ARTIFACT_NAME,\n workspace_id: workspaceId,\n },\n parseArtifact,\n options,\n );\n}\n\nexport async function createInitiative(\n input: {\n summary?: string;\n title: string;\n workspaceId?: string;\n },\n options: InitiativeClientOptions = {},\n): Promise<OrgxInitiative> {\n const title = input.title.trim();\n if (!title) {\n throw new Error(\"Initiative title is required.\");\n }\n\n return createEntity(\n \"initiative\",\n {\n title,\n status: \"active\",\n ...(input.summary?.trim() ? { summary: input.summary.trim() } : {}),\n ...(input.workspaceId?.trim() ? { workspace_id: input.workspaceId.trim() } : {}),\n },\n parseInitiative,\n options,\n );\n}\n\nexport async function ensureFounderDemoInitiative(\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n options: InitiativeClientOptions = {},\n): Promise<FounderDemoInitiativeResult> {\n const existingRecord = readWizardState(options.statePath)?.demoInitiative;\n const matchingRecord = existingRecord?.workspaceId === workspace.id ? existingRecord : undefined;\n const auth = await requireOrgxAuth(options);\n\n const initiative = matchingRecord\n ? {\n id: matchingRecord.id,\n title: matchingRecord.title,\n }\n : await createInitiative(\n {\n title: FOUNDER_DEMO_INITIATIVE_TITLE,\n summary: FOUNDER_DEMO_INITIATIVE_SUMMARY,\n workspaceId: workspace.id,\n },\n options,\n );\n const liveUrl = matchingRecord?.liveUrl || buildLiveUrl(auth.baseUrl, initiative.id);\n const decision = matchingRecord?.decisionId\n ? matchingRecord.decisionStatus === \"approved\" && matchingRecord.decisionTitle\n ? {\n id: matchingRecord.decisionId,\n status: matchingRecord.decisionStatus,\n title: matchingRecord.decisionTitle,\n }\n : await approveFounderDemoDecision(matchingRecord.decisionId, options)\n : await approveFounderDemoDecision(\n (\n await createFounderDemoDecision(initiative, workspace.id, options)\n ).id,\n options,\n );\n const artifact = matchingRecord?.artifactId && matchingRecord.artifactName\n ? {\n id: matchingRecord.artifactId,\n name: matchingRecord.artifactName,\n ...(matchingRecord.artifactType ? { type: matchingRecord.artifactType } : {}),\n ...(matchingRecord.artifactUrl ? { url: matchingRecord.artifactUrl } : {}),\n }\n : await createFounderDemoArtifact(initiative, liveUrl, workspace.id, options);\n const record = toDemoInitiativeRecord(artifact, decision, initiative, liveUrl, workspace);\n\n updateWizardState(\n (current) => ({\n ...current,\n demoInitiative: record,\n }),\n options.statePath,\n );\n\n return {\n artifact,\n created: !matchingRecord,\n decision,\n initiative,\n liveUrl,\n };\n}\n\nexport async function ensureFirstValueInitiative(\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n options: InitiativeClientOptions & {\n summary?: string;\n title?: string;\n } = {},\n): Promise<FirstValueInitiativeResult> {\n const existingRecord = readWizardState(options.statePath)?.firstValueInitiative;\n const matchingRecord = existingRecord?.workspaceId === workspace.id ? existingRecord : undefined;\n const auth = await requireOrgxAuth(options);\n\n if (matchingRecord) {\n return {\n created: false,\n initiative: {\n id: matchingRecord.id,\n title: matchingRecord.title,\n ...(matchingRecord.summary ? { summary: matchingRecord.summary } : {}),\n },\n liveUrl: matchingRecord.liveUrl || buildLiveUrl(auth.baseUrl, matchingRecord.id),\n };\n }\n\n const initiative = await createInitiative(\n {\n title: options.title?.trim() || FIRST_VALUE_INITIATIVE_TITLE,\n summary: options.summary?.trim() || FIRST_VALUE_INITIATIVE_SUMMARY,\n workspaceId: workspace.id,\n },\n options,\n );\n const liveUrl = buildLiveUrl(auth.baseUrl, initiative.id);\n\n updateWizardState(\n (current) => ({\n ...current,\n firstValueInitiative: toFirstValueInitiativeRecord(initiative, liveUrl, workspace),\n }),\n options.statePath,\n );\n\n return {\n created: true,\n initiative,\n liveUrl,\n };\n}\n\nexport async function ensureOnboardingTask(\n workspace: Pick<OrgxWorkspace, \"id\" | \"name\">,\n options: InitiativeClientOptions & { initiativeId?: string } = {},\n): Promise<OrgxTask> {\n const existingRecord = readWizardState(options.statePath)?.onboardingTask;\n if (existingRecord?.workspaceId === workspace.id) {\n return {\n id: existingRecord.id,\n title: existingRecord.title,\n ...(existingRecord.status ? { status: existingRecord.status } : {}),\n };\n }\n\n const initiativeId = options.initiativeId?.trim();\n if (!initiativeId) {\n throw new Error(\n \"Starter onboarding task requires an initiative context. Re-run setup with the founder preset or create an initiative before requesting onboarding tasks.\",\n );\n }\n\n const workstream = await createEntity(\n \"workstream\",\n {\n initiative_id: initiativeId,\n status: \"active\",\n summary: ONBOARDING_WORKSTREAM_SUMMARY,\n title: ONBOARDING_WORKSTREAM_TITLE,\n workspace_id: workspace.id,\n },\n parseWorkstream,\n options,\n );\n\n const task = await createEntity(\n \"task\",\n {\n initiative_id: initiativeId,\n status: \"todo\",\n summary: ONBOARDING_TASK_SUMMARY,\n title: ONBOARDING_TASK_TITLE,\n workstream_id: workstream.id,\n workspace_id: workspace.id,\n },\n parseTask,\n options,\n );\n\n updateWizardState(\n (current) => ({\n ...current,\n onboardingTask: toOnboardingTaskRecord(task, workspace, {\n initiativeId,\n workstreamId: workstream.id,\n }),\n }),\n options.statePath,\n );\n\n return task;\n}\n","import type { CreateWorkspaceInput, OrgxWorkspace, SetDefaultWorkspaceInput } from \"./workspaces.js\";\n\nconst CREATE_WORKSPACE_VALUE = \"__create_workspace__\";\nconst SKIP_WORKSPACE_VALUE = \"__skip_workspace__\";\nconst REAUTH_WORKSPACE_VALUE = \"__reauth_workspace__\";\n\nexport interface WorkspaceSetupClient {\n createWorkspace(input: CreateWorkspaceInput): Promise<OrgxWorkspace>;\n getCurrentWorkspace(): Promise<OrgxWorkspace | null>;\n listWorkspaces(): Promise<OrgxWorkspace[]>;\n setDefaultWorkspace(\n input: SetDefaultWorkspaceInput,\n ): Promise<{ changed: boolean; workspace: OrgxWorkspace }>;\n}\n\nexport interface WorkspaceSelectOption {\n hint?: string;\n label: string;\n value: string;\n}\n\nexport interface WorkspaceSetupPrompts {\n cancel(message: string): void;\n isCancel(value: unknown): boolean;\n select(input: {\n initialValue?: string | undefined;\n message: string;\n options: WorkspaceSelectOption[];\n }): Promise<string | symbol>;\n text(input: {\n initialValue?: string | undefined;\n message: string;\n placeholder?: string;\n validate?: (value: string | undefined) => Error | string | undefined;\n }): Promise<string | symbol>;\n}\n\nexport interface WorkspaceSetupOptions {\n interactive: boolean;\n skipIfConfigured?: boolean;\n}\n\nexport interface WorkspaceSetupResult {\n created?: boolean;\n defaultChanged?: boolean;\n message: string;\n /**\n * \"reauth_requested\" — the caller should trigger the OAuth login flow and\n * then rerun setup. This is used when the key authenticates but returns no\n * workspaces — a strong signal the key is bound to a different Supabase\n * user than the one the human signs into via OAuth.\n */\n status: \"cancelled\" | \"skipped\" | \"unchanged\" | \"updated\" | \"reauth_requested\";\n workspace?: OrgxWorkspace;\n}\n\nfunction trimDescription(value: string): string | undefined {\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction cancelResult(\n prompts: WorkspaceSetupPrompts,\n message = \"Workspace bootstrap cancelled.\",\n): WorkspaceSetupResult {\n prompts.cancel(message);\n return {\n message,\n status: \"cancelled\",\n };\n}\n\nfunction buildWorkspaceLabel(workspace: OrgxWorkspace, currentWorkspaceId?: string): string {\n const suffixes: string[] = [];\n\n if (workspace.isDefault) {\n suffixes.push(\"default\");\n }\n\n if (workspace.id === currentWorkspaceId) {\n suffixes.push(\"current\");\n }\n\n if (suffixes.length === 0) {\n return workspace.name;\n }\n\n return `${workspace.name} (${suffixes.join(\", \")})`;\n}\n\nexport function buildWorkspaceSelectOptions(\n workspaces: OrgxWorkspace[],\n currentWorkspaceId?: string,\n): WorkspaceSelectOption[] {\n const options = workspaces.map((workspace) => ({\n value: workspace.id,\n label: buildWorkspaceLabel(workspace, currentWorkspaceId),\n ...(workspace.description ? { hint: workspace.description } : {}),\n }));\n\n options.push(\n {\n value: CREATE_WORKSPACE_VALUE,\n label: \"Create a new workspace\",\n hint: \"Name it here and set it as the default for this machine.\",\n },\n {\n value: SKIP_WORKSPACE_VALUE,\n label: \"Skip for now\",\n hint: \"Leave workspace selection unchanged and finish setup.\",\n },\n );\n\n return options;\n}\n\nasync function promptForWorkspaceName(prompts: WorkspaceSetupPrompts): Promise<string | symbol> {\n return prompts.text({\n message: \"Workspace name\",\n placeholder: \"Founders\",\n validate(value) {\n if (!value || value.trim().length === 0) {\n return \"Workspace name is required.\";\n }\n\n return undefined;\n },\n });\n}\n\nasync function promptForWorkspaceDescription(\n prompts: WorkspaceSetupPrompts,\n): Promise<string | symbol> {\n return prompts.text({\n message: \"Workspace description\",\n placeholder: \"Optional\",\n });\n}\n\nasync function createAndSelectWorkspace(\n client: WorkspaceSetupClient,\n prompts: WorkspaceSetupPrompts,\n): Promise<WorkspaceSetupResult> {\n const name = await promptForWorkspaceName(prompts);\n if (prompts.isCancel(name)) {\n return cancelResult(prompts);\n }\n if (typeof name !== \"string\") {\n return cancelResult(prompts);\n }\n\n const description = await promptForWorkspaceDescription(prompts);\n if (prompts.isCancel(description)) {\n return cancelResult(prompts);\n }\n if (typeof description !== \"string\") {\n return cancelResult(prompts);\n }\n\n const trimmedDescription = trimDescription(description);\n const createWorkspaceInput: CreateWorkspaceInput = trimmedDescription\n ? { name, description: trimmedDescription }\n : { name };\n\n const created = await client.createWorkspace(createWorkspaceInput);\n\n if (created.isDefault) {\n return {\n created: true,\n defaultChanged: false,\n message: `Created \"${created.name}\" and it is already the default OrgX workspace.`,\n status: \"updated\",\n workspace: created,\n };\n }\n\n const promoted = await client.setDefaultWorkspace({ id: created.id });\n return {\n created: true,\n defaultChanged: promoted.changed,\n message: `Created \"${promoted.workspace.name}\" and set it as the default OrgX workspace.`,\n status: \"updated\",\n workspace: promoted.workspace,\n };\n}\n\nexport async function runWorkspaceSetup(\n client: WorkspaceSetupClient,\n prompts: WorkspaceSetupPrompts,\n options: WorkspaceSetupOptions,\n): Promise<WorkspaceSetupResult> {\n if (!options.interactive) {\n return {\n message:\n \"Interactive workspace bootstrap skipped because this shell is not attached to a TTY.\",\n status: \"skipped\",\n };\n }\n\n const workspaces = await client.listWorkspaces();\n const currentWorkspace =\n workspaces.length > 0\n ? await client.getCurrentWorkspace().catch(() => workspaces.find((workspace) => workspace.isDefault) ?? null)\n : null;\n\n if (workspaces.length === 0) {\n // The API key authenticated successfully (we reached this function) but\n // the server returned zero workspaces for the resolved user. That is\n // ambiguous: it could mean a genuinely new account, OR the key is bound\n // to a different Supabase user row than the one that owns this person's\n // workspaces (e.g. the key was provisioned before the OAuth/Clerk sign-in\n // unified the user record). Creating a new workspace in that second case\n // silently forks the user's data — so surface the choice explicitly and\n // offer re-authentication as the first-class recovery path.\n const action = await prompts.select({\n message:\n \"OrgX authenticated, but returned 0 workspaces for this key. How should setup proceed?\",\n options: [\n {\n value: REAUTH_WORKSPACE_VALUE,\n label: \"Re-authenticate (recommended if you expected workspaces)\",\n hint: \"Run `wizard auth login` to re-link via OAuth if your API key is bound to a different user identity.\",\n },\n {\n value: CREATE_WORKSPACE_VALUE,\n label: \"Create a new workspace\",\n hint: \"Use this only for a truly new account — this will fork data if your key is misbound.\",\n },\n {\n value: SKIP_WORKSPACE_VALUE,\n label: \"Skip for now\",\n hint: \"Finish surface setup without touching workspaces.\",\n },\n ],\n initialValue: REAUTH_WORKSPACE_VALUE,\n });\n\n if (prompts.isCancel(action)) {\n return cancelResult(prompts);\n }\n\n if (action === REAUTH_WORKSPACE_VALUE) {\n return {\n message:\n \"Re-authentication requested. Run `wizard auth login`, then rerun `wizard setup`.\",\n status: \"reauth_requested\",\n };\n }\n\n if (action === SKIP_WORKSPACE_VALUE) {\n return {\n message: \"Workspace bootstrap skipped.\",\n status: \"skipped\",\n };\n }\n\n return createAndSelectWorkspace(client, prompts);\n }\n\n if (options.skipIfConfigured && currentWorkspace) {\n return {\n defaultChanged: false,\n message: `Using \"${currentWorkspace.name}\" as the default OrgX workspace.`,\n status: \"unchanged\",\n workspace: currentWorkspace,\n };\n }\n\n const initialWorkspaceId =\n currentWorkspace?.id ??\n workspaces.find((workspace) => workspace.isDefault)?.id ??\n workspaces[0]?.id;\n const selected = await prompts.select({\n message: \"Choose the OrgX workspace this machine should use by default.\",\n options: buildWorkspaceSelectOptions(\n workspaces,\n currentWorkspace?.id ?? workspaces.find((workspace) => workspace.isDefault)?.id,\n ),\n ...(initialWorkspaceId ? { initialValue: initialWorkspaceId } : {}),\n });\n\n if (prompts.isCancel(selected)) {\n return cancelResult(prompts);\n }\n if (typeof selected !== \"string\") {\n return cancelResult(prompts);\n }\n\n if (selected === SKIP_WORKSPACE_VALUE) {\n return {\n message: \"Workspace bootstrap skipped.\",\n status: \"skipped\",\n ...(currentWorkspace ? { workspace: currentWorkspace } : {}),\n };\n }\n\n if (selected === CREATE_WORKSPACE_VALUE) {\n return createAndSelectWorkspace(client, prompts);\n }\n\n const chosenWorkspace = workspaces.find((workspace) => workspace.id === selected);\n if (!chosenWorkspace) {\n throw new Error(`Selected workspace ${selected} is no longer available.`);\n }\n\n if (chosenWorkspace.isDefault) {\n return {\n defaultChanged: false,\n message: `\"${chosenWorkspace.name}\" is already the default OrgX workspace.`,\n status: \"unchanged\",\n workspace: chosenWorkspace,\n };\n }\n\n const promoted = await client.setDefaultWorkspace({ id: chosenWorkspace.id });\n return {\n defaultChanged: promoted.changed,\n message: `Set \"${promoted.workspace.name}\" as the default OrgX workspace.`,\n status: promoted.changed ? \"updated\" : \"unchanged\",\n workspace: promoted.workspace,\n };\n}\n","import {\n ensureFounderDemoInitiative,\n type FounderDemoInitiativeResult,\n} from \"./initiatives.js\";\nimport { persistContinuityDefaults, type ContinuitySeed } from \"./continuity.js\";\nimport {\n DEFAULT_ORGX_SKILL_PACKS,\n installOrgxSkills,\n type SkillsInstallReport,\n} from \"./skills.js\";\nimport { listOrgxPluginStatuses } from \"./plugins.js\";\nimport {\n runWorkspaceSetup,\n type WorkspaceSetupOptions,\n type WorkspaceSetupPrompts,\n type WorkspaceSetupResult,\n} from \"./setup-workspace.js\";\nimport { listSurfaceStatuses, setupDetectedSurfaces, type SurfaceMutationResult } from \"../surfaces/registry.js\";\nimport {\n createWorkspace,\n getCurrentWorkspace,\n listWorkspaces,\n setDefaultWorkspace,\n type OrgxWorkspace,\n} from \"./workspaces.js\";\nimport type { WizardStateRecord } from \"./wizard-state.js\";\n\nexport interface FounderPresetResult {\n continuity: WizardStateRecord;\n demoInitiative?: FounderDemoInitiativeResult;\n skillReport: SkillsInstallReport;\n surfaceResults: SurfaceMutationResult[];\n workspace: OrgxWorkspace | null;\n workspaceSetup?: WorkspaceSetupResult;\n}\n\nexport async function runFounderPreset(\n prompts: WorkspaceSetupPrompts,\n options: WorkspaceSetupOptions & { pluginTargets?: readonly string[] },\n): Promise<FounderPresetResult | WorkspaceSetupResult> {\n const surfaceResults = await setupDetectedSurfaces();\n const pluginTargets = options.pluginTargets ?? (\n await listOrgxPluginStatuses()\n )\n .filter((status) => status.installed)\n .map((status) => status.target);\n const skillReport = await installOrgxSkills({\n pluginTargets,\n skillNames: [...DEFAULT_ORGX_SKILL_PACKS],\n });\n\n let workspaceSetup: WorkspaceSetupResult | undefined;\n let workspace = await getCurrentWorkspace().catch(() => null);\n\n if (workspace || options.interactive) {\n workspaceSetup = await runWorkspaceSetup(\n {\n createWorkspace,\n getCurrentWorkspace,\n listWorkspaces,\n setDefaultWorkspace,\n },\n prompts,\n options,\n );\n\n if (workspaceSetup.status === \"cancelled\") {\n return workspaceSetup;\n }\n\n workspace = workspaceSetup.workspace ?? workspace ?? await getCurrentWorkspace().catch(() => null);\n }\n\n const continuity = persistContinuityDefaults({\n statuses: listSurfaceStatuses(),\n workspace,\n });\n\n let demoInitiative: FounderDemoInitiativeResult | undefined;\n if (workspace) {\n demoInitiative = await ensureFounderDemoInitiative(workspace);\n }\n\n return {\n continuity,\n ...(demoInitiative ? { demoInitiative } : {}),\n skillReport,\n surfaceResults,\n workspace,\n ...(workspaceSetup ? { workspaceSetup } : {}),\n };\n}\n","import type { SurfaceMutationResult } from \"../surfaces/registry.js\";\n\nexport type MutationSummary = {\n name: string;\n state: \"updated\" | \"unchanged\";\n message: string;\n};\n\nexport function summarizeMutationResults(\n results: SurfaceMutationResult[],\n): MutationSummary[] {\n return results.map((result) => ({\n name: result.name,\n state: result.changed ? \"updated\" : \"unchanged\",\n message: result.message,\n }));\n}\n","import type { DoctorAssessment } from \"../surfaces/registry.js\";\n\nexport const HOSTED_MCP_OUTAGE_TITLE = \"Hosted OrgX MCP is unreachable.\";\n\nexport interface SetupVerificationSummary {\n hostedMcpDegraded: boolean;\n status: \"degraded\" | \"error\" | \"ok\" | \"warning\";\n}\n\nexport function getSetupVerificationHeadline(summary: SetupVerificationSummary): string {\n switch (summary.status) {\n case \"degraded\":\n return \"Hosted OrgX MCP is down; local setup can still continue.\";\n case \"error\":\n return \"Issues detected\";\n case \"warning\":\n return \"Warnings detected\";\n case \"ok\":\n return \"All systems ready.\";\n }\n}\n\nexport function summarizeSetupVerification(\n assessment: DoctorAssessment,\n): SetupVerificationSummary {\n const errors = assessment.issues.filter((issue) => issue.level === \"error\");\n if (errors.length === 0) {\n return {\n hostedMcpDegraded: false,\n status: assessment.issues.length > 0 ? \"warning\" : \"ok\",\n };\n }\n\n const hostedMcpDegraded = errors.every((issue) => issue.title === HOSTED_MCP_OUTAGE_TITLE);\n return {\n hostedMcpDegraded,\n status: hostedMcpDegraded ? \"degraded\" : \"error\",\n };\n}\n","import type { DoctorAssessment, DoctorReport } from \"../surfaces/registry.js\";\nimport type { FirstValueInitiativeResult, FounderDemoInitiativeResult, OrgxTask } from \"./initiatives.js\";\nimport type { SetupVerificationSummary } from \"./setup-verification.js\";\nimport type { WorkspaceSetupResult } from \"./setup-workspace.js\";\nimport type { WizardAgentRosterRecord } from \"./wizard-state.js\";\n\nfunction withBaseProperties(\n properties: Record<string, unknown>,\n base: Record<string, unknown>,\n): Record<string, unknown> {\n return {\n ...base,\n ...properties,\n };\n}\n\nexport function buildWorkspaceSetupTelemetryProperties(\n result: WorkspaceSetupResult,\n base: Record<string, unknown> = {},\n): Record<string, unknown> {\n return withBaseProperties(\n {\n created: result.created === true,\n default_changed: result.defaultChanged === true,\n has_workspace: Boolean(result.workspace),\n status: result.status,\n },\n base,\n );\n}\n\nexport function buildOnboardingTaskTelemetryProperties(\n input: {\n created: boolean;\n hasInitiative: boolean;\n task: Pick<OrgxTask, \"status\">;\n },\n base: Record<string, unknown> = {},\n): Record<string, unknown> {\n return withBaseProperties(\n {\n created: input.created,\n has_initiative: input.hasInitiative,\n task_status: input.task.status ?? \"unknown\",\n },\n base,\n );\n}\n\nexport function buildAgentRosterTelemetryProperties(\n input: {\n roster: WizardAgentRosterRecord;\n strategy: \"default\" | \"guided\";\n },\n base: Record<string, unknown> = {},\n): Record<string, unknown> {\n return withBaseProperties(\n {\n agent_count: input.roster.agents.length,\n domain_count: new Set(input.roster.agents.map((agent) => agent.domain)).size,\n strategy: input.strategy,\n },\n base,\n );\n}\n\nexport function buildFounderDemoTelemetryProperties(\n result: FounderDemoInitiativeResult,\n base: Record<string, unknown> = {},\n): Record<string, unknown> {\n return withBaseProperties(\n {\n created: result.created,\n decision_status: result.decision.status ?? \"unknown\",\n has_artifact_url: Boolean(result.artifact.url),\n },\n base,\n );\n}\n\nexport function buildFirstValueInitiativeTelemetryProperties(\n result: FirstValueInitiativeResult,\n base: Record<string, unknown> = {},\n): Record<string, unknown> {\n return withBaseProperties(\n {\n created: result.created,\n has_live_url: Boolean(result.liveUrl),\n },\n base,\n );\n}\n\nexport function buildDoctorTelemetryProperties(\n report: DoctorReport,\n assessment: DoctorAssessment,\n verification: SetupVerificationSummary,\n base: Record<string, unknown> = {},\n): Record<string, unknown> {\n const errorCount = assessment.issues.filter((issue) => issue.level === \"error\").length;\n const warningCount = assessment.issues.filter((issue) => issue.level === \"warning\").length;\n\n return withBaseProperties(\n {\n auth_configured: report.auth.configured,\n auth_ok: report.auth.ok,\n configured_surface_count: report.surfaces.filter((surface) => surface.configured).length,\n detected_surface_count: report.surfaces.filter((surface) => surface.detected).length,\n error_count: errorCount,\n hosted_mcp_degraded: verification.hostedMcpDegraded,\n hosted_mcp_ok: report.hostedMcp.ok,\n hosted_mcp_tool_ok: report.hostedMcpTool.ok,\n issue_count: assessment.issues.length,\n openclaw_available: !report.openclaw.skipped,\n openclaw_ok: report.openclaw.ok,\n status: verification.status,\n warning_count: warningCount,\n workspace_configured: report.workspace.configured,\n workspace_ok: report.workspace.ok,\n },\n base,\n );\n}\n","import { getOrCreateWizardInstallationId } from \"./wizard-state.js\";\n\nconst POSTHOG_DEFAULT_HOST = \"https://us.i.posthog.com\";\nconst WIZARD_LIB = \"@useorgx/wizard\";\n\nfunction isTruthyEnv(value: string | undefined): boolean {\n if (!value) return false;\n\n switch (value.trim().toLowerCase()) {\n case \"1\":\n case \"true\":\n case \"yes\":\n case \"y\":\n case \"on\":\n return true;\n default:\n return false;\n }\n}\n\nfunction isWizardTelemetryDisabled(): boolean {\n const explicitEnable = isTruthyEnv(process.env.ORGX_TELEMETRY_ENABLED);\n if (!explicitEnable) return true;\n\n return (\n isTruthyEnv(process.env.ORGX_TELEMETRY_DISABLED) ||\n isTruthyEnv(process.env.OPENCLAW_TELEMETRY_DISABLED) ||\n isTruthyEnv(process.env.POSTHOG_DISABLED)\n );\n}\n\nfunction resolvePosthogApiKey(): string | null {\n const value =\n process.env.ORGX_POSTHOG_API_KEY ??\n process.env.POSTHOG_API_KEY ??\n process.env.ORGX_POSTHOG_KEY ??\n process.env.POSTHOG_KEY ??\n \"\";\n const trimmed = value.trim();\n return trimmed || null;\n}\n\nfunction resolvePosthogHost(): string {\n const value =\n process.env.ORGX_POSTHOG_HOST ??\n process.env.POSTHOG_HOST ??\n process.env.ORGX_POSTHOG_API_HOST ??\n process.env.POSTHOG_API_HOST ??\n \"\";\n const trimmed = value.trim();\n return trimmed || POSTHOG_DEFAULT_HOST;\n}\n\nfunction toPosthogBatchUrl(host: string): string {\n try {\n return new URL(\"/batch/\", host).toString();\n } catch {\n return `${POSTHOG_DEFAULT_HOST}/batch/`;\n }\n}\n\nexport async function trackWizardTelemetry(\n event: string,\n properties: Record<string, unknown> = {},\n options: { statePath?: string; timestamp?: string } = {},\n): Promise<boolean> {\n if (isWizardTelemetryDisabled()) return false;\n\n const apiKey = resolvePosthogApiKey();\n if (!apiKey) return false;\n\n const installationId = getOrCreateWizardInstallationId(options.statePath);\n const timestamp = options.timestamp ?? new Date().toISOString();\n const response = await fetch(toPosthogBatchUrl(resolvePosthogHost()), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n api_key: apiKey,\n batch: [\n {\n type: \"capture\",\n event,\n distinct_id: installationId,\n properties: {\n $lib: WIZARD_LIB,\n source: WIZARD_LIB,\n wizard_installation_id: installationId,\n ...properties,\n },\n timestamp,\n },\n ],\n sent_at: timestamp,\n }),\n }).catch(() => null);\n\n return response?.ok === true;\n}\n","/**\n * Phase II · M-P5 — CLI intent capture\n *\n * Client-side bindings for the OrgX intents API (M-P2). The wizard POSTs a raw\n * intent, the server classifies it to an agent + generates a plan preview, and\n * the CLI surface renders that payload with the OrgX terminal vocabulary\n * (agent-colored routing line, mono confidence decimal, box-drawn plan, `>>`\n * hotkey bar). Approve / archive PATCH the row; \"edit in browser\" hands off to\n * `/command?intent=<slug>`.\n *\n * The contract mirrors `orgx/types/intents.ts` in the main monorepo; the shape\n * is duplicated here (not imported) because orgx-wizard is a separate npm\n * package shipped independently. Keeping the types narrow + local lets us\n * avoid a cross-repo dependency while still being strict at the boundary.\n */\n\nimport {\n buildOrgxApiUrl,\n resolveOrgxAuth,\n type ResolveOrgxAuthOptions,\n} from \"./auth.js\";\nimport { isRecord } from \"./fs.js\";\n\n/** Canonical agent slugs the classifier can emit (mirror of @/types/intents). */\nexport const AGENT_SLUGS = [\n \"mark\",\n \"eli\",\n \"dana\",\n \"pace\",\n \"sage\",\n \"orion\",\n \"xandy\",\n] as const;\n\nexport type AgentSlug = (typeof AGENT_SLUGS)[number];\n\nexport const INTENT_STATUSES = [\n \"pending\",\n \"approved\",\n \"adjusted\",\n \"archived\",\n] as const;\n\nexport type IntentStatus = (typeof INTENT_STATUSES)[number];\n\n/** Confidence bucket returned by the server. */\nexport type IntentConfidence = \"low\" | \"med\" | \"high\";\n\nexport interface IntentPlanStep {\n title: string;\n detail?: string;\n agent_slug?: AgentSlug;\n}\n\nexport interface IntentPlanPreview {\n steps: IntentPlanStep[];\n eta: string;\n confidence: IntentConfidence;\n}\n\nexport interface Intent {\n id: string;\n workspace_id: string;\n slug: string;\n text: string;\n status: IntentStatus;\n suggested_agent_slug: AgentSlug | null;\n plan_preview: IntentPlanPreview;\n approved_at: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface CreateIntentInput {\n workspace_id: string;\n text: string;\n}\n\nexport interface UpdateIntentInput {\n status: Exclude<IntentStatus, \"pending\">;\n text?: string;\n plan_preview?: IntentPlanPreview;\n}\n\nexport interface OrgxIntentsClientOptions extends ResolveOrgxAuthOptions {}\n\n/** Role labels for the `→ Agent · Role` routing line. */\nexport const AGENT_ROLES: Record<AgentSlug, string> = {\n mark: \"Partnerships\",\n eli: \"Engineering\",\n dana: \"Brand\",\n pace: \"Product\",\n sage: \"Strategy\",\n orion: \"Routing\",\n xandy: \"Default\",\n};\n\n/**\n * Deterministic bucket → decimal mapping used by the CLI render layer.\n *\n * The design spec (Phase II · M-P0 Surface 3) locks the CLI to a mono\n * confidence decimal (`0.87`) and explicitly rejects `low / med / high`\n * buckets. The M-P2 API still returns the bucket, so we render a\n * representative decimal per bucket here. Values are chosen to match the\n * spec's example band (0.55 / 0.78 / 0.92) and to read like the output of\n * a real classifier rather than round magic numbers.\n */\nexport const CONFIDENCE_DECIMAL: Record<IntentConfidence, number> = {\n low: 0.55,\n med: 0.78,\n high: 0.92,\n};\n\n/**\n * Per-agent ANSI 256-color codes used to tint the `→ Agent · Role` routing\n * line. Values mirror the tokens called out in the M-P0 spec so the terminal\n * identity stays aligned with the web `--agent-accent-rgb` directory.\n */\nexport const AGENT_ANSI_256: Record<AgentSlug, number> = {\n pace: 34, // green\n eli: 44, // cyan\n mark: 208, // orange\n sage: 135, // purple\n orion: 214, // amber\n dana: 199, // pink\n xandy: 37, // teal\n};\n\nfunction parseAgentSlug(value: unknown): AgentSlug | null {\n if (typeof value !== \"string\") return null;\n return (AGENT_SLUGS as readonly string[]).includes(value)\n ? (value as AgentSlug)\n : null;\n}\n\nfunction parseStatus(value: unknown): IntentStatus | null {\n if (typeof value !== \"string\") return null;\n return (INTENT_STATUSES as readonly string[]).includes(value)\n ? (value as IntentStatus)\n : null;\n}\n\nfunction parseConfidence(value: unknown): IntentConfidence {\n if (value === \"low\" || value === \"med\" || value === \"high\") return value;\n return \"med\";\n}\n\nfunction parsePlanStep(value: unknown): IntentPlanStep | null {\n if (!isRecord(value)) return null;\n const title = typeof value.title === \"string\" ? value.title.trim() : \"\";\n if (!title) return null;\n\n const detail =\n typeof value.detail === \"string\" && value.detail.trim().length > 0\n ? value.detail\n : undefined;\n const agentSlug = parseAgentSlug(value.agent_slug);\n\n const step: IntentPlanStep = { title };\n if (detail !== undefined) step.detail = detail;\n if (agentSlug !== null) step.agent_slug = agentSlug;\n return step;\n}\n\nfunction parsePlanPreview(value: unknown): IntentPlanPreview {\n if (!isRecord(value)) {\n return { steps: [], eta: \"under a week\", confidence: \"med\" };\n }\n\n const steps = Array.isArray(value.steps)\n ? value.steps\n .map(parsePlanStep)\n .filter((step): step is IntentPlanStep => step !== null)\n : [];\n const eta =\n typeof value.eta === \"string\" && value.eta.trim().length > 0\n ? value.eta\n : \"under a week\";\n return {\n steps,\n eta,\n confidence: parseConfidence(value.confidence),\n };\n}\n\nexport function parseIntent(value: unknown): Intent | null {\n if (!isRecord(value)) return null;\n\n const id = typeof value.id === \"string\" ? value.id : null;\n const workspaceId =\n typeof value.workspace_id === \"string\" ? value.workspace_id : null;\n const slug = typeof value.slug === \"string\" ? value.slug : null;\n const text = typeof value.text === \"string\" ? value.text : null;\n const status = parseStatus(value.status);\n const createdAt =\n typeof value.created_at === \"string\" ? value.created_at : null;\n const updatedAt =\n typeof value.updated_at === \"string\" ? value.updated_at : null;\n\n if (!id || !workspaceId || !slug || !text || !status || !createdAt || !updatedAt) {\n return null;\n }\n\n return {\n id,\n workspace_id: workspaceId,\n slug,\n text,\n status,\n suggested_agent_slug: parseAgentSlug(value.suggested_agent_slug),\n plan_preview: parsePlanPreview(value.plan_preview),\n approved_at:\n typeof value.approved_at === \"string\" ? value.approved_at : null,\n created_at: createdAt,\n updated_at: updatedAt,\n };\n}\n\nasync function parseResponseBody(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction formatHttpError(status: number, body: unknown): string {\n if (typeof body === \"string\" && body.trim().length > 0) {\n return `HTTP ${status}: ${body}`;\n }\n if (isRecord(body)) {\n // The intents API wraps errors as `{ error: { code, message } }`.\n if (isRecord(body.error)) {\n const message =\n typeof body.error.message === \"string\" ? body.error.message : null;\n const code = typeof body.error.code === \"string\" ? body.error.code : null;\n if (message) return `HTTP ${status} (${code ?? \"error\"}): ${message}`;\n }\n if (typeof body.error === \"string\" && body.error.trim().length > 0) {\n return `HTTP ${status}: ${body.error}`;\n }\n }\n return `HTTP ${status}`;\n}\n\nasync function requireOrgxAuth(options: OrgxIntentsClientOptions = {}) {\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n throw new Error(\n \"No OrgX API key configured. Run `orgx-wizard auth login` or `orgx-wizard auth set-key <oxk_...>` first.\",\n );\n }\n return auth;\n}\n\n/**\n * POST /api/v1/intents — create a pending intent.\n *\n * The server classifies the raw text to an agent slug and generates a plan\n * preview before persisting. The returned `Intent` row carries the slug used\n * for the browser handoff URL (`/command?intent=<slug>`).\n */\nexport async function createIntent(\n input: CreateIntentInput,\n options: OrgxIntentsClientOptions = {},\n): Promise<Intent> {\n const text = input.text.trim();\n if (!text) {\n throw new Error(\"Intent text is required.\");\n }\n if (text.length > 4_000) {\n throw new Error(\"Intent text exceeds 4,000 characters.\");\n }\n\n const workspaceId = input.workspace_id.trim();\n if (!workspaceId) {\n throw new Error(\"Workspace id is required.\");\n }\n\n const auth = await requireOrgxAuth(options);\n const url = buildOrgxApiUrl(\"/v1/intents\", auth.baseUrl);\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ workspace_id: workspaceId, text }),\n signal: AbortSignal.timeout(15_000),\n });\n const body = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new Error(\n `Failed to create intent. ${formatHttpError(response.status, body)}`,\n );\n }\n\n const intent = parseIntent(body);\n if (!intent) {\n throw new Error(\"OrgX returned an unexpected intent payload.\");\n }\n return intent;\n}\n\n/**\n * PATCH /api/v1/intents/:id — transition an intent to approved / adjusted /\n * archived. The hotkey bar uses this for `[A]pprove` and `[X]archive`.\n */\nexport async function updateIntent(\n id: string,\n input: UpdateIntentInput,\n options: OrgxIntentsClientOptions = {},\n): Promise<Intent> {\n const trimmedId = id.trim();\n if (!trimmedId) {\n throw new Error(\"Intent id is required.\");\n }\n\n const auth = await requireOrgxAuth(options);\n const url = buildOrgxApiUrl(`/v1/intents/${encodeURIComponent(trimmedId)}`, auth.baseUrl);\n const response = await fetch(url, {\n method: \"PATCH\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(input),\n signal: AbortSignal.timeout(15_000),\n });\n const body = await parseResponseBody(response);\n\n if (!response.ok) {\n throw new Error(\n `Failed to update intent. ${formatHttpError(response.status, body)}`,\n );\n }\n\n const intent = parseIntent(body);\n if (!intent) {\n throw new Error(\"OrgX returned an unexpected intent update payload.\");\n }\n return intent;\n}\n\n/**\n * Build the handoff URL for the web composer. Used by the `[E]dit in browser`\n * hotkey and by the approve flow's confirmation line.\n */\nexport function buildIntentHandoffUrl(\n slug: string,\n options: { baseUrl?: string } = {},\n): string {\n const base = options.baseUrl?.trim() || \"https://useorgx.com\";\n const normalized = base.replace(/\\/+$/, \"\");\n return `${normalized}/command?intent=${encodeURIComponent(slug)}`;\n}\n","/**\n * Phase II · M-P5 — Terminal rendering for Surface 3 (CLI Intent capture).\n *\n * Pure, side-effect-free render helpers. The CLI action layer calls these to\n * build strings it then prints — keeping the module testable without stubbing\n * `process.stdout` or picocolors.\n *\n * Style budget comes from the M-P0 design spec:\n * - Agent-colored `→ Agent · Role` routing line (ANSI 256 per-agent)\n * - Mono confidence decimal (never a bucket word)\n * - Box-drawn plan preview — no ASCII art, no drop-shadow-via-shading\n * - `>>` hotkey bar with single-letter verbs `[A]pprove [E]dit [X]archive [Q]uit`\n * - Respect NO_COLOR (fall back to plain ASCII) + CI / non-TTY (skip spinners)\n */\n\nimport {\n AGENT_ANSI_256,\n AGENT_ROLES,\n CONFIDENCE_DECIMAL,\n type AgentSlug,\n type IntentPlanPreview,\n} from \"./intents.js\";\n\nexport interface RenderOptions {\n /** Disable ANSI color output. Derived from NO_COLOR env by default. */\n noColor?: boolean;\n /**\n * Disable unicode box-drawing / glyphs. Falls back to ASCII equivalents —\n * used when the locale cannot represent the characters. Distinct from\n * `noColor`: a truecolor terminal in a plain LC_ALL=C locale wants color on,\n * unicode off.\n */\n asciiOnly?: boolean;\n}\n\n/**\n * Cheap env snapshot so CLI action code can pass the same options to every\n * render helper without repeatedly consulting process.env.\n */\nexport function detectRenderCapabilities(\n env: NodeJS.ProcessEnv = process.env,\n): Required<RenderOptions> {\n const noColor = Boolean(env.NO_COLOR && env.NO_COLOR.length > 0);\n // Many CI runners (`CI=1`) honor NO_COLOR automatically, but some don't.\n // We defer to NO_COLOR for color decisions and only use CI/non-TTY to\n // downgrade motion (see isInteractive).\n const asciiOnly =\n (env.LC_ALL ?? \"\").toUpperCase() === \"C\" ||\n (env.LANG ?? \"\").toUpperCase() === \"C\";\n return { noColor, asciiOnly };\n}\n\n/**\n * Whether the wizard should render motion (spinners, line-by-line stagger).\n * Returns false in CI, when stdout is not a TTY, or when reduced-motion\n * heuristics apply. CLI action code checks this before starting a spinner\n * and prints a plain status line instead.\n */\nexport function isInteractive(\n env: NodeJS.ProcessEnv = process.env,\n isTTY: boolean = Boolean((process.stdout as { isTTY?: boolean }).isTTY),\n): boolean {\n if (!isTTY) return false;\n if (env.CI === \"1\" || env.CI === \"true\") return false;\n // GitHub Actions / Circle / etc. generally set CI; this is belt + suspenders.\n if (env.GITHUB_ACTIONS === \"true\") return false;\n return true;\n}\n\nconst CSI = \"\\u001b[\";\n\nfunction wrap(code: string, text: string, enabled: boolean): string {\n if (!enabled) return text;\n return `${CSI}${code}m${text}${CSI}0m`;\n}\n\nexport function colorize(\n text: string,\n ansi256: number,\n options: RenderOptions = {},\n): string {\n return wrap(`38;5;${ansi256}`, text, !options.noColor);\n}\n\nexport function bold(text: string, options: RenderOptions = {}): string {\n return wrap(\"1\", text, !options.noColor);\n}\n\nexport function dim(text: string, options: RenderOptions = {}): string {\n return wrap(\"2\", text, !options.noColor);\n}\n\n/**\n * Format a confidence decimal with two digits (`0.87`). The design spec locks\n * this to the mono two-digit form; we never emit a bucket word.\n */\nexport function formatConfidence(value: number): string {\n const bounded = Math.max(0, Math.min(1, value));\n return bounded.toFixed(2);\n}\n\n/**\n * `→ Pace · Product confidence 0.87`\n *\n * The agent name is colored via the ANSI 256 directory; the rest of the line\n * stays in default foreground so the eye anchors on the identity. Role comes\n * from AGENT_ROLES so copy is stable across CLI and web.\n */\nexport function renderRoutingLine(\n agent: AgentSlug,\n confidence: number,\n options: RenderOptions = {},\n): string {\n const arrow = options.asciiOnly ? \"->\" : \"→\";\n const separator = options.asciiOnly ? \" - \" : \" · \";\n const role = AGENT_ROLES[agent];\n const name = agent.charAt(0).toUpperCase() + agent.slice(1);\n const coloredName = colorize(name, AGENT_ANSI_256[agent], options);\n const confidenceLabel = dim(\"confidence\", options);\n const confidenceValue = formatConfidence(confidence);\n return ` ${arrow} ${bold(coloredName, options)}${separator}${role} ${confidenceLabel} ${confidenceValue}`;\n}\n\n/**\n * Derive the CLI confidence decimal from the server payload. The M-P2 API\n * returns a bucket (`low | med | high`); the spec requires a decimal on this\n * surface, so we map through a deterministic directory. When a later\n * milestone upgrades the classifier to emit a real score, the CLI can switch\n * to that number without changing the render layer.\n */\nexport function resolveConfidenceDecimal(\n plan: IntentPlanPreview,\n): number {\n return CONFIDENCE_DECIMAL[plan.confidence];\n}\n\n/**\n * Render the box-drawn plan preview block.\n *\n * ┌─ Plan preview ─────────────────────┐\n * │ 1. Draft outreach positioning │\n * │ 2. Build target list (50 accounts) │\n * │ 3. Send first wave this week │\n * │ │\n * │ ETA under a week │\n * └────────────────────────────────────┘\n *\n * No drop shadow, no color fills, no rainbow borders — box-drawing only,\n * per the mediocrity risk call-outs in the spec (\"over-ASCII-art trap\").\n */\nexport function renderPlanPreview(\n plan: IntentPlanPreview,\n options: RenderOptions = {},\n): string {\n const horizontal = options.asciiOnly ? \"-\" : \"─\";\n const topLeft = options.asciiOnly ? \"+\" : \"┌\";\n const topRight = options.asciiOnly ? \"+\" : \"┐\";\n const bottomLeft = options.asciiOnly ? \"+\" : \"└\";\n const bottomRight = options.asciiOnly ? \"+\" : \"┘\";\n const vertical = options.asciiOnly ? \"|\" : \"│\";\n\n const steps = plan.steps.map((step, index) => {\n const number = `${index + 1}.`.padEnd(3, \" \");\n return `${number} ${step.title}`;\n });\n const etaLine = `ETA ${plan.eta}`;\n\n const lines = [...steps, \"\", etaLine];\n const label = \"Plan preview\";\n // Body row format is `│ <content> │` — content gets one space padding on\n // each side, so the inner-content column has width `contentWidth`.\n const contentWidth = Math.max(\n // Keep enough room for the top-chrome label plus its \"─ \" prefix and\n // a minimum trailing dash so the border visually wraps the label.\n label.length + 4,\n ...lines.map((line) => line.length),\n );\n\n // Total horizontal glyph count inside the chrome (matches bottom border).\n const innerWidth = contentWidth + 2; // leading + trailing space per body row\n // Top chrome: \"┌─ Plan preview ─────────────┐\" — same glyph count as bottom.\n const leadingDashes = horizontal.repeat(1);\n const trailingDashes = horizontal.repeat(\n Math.max(1, innerWidth - label.length - 3), // leading dash + 2 spaces\n );\n const top = `${topLeft}${leadingDashes} ${label} ${trailingDashes}${topRight}`;\n\n const body = lines\n .map((line) => {\n const padded = line.padEnd(contentWidth, \" \");\n return `${vertical} ${padded} ${vertical}`;\n })\n .join(\"\\n\");\n\n const bottom = `${bottomLeft}${horizontal.repeat(innerWidth)}${bottomRight}`;\n\n return [top, body, bottom].join(\"\\n\");\n}\n\n/**\n * `>> [A]pprove [E]dit in browser [X]archive [Q]uit`\n *\n * Single-letter hotkeys, mono-spaced, opinionated verb order. Approve is the\n * default. Colors mirror the web token directory: lime for the primary verb,\n * amber for adjust/edit, rose for archive, dim for quit.\n */\nexport interface HotkeyBarEntry {\n key: string;\n label: string;\n tone?: \"primary\" | \"warning\" | \"danger\" | \"neutral\";\n}\n\nconst TONE_ANSI: Record<NonNullable<HotkeyBarEntry[\"tone\"]>, number> = {\n primary: 190, // lime (--ox-primary)\n warning: 214, // amber (adjust)\n danger: 203, // rose (archive)\n neutral: 244, // bright black (quit)\n};\n\nexport function renderHotkeyBar(\n entries: HotkeyBarEntry[],\n options: RenderOptions = {},\n): string {\n const prefix = options.asciiOnly ? \">>\" : \">>\";\n const segments = entries.map((entry) => {\n const tone = entry.tone ?? \"neutral\";\n const keyLabel = `[${entry.key.toUpperCase()}]`;\n const coloredKey = colorize(keyLabel, TONE_ANSI[tone], options);\n return `${coloredKey}${entry.label}`;\n });\n return `${prefix} ${segments.join(\" \")}`;\n}\n\nexport const DEFAULT_HOTKEYS: HotkeyBarEntry[] = [\n { key: \"a\", label: \"pprove\", tone: \"primary\" },\n { key: \"e\", label: \"dit in browser\", tone: \"warning\" },\n { key: \"x\", label: \"archive\", tone: \"danger\" },\n { key: \"q\", label: \"uit\", tone: \"neutral\" },\n];\n\n/**\n * Normalize a keystroke to one of the hotkey verbs. Returns `null` for\n * ignored keys (CLI re-prompts instead of misinterpreting ambiguous input).\n */\nexport type IntentAction = \"approve\" | \"edit\" | \"archive\" | \"quit\";\n\nexport function normalizeHotkey(input: string): IntentAction | null {\n const trimmed = input.trim().toLowerCase();\n if (trimmed.length === 0) return null;\n const ch = trimmed.charAt(0);\n switch (ch) {\n case \"a\":\n return \"approve\";\n case \"e\":\n return \"edit\";\n case \"x\":\n return \"archive\";\n case \"q\":\n return \"quit\";\n default:\n return null;\n }\n}\n","import {\n buildOrgxApiUrl,\n resolveOrgxAuth,\n type ResolveOrgxAuthOptions,\n} from \"./auth.js\";\nimport type { OrgxWorkspace } from \"./workspaces.js\";\nimport {\n getDailyBriefOnboardingDecision,\n recordDailyBriefOnboardingDecision,\n} from \"./wizard-state.js\";\n\n/**\n * Pull a short, user-readable hint out of an HTTP error body. Handles the\n * three shapes the orgx backend emits:\n * { error: \"string\" }\n * { error: { code?, message? } }\n * { error: \"...\", details: { fieldErrors?: {...} } }\n * Falls back to null if nothing useful is present (caller uses `HTTP NNN`).\n */\nfunction extractErrorHint(body: string): string | null {\n if (!body) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return body.slice(0, 160);\n }\n if (!parsed || typeof parsed !== \"object\") return null;\n const obj = parsed as Record<string, unknown>;\n const err = obj.error;\n if (typeof err === \"string\") return err;\n if (err && typeof err === \"object\") {\n const message = (err as Record<string, unknown>).message;\n if (typeof message === \"string\") return message;\n const code = (err as Record<string, unknown>).code;\n if (typeof code === \"string\") return code;\n }\n return null;\n}\n\n/**\n * Daily Brief + Trust Loop — wizard onboarding capture.\n *\n * Mirrors the web OnboardingCaptureScreen component at four steps:\n * Step A — agent roster preview (defaults, no customization in CLI for v1)\n * Step B — baseline prompts for task-type minutes\n * Step C — optional weekly time-saved goal\n * Step D — send-time preference (local time + timezone auto-detected)\n *\n * Commits atomically via POST /api/v1/onboarding/daily-brief.\n *\n * Gated on GET /api/v1/onboarding/daily-brief returning\n * workspaces[n].onboardingCompletedAt IS NULL — existing paired users\n * (v0.1.16 fast-path) skip unless they've never completed the capture.\n */\n\nexport interface DailyBriefOnboardingPrompts {\n cancel(message: string): void;\n isCancel(value: unknown): boolean;\n text(input: {\n initialValue?: string | undefined;\n message: string;\n placeholder?: string;\n validate?: (value: string | undefined) => Error | string | undefined;\n }): Promise<string | symbol>;\n select(input: {\n initialValue?: string | undefined;\n message: string;\n options: { label: string; value: string; hint?: string }[];\n }): Promise<string | symbol>;\n confirm(input: { message: string; initialValue?: boolean }): Promise<boolean | symbol>;\n}\n\nexport interface DailyBriefOnboardingOptions {\n authOptions?: ResolveOrgxAuthOptions;\n force?: boolean;\n interactive: boolean;\n skip?: boolean;\n statePath?: string;\n workspace: OrgxWorkspace | null;\n prompts: DailyBriefOnboardingPrompts;\n}\n\nexport interface DailyBriefOnboardingResult {\n status:\n | \"completed\"\n | \"skipped_non_interactive\"\n | \"skipped_already_completed\"\n | \"skipped_no_workspace\"\n | \"skipped_user\"\n | \"cancelled\"\n | \"failed\";\n message: string;\n previewUrl?: string;\n error?: string;\n}\n\ninterface BaselinePrompt {\n task_type: string;\n label: string;\n placeholder: string;\n}\n\nconst BASELINE_PROMPTS: BaselinePrompt[] = [\n { task_type: \"code_review\", label: \"Code review\", placeholder: \"20\" },\n { task_type: \"prd_draft\", label: \"PRD draft\", placeholder: \"45\" },\n { task_type: \"test_writeup\", label: \"Test writeup\", placeholder: \"25\" },\n { task_type: \"pr_description\", label: \"PR description\", placeholder: \"10\" },\n { task_type: \"launch_post\", label: \"Launch post\", placeholder: \"60\" },\n { task_type: \"architecture_doc\", label: \"Architecture doc\", placeholder: \"90\" },\n];\n\nconst DAILY_BRIEF_SETUP_CHOICES = {\n defaults: \"defaults\",\n customize: \"customize\",\n skip: \"skip\",\n} as const;\n\nfunction buildDefaultBaselines(): { task_type: string; minutes: number; confidence: number }[] {\n return BASELINE_PROMPTS.map((bp) => ({\n task_type: bp.task_type,\n minutes: Number.parseInt(bp.placeholder, 10),\n confidence: 0.4,\n }));\n}\n\nfunction buildDefaultGoals(): {\n goal_type: \"time_saved_weekly\";\n target_value: number;\n unit: string;\n period: \"weekly\";\n}[] {\n return [\n {\n goal_type: \"time_saved_weekly\",\n target_value: 180,\n unit: \"minutes\",\n period: \"weekly\",\n },\n ];\n}\n\nfunction normalizeSendTime(value: string): string {\n return value.trim().length === 4 ? `0${value.trim()}` : value.trim();\n}\n\nfunction recordSkipped(\n workspace: OrgxWorkspace,\n statePath?: string,\n): DailyBriefOnboardingResult {\n recordDailyBriefOnboardingDecision(\n {\n workspaceId: workspace.id,\n workspaceName: workspace.name,\n status: \"skipped\",\n skippedAt: new Date().toISOString(),\n },\n statePath,\n );\n return {\n status: \"skipped_user\",\n message: \"Daily Brief setup skipped. Run `wizard setup --daily-brief` when ready.\",\n };\n}\n\nexport async function runDailyBriefOnboarding(\n options: DailyBriefOnboardingOptions,\n): Promise<DailyBriefOnboardingResult> {\n if (!options.workspace) {\n return {\n status: \"skipped_no_workspace\",\n message: \"Daily Brief onboarding skipped — no workspace resolved.\",\n };\n }\n\n if (options.skip) {\n return recordSkipped(options.workspace, options.statePath);\n }\n\n const localDecision = getDailyBriefOnboardingDecision(\n options.workspace.id,\n options.statePath,\n );\n if (!options.force && localDecision) {\n return {\n status: \"skipped_already_completed\",\n message:\n localDecision.status === \"completed\"\n ? \"Daily Brief onboarding already completed for this workspace.\"\n : \"Daily Brief setup was skipped for this workspace. Run `wizard setup --daily-brief` to configure.\",\n };\n }\n\n if (!options.interactive) {\n return {\n status: \"skipped_non_interactive\",\n message: \"Daily Brief onboarding skipped — not attached to a TTY.\",\n };\n }\n\n const auth = await resolveOrgxAuth(options.authOptions);\n if (!auth) {\n return {\n status: \"failed\",\n message: \"Daily Brief onboarding needs OrgX auth.\",\n error: \"no_auth\",\n };\n }\n\n // Gate: is this workspace already onboarded?\n const state = await fetchOnboardingState(auth).catch(() => null);\n if (state) {\n const row = state.workspaces.find((w) => w.id === options.workspace!.id);\n if (row?.onboardingCompletedAt) {\n recordDailyBriefOnboardingDecision(\n {\n workspaceId: options.workspace.id,\n workspaceName: options.workspace.name,\n status: \"completed\",\n completedAt: row.onboardingCompletedAt,\n },\n options.statePath,\n );\n return {\n status: \"skipped_already_completed\",\n message: \"Daily Brief onboarding already completed for this workspace.\",\n };\n }\n }\n\n const { prompts } = options;\n\n const setupChoice = await prompts.select({\n message: \"Set up Daily Brief now?\",\n initialValue: DAILY_BRIEF_SETUP_CHOICES.defaults,\n options: [\n {\n value: DAILY_BRIEF_SETUP_CHOICES.defaults,\n label: \"Use defaults\",\n hint: \"20m code review, 45m PRD, 07:00 daily.\",\n },\n {\n value: DAILY_BRIEF_SETUP_CHOICES.customize,\n label: \"Customize baselines\",\n hint: \"Answer baseline and delivery questions.\",\n },\n {\n value: DAILY_BRIEF_SETUP_CHOICES.skip,\n label: \"Skip and remember\",\n hint: \"Do not ask again unless you pass --daily-brief.\",\n },\n ],\n });\n if (prompts.isCancel(setupChoice)) {\n return { status: \"cancelled\", message: \"Daily Brief onboarding cancelled.\" };\n }\n if (setupChoice === DAILY_BRIEF_SETUP_CHOICES.skip) {\n return recordSkipped(options.workspace, options.statePath);\n }\n\n const shouldCustomize = setupChoice === DAILY_BRIEF_SETUP_CHOICES.customize;\n\n const baselines: { task_type: string; minutes: number; confidence: number }[] =\n shouldCustomize ? [] : buildDefaultBaselines();\n if (shouldCustomize) {\n for (const bp of BASELINE_PROMPTS) {\n const answer = await prompts.text({\n message: `${bp.label} minutes`,\n placeholder: bp.placeholder,\n validate(value) {\n if (!value || value.trim() === \"\") return undefined;\n const n = Number.parseInt(value, 10);\n if (!Number.isFinite(n) || n <= 0 || n > 24 * 60) {\n return \"Enter 1-1440 or leave blank.\";\n }\n return undefined;\n },\n });\n if (prompts.isCancel(answer)) {\n return { status: \"cancelled\", message: \"Daily Brief onboarding cancelled.\" };\n }\n if (typeof answer === \"string\" && answer.trim() !== \"\") {\n const minutes = Number.parseInt(answer, 10);\n if (Number.isFinite(minutes) && minutes > 0) {\n baselines.push({ task_type: bp.task_type, minutes, confidence: 0.5 });\n }\n }\n }\n }\n\n const goals: {\n goal_type: \"time_saved_weekly\";\n target_value: number;\n unit: string;\n period: \"weekly\";\n }[] = shouldCustomize ? [] : buildDefaultGoals();\n if (shouldCustomize) {\n const goalAnswer = await prompts.text({\n message: \"Weekly time-saved target minutes\",\n placeholder: \"180\",\n validate(value) {\n if (!value || value.trim() === \"\") return undefined;\n const n = Number.parseInt(value, 10);\n if (!Number.isFinite(n) || n <= 0) {\n return \"Enter a positive number or leave blank.\";\n }\n return undefined;\n },\n });\n if (prompts.isCancel(goalAnswer)) {\n return { status: \"cancelled\", message: \"Daily Brief onboarding cancelled.\" };\n }\n if (typeof goalAnswer === \"string\" && goalAnswer.trim() !== \"\") {\n const target = Number.parseInt(goalAnswer, 10);\n if (Number.isFinite(target) && target > 0) {\n goals.push({\n goal_type: \"time_saved_weekly\",\n target_value: target,\n unit: \"minutes\",\n period: \"weekly\",\n });\n }\n }\n }\n\n let sendTimeLocal = \"07:00\";\n let onlyOnAttention = false;\n if (shouldCustomize) {\n const sendTimeAnswer = await prompts.text({\n message: \"Daily brief time (HH:MM)\",\n placeholder: \"07:00\",\n validate(value) {\n if (!value || value.trim() === \"\") return undefined;\n if (!/^\\d{1,2}:\\d{2}$/.test(value.trim())) {\n return \"Use HH:MM (24h).\";\n }\n return undefined;\n },\n });\n if (prompts.isCancel(sendTimeAnswer)) {\n return { status: \"cancelled\", message: \"Daily Brief onboarding cancelled.\" };\n }\n sendTimeLocal =\n typeof sendTimeAnswer === \"string\" && sendTimeAnswer.trim()\n ? normalizeSendTime(sendTimeAnswer)\n : \"07:00\";\n\n const onlyOnAttentionAnswer = await prompts.confirm({\n message: \"Email only when attention is needed?\",\n initialValue: false,\n });\n if (prompts.isCancel(onlyOnAttentionAnswer)) {\n return { status: \"cancelled\", message: \"Daily Brief onboarding cancelled.\" };\n }\n onlyOnAttention = Boolean(onlyOnAttentionAnswer);\n }\n\n // Commit\n const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || \"UTC\";\n\n const commitPayload = {\n workspace_id: options.workspace.id,\n agent_roster: [\n { id: \"engineering-agent\", display_name: \"Eli\", color: \"6, 182, 212\", enabled: true },\n { id: \"product-agent\", display_name: \"Pace\", color: \"22, 163, 74\", enabled: true },\n { id: \"marketing-agent\", display_name: \"Mark\", color: \"249, 115, 22\", enabled: true },\n { id: \"orchestrator-agent\", display_name: \"Xandy\", color: \"20, 184, 166\", enabled: true },\n ],\n baselines,\n goals,\n starter_skill_loadouts: [],\n notification_preference: {\n channel: \"email\" as const,\n digest_kind: \"daily_brief\" as const,\n enabled: true,\n send_time_local: `${sendTimeLocal}:00`,\n timezone,\n only_on_attention: onlyOnAttention,\n },\n };\n\n const commitResponse = await fetch(buildOrgxApiUrl(\"/v1/onboarding/daily-brief\", auth.baseUrl), {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(commitPayload),\n signal: AbortSignal.timeout(10_000),\n });\n\n if (!commitResponse.ok) {\n const text = await commitResponse.text().catch(() => \"\");\n const hint = extractErrorHint(text) ?? `HTTP ${commitResponse.status}`;\n return {\n status: \"failed\",\n message: `Could not commit onboarding capture — ${hint}`,\n error: `HTTP ${commitResponse.status}: ${text.slice(0, 200)}`,\n };\n }\n\n const commitBody = (await commitResponse.json().catch(() => ({}))) as {\n daily_brief_preview_url?: unknown;\n };\n const previewUrl =\n typeof commitBody.daily_brief_preview_url === \"string\"\n ? commitBody.daily_brief_preview_url\n : \"/today?mode=preview\";\n recordDailyBriefOnboardingDecision(\n {\n workspaceId: options.workspace.id,\n workspaceName: options.workspace.name,\n status: \"completed\",\n completedAt: new Date().toISOString(),\n },\n options.statePath,\n );\n return {\n status: \"completed\",\n message: \"Your Daily Brief is configured. First brief lands tomorrow.\",\n previewUrl,\n };\n}\n\ninterface OnboardingStateResponse {\n ok: boolean;\n workspaces: Array<{\n id: string;\n name: string;\n onboardingCompletedAt: string | null;\n }>;\n}\n\nasync function fetchOnboardingState(\n auth: { apiKey: string; baseUrl: string },\n): Promise<OnboardingStateResponse | null> {\n try {\n const res = await fetch(\n buildOrgxApiUrl(\"/v1/onboarding/daily-brief\", auth.baseUrl),\n {\n method: \"GET\",\n headers: { Authorization: `Bearer ${auth.apiKey}` },\n signal: AbortSignal.timeout(5_000),\n },\n );\n if (!res.ok) return null;\n const body = (await res.json()) as OnboardingStateResponse;\n if (!body || !Array.isArray(body.workspaces)) return null;\n return body;\n } catch {\n return null;\n }\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, join, relative } from \"node:path\";\n\nimport { CLAUDE_PROJECTS_DIR, CODEX_SESSIONS_DIR } from \"../constants.js\";\nimport { isRecord } from \"./fs.js\";\nimport type { FounderLoopImport } from \"./self-audit.js\";\n\nexport const AI_SESSION_SOURCES = [\"codex\", \"claude\"] as const;\n\nexport type AiSessionSource = (typeof AI_SESSION_SOURCES)[number];\n\nexport interface LoadAiSessionImportsOptions {\n claudeProjectsDir?: string;\n codexSessionsDir?: string;\n limitPerSource?: number;\n maxBytesPerFile?: number;\n now?: Date;\n sinceDays?: number;\n sources: readonly AiSessionSource[];\n}\n\nexport interface LoadAiSessionImportsResult {\n connectedSources: string[];\n imports: FounderLoopImport[];\n missingSources: string[];\n scannedFiles: number;\n skippedFiles: number;\n}\n\ninterface CandidateFile {\n mtimeMs: number;\n path: string;\n source: AiSessionSource;\n}\n\nconst DEFAULT_LIMIT_PER_SOURCE = 3;\nconst DEFAULT_SINCE_DAYS = 30;\nconst DEFAULT_MAX_BYTES_PER_FILE = 1_000_000;\nconst AUDIT_RELEVANT_LINE_PATTERN =\n /\\b(decision|decided|artifact|receipt|proof|commitment|committed|next action|follow[- ]?up|outcome|result|impact|roi|economics|token|cost|saved|open loop|gap|blocker|risk|owner|dri|writeback|rollback|quality score|mcp|tool call|orgx_emit_activity|orgx_apply_changeset|complete_with_proof|scaffold_initiative|mcp__orgx__)\\b/i;\nconst STRONG_AUDIT_LINE_PATTERN =\n /^(?:[-*]\\s*)?(?:decision|artifact|receipt|proof|commitment|next action|follow[- ]?up|outcome|result|impact|roi|economics|open loop|gap|blocker|risk|owner|dri|rollback|quality score)\\s*:/i;\nconst ORGX_TOOL_SIGNAL_PATTERN =\n /\\b(?:mcp__orgx__|orgx_emit_activity|orgx_apply_changeset|complete_with_proof|scaffold_initiative|get_task_with_context|ship_batch|record_outcome|orgx_free_audit)\\b/i;\nconst INSTRUCTION_BOILERPLATE_PATTERN =\n /^(?:#{1,6}\\s*)?(?:agents\\.md|instructions?|codex guardrails|precedence|read before you write|use exactly what was specified|don'?t confuse technologies|repo \\+ scope hygiene|initiative \\/ mcp discipline|ui quality bar|verification standards|secrets \\+ safety|patch\\/editing rules|commit \\/ pr \\/ merge protocol|output style|mcp integration|agent domains|skills|conventions)\\b/i;\nconst IMPERATIVE_BOILERPLATE_PATTERN =\n /^[-*]\\s+(?:if the user|when the user|if mcp|when agents|never|always|do not|don'?t|default to|treat|produce|pick|verify|avoid|match|use exactly|keep system boundaries|quote bracketed|for orgx|when capture tooling|if no meaningful|do \\*\\*not\\*\\*)\\b/i;\nconst CODE_OR_DOC_NOISE_PATTERN =\n /^(?:[-*]\\s*)?(?:https?:\\/\\/|\\/|\\.{0,2}\\/|[A-Za-z]:\\/|`{1,3}|\"{1,2}[A-Za-z0-9:_-]+\":|\\d+\\s*$|\\d+\\t|import\\s|export\\s|const\\s|let\\s|var\\s|function\\s|type\\s|interface\\s|CREATE\\s+TABLE|ALTER\\s+TABLE|SELECT\\s+|INSERT\\s+|UPDATE\\s+|DELETE\\s+)/i;\nconst EMPTY_AUDIT_LABEL_PATTERN =\n /^(?:[-*]\\s*)?(?:decision|artifact|receipt|proof|commitment|next action|follow[- ]?up|outcome|result|impact|roi|economics|open loop|gap|blocker|risk|owner|dri|rollback|quality score)\\s*:\\s*[\\[{(;,]*$/i;\nconst TYPE_SIGNATURE_NOISE_PATTERN =\n /^(?:[-*]\\s*)?(?:decision|artifact|receipt|proof|commitment|next action|follow[- ]?up|outcome|result|impact|roi|economics|open loop|gap|blocker|risk|owner|dri|rollback|quality score)\\s*:\\s*[A-Za-z_$][\\w$]*(?:<[^>]+>)?[\\s,;)]*$/i;\nconst TOOL_CATALOG_NOISE_PATTERN =\n /^(?:[-*]\\s*)?(?:[a-z][\\w.:-]*\\s*\\([^)]+\\),?\\s*){2,}$/i;\nconst BARE_TOOL_SIGNAL_PATTERN =\n /^(?:\\d+\\.\\s*|[-*]\\s*)?(?:mcp__orgx__[\\w-]*|orgx_emit_activity|orgx_apply_changeset|complete_with_proof|scaffold_initiative|get_task_with_context|ship_batch|record_outcome|orgx_free_audit)\\s*$/i;\nconst TOOL_QUESTION_NOISE_PATTERN =\n /^(?:\\d+\\.\\s*)?\\*\\*[^*]+\\*\\*.*\\?\\s*(?:\\([^)]*\\b(?:mcp|scaffold_initiative|start_plan_session)\\b[^)]*\\)\\.?)?$/i;\nconst SOURCE_REFERENCE_NOISE_PATTERN =\n /(?:^|\\s)(?:\\.{0,2}\\/)?(?:orgx|src|lib|workers|public|scripts|tests|apps|packages)\\/[\\w./-]+\\.(?:ts|tsx|js|jsx|json|md|txt|sql|py)(?::\\d+)?\\b/i;\nconst FILE_REFERENCE_NOISE_PATTERN =\n /\\b[\\w.-]+\\.(?:ts|tsx|js|jsx|json|md|txt|sql|py)(?::\\d+(?:[–-]\\d+)?)?\\b/i;\nconst LOCAL_ASSET_REFERENCE_PATTERN =\n /(?:<BlogImage\\b|source:\\s*\\/Users\\/|\\/blog\\/[\\w./-]+\\.(?:png|jpg|jpeg|webp|gif))/i;\nconst LINE_NUMBER_SOURCE_NOISE_PATTERN =\n /^\\d+(?::|\\s+)\\s*/i;\nconst TOOL_WORKFLOW_NOISE_PATTERN =\n /(?:→|->).*\\b(?:scaffold_initiative|spawn_agent_task|record_outcome|submit_learning|get_outcome_attribution|mcp__orgx__)\\b/i;\nconst TOOL_FAILURE_PATTERN =\n /^(?:\\d+\\.\\s*)?(?:mcp__orgx__[\\w-]*|orgx_emit_activity|orgx_apply_changeset|complete_with_proof|scaffold_initiative|get_task_with_context|ship_batch|record_outcome|orgx_free_audit)\\b.*\\b(?:rejected|requires|failed|fails|error|invalid|unavailable|timeout|timed out|not\\s+(?:called|dispatched|wired|created|available)|missing|broken)\\b/i;\nconst RUNTIME_FAILURE_PATTERN =\n /\\b(?:mcp__orgx__[\\w-]*|orgx_emit_activity|orgx_apply_changeset|complete_with_proof|scaffold_initiative|get_task_with_context|ship_batch|record_outcome|submit_learning|spawn_agent_task|agent run)\\b.*\\b(?:rejected|requires|failed|fails|error|invalid|unavailable|timeout|timed out|never|no\\s+\\w+|not\\s+(?:called|dispatched|wired|created|available|append)|missing|broken|only\\s+in\\s+agent\\s+skill\\s+prompts)\\b/i;\nconst PROCESS_NARRATION_NOISE_PATTERN =\n /^(?:now i\\b|let me\\b|i (?:have|need|will|can)\\b|i['’]ll\\b|i['’]m\\b|so\\b.*\\b(?:confirm|check|verify|fetches)\\b)/i;\n\nexport function parseAiSessionSources(value?: string): AiSessionSource[] {\n if (!value?.trim()) return [];\n\n const requested = value\n .split(\",\")\n .map((item) => item.trim().toLowerCase())\n .filter(Boolean);\n const expanded = requested.includes(\"all\") ? [...AI_SESSION_SOURCES] : requested;\n const deduped = [...new Set(expanded)];\n const invalid = deduped.filter((source) => !AI_SESSION_SOURCES.includes(source as AiSessionSource));\n if (invalid.length > 0) {\n throw new Error(`Unsupported AI-session source: ${invalid.join(\", \")}. Use codex, claude, or all.`);\n }\n\n return deduped as AiSessionSource[];\n}\n\nfunction parseJsonLine(line: string): unknown {\n try {\n return JSON.parse(line);\n } catch {\n return null;\n }\n}\n\nfunction asText(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) {\n return value\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (!isRecord(item)) return \"\";\n if (typeof item.text === \"string\") return item.text;\n if (typeof item.content === \"string\") return item.content;\n return \"\";\n })\n .filter(Boolean)\n .join(\"\\n\");\n }\n if (isRecord(value) && typeof value.text === \"string\") return value.text;\n return \"\";\n}\n\nfunction stringFromRecord(record: Record<string, unknown>, key: string): string | undefined {\n const value = record[key];\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction numberFromRecord(record: Record<string, unknown>, key: string): number | undefined {\n const value = record[key];\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction normalizeJsonAuditLine(line: string): string | null {\n if (!line.startsWith(\"{\")) return null;\n\n const parsed = parseJsonLine(line);\n if (!isRecord(parsed)) return null;\n\n const summary = stringFromRecord(parsed, \"summary\");\n const stats = isRecord(parsed.summary_stats) ? parsed.summary_stats : undefined;\n const requestedCount = stats ? numberFromRecord(stats, \"requested_count\") : undefined;\n const createdCount = stats ? numberFromRecord(stats, \"created_count\") : undefined;\n const failedCount = stats ? numberFromRecord(stats, \"failed_count\") : undefined;\n\n const hierarchy = isRecord(parsed.hierarchy) ? parsed.hierarchy : undefined;\n const initiative = hierarchy && isRecord(hierarchy.initiative) ? hierarchy.initiative : undefined;\n const initiativeTitle = initiative ? stringFromRecord(initiative, \"title\") ?? stringFromRecord(initiative, \"name\") : undefined;\n const initiativeError = initiative ? stringFromRecord(initiative, \"error\") : undefined;\n\n if (\n summary &&\n requestedCount !== undefined &&\n createdCount !== undefined &&\n failedCount !== undefined &&\n /\\bcreated\\b/i.test(summary)\n ) {\n const titleSuffix = initiativeTitle ? ` for ${initiativeTitle}` : \"\";\n const errorSuffix = initiativeError ? `; ${initiativeError.replace(/\\.+$/, \"\")}` : \"\";\n if (failedCount > 0) {\n return `Blocker: OrgX scaffold created ${createdCount}/${requestedCount} entities${titleSuffix}${errorSuffix}.`;\n }\n return `Artifact: OrgX scaffold created ${createdCount}/${requestedCount} entities${titleSuffix}.`;\n }\n\n return null;\n}\n\nfunction normalizeAuditRelevantLine(line: string): string | null {\n const trimmed = line.trim();\n if (!trimmed) return null;\n\n const jsonLine = normalizeJsonAuditLine(trimmed);\n if (jsonLine) return jsonLine;\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) return null;\n\n if (SOURCE_REFERENCE_NOISE_PATTERN.test(trimmed)) return null;\n if (FILE_REFERENCE_NOISE_PATTERN.test(trimmed)) return null;\n if (LOCAL_ASSET_REFERENCE_PATTERN.test(trimmed)) return null;\n if (LINE_NUMBER_SOURCE_NOISE_PATTERN.test(trimmed)) return null;\n if (/^audit\\s+\\/Users\\//i.test(trimmed)) return null;\n if (/^#{1,6}\\s/.test(trimmed)) return null;\n if (PROCESS_NARRATION_NOISE_PATTERN.test(trimmed)) return null;\n if (/^(?:\\d+\\.\\s*)?(?:[-*]\\s*)?(?:\\*\\*)?\\b(?:integration gaps|gaps between)\\b/i.test(trimmed)) return null;\n if (/^\\s*[-*]\\s+the `?orgx`? mcp tools listed/i.test(trimmed)) return null;\n if (TOOL_WORKFLOW_NOISE_PATTERN.test(trimmed)) return null;\n\n const toolFailure = trimmed.match(TOOL_FAILURE_PATTERN);\n if (toolFailure) {\n return `Blocker: ${trimmed.replace(/^\\d+\\.\\s*/, \"\")}`;\n }\n if (RUNTIME_FAILURE_PATTERN.test(trimmed)) {\n const label = /^no programmatic\\b/i.test(trimmed) ? \"Gap\" : \"Blocker\";\n return `${label}: ${trimmed.replace(/^\\d+\\.\\s*/, \"\")}`;\n }\n\n if (!AUDIT_RELEVANT_LINE_PATTERN.test(trimmed)) return null;\n if (!STRONG_AUDIT_LINE_PATTERN.test(trimmed) && !ORGX_TOOL_SIGNAL_PATTERN.test(trimmed)) return null;\n if (INSTRUCTION_BOILERPLATE_PATTERN.test(trimmed)) return null;\n if (IMPERATIVE_BOILERPLATE_PATTERN.test(trimmed)) return null;\n if (CODE_OR_DOC_NOISE_PATTERN.test(trimmed)) return null;\n if (EMPTY_AUDIT_LABEL_PATTERN.test(trimmed)) return null;\n if (TYPE_SIGNATURE_NOISE_PATTERN.test(trimmed)) return null;\n if (TOOL_CATALOG_NOISE_PATTERN.test(trimmed)) return null;\n if ((trimmed.match(/\\b[a-z][\\w.:-]*\\s*\\([^)]+\\)/g) ?? []).length >= 2) return null;\n if (BARE_TOOL_SIGNAL_PATTERN.test(trimmed)) return null;\n if (TOOL_QUESTION_NOISE_PATTERN.test(trimmed)) return null;\n if (/^[-*]\\s+all agents\\b/i.test(trimmed)) return null;\n\n return trimmed;\n}\n\nfunction extractCodexMessageText(record: unknown): string {\n if (!isRecord(record) || record.type !== \"response_item\" || !isRecord(record.payload)) {\n return \"\";\n }\n\n const payload = record.payload;\n if (payload.type !== \"message\" || (payload.role !== \"user\" && payload.role !== \"assistant\")) {\n return \"\";\n }\n\n return asText(payload.content);\n}\n\nfunction extractClaudeMessageText(record: unknown): string {\n if (!isRecord(record) || record.isMeta === true || !isRecord(record.message)) {\n return \"\";\n }\n\n const message = record.message;\n if (message.role !== \"user\" && message.role !== \"assistant\") {\n return \"\";\n }\n\n const text = asText(message.content);\n if (/^<local-command-caveat>/i.test(text.trim())) return \"\";\n return text;\n}\n\nfunction keepAuditRelevantLines(text: string): string[] {\n return text\n .split(/\\r?\\n/)\n .map((line) => normalizeAuditRelevantLine(line))\n .filter((line): line is string => Boolean(line));\n}\n\nfunction collectJsonlFiles(root: string, source: AiSessionSource): CandidateFile[] {\n if (!existsSync(root)) return [];\n\n const files: CandidateFile[] = [];\n const stack = [root];\n\n while (stack.length > 0) {\n const current = stack.pop();\n if (!current) continue;\n\n let entries: string[];\n try {\n entries = readdirSync(current);\n } catch {\n continue;\n }\n\n for (const entry of entries) {\n const path = join(current, entry);\n let stats;\n try {\n stats = statSync(path);\n } catch {\n continue;\n }\n\n if (stats.isDirectory()) {\n stack.push(path);\n continue;\n }\n if (stats.isFile() && path.endsWith(\".jsonl\")) {\n files.push({ mtimeMs: stats.mtimeMs, path, source });\n }\n }\n }\n\n return files;\n}\n\nfunction readSessionImport(\n candidate: CandidateFile,\n root: string,\n options: {\n maxBytesPerFile: number;\n },\n): FounderLoopImport | null {\n let stats;\n try {\n stats = statSync(candidate.path);\n } catch {\n return null;\n }\n if (stats.size > options.maxBytesPerFile) return null;\n\n const extractor = candidate.source === \"codex\" ? extractCodexMessageText : extractClaudeMessageText;\n const lines = readFileSync(candidate.path, \"utf8\").split(/\\r?\\n/);\n const relevantLines: string[] = [];\n\n for (const line of lines) {\n const record = parseJsonLine(line);\n const text = extractor(record);\n if (!text) continue;\n relevantLines.push(...keepAuditRelevantLines(text));\n }\n\n const deduped = [...new Set(relevantLines)].slice(0, 80);\n if (deduped.length === 0) return null;\n\n const relativePath = relative(root, candidate.path);\n return {\n sourceId: `${candidate.source}:${basename(candidate.path, \".jsonl\")}`,\n sourceLabel: `${candidate.source === \"codex\" ? \"Codex\" : \"Claude\"} session ${relativePath}`,\n text: deduped.join(\"\\n\"),\n };\n}\n\nexport function loadAiSessionImports(options: LoadAiSessionImportsOptions): LoadAiSessionImportsResult {\n const now = options.now ?? new Date();\n const sinceMs = now.getTime() - (options.sinceDays ?? DEFAULT_SINCE_DAYS) * 24 * 60 * 60 * 1000;\n const limitPerSource = Math.max(1, options.limitPerSource ?? DEFAULT_LIMIT_PER_SOURCE);\n const maxBytesPerFile = Math.max(1, options.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE);\n const roots: Record<AiSessionSource, string> = {\n claude: options.claudeProjectsDir ?? CLAUDE_PROJECTS_DIR,\n codex: options.codexSessionsDir ?? CODEX_SESSIONS_DIR,\n };\n const imports: FounderLoopImport[] = [];\n const connectedSources: string[] = [];\n const missingSources: string[] = [];\n let scannedFiles = 0;\n let skippedFiles = 0;\n\n for (const source of options.sources) {\n const root = roots[source];\n const candidates = collectJsonlFiles(root, source)\n .filter((file) => file.mtimeMs >= sinceMs)\n .sort((a, b) => b.mtimeMs - a.mtimeMs);\n\n if (candidates.length === 0) {\n missingSources.push(`${source} session store`);\n continue;\n }\n\n let importedForSource = 0;\n for (const candidate of candidates) {\n if (importedForSource >= limitPerSource) break;\n scannedFiles += 1;\n\n const imported = readSessionImport(candidate, root, { maxBytesPerFile });\n if (!imported) {\n skippedFiles += 1;\n continue;\n }\n\n imports.push(imported);\n importedForSource += 1;\n }\n\n if (importedForSource > 0) {\n connectedSources.push(`${source === \"codex\" ? \"Codex\" : \"Claude\"} local sessions`);\n } else {\n missingSources.push(`${source} audit-relevant session lines`);\n }\n }\n\n return {\n connectedSources,\n imports,\n missingSources,\n scannedFiles,\n skippedFiles,\n };\n}\n","import { createHash } from \"node:crypto\";\n\nimport { buildOrgxApiUrl, normalizeOrgxBaseUrl, resolveOrgxAuth, type ResolveOrgxAuthOptions } from \"./auth.js\";\nimport { isRecord } from \"./fs.js\";\n\nexport const SELF_AUDIT_SCHEMA_VERSION = \"2026-04-27\" as const;\n\nexport const AUDIT_DIMENSIONS = [\n \"queryability\",\n \"proof_density\",\n \"loop_closure\",\n \"context_debt\",\n \"autonomy_readiness\",\n \"roi_visibility\",\n] as const;\n\nexport type AuditDimension = (typeof AUDIT_DIMENSIONS)[number];\n\nexport type FounderLoopItemType =\n | \"decision\"\n | \"commitment\"\n | \"artifact\"\n | \"open_loop\"\n | \"next_action\"\n | \"outcome\"\n | \"economics\";\n\nexport interface AuditWorkspaceRef {\n id: string;\n name: string;\n}\n\nexport interface FounderLoopImport {\n sourceId: string;\n sourceLabel: string;\n text: string;\n}\n\nexport interface FounderLoopItem {\n type: FounderLoopItemType;\n text: string;\n sourceId: string;\n sourceLabel: string;\n evidenceRef: string;\n lineNumber: number;\n}\n\nexport interface SelfAuditSignals {\n approvedWritebackTargets: number;\n artifactsWithNextActions: number;\n artifactsWithOwners: number;\n completedWorkItems: number;\n completedWorkWithProof: number;\n connectedSources: number;\n decisionsWithEvidence: number;\n economicSignals: number;\n missingSources: number;\n openLoops: number;\n outcomeLinkedItems: number;\n repeatedContextPrompts: number;\n totalArtifacts: number;\n totalContextItems: number;\n totalDecisions: number;\n unresolvedCommitments: number;\n}\n\nexport type AuditScores = Record<AuditDimension, number>;\n\nexport interface AuditFinding {\n dimension: AuditDimension;\n severity: \"critical\" | \"warning\" | \"info\";\n title: string;\n evidence: string;\n recommendation: string;\n}\n\nexport interface ArtifactInvariant {\n goal_ref: string;\n owner_ref: string;\n decision_refs: string[];\n evidence_refs: string[];\n next_action_ref: string;\n proof_requirement: \"artifact\" | \"verification\" | \"external-link\" | \"human-review\";\n retrieval_scope: string;\n}\n\nexport interface SelfAuditPlan {\n artifact_type: \"ai_native_self_audit_plan\";\n artifact_hash: string;\n artifact_invariant: ArtifactInvariant;\n audit_scope: {\n loop: \"founder\";\n time_window_days: number;\n connected_sources: string[];\n missing_sources: string[];\n };\n extracted_items: FounderLoopItem[];\n findings: AuditFinding[];\n generated_at: string;\n recommended_follow_up: {\n title: string;\n summary: string;\n rollback: string;\n };\n recommended_initiative: {\n title: string;\n summary: string;\n workstreams: Array<{\n title: string;\n purpose: string;\n tasks: Array<{\n title: string;\n proof_requirement: string;\n }>;\n }>;\n };\n safe_writeback_plan: Array<{\n target: \"orgx\";\n action: string;\n approval: \"required\";\n rollback: string;\n }>;\n schema_version: typeof SELF_AUDIT_SCHEMA_VERSION;\n scores: AuditScores;\n self_critique: Array<{\n dimension: AuditDimension;\n target: number;\n score: number;\n passed: boolean;\n gap: string;\n }>;\n signals: SelfAuditSignals;\n workspace: AuditWorkspaceRef;\n}\n\nexport interface BuildSelfAuditPlanInput {\n connectedSources?: string[];\n generatedAt?: string;\n imports: FounderLoopImport[];\n missingSources?: string[];\n timeWindowDays?: number;\n workspace: AuditWorkspaceRef;\n}\n\nexport interface OrgxWriteOptions extends ResolveOrgxAuthOptions {\n dryRun?: boolean;\n}\n\nexport interface CreateAuditArtifactOptions extends OrgxWriteOptions {\n initiativeId: string;\n markdown: string;\n plan: SelfAuditPlan;\n}\n\nexport interface CreateAuditInitiativeOptions extends OrgxWriteOptions {\n plan: SelfAuditPlan;\n}\n\nexport interface CreateAuditFollowUpOptions extends OrgxWriteOptions {\n initiativeId: string;\n milestoneId?: string;\n plan: SelfAuditPlan;\n workstreamId?: string;\n}\n\nexport interface OrgxEntityRef {\n id: string;\n title: string;\n}\n\nfunction clampScore(value: number): number {\n return Math.max(0, Math.min(100, Math.round(value)));\n}\n\nfunction ratio(numerator: number, denominator: number, fallback = 0): number {\n if (denominator <= 0) return fallback;\n return numerator / denominator;\n}\n\nfunction includesAny(value: string, patterns: readonly RegExp[]): boolean {\n return patterns.some((pattern) => pattern.test(value));\n}\n\nfunction classifyLine(line: string): FounderLoopItemType | null {\n const normalized = line.trim();\n if (!normalized) return null;\n\n if (/^(decision|decided|we decided|d:)\\b/i.test(normalized)) return \"decision\";\n if (/^(commitment|committed|promise|promised|todo:|we will)\\b/i.test(normalized)) return \"commitment\";\n if (/^(artifact|receipt|proof|shipped|implemented|commit|pr:)\\b/i.test(normalized)) return \"artifact\";\n if (/^(open loop|gap|blocker|risk|missing|needs|unresolved)\\b/i.test(normalized)) return \"open_loop\";\n if (/^(next action|follow[- ]?up|next step|action:)\\b/i.test(normalized)) return \"next_action\";\n if (/^(outcome|result|impact|metric|adoption)\\b/i.test(normalized)) return \"outcome\";\n if (/^(roi|economics|token|tokens|cost|saved|time saved|api bill)\\b/i.test(normalized)) return \"economics\";\n\n return null;\n}\n\nexport function extractFounderLoopItems(imports: readonly FounderLoopImport[]): FounderLoopItem[] {\n const items: FounderLoopItem[] = [];\n\n for (const source of imports) {\n const lines = source.text.split(/\\r?\\n/);\n lines.forEach((line, index) => {\n const type = classifyLine(line);\n if (!type) return;\n\n const lineNumber = index + 1;\n items.push({\n evidenceRef: `${source.sourceId}:L${lineNumber}`,\n lineNumber,\n sourceId: source.sourceId,\n sourceLabel: source.sourceLabel,\n text: line.trim(),\n type,\n });\n });\n }\n\n return items;\n}\n\nexport function buildSelfAuditSignals(\n imports: readonly FounderLoopImport[],\n items: readonly FounderLoopItem[],\n options: {\n connectedSources?: readonly string[];\n missingSources?: readonly string[];\n } = {},\n): SelfAuditSignals {\n const allText = imports.map((source) => source.text).join(\"\\n\");\n const lower = allText.toLowerCase();\n const decisions = items.filter((item) => item.type === \"decision\");\n const artifacts = items.filter((item) => item.type === \"artifact\");\n const commitments = items.filter((item) => item.type === \"commitment\");\n const nextActions = items.filter((item) => item.type === \"next_action\");\n const outcomes = items.filter((item) => item.type === \"outcome\");\n const economics = items.filter((item) => item.type === \"economics\");\n const proofMentions = (lower.match(/\\b(proof|verified|verification|receipt|quality score|artifact)\\b/g) ?? []).length;\n const ownerMentions = (lower.match(/\\b(owner|dri|responsible|agent:|founder)\\b/g) ?? []).length;\n const artifactNextActionMentions = artifacts.filter((item) =>\n includesAny(item.text.toLowerCase(), [/\\bnext action\\b/, /\\bfollow[- ]?up\\b/, /\\brollback\\b/]),\n ).length;\n const writebackMentions = (lower.match(/\\b(approve|approved|writeback|rollback|create task|follow-up task)\\b/g) ?? []).length;\n const repeatedContextPrompts = (\n lower.match(/\\b(recap|catch you up|context again|restate|reread|remind me)\\b/g) ?? []\n ).length;\n\n return {\n approvedWritebackTargets: Math.min(3, writebackMentions),\n artifactsWithNextActions: Math.min(artifacts.length, nextActions.length + artifactNextActionMentions),\n artifactsWithOwners: Math.min(artifacts.length, ownerMentions),\n completedWorkItems: artifacts.length,\n completedWorkWithProof: Math.min(artifacts.length, proofMentions),\n connectedSources: Math.max(options.connectedSources?.length ?? 0, imports.length),\n decisionsWithEvidence: decisions.length,\n economicSignals: economics.length + (lower.includes(\"token\") || lower.includes(\"cost\") || lower.includes(\"saved\") ? 1 : 0),\n missingSources: options.missingSources?.length ?? 0,\n openLoops: items.filter((item) => item.type === \"open_loop\").length,\n outcomeLinkedItems: outcomes.length,\n repeatedContextPrompts,\n totalArtifacts: artifacts.length,\n totalContextItems: Math.max(items.length, allText.split(/\\s+/).filter(Boolean).length),\n totalDecisions: decisions.length,\n unresolvedCommitments: Math.max(0, commitments.length - nextActions.length - outcomes.length),\n };\n}\n\nexport function scoreSelfAudit(signals: SelfAuditSignals): AuditScores {\n const queryability = clampScore(\n 30\n + ratio(signals.decisionsWithEvidence, Math.max(1, signals.totalDecisions), 0) * 25\n + Math.min(20, signals.connectedSources * 5)\n + Math.min(30, (signals.totalArtifacts + signals.outcomeLinkedItems + signals.approvedWritebackTargets) * 5),\n );\n const proofDensity = clampScore(\n 30\n + ratio(signals.completedWorkWithProof, Math.max(1, signals.completedWorkItems), 0) * 35\n + ratio(signals.artifactsWithOwners, Math.max(1, signals.totalArtifacts), 0) * 20\n + ratio(signals.artifactsWithNextActions, Math.max(1, signals.totalArtifacts), 0) * 15,\n );\n const loopClosure = clampScore(\n 40\n + Math.min(25, signals.outcomeLinkedItems * 25)\n + Math.min(35, signals.approvedWritebackTargets * 20)\n + (signals.openLoops === 0 ? 15 : Math.max(0, 15 - signals.openLoops * 3)),\n );\n const contextDebt = clampScore(\n 100\n - Math.min(35, signals.repeatedContextPrompts * 10)\n - Math.min(35, signals.openLoops * 6)\n - Math.min(20, signals.missingSources * 4)\n - Math.min(10, signals.unresolvedCommitments * 3),\n );\n const autonomyReadiness = clampScore(\n 35\n + Math.min(30, signals.approvedWritebackTargets * 15)\n + Math.min(20, signals.completedWorkWithProof * 5)\n + (signals.openLoops <= 1 ? 15 : 5),\n );\n const roiVisibility = clampScore(\n 30\n + Math.min(40, signals.economicSignals * 18)\n + Math.min(25, signals.outcomeLinkedItems * 25)\n + Math.min(10, signals.completedWorkWithProof * 3),\n );\n\n return {\n autonomy_readiness: autonomyReadiness,\n context_debt: contextDebt,\n loop_closure: loopClosure,\n proof_density: proofDensity,\n queryability,\n roi_visibility: roiVisibility,\n };\n}\n\nfunction buildFindings(scores: AuditScores, signals: SelfAuditSignals): AuditFinding[] {\n const findings: AuditFinding[] = [];\n\n for (const dimension of AUDIT_DIMENSIONS) {\n const score = scores[dimension];\n if (score >= 95) {\n findings.push({\n dimension,\n evidence: `Score ${score}/100 meets the Phase 2 target.`,\n recommendation: \"Keep this dimension gated by evidence so the score stays earned.\",\n severity: \"info\",\n title: `${dimension.replace(/_/g, \" \")} is at the 95+ target`,\n });\n continue;\n }\n\n const recommendationByDimension: Record<AuditDimension, string> = {\n autonomy_readiness: \"Keep writeback approval-gated and add rollback references to every generated action.\",\n context_debt: \"Reduce repeated context prompts and close unresolved open loops with task or decision artifacts.\",\n loop_closure: \"Add outcome references and approved follow-up writebacks so planning changes after execution.\",\n proof_density: \"Attach owners, next actions, and verification proof to every completed work artifact.\",\n queryability: \"Add cited decisions, artifacts, connected sources, and retrieval scope to the audit output.\",\n roi_visibility: \"Add token/time/cost evidence plus an outcome review so ROI is not a narrative claim.\",\n };\n\n findings.push({\n dimension,\n evidence: `Score ${score}/100. Signals: ${JSON.stringify({\n approvedWritebackTargets: signals.approvedWritebackTargets,\n completedWorkWithProof: signals.completedWorkWithProof,\n economicSignals: signals.economicSignals,\n openLoops: signals.openLoops,\n outcomeLinkedItems: signals.outcomeLinkedItems,\n repeatedContextPrompts: signals.repeatedContextPrompts,\n })}`,\n recommendation: recommendationByDimension[dimension],\n severity: score < 60 ? \"critical\" : \"warning\",\n title: `${dimension.replace(/_/g, \" \")} needs evidence before it can be called 95+`,\n });\n }\n\n return findings;\n}\n\nfunction buildSelfCritique(scores: AuditScores): SelfAuditPlan[\"self_critique\"] {\n return AUDIT_DIMENSIONS.map((dimension) => {\n const score = scores[dimension];\n return {\n dimension,\n gap: score >= 95\n ? \"No score gap. Preserve evidence and regression-test this dimension.\"\n : `Needs ${95 - score} more points of verified product evidence before claiming 95+.`,\n passed: score >= 95,\n score,\n target: 95,\n };\n });\n}\n\nfunction hashPlanPayload(payload: unknown): string {\n return createHash(\"sha256\").update(JSON.stringify(payload)).digest(\"hex\");\n}\n\nexport function buildSelfAuditPlan(input: BuildSelfAuditPlanInput): SelfAuditPlan {\n if (input.imports.length === 0) {\n throw new Error(\"At least one AI-session import is required to run the Founder Loop audit.\");\n }\n\n const items = extractFounderLoopItems(input.imports);\n const connectedSources = input.connectedSources ?? input.imports.map((source) => source.sourceLabel);\n const missingSources = input.missingSources ?? [];\n const signals = buildSelfAuditSignals(input.imports, items, {\n connectedSources,\n missingSources,\n });\n const scores = scoreSelfAudit(signals);\n const evidenceRefs = items.slice(0, 12).map((item) => item.evidenceRef);\n const decisions = items.filter((item) => item.type === \"decision\");\n const nextAction = items.find((item) => item.type === \"next_action\");\n\n const basePlan = {\n artifact_type: \"ai_native_self_audit_plan\" as const,\n audit_scope: {\n connected_sources: connectedSources,\n loop: \"founder\" as const,\n missing_sources: missingSources,\n time_window_days: input.timeWindowDays ?? 30,\n },\n extracted_items: items,\n findings: buildFindings(scores, signals),\n generated_at: input.generatedAt ?? new Date().toISOString(),\n recommended_follow_up: {\n rollback: \"Delete or close the generated OrgX follow-up task if the founder rejects the audit recommendation.\",\n summary: nextAction?.text ?? \"Review the audit findings, approve one follow-up action, and attach proof after execution.\",\n title: \"Review AI-native self-audit findings and approve first follow-up\",\n },\n recommended_initiative: {\n summary:\n \"Generated by @useorgx/wizard audit to close the first Founder Loop from AI-session context, proof artifacts, approved writeback, and outcome review.\",\n title: `Close Founder Loop: ${input.workspace.name} AI-native operating loop`,\n workstreams: [\n {\n purpose: \"Capture AI-session context, decisions, commitments, and open loops.\",\n tasks: [\n {\n proof_requirement: \"AI-session import with cited evidence references.\",\n title: \"Import founder AI-session context\",\n },\n ],\n title: \"Founder Context Ingest\",\n },\n {\n purpose: \"Turn completed work into artifacts with owners, proof, and next actions.\",\n tasks: [\n {\n proof_requirement: \"Artifact metadata includes owner, evidence refs, and retrieval scope.\",\n title: \"Attach proof artifacts to completed work\",\n },\n ],\n title: \"Proof Chain\",\n },\n {\n purpose: \"Write one approved follow-up action into OrgX with rollback context.\",\n tasks: [\n {\n proof_requirement: \"Approved OrgX task with rollback and evidence references.\",\n title: \"Approve first OrgX follow-up writeback\",\n },\n ],\n title: \"Safe Writeback\",\n },\n {\n purpose: \"Record outcome and economics so the next plan learns from execution.\",\n tasks: [\n {\n proof_requirement: \"Founder review with time/token/value estimate and attribution confidence.\",\n title: \"Record outcome and economics review\",\n },\n ],\n title: \"Outcome Review\",\n },\n ],\n },\n safe_writeback_plan: [\n {\n action: \"create_follow_up_task\",\n approval: \"required\" as const,\n rollback: \"Delete or close the generated task and preserve the audit artifact as a rejected recommendation.\",\n target: \"orgx\" as const,\n },\n ],\n schema_version: SELF_AUDIT_SCHEMA_VERSION,\n scores,\n self_critique: buildSelfCritique(scores),\n signals,\n workspace: input.workspace,\n };\n const invariant: ArtifactInvariant = {\n decision_refs: decisions.map((item) => item.evidenceRef),\n evidence_refs: evidenceRefs,\n goal_ref: `workspace:${input.workspace.id}:ai-native-self-audit`,\n next_action_ref: nextAction?.evidenceRef ?? \"manual-next-action:review-audit\",\n owner_ref: \"founder:dri\",\n proof_requirement: \"verification\",\n retrieval_scope:\n \"Retrieve the imported AI-session context, extracted Founder Loop items, audit scores, findings, writeback plan, and outcome review.\",\n };\n const artifactHash = hashPlanPayload({ ...basePlan, artifact_invariant: invariant });\n\n return {\n ...basePlan,\n artifact_hash: artifactHash,\n artifact_invariant: invariant,\n };\n}\n\nexport function renderSelfAuditMarkdown(plan: SelfAuditPlan): string {\n const lines = [\n \"# AI-Native Founder Loop Self-Audit\",\n \"\",\n `Generated: ${plan.generated_at}`,\n `Workspace: ${plan.workspace.name} (${plan.workspace.id})`,\n `Artifact hash: ${plan.artifact_hash}`,\n \"\",\n \"## Scores\",\n \"\",\n \"| Dimension | Score | Target | Status |\",\n \"| --- | ---: | ---: | --- |\",\n ...AUDIT_DIMENSIONS.map((dimension) => {\n const score = plan.scores[dimension];\n return `| ${dimension.replace(/_/g, \" \")} | ${score} | 95 | ${score >= 95 ? \"pass\" : \"gap\"} |`;\n }),\n \"\",\n \"## Self-Critique\",\n \"\",\n ...plan.self_critique.map((item) => `- ${item.dimension}: ${item.gap}`),\n \"\",\n \"## Findings\",\n \"\",\n ...plan.findings.map((finding) => [\n `### ${finding.title}`,\n \"\",\n `- Severity: ${finding.severity}`,\n `- Evidence: ${finding.evidence}`,\n `- Recommendation: ${finding.recommendation}`,\n \"\",\n ].join(\"\\n\")),\n \"## Extracted Founder Loop Items\",\n \"\",\n ...plan.extracted_items.map((item) => `- ${item.type}: ${item.text} (${item.evidenceRef})`),\n \"\",\n \"## Recommended Initiative\",\n \"\",\n `Title: ${plan.recommended_initiative.title}`,\n \"\",\n plan.recommended_initiative.summary,\n \"\",\n \"## Approved Follow-Up Candidate\",\n \"\",\n `Title: ${plan.recommended_follow_up.title}`,\n \"\",\n plan.recommended_follow_up.summary,\n \"\",\n `Rollback: ${plan.recommended_follow_up.rollback}`,\n \"\",\n \"## Artifact Invariant\",\n \"\",\n \"```json\",\n JSON.stringify(plan.artifact_invariant, null, 2),\n \"```\",\n \"\",\n ];\n\n return lines.join(\"\\n\");\n}\n\nfunction parseEntityRef(payload: unknown): OrgxEntityRef {\n const entity = isRecord(payload) && isRecord(payload.data) ? payload.data : payload;\n if (!isRecord(entity)) {\n throw new Error(\"OrgX returned an unexpected entity payload.\");\n }\n\n const id = typeof entity.id === \"string\" ? entity.id : \"\";\n const title = typeof entity.title === \"string\"\n ? entity.title\n : typeof entity.name === \"string\"\n ? entity.name\n : \"\";\n if (!id || !title) {\n throw new Error(\"OrgX returned an incomplete entity payload.\");\n }\n\n return { id, title };\n}\n\nasync function parseResponseBody(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nfunction formatHttpError(status: number, body: unknown): string {\n if (typeof body === \"string\" && body.trim().length > 0) {\n return `HTTP ${status}: ${body}`;\n }\n if (isRecord(body) && typeof body.error === \"string\" && body.error.trim().length > 0) {\n return `HTTP ${status}: ${body.error}`;\n }\n if (isRecord(body) && isRecord(body.error) && typeof body.error.message === \"string\") {\n return `HTTP ${status}: ${body.error.message}`;\n }\n return `HTTP ${status}`;\n}\n\nasync function createOrgxEntity(\n body: Record<string, unknown>,\n options: OrgxWriteOptions,\n): Promise<OrgxEntityRef> {\n if (options.dryRun) {\n return {\n id: `dry-run-${String(body.type ?? \"entity\")}`,\n title: String(body.title ?? body.name ?? \"Dry-run entity\"),\n };\n }\n\n const auth = await resolveOrgxAuth(options);\n if (!auth) {\n throw new Error(\"No OrgX API key configured. Run `wizard auth login` before using writeback flags.\");\n }\n\n const response = await fetch(buildOrgxApiUrl(\"/entities\", auth.baseUrl), {\n body: JSON.stringify(body),\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n method: \"POST\",\n signal: AbortSignal.timeout(15_000),\n });\n const responseBody = await parseResponseBody(response);\n if (!response.ok) {\n throw new Error(`Failed to create ${String(body.type ?? \"entity\")}. ${formatHttpError(response.status, responseBody)}`);\n }\n\n return parseEntityRef(responseBody);\n}\n\nexport async function createAuditArtifact(\n options: CreateAuditArtifactOptions,\n): Promise<OrgxEntityRef> {\n const { initiativeId, markdown, plan } = options;\n return createOrgxEntity(\n {\n artifact_type: \"shared.project_handbook\",\n description: \"AI-native Founder Loop self-audit generated by @useorgx/wizard audit.\",\n entity_id: initiativeId,\n entity_type: \"initiative\",\n external_url: `orgx-wizard://audit/${plan.artifact_hash}`,\n initiative_id: initiativeId,\n metadata: {\n ...plan.artifact_invariant,\n artifact_hash: plan.artifact_hash,\n atomic_unit_type: \"ai_native_self_audit\",\n completion_state: \"generated\",\n schema_validated: true,\n scores: plan.scores,\n },\n name: `AI-Native Self-Audit: ${plan.workspace.name}`,\n preview_markdown: markdown.slice(0, 8000),\n status: \"in_review\",\n type: \"artifact\",\n workspace_id: plan.workspace.id,\n },\n options,\n );\n}\n\nexport async function createInitiativeFromAuditPlan(\n options: CreateAuditInitiativeOptions,\n): Promise<OrgxEntityRef> {\n const { plan } = options;\n return createOrgxEntity(\n {\n metadata: {\n artifact_hash: plan.artifact_hash,\n audit_score_snapshot: plan.scores,\n source: \"ai_native_self_audit\",\n source_artifact_type: \"ai_native_self_audit_plan\",\n },\n status: \"active\",\n summary: plan.recommended_initiative.summary,\n title: plan.recommended_initiative.title,\n type: \"initiative\",\n workspace_id: plan.workspace.id,\n },\n options,\n );\n}\n\nexport async function createAuditFollowUpTask(\n options: CreateAuditFollowUpOptions,\n): Promise<OrgxEntityRef> {\n const { initiativeId, milestoneId, plan, workstreamId } = options;\n const resolvedWorkstreamId = workstreamId?.trim() || (\n await createOrgxEntity(\n {\n initiative_id: initiativeId,\n metadata: {\n artifact_hash: plan.artifact_hash,\n source: \"ai_native_self_audit\",\n },\n status: \"active\",\n summary: \"Follow-up workstream created by @useorgx/wizard audit so the approved action has execution context.\",\n title: \"AI-native self-audit follow-up\",\n type: \"workstream\",\n workspace_id: plan.workspace.id,\n },\n options,\n )\n ).id;\n const resolvedMilestoneId = milestoneId?.trim() || (\n await createOrgxEntity(\n {\n initiative_id: initiativeId,\n metadata: {\n artifact_hash: plan.artifact_hash,\n source: \"ai_native_self_audit\",\n },\n status: \"planned\",\n summary: \"Milestone created by @useorgx/wizard audit so the approved follow-up task has proof-chain hierarchy.\",\n title: \"AI-native self-audit follow-up\",\n type: \"milestone\",\n workspace_id: plan.workspace.id,\n workstream_id: resolvedWorkstreamId,\n },\n options,\n )\n ).id;\n\n return createOrgxEntity(\n {\n description: `${plan.recommended_follow_up.summary}\\n\\nRollback: ${plan.recommended_follow_up.rollback}`,\n initiative_id: initiativeId,\n milestone_id: resolvedMilestoneId,\n metadata: {\n ...plan.artifact_invariant,\n artifact_hash: plan.artifact_hash,\n source: \"ai_native_self_audit\",\n source_action: \"approved_follow_up_writeback\",\n },\n priority: \"high\",\n status: \"todo\",\n title: plan.recommended_follow_up.title,\n type: \"task\",\n workstream_id: resolvedWorkstreamId,\n workspace_id: plan.workspace.id,\n },\n options,\n );\n}\n\nexport function normalizeAuditBaseUrl(value?: string): string {\n return normalizeOrgxBaseUrl(value);\n}\n","import { createHash } from \"node:crypto\";\n\nimport { extractFounderLoopItems, type FounderLoopImport, type FounderLoopItem } from \"./self-audit.js\";\n\nexport const WORK_GRAPH_SCHEMA_VERSION = \"2026-05-07\" as const;\nexport const WORK_GRAPH_FINGERPRINT_VERSION = \"wgf_v1\" as const;\nexport const WORK_GRAPH_EXTRACTION_SCHEMA_VERSION = \"2026-05-07.ai-client-search.v1\" as const;\n\nexport const WORK_GRAPH_FINDING_TYPES = [\n \"action\",\n \"decision\",\n \"artifact\",\n \"blocker\",\n \"person\",\n \"business\",\n \"product_surface\",\n \"goal\",\n \"outcome\",\n \"initiative_candidate\",\n \"missed_orchestration_opportunity\",\n] as const;\n\nexport type WorkGraphFindingType = (typeof WORK_GRAPH_FINDING_TYPES)[number];\n\nexport type WorkGraphSourceClient =\n | \"codex\"\n | \"claude\"\n | \"claude-code\"\n | \"cursor\"\n | \"openclaw\"\n | \"slack\"\n | \"mcp\"\n | \"github\"\n | \"linear\"\n | \"gmail\"\n | \"calendar\"\n | \"notion\"\n | \"docs\"\n | \"manual\"\n | \"wizard\"\n | \"api\"\n | \"unknown\";\n\nexport type WorkGraphFinalState = \"completed\" | \"blocked\" | \"in_progress\" | \"unknown\";\n\nexport interface WorkGraphWorkspaceRef {\n id: string;\n name: string;\n}\n\nexport interface WorkGraphSourceCoverage {\n connected: string[];\n missing: string[];\n mcpObserved: boolean;\n orgxObserved: boolean;\n orgxMcpCalled: boolean;\n skillOnlySignal: boolean;\n coverage_score?: number;\n manifests?: WorkGraphSourceCoverageManifest[];\n notes?: string[];\n}\n\nexport interface WorkGraphSourceCoverageManifest {\n source_client: WorkGraphSourceClient;\n source_label: string;\n status: \"connected\" | \"partial\" | \"missing\";\n searched_sources: string[];\n searched_session_count: number;\n skipped_session_count: number;\n query_count: number;\n finding_count: number;\n confidence: number;\n notes: string[];\n}\n\nexport interface WorkGraphSourceEvent {\n schema_version: typeof WORK_GRAPH_SCHEMA_VERSION;\n source_client: WorkGraphSourceClient;\n source_id: string;\n source_label: string;\n event_type: \"session_excerpt\" | \"client_extraction\" | \"tool_signal\" | \"source_coverage\";\n text: string;\n evidence_ref: string;\n metadata: Record<string, unknown>;\n}\n\nexport type WorkGraphAttributionKind =\n | \"action\"\n | \"decision\"\n | \"artifact\"\n | \"person\"\n | \"agent\"\n | \"tool\"\n | \"business\"\n | \"product_surface\"\n | \"goal\"\n | \"source\";\n\nexport type WorkGraphRedactionState = \"public_summary\" | \"private\" | \"redacted\";\nexport type WorkGraphReviewState =\n | \"unreviewed\"\n | \"confirmed\"\n | \"needs_merge\"\n | \"hidden\"\n | \"important\"\n | \"dismissed\";\n\nexport interface WorkGraphEvidenceRef {\n id: string;\n source_client: WorkGraphSourceClient;\n source_id: string;\n label: string;\n summary: string;\n occurred_at?: string;\n confidence: number;\n redaction_state: WorkGraphRedactionState;\n metadata: Record<string, unknown>;\n}\n\nexport interface WorkGraphAttributionSourceEvent {\n source_client: WorkGraphSourceClient;\n source_id: string;\n source_label: string;\n event_type:\n | \"session_excerpt\"\n | \"client_extraction\"\n | \"runtime_hook\"\n | \"tool_signal\"\n | \"source_coverage\"\n | \"mcp_call\"\n | \"repo_artifact\"\n | \"slack_message\"\n | \"github_event\"\n | \"linear_event\"\n | \"gmail_message\"\n | \"calendar_event\"\n | \"doc_signal\"\n | \"manual_review\";\n occurred_at?: string;\n evidence_ref: string;\n actor_ref?: string;\n artifact_refs?: string[];\n confidence: number;\n metadata: Record<string, unknown>;\n}\n\nexport interface WorkGraphAttributionNode {\n id: string;\n kind: WorkGraphAttributionKind;\n label: string;\n summary: string;\n source_client?: WorkGraphSourceClient;\n evidence_refs: string[];\n linked_node_ids: string[];\n confidence: number;\n weight: number;\n review_state: WorkGraphReviewState;\n dedupe_key?: string;\n metadata: Record<string, unknown>;\n}\n\nexport interface WorkGraphAttributionSpine {\n source_events: WorkGraphAttributionSourceEvent[];\n actions: WorkGraphAttributionNode[];\n decisions: WorkGraphAttributionNode[];\n artifacts: WorkGraphAttributionNode[];\n people: WorkGraphAttributionNode[];\n agents: WorkGraphAttributionNode[];\n tools: WorkGraphAttributionNode[];\n businesses: WorkGraphAttributionNode[];\n product_surfaces: WorkGraphAttributionNode[];\n goals: WorkGraphAttributionNode[];\n sources: WorkGraphAttributionNode[];\n initiative_candidates: WorkGraphAttributionNode[];\n evidence_refs: WorkGraphEvidenceRef[];\n confidence: number;\n dedupe_keys: string[];\n privacy: {\n redaction_state: \"public_summary\";\n raw_transcripts_included: false;\n public_summary_only: true;\n };\n review: {\n pending_count: number;\n correction_affordances: Array<\"confirm\" | \"merge\" | \"hide\" | \"mark_important\" | \"launch_or_dismiss\">;\n };\n}\n\nexport interface WorkGraphFinding {\n type: WorkGraphFindingType;\n title: string;\n summary: string;\n source_client: WorkGraphSourceClient;\n source_id: string;\n evidence_ref: string;\n confidence: number;\n metadata: Record<string, unknown>;\n}\n\nexport interface WorkGraphClientExtractionFinding {\n type: WorkGraphFindingType;\n title: string;\n summary: string;\n source_client?: WorkGraphSourceClient;\n source_id?: string;\n source_label?: string;\n evidence_ref?: string;\n confidence?: number;\n occurred_at?: string;\n actor_id?: string;\n redacted_verbatim?: string;\n privacy_state?: \"public\" | \"redacted\" | \"private\";\n metadata?: Record<string, unknown>;\n}\n\nexport interface WorkGraphClientExtraction {\n schema_version?: string;\n extraction_id?: string;\n source_client: WorkGraphSourceClient;\n source_label?: string;\n searched_sources?: string[];\n search_queries?: Array<{\n id: string;\n lens: string;\n query: string;\n result_count?: number;\n }>;\n extraction_quality?: {\n confidence?: number;\n searched_session_count?: number;\n skipped_session_count?: number;\n notes?: string[];\n };\n findings: WorkGraphClientExtractionFinding[];\n}\n\nexport interface WorkGraphClientExtractionSummary {\n extraction_id: string;\n source_client: WorkGraphSourceClient;\n source_label: string;\n searched_source_count: number;\n searched_session_count: number;\n skipped_session_count: number;\n query_count: number;\n finding_count: number;\n confidence: number;\n notes: string[];\n}\n\nexport interface WorkGraphExtractionSchema {\n schema_version: typeof WORK_GRAPH_EXTRACTION_SCHEMA_VERSION;\n mode: \"ai_client_session_search\";\n objective: string;\n privacy_contract: string[];\n source_search_strategy: Array<{\n id: string;\n lens: string;\n query: string;\n return_when: string;\n }>;\n required_output: Record<string, unknown>;\n quality_bar: string[];\n reject_as_noise: string[];\n}\n\nexport interface WorkGraphExtractionProtocol {\n schema_version: typeof WORK_GRAPH_EXTRACTION_SCHEMA_VERSION;\n mode: \"ai_client_session_search\";\n prompt: string;\n schema: WorkGraphExtractionSchema;\n}\n\nexport interface WorkGraphOpportunityScore {\n overall: number;\n value_potential: number;\n evidence_quality: number;\n urgency: number;\n owner_clarity: number;\n automation_potential: number;\n orgx_fit: number;\n}\n\nexport interface WorkGraphExecutionQualityScore {\n overall: number;\n evidence_coverage: number;\n source_attribution: number;\n trail_depth: number;\n insight_depth: number;\n actionability: number;\n impact_confidence: number;\n notes: string[];\n}\n\nexport interface WorkGraphImpactProjection {\n time_saved_hours_per_week: number;\n acceleration_percent: number;\n estimated_monthly_value_usd: number;\n confidence: number;\n basis: string[];\n assumptions: string[];\n}\n\nexport interface WorkGraphKickoffCandidate {\n title: string;\n summary: string;\n reason: string;\n finding_refs: string[];\n priority: \"p0\" | \"p1\" | \"p2\";\n}\n\nexport type WorkGraphEntityType =\n | \"idea\"\n | \"initiative\"\n | \"workstream\"\n | \"milestone\"\n | \"task\"\n | \"decision\"\n | \"artifact\"\n | \"person\"\n | \"business\"\n | \"blocker\"\n | \"agent\"\n | \"tool\"\n | \"source\"\n | \"surface\"\n | \"outcome\";\n\nexport type WorkGraphTrailKind =\n | \"idea_trail\"\n | \"initiative_trail\"\n | \"decision_trail\"\n | \"artifact_trail\"\n | \"person_trail\"\n | \"business_trail\"\n | \"blocker_trail\"\n | \"agent_trail\"\n | \"tool_trail\"\n | \"source_trail\"\n | \"outcome_trail\";\n\nexport type WorkGraphTrailState =\n | \"observed\"\n | \"inferred\"\n | \"claimed\"\n | \"verified\"\n | \"missing_evidence\"\n | \"blocked\"\n | \"stale\"\n | \"decaying\"\n | \"resolved\"\n | \"disputed\"\n | \"contradicted\";\n\nexport type WorkGraphTrailValence =\n | \"healthy\"\n | \"useful_recurrence\"\n | \"wasteful_recurrence\"\n | \"risk\"\n | \"leak\"\n | \"opportunity\"\n | \"zombie\"\n | \"escalating\";\n\nexport interface WorkGraphTrailEvent {\n id: string;\n trail_id: string;\n event_type:\n | \"signal_detected\"\n | \"idea_created\"\n | \"initiative_created\"\n | \"decision_inferred\"\n | \"decision_promoted\"\n | \"artifact_created\"\n | \"artifact_verified\"\n | \"owner_assigned\"\n | \"blocker_detected\"\n | \"source_connected\"\n | \"outcome_recorded\"\n | \"recommendation_generated\";\n entity_id: string;\n entity_type: WorkGraphEntityType;\n timestamp: string;\n actor_id?: string;\n source_id: string;\n source_type: WorkGraphSourceClient;\n redacted_verbatim?: string;\n confidence: number;\n evidence_refs: string[];\n privacy_state: \"public\" | \"redacted\" | \"private\";\n}\n\nexport interface WorkGraphTrailEdge {\n id: string;\n from_event_id: string;\n to_event_id: string;\n relation:\n | \"caused\"\n | \"informed\"\n | \"blocked\"\n | \"resolved\"\n | \"created\"\n | \"verified\"\n | \"assigned\"\n | \"depends_on\"\n | \"duplicates\"\n | \"recurred_as\"\n | \"converted_to\"\n | \"contradicted\";\n state: \"captured\" | \"inferred\" | \"missing\";\n confidence: number;\n evidence_refs: string[];\n}\n\nexport interface WorkGraphTrailRecommendation {\n id: string;\n title: string;\n summary: string;\n action_type: \"launch_initiative\" | \"promote_decision\" | \"attach_artifact\" | \"assign_owner\" | \"connect_source\" | \"verify_outcome\";\n trail_ids: string[];\n evidence_refs: string[];\n priority: \"p0\" | \"p1\" | \"p2\";\n expected_lift: string;\n confidence: number;\n}\n\nexport interface WorkGraphTrail {\n id: string;\n kind: WorkGraphTrailKind;\n title: string;\n summary: string;\n subject_entity_id: string;\n subject_entity_type: WorkGraphEntityType;\n state: WorkGraphTrailState;\n valence: WorkGraphTrailValence;\n confidence: number;\n recurrence_score: number;\n impact_score: number;\n privacy_state: \"public\" | \"redacted\" | \"private\";\n events: WorkGraphTrailEvent[];\n edges: WorkGraphTrailEdge[];\n evidence_refs: string[];\n blocker_ids: string[];\n recommendation_ids: string[];\n created_at: string;\n updated_at: string;\n shape:\n | \"single_signal\"\n | \"dense_recent_cluster\"\n | \"chronic_recurrence\"\n | \"zombie_revival\"\n | \"accelerating_issue\"\n | \"healthy_execution\"\n | \"decision_heavy_artifact_light\"\n | \"artifact_heavy_decision_light\";\n}\n\nexport interface WorkGraphRecurringPattern {\n id: string;\n title: string;\n description: string;\n pattern_type:\n | \"trapped_decision\"\n | \"orphaned_artifact\"\n | \"missing_owner\"\n | \"repeated_work\"\n | \"missing_source\"\n | \"tooling_mismatch\"\n | \"unverified_outcome\"\n | \"handoff_friction\"\n | \"business_signal_unclaimed\";\n affected_trail_ids: string[];\n affected_entity_ids: string[];\n recurrence_count: number;\n severity: \"low\" | \"medium\" | \"high\" | \"critical\";\n confidence: number;\n valence: WorkGraphTrailValence;\n root_cause_hypothesis: string;\n recommended_runtime_action_id?: string;\n}\n\nexport interface WorkGraphMirrorClaim {\n id: string;\n text: string;\n evidence_refs: string[];\n confidence: number;\n}\n\nexport interface WorkGraphMirror {\n headline: string;\n body: string;\n lens: \"all\" | \"ideas\" | \"decisions\" | \"artifacts\" | \"people\" | \"businesses\" | \"blockers\" | \"agents_tools\" | \"sources\";\n claims: WorkGraphMirrorClaim[];\n primary_trail_id?: string;\n generated_at: string;\n}\n\nexport interface WorkGraphTensionMetric {\n id: string;\n label: string;\n value: string;\n tone: \"good\" | \"warning\" | \"danger\" | \"muted\";\n trail_ids: string[];\n evidence_refs: string[];\n explanation: string;\n}\n\nexport interface WorkGraphFingerprintBasis {\n schema_version: typeof WORK_GRAPH_SCHEMA_VERSION;\n fingerprint_version: typeof WORK_GRAPH_FINGERPRINT_VERSION;\n workspace_hash: string;\n source_clients: WorkGraphSourceClient[];\n connected_source_hashes: string[];\n missing_source_hashes: string[];\n finding_type_counts: Partial<Record<WorkGraphFindingType, number>>;\n pattern_hashes: string[];\n trail_shape_hashes: string[];\n recurring_pattern_hashes: string[];\n kickoff_hashes: string[];\n raw_transcripts_included: false;\n}\n\nexport interface WorkGraphSignupHydration {\n strategy: \"work_graph_fingerprint_claim\";\n hydration_key: string;\n eligible: boolean;\n notes: string[];\n}\n\nexport interface SessionReconciliationReport {\n schema_version: typeof WORK_GRAPH_SCHEMA_VERSION;\n report_id: string;\n idempotency_key: string;\n work_graph_fingerprint: string;\n fingerprint_version: typeof WORK_GRAPH_FINGERPRINT_VERSION;\n fingerprint_basis: WorkGraphFingerprintBasis;\n signup_hydration: WorkGraphSignupHydration;\n generated_at: string;\n source_client: \"wizard\";\n session_id: string;\n workspace: WorkGraphWorkspaceRef;\n extraction_protocol: WorkGraphExtractionProtocol;\n client_extractions: WorkGraphClientExtractionSummary[];\n source_coverage: WorkGraphSourceCoverage;\n final_state: WorkGraphFinalState;\n events: WorkGraphSourceEvent[];\n findings: WorkGraphFinding[];\n missed_orchestration_opportunities: WorkGraphFinding[];\n trails: WorkGraphTrail[];\n recurring_patterns: WorkGraphRecurringPattern[];\n recommendations: WorkGraphTrailRecommendation[];\n mirror: WorkGraphMirror;\n tension_metrics: WorkGraphTensionMetric[];\n attribution_spine: WorkGraphAttributionSpine;\n opportunity_score: WorkGraphOpportunityScore;\n execution_quality: WorkGraphExecutionQualityScore;\n impact_projection: WorkGraphImpactProjection;\n initiative_kickoffs: WorkGraphKickoffCandidate[];\n redaction_level: \"summary_only\";\n raw_transcripts_sent: false;\n}\n\nexport interface BuildSessionReconciliationReportInput {\n clientExtractions?: readonly WorkGraphClientExtraction[];\n connectedSources?: readonly string[];\n generatedAt?: string;\n imports: readonly FounderLoopImport[];\n missingSources?: readonly string[];\n sessionId?: string;\n workspace: WorkGraphWorkspaceRef;\n}\n\nfunction clampScore(value: number): number {\n return Math.max(0, Math.min(100, Math.round(value)));\n}\n\nfunction hashJson(value: unknown): string {\n return createHash(\"sha256\")\n .update(JSON.stringify(value))\n .digest(\"hex\");\n}\n\nfunction normalizeFingerprintText(value: string): string {\n return value\n .toLowerCase()\n .replace(/https?:\\/\\/\\S+/g, \"url\")\n .replace(/[0-9a-f]{12,}/g, \"hash\")\n .replace(/\\b[0-9a-f]{8}-[0-9a-f-]{27,}\\b/g, \"uuid\")\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 600);\n}\n\nfunction shortHash(value: unknown, length = 16): string {\n return hashJson(value).slice(0, length);\n}\n\nfunction sortedUnique<T extends string>(values: readonly T[]): T[] {\n return [...new Set(values)].sort();\n}\n\nfunction slugPart(value: string): string {\n const normalized = normalizeFingerprintText(value)\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n .slice(0, 64);\n return normalized || \"unknown\";\n}\n\nfunction sourceClientForImport(source: FounderLoopImport): WorkGraphSourceClient {\n const raw = `${source.sourceId} ${source.sourceLabel}`.toLowerCase();\n if (raw.includes(\"codex\")) return \"codex\";\n if (raw.includes(\"claude-code\")) return \"claude-code\";\n if (raw.includes(\"claude\")) return \"claude\";\n if (raw.includes(\"cursor\")) return \"cursor\";\n if (raw.includes(\"openclaw\")) return \"openclaw\";\n if (raw.includes(\"slack\")) return \"slack\";\n if (raw.includes(\"github\")) return \"github\";\n if (raw.includes(\"linear\")) return \"linear\";\n if (raw.includes(\"gmail\") || raw.includes(\"email\")) return \"gmail\";\n if (raw.includes(\"calendar\") || raw.includes(\"meeting\")) return \"calendar\";\n if (raw.includes(\"notion\")) return \"notion\";\n if (raw.includes(\"doc\")) return \"docs\";\n if (raw.includes(\"mcp\")) return \"mcp\";\n if (raw.includes(\"api\")) return \"api\";\n if (raw.includes(\"manual\") || raw.includes(\"wizard-audit-input\")) return \"manual\";\n return \"unknown\";\n}\n\nfunction normalizeSourceClient(value: unknown): WorkGraphSourceClient {\n if (typeof value !== \"string\") return \"unknown\";\n const normalized = value.trim().toLowerCase();\n if (\n normalized === \"codex\" ||\n normalized === \"claude\" ||\n normalized === \"claude-code\" ||\n normalized === \"cursor\" ||\n normalized === \"openclaw\" ||\n normalized === \"slack\" ||\n normalized === \"mcp\" ||\n normalized === \"github\" ||\n normalized === \"linear\" ||\n normalized === \"gmail\" ||\n normalized === \"calendar\" ||\n normalized === \"notion\" ||\n normalized === \"docs\" ||\n normalized === \"manual\" ||\n normalized === \"wizard\" ||\n normalized === \"api\"\n ) {\n return normalized;\n }\n if (normalized.includes(\"claude\")) return \"claude\";\n if (normalized.includes(\"codex\")) return \"codex\";\n if (normalized.includes(\"cursor\")) return \"cursor\";\n if (normalized.includes(\"slack\")) return \"slack\";\n if (normalized.includes(\"github\")) return \"github\";\n if (normalized.includes(\"linear\")) return \"linear\";\n if (normalized.includes(\"gmail\") || normalized.includes(\"email\")) return \"gmail\";\n if (normalized.includes(\"calendar\") || normalized.includes(\"meeting\")) return \"calendar\";\n if (normalized.includes(\"notion\")) return \"notion\";\n if (normalized.includes(\"doc\")) return \"docs\";\n if (normalized.includes(\"mcp\")) return \"mcp\";\n return \"unknown\";\n}\n\nfunction sourceClientFromText(value: string): WorkGraphSourceClient {\n const normalized = value.toLowerCase();\n if (/\\bclaude-code\\b|\\.claude\\/projects|claude:/.test(normalized)) return \"claude\";\n if (/\\bcodex\\b|\\.codex\\/sessions|rollout-/.test(normalized)) return \"codex\";\n if (/\\bcursor\\b/.test(normalized)) return \"cursor\";\n if (/\\bopenclaw\\b/.test(normalized)) return \"openclaw\";\n if (/\\bslack\\b/.test(normalized)) return \"slack\";\n if (/\\bgithub\\b|\\bgit:|pull request|commit\\b/.test(normalized)) return \"github\";\n if (/\\blinear\\b/.test(normalized)) return \"linear\";\n if (/\\bgmail\\b|\\bemail\\b/.test(normalized)) return \"gmail\";\n if (/\\bcalendar\\b|\\bmeeting\\b/.test(normalized)) return \"calendar\";\n if (/\\bnotion\\b/.test(normalized)) return \"notion\";\n if (/\\bdocs?\\b|google drive/.test(normalized)) return \"docs\";\n if (/\\bmcp\\b|mcp__|orgx_emit|scaffold_initiative|ship_batch/.test(normalized)) return \"mcp\";\n if (/\\borgx api\\b|\\bapi\\b/.test(normalized)) return \"api\";\n return \"unknown\";\n}\n\nfunction sourceClientForExtractionFinding(\n extraction: WorkGraphClientExtraction,\n finding: WorkGraphClientExtractionFinding,\n): WorkGraphSourceClient {\n const explicit = normalizeSourceClient(finding.source_client);\n if (explicit !== \"unknown\") return explicit;\n const inferred = sourceClientFromText([\n finding.source_id ?? \"\",\n finding.source_label ?? \"\",\n finding.evidence_ref ?? \"\",\n finding.summary ?? \"\",\n ].join(\"\\n\"));\n if (inferred !== \"unknown\") return inferred;\n return normalizeSourceClient(extraction.source_client);\n}\n\nfunction arrayOfStrings(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction normalizeFindingType(value: unknown): WorkGraphFindingType | null {\n if (typeof value !== \"string\") return null;\n const normalized = value.trim().toLowerCase();\n return WORK_GRAPH_FINDING_TYPES.includes(normalized as WorkGraphFindingType)\n ? normalized as WorkGraphFindingType\n : null;\n}\n\nfunction normalizeConfidence(value: unknown, fallback = 0.72): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return fallback;\n return Math.max(0.1, Math.min(0.99, Number(value.toFixed(2))));\n}\n\nfunction titleFromText(text: string, fallback: string): string {\n const lower = text.toLowerCase();\n if (lower.includes(\"mcp__orgx__list_entities\") && lower.includes(\"zod\")) {\n return \"OrgX MCP list_entities is failing schema validation\";\n }\n if (lower.includes(\"scaffold_initiative\") && lower.includes(\"auto_continue\") && lower.includes(\"dispatch\")) {\n return \"scaffold_initiative creates ready streams without dispatching agent runs\";\n }\n if (lower.includes(\"operation qa loop\") && lower.includes(\"0/\") && lower.includes(\"entities\")) {\n return \"OrgX scaffold fails to create Operation QA Loop entities\";\n }\n if (lower.includes(\"production-only redirect\") || lower.includes(\"livedemopageclient\")) {\n return \"Production route behavior changed without durable approval\";\n }\n\n const normalized = text\n .replace(/[`*_>#]/g, \"\")\n .replace(/^\\s*[-*\\d.)]+\\s*/, \"\")\n .replace(/^\\s*(decision|artifact|commitment|next action|follow[- ]?up|outcome|roi|economics|open loop|gap|blocker|risk|goal|summary)\\s*:\\s*/i, \"\")\n .replace(/^\\s*(fix|fixing|debug|investigate|continue|todo)\\s+(the\\s+)?(bug|issue|problem)\\s*[:.-]?\\s*/i, \"\")\n .replace(/^\\s*one\\s+bug\\s+surfaced\\s*:\\s*/i, \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n const firstSentence = normalized.split(/[.!?]\\s/)[0]?.trim() || normalized;\n const firstClause = firstSentence.split(/\\s[-:;]\\s/)[0]?.trim() || firstSentence;\n return (firstClause || fallback).slice(0, 110);\n}\n\nfunction normalizeClientExtractionId(extraction: WorkGraphClientExtraction, index: number): string {\n return extraction.extraction_id?.trim()\n || `${extraction.source_client || \"unknown\"}:client-extraction:${index + 1}`;\n}\n\nexport function buildWorkGraphExtractionProtocol(): WorkGraphExtractionProtocol {\n const schema: WorkGraphExtractionSchema = {\n schema_version: WORK_GRAPH_EXTRACTION_SCHEMA_VERSION,\n mode: \"ai_client_session_search\",\n objective:\n \"Search the AI client's own sessions, logs, tool calls, and local transcript index to extract durable work-graph evidence for OrgX.\",\n privacy_contract: [\n \"Do not return raw transcripts.\",\n \"Return short redacted verbatim snippets only when they materially support a finding.\",\n \"Prefer evidence refs, session ids, timestamps, source ids, and hashes over full content.\",\n \"Mark private customer/person data as private or redacted.\",\n \"Do not invent people, decisions, artifacts, or outcomes that are not supported by a source event.\",\n ],\n source_search_strategy: [\n {\n id: \"decisions\",\n lens: \"Decision trails\",\n query:\n \"Find choices, tradeoffs, approvals, rejected options, contradictions, architecture calls, product calls, and decisions that were restated later.\",\n return_when:\n \"A choice shaped future work, blocked work, or should become durable organizational memory.\",\n },\n {\n id: \"artifacts\",\n lens: \"Artifact trails\",\n query:\n \"Find created or modified artifacts: PRs, files, docs, designs, prompts, plans, reports, screenshots, deployed routes, tests, and verification receipts.\",\n return_when:\n \"The artifact has a source event, proof reference, downstream use, owner, or missing verification.\",\n },\n {\n id: \"blockers\",\n lens: \"Blocker trails\",\n query:\n \"Find failed tool calls, timeouts, rejected validators, missing auth, missing source coverage, repeated unresolved questions, stalled owners, and external blockers.\",\n return_when:\n \"The blocker explains why work did not become durable, verified, assigned, or shipped.\",\n },\n {\n id: \"people_businesses\",\n lens: \"People and business trails\",\n query:\n \"Find users, customers, buyers, stakeholders, reviewers, teams, businesses, accounts, deal context, support signals, and market signals connected to work or decisions.\",\n return_when:\n \"A person or business changes priority, ownership, revenue potential, customer pain, or follow-up urgency.\",\n },\n {\n id: \"coordination_sources\",\n lens: \"Coordination and calendar/email trails\",\n query:\n \"Find Slack threads, emails, meetings, docs, handoffs, approvals, owner changes, follow-ups, and coordination gaps that explain how work moved or stalled outside the AI client.\",\n return_when:\n \"The coordination source proves ownership, urgency, approval, customer context, or a missing source needed for attribution.\",\n },\n {\n id: \"product_surfaces\",\n lens: \"Product surface trails\",\n query:\n \"Find surfaces such as live rooms, command center, widgets, plugins, wizard flows, public pages, APIs, MCP tools, Slack/GitHub/Linear integrations, and signup/claim flows.\",\n return_when:\n \"A surface was changed, verified, blocked, requested, or connected to a goal or artifact.\",\n },\n {\n id: \"agents_tools_sources\",\n lens: \"Agent/tool/source trails\",\n query:\n \"Find agent runs, subagents, MCP calls, hook lifecycle events, tool availability, tool misses, source coverage, and runtime writeback behavior.\",\n return_when:\n \"The event proves whether OrgX was called, skipped, unavailable, or only mentioned in instructions.\",\n },\n {\n id: \"outcomes_roi\",\n lens: \"Outcome and ROI trails\",\n query:\n \"Find shipped/completed work, test/browser/deploy verification, outcomes, time saved, cost, revenue, customer impact, attribution, and expected lift.\",\n return_when:\n \"The outcome can be tied to evidence and a prior decision, artifact, blocker, or source.\",\n },\n {\n id: \"recurrence\",\n lens: \"Recurring patterns\",\n query:\n \"Find repeated shapes across sessions: trapped decisions, orphaned artifacts, missing owner, repeated work, source gaps, tooling mismatch, unverified outcomes, handoff friction, and unclaimed business signals.\",\n return_when:\n \"The same pattern appears across multiple sessions, days, tools, actors, or product surfaces.\",\n },\n ],\n required_output: {\n schema_version: WORK_GRAPH_EXTRACTION_SCHEMA_VERSION,\n extraction_id: \"stable id for this extraction run\",\n source_client: \"codex | claude | claude-code | cursor | openclaw | slack | mcp | github | linear | gmail | calendar | notion | docs | manual | api | unknown\",\n source_label: \"human-readable source label\",\n searched_sources: [\"session/log/source group names searched\"],\n search_queries: [\n {\n id: \"decisions\",\n lens: \"Decision trails\",\n query: \"query actually used\",\n result_count: 0,\n },\n ],\n extraction_quality: {\n confidence: 0.0,\n searched_session_count: 0,\n skipped_session_count: 0,\n notes: [\"limits, permissions, or gaps\"],\n },\n findings: [\n {\n type: \"decision | artifact | blocker | person | business | product_surface | goal | outcome | action | initiative_candidate | missed_orchestration_opportunity\",\n title: \"short durable title, not a raw line\",\n summary: \"one sentence explaining why this matters\",\n source_client: \"optional override when a blended extractor found evidence from another client\",\n source_id: \"session/tool/source id\",\n source_label: \"source label\",\n evidence_ref: \"stable evidence pointer\",\n confidence: 0.0,\n occurred_at: \"ISO timestamp if known\",\n actor_id: \"redacted actor id if known\",\n redacted_verbatim: \"short supporting excerpt only\",\n privacy_state: \"public | redacted | private\",\n metadata: {\n related_entity_names: [],\n related_source_ids: [],\n recurrence_count: 0,\n state: \"observed | inferred | verified | blocked | missing_evidence\",\n },\n },\n ],\n },\n quality_bar: [\n \"Search broadly before summarizing; do not stop at the newest session if older sessions contain recurrence.\",\n \"Every finding must include a source id or evidence ref.\",\n \"A trail starts only from evidence-bearing work signals, not empty labels, code type signatures, tool catalogs, or guardrail text.\",\n \"Prefer fewer, higher-confidence findings over many shallow lines.\",\n \"Include negative evidence when OrgX/MCP was available but not called.\",\n \"Separate actual tool calls from textual mentions of tool names.\",\n \"Mark confidence below 0.6 when the finding is inferred from weak or single-source evidence.\",\n \"Do not emit raw JSON tool payloads; summarize the tool result into a blocker/artifact/outcome finding.\",\n ],\n reject_as_noise: [\n \"AGENTS.md or system guardrail instructions.\",\n \"Source-code paths and line-number references unless the code change itself is the artifact.\",\n \"Bare labels like Decision:, Receipt:, Impact:, or proof: {.\",\n \"Type signatures such as outcome: string; or decision: ReviewableDecision;\",\n \"Tool catalogs and lists of available MCP tools.\",\n \"Planning narration like let me check, now I will inspect, or I need to verify.\",\n \"Generic MCP/AI commentary without a concrete work event.\",\n ],\n };\n\n const prompt = [\n \"You are generating an OrgX Work Graph extraction from your own AI-client session/search logs.\",\n \"Search across available local sessions, transcripts, tool-call logs, hook events, and source indexes using every lens in the schema.\",\n \"Return JSON only. Match the required_output shape exactly. Do not return raw transcripts.\",\n \"The output will initiate Work Graph Trails, so every finding must be evidence-bearing and useful enough for a human to inspect.\",\n ].join(\" \");\n\n return {\n schema_version: WORK_GRAPH_EXTRACTION_SCHEMA_VERSION,\n mode: \"ai_client_session_search\",\n prompt,\n schema,\n };\n}\n\nfunction findingTypeForItem(item: FounderLoopItem): WorkGraphFindingType {\n switch (item.type) {\n case \"decision\":\n return \"decision\";\n case \"artifact\":\n return \"artifact\";\n case \"open_loop\":\n return \"blocker\";\n case \"commitment\":\n case \"next_action\":\n case \"outcome\":\n return \"action\";\n case \"economics\":\n return \"business\";\n }\n}\n\nfunction evidenceRefFor(sourceId: string, index: number): string {\n return `${sourceId}:derived:${index + 1}`;\n}\n\nfunction includesAny(text: string, patterns: readonly RegExp[]): boolean {\n return patterns.some((pattern) => pattern.test(text));\n}\n\nfunction buildCoverage(\n imports: readonly FounderLoopImport[],\n connectedSources: readonly string[],\n missingSources: readonly string[],\n clientExtractions: readonly WorkGraphClientExtraction[] = [],\n): WorkGraphSourceCoverage {\n const findings = buildClientExtractionFindings(clientExtractions);\n const sourceClients = sortedUnique([\n ...imports.map(sourceClientForImport),\n ...findings.map((finding) => finding.source_client),\n ...clientExtractions.map((extraction) => normalizeSourceClient(extraction.source_client)),\n ].filter((source): source is WorkGraphSourceClient => source !== \"unknown\"));\n const extractionText = clientExtractions\n .flatMap((extraction) => [\n extraction.source_client,\n extraction.source_label ?? \"\",\n ...(extraction.searched_sources ?? []),\n ...(extraction.findings ?? []).flatMap((finding) => [\n finding.title,\n finding.summary,\n finding.redacted_verbatim ?? \"\",\n ]),\n ])\n .join(\"\\n\");\n const allText = `${imports.map((source) => source.text).join(\"\\n\")}\\n${extractionText}`.toLowerCase();\n const orgxObserved = /\\borgx\\b|useorgx|mcp__orgx__|orgx_/i.test(allText);\n const mcpObserved = /\\bmcp\\b|mcp__|tool call|tools\\/call|call_tool|orgx_emit_activity/i.test(allText);\n const orgxMcpCalled = /mcp__orgx__|orgx_emit_activity|orgx_apply_changeset|complete_with_proof|scaffold_initiative/i.test(allText);\n const skillOnlySignal = orgxObserved && !orgxMcpCalled && /\\bskill|instructions|agent|workflow\\b/i.test(allText);\n const inferredConnected = [\n ...connectedSources,\n ...(sourceClients.includes(\"codex\") ? [\"Codex sessions\"] : []),\n ...(sourceClients.includes(\"claude\") || sourceClients.includes(\"claude-code\") ? [\"Claude Code sessions\"] : []),\n ...(sourceClients.includes(\"github\") ? [\"Git/GitHub proof\"] : []),\n ...(sourceClients.includes(\"mcp\") ? [\"MCP tool telemetry\"] : []),\n ...(sourceClients.includes(\"slack\") ? [\"Slack coordination\"] : []),\n ];\n const inferredMissing = [\n ...missingSources,\n ...(sourceClients.includes(\"slack\") ? [] : [\"Slack coordination\"]),\n ...(sourceClients.includes(\"github\") ? [] : [\"GitHub PR/commit proof\"]),\n ...(allText.includes(\"hook\") || allText.includes(\"outbox\") ? [] : [\"Runtime hook outbox replay\"]),\n ];\n const connected = sortedUnique(inferredConnected.filter(Boolean));\n const missing = sortedUnique(inferredMissing.filter((source) => !connected.includes(source)));\n const manifests = buildSourceCoverageManifests({\n clientExtractions,\n connectedSources: connected,\n findings,\n imports,\n missingSources: missing,\n });\n const partialCount = manifests.filter((manifest) => manifest.status === \"partial\").length;\n const coverageScore = clampScore(\n 28 +\n Math.min(34, connected.length * 7) +\n Math.min(18, findings.length * 2) +\n (sourceClients.includes(\"codex\") ? 6 : 0) +\n (sourceClients.includes(\"claude\") || sourceClients.includes(\"claude-code\") ? 6 : 0) -\n missing.length * 7 -\n partialCount * 3,\n );\n\n return {\n connected,\n missing,\n mcpObserved,\n orgxObserved,\n orgxMcpCalled,\n skillOnlySignal,\n coverage_score: coverageScore,\n manifests,\n notes: [\n \"OrgX/MCP writeback is one coverage signal; it is not required for the audit to find useful work.\",\n missing.length > 0\n ? `Coverage is limited by missing sources: ${missing.join(\", \")}.`\n : \"Connected sources are sufficient for a first-pass operating profile, but still require user review.\",\n ],\n };\n}\n\nfunction buildSourceCoverageManifests(input: {\n clientExtractions: readonly WorkGraphClientExtraction[];\n connectedSources: readonly string[];\n findings: readonly WorkGraphFinding[];\n imports: readonly FounderLoopImport[];\n missingSources: readonly string[];\n}): WorkGraphSourceCoverageManifest[] {\n const manifests = new Map<string, WorkGraphSourceCoverageManifest>();\n const addManifest = (manifest: WorkGraphSourceCoverageManifest) => {\n const key = `${manifest.source_client}:${manifest.source_label}`;\n const previous = manifests.get(key);\n if (!previous) {\n manifests.set(key, manifest);\n return;\n }\n manifests.set(key, {\n ...previous,\n status: previous.status === \"connected\" || manifest.status === \"connected\"\n ? \"connected\"\n : previous.status === \"partial\" || manifest.status === \"partial\"\n ? \"partial\"\n : \"missing\",\n searched_sources: sortedUnique([...previous.searched_sources, ...manifest.searched_sources]),\n searched_session_count: previous.searched_session_count + manifest.searched_session_count,\n skipped_session_count: previous.skipped_session_count + manifest.skipped_session_count,\n query_count: previous.query_count + manifest.query_count,\n finding_count: previous.finding_count + manifest.finding_count,\n confidence: Math.max(previous.confidence, manifest.confidence),\n notes: sortedUnique([...previous.notes, ...manifest.notes]),\n });\n };\n\n for (const extraction of input.clientExtractions) {\n const extractionFindings = buildClientExtractionFindings([extraction]);\n const byClient = new Map<WorkGraphSourceClient, WorkGraphFinding[]>();\n for (const finding of extractionFindings) {\n byClient.set(finding.source_client, [...(byClient.get(finding.source_client) ?? []), finding]);\n }\n for (const [sourceClient, findings] of byClient) {\n const searchedSources = extraction.searched_sources ?? [];\n addManifest({\n source_client: sourceClient,\n source_label: labelForSourceClient(sourceClient),\n status: findings.length > 0 ? \"connected\" : \"partial\",\n searched_sources: searchedSources,\n searched_session_count: extraction.extraction_quality?.searched_session_count ?? 0,\n skipped_session_count: extraction.extraction_quality?.skipped_session_count ?? 0,\n query_count: extraction.search_queries?.length ?? 0,\n finding_count: findings.length,\n confidence: normalizeConfidence(extraction.extraction_quality?.confidence, 0.74),\n notes: extraction.extraction_quality?.notes ?? [],\n });\n }\n }\n\n for (const source of input.imports) {\n const sourceClient = sourceClientForImport(source);\n addManifest({\n source_client: sourceClient,\n source_label: source.sourceLabel,\n status: \"connected\",\n searched_sources: [source.sourceId],\n searched_session_count: 1,\n skipped_session_count: 0,\n query_count: 0,\n finding_count: input.findings.filter((finding) => finding.source_id === source.sourceId).length,\n confidence: 0.62,\n notes: [\"Fallback line-level import; lower confidence than client-native extraction.\"],\n });\n }\n\n for (const source of input.missingSources) {\n addManifest({\n source_client: sourceClientFromText(source),\n source_label: source,\n status: \"missing\",\n searched_sources: [],\n searched_session_count: 0,\n skipped_session_count: 0,\n query_count: 0,\n finding_count: 0,\n confidence: 0,\n notes: [\"Not connected or not searched in this audit pass.\"],\n });\n }\n\n return [...manifests.values()].sort((left, right) => {\n const rank = { connected: 0, partial: 1, missing: 2 };\n return rank[left.status] - rank[right.status] || right.finding_count - left.finding_count;\n });\n}\n\nfunction labelForSourceClient(sourceClient: WorkGraphSourceClient): string {\n switch (sourceClient) {\n case \"codex\":\n return \"Codex sessions\";\n case \"claude\":\n case \"claude-code\":\n return \"Claude Code sessions\";\n case \"mcp\":\n return \"MCP tool telemetry\";\n case \"github\":\n return \"Git/GitHub proof\";\n case \"slack\":\n return \"Slack coordination\";\n case \"linear\":\n return \"Linear issues\";\n case \"gmail\":\n return \"Email coordination\";\n case \"calendar\":\n return \"Calendar/meeting context\";\n case \"notion\":\n case \"docs\":\n return \"Docs\";\n default:\n return sourceClient.replace(/[-_]/g, \" \").replace(/\\b\\w/g, (char) => char.toUpperCase());\n }\n}\n\nexport function summarizeClientExtractions(\n clientExtractions: readonly WorkGraphClientExtraction[],\n): WorkGraphClientExtractionSummary[] {\n return clientExtractions.map((extraction, index) => {\n const extractionId = normalizeClientExtractionId(extraction, index);\n return {\n extraction_id: extractionId,\n source_client: normalizeSourceClient(extraction.source_client),\n source_label: extraction.source_label?.trim() || `${extraction.source_client || \"Unknown\"} AI-client extraction`,\n searched_source_count: extraction.searched_sources?.length ?? 0,\n searched_session_count: extraction.extraction_quality?.searched_session_count ?? 0,\n skipped_session_count: extraction.extraction_quality?.skipped_session_count ?? 0,\n query_count: extraction.search_queries?.length ?? 0,\n finding_count: extraction.findings.length,\n confidence: normalizeConfidence(extraction.extraction_quality?.confidence, 0.74),\n notes: extraction.extraction_quality?.notes ?? [],\n };\n });\n}\n\nexport function buildClientExtractionEvents(\n clientExtractions: readonly WorkGraphClientExtraction[],\n): WorkGraphSourceEvent[] {\n return summarizeClientExtractions(clientExtractions).map((summary) => ({\n schema_version: WORK_GRAPH_SCHEMA_VERSION,\n source_client: summary.source_client,\n source_id: summary.extraction_id,\n source_label: summary.source_label,\n event_type: \"client_extraction\",\n text: [\n `${summary.finding_count} structured findings extracted by ${summary.source_client}.`,\n `${summary.query_count} search queries across ${summary.searched_source_count} searched source groups.`,\n `Extraction confidence: ${summary.confidence}.`,\n ].join(\" \"),\n evidence_ref: `${summary.extraction_id}:summary`,\n metadata: {\n finding_count: summary.finding_count,\n query_count: summary.query_count,\n searched_source_count: summary.searched_source_count,\n searched_session_count: summary.searched_session_count,\n skipped_session_count: summary.skipped_session_count,\n raw_transcript_sent: false,\n },\n }));\n}\n\nexport function buildClientExtractionFindings(\n clientExtractions: readonly WorkGraphClientExtraction[],\n): WorkGraphFinding[] {\n const findings: WorkGraphFinding[] = [];\n\n clientExtractions.forEach((extraction, extractionIndex) => {\n const extractionId = normalizeClientExtractionId(extraction, extractionIndex);\n const extractionSourceClient = normalizeSourceClient(extraction.source_client);\n const sourceLabel = extraction.source_label?.trim() || `${extractionSourceClient} AI-client extraction`;\n extraction.findings.forEach((finding, findingIndex) => {\n const type = normalizeFindingType(finding.type);\n const title = finding.title?.trim();\n const summary = finding.summary?.trim();\n if (!type || !title || !summary) return;\n const sourceClient = sourceClientForExtractionFinding(extraction, finding);\n\n findings.push({\n type,\n title: title.slice(0, 180),\n summary,\n source_client: sourceClient,\n source_id: finding.source_id?.trim() || extractionId,\n evidence_ref: finding.evidence_ref?.trim() || `${extractionId}:F${findingIndex + 1}`,\n confidence: normalizeConfidence(finding.confidence, normalizeConfidence(extraction.extraction_quality?.confidence, 0.76)),\n metadata: {\n source_label: finding.source_label?.trim() || sourceLabel,\n extraction_id: extractionId,\n schema_version: extraction.schema_version ?? null,\n occurred_at: finding.occurred_at ?? null,\n actor_id: finding.actor_id ?? null,\n redacted_verbatim: finding.redacted_verbatim ?? null,\n privacy_state: finding.privacy_state ?? \"redacted\",\n ...(finding.metadata ?? {}),\n },\n });\n });\n });\n\n return findings;\n}\n\nfunction nativeExtractionFindingType(line: string): WorkGraphFindingType | null {\n const lower = line.toLowerCase();\n if (/^\\s*(?:decision|decided|choice|approved|rejected)\\s*:/i.test(line)) return \"decision\";\n if (/^\\s*(?:artifact|receipt|proof)\\s*:/i.test(line)) return \"artifact\";\n if (/^\\s*(?:outcome|result|impact)\\s*:/i.test(line)) return \"outcome\";\n if (/^\\s*(?:roi|economics)\\s*:/i.test(line)) return \"business\";\n if (/^\\s*(?:next action|follow[- ]?up|commitment)\\s*:/i.test(line)) return \"action\";\n if (/^\\s*(?:blocker|risk|gap|open loop|rollback)\\s*:/i.test(line)) return lower.includes(\"source\") ? \"missed_orchestration_opportunity\" : \"blocker\";\n if (/\\b(?:failed|fails|error|invalid|unavailable|timeout|timed out|not called|not dispatched|missing|broken)\\b/i.test(line)) {\n if (/\\b(?:tool|mcp|orgx|writeback|source|hook|outbox)\\b/i.test(line)) return \"missed_orchestration_opportunity\";\n return \"blocker\";\n }\n if (/\\b(?:created|generated|implemented|shipped|verified|passed)\\b/i.test(line)) return \"artifact\";\n if (/\\b(?:owner|dri|assigned)\\b/i.test(line)) return \"person\";\n if (/\\b(?:initiative|workstream|milestone|launch|goal)\\b/i.test(line)) return \"goal\";\n return null;\n}\n\nfunction nativeEpisodeType(line: string): string {\n if (/\\b(?:plan|decide|decision|choice|tradeoff|approve|reject)\\b/i.test(line)) return \"planning\";\n if (/\\b(?:implemented|created|generated|edited|file|diff|commit|artifact)\\b/i.test(line)) return \"implementation\";\n if (/\\b(?:failed|fails|error|timeout|invalid|debug|retry|blocked|blocker)\\b/i.test(line)) return \"debugging\";\n if (/\\b(?:verified|passed|test|browser|qa|proof|outcome)\\b/i.test(line)) return \"verification\";\n return \"handoff\";\n}\n\nfunction nativeFindingConfidence(type: WorkGraphFindingType, line: string): number {\n let confidence = type === \"decision\" || type === \"artifact\" || type === \"outcome\" ? 0.78 : 0.72;\n if (/^\\s*(?:decision|artifact|blocker|outcome|proof|result|next action|open loop|risk|gap)\\s*:/i.test(line)) confidence += 0.08;\n if (/\\b(?:mcp__orgx__|scaffold_initiative|orgx_emit_activity|complete_with_proof|github|codex|claude)\\b/i.test(line)) confidence += 0.05;\n if (line.length < 32) confidence -= 0.1;\n return normalizeConfidence(confidence, 0.72);\n}\n\nfunction nativeRelatedEntityNames(line: string): string[] {\n const candidates = [\n ...Array.from(line.matchAll(/`([^`]{3,80})`/g)).map((match) => match[1] ?? \"\"),\n ...Array.from(line.matchAll(/\\b(?:OrgX|MCP|Codex|Claude|Slack|GitHub|Cursor|ChatGPT|Work Graph|Profile|Scaffold Initiative|Operation QA Loop|Runtime Hook|Eject Bay|Trail Inspector)\\b/gi)).map((match) => match[0] ?? \"\"),\n ];\n return sortedUnique(\n candidates\n .map((candidate) => candidate.trim())\n .filter((candidate) => candidate.length >= 3)\n .slice(0, 8)\n );\n}\n\nfunction supportsNativeExtraction(sourceClient: WorkGraphSourceClient) {\n return sourceClient === \"codex\" || sourceClient === \"claude\" || sourceClient === \"claude-code\";\n}\n\nexport function buildNativeAiClientExtractions(\n imports: readonly FounderLoopImport[],\n generatedAt = new Date().toISOString(),\n): WorkGraphClientExtraction[] {\n const grouped = new Map<WorkGraphSourceClient, {\n findings: WorkGraphClientExtractionFinding[];\n searchedSources: string[];\n searchedSessionCount: number;\n skippedSessionCount: number;\n }>();\n\n for (const source of imports) {\n const sourceClient = sourceClientForImport(source);\n if (!supportsNativeExtraction(sourceClient)) continue;\n\n const bucket = grouped.get(sourceClient) ?? {\n findings: [],\n searchedSources: [],\n searchedSessionCount: 0,\n skippedSessionCount: 0,\n };\n bucket.searchedSources.push(source.sourceId);\n bucket.searchedSessionCount += 1;\n\n source.text.split(/\\r?\\n/).forEach((line, lineIndex) => {\n const trimmed = line.trim();\n if (!trimmed) return;\n const type = nativeExtractionFindingType(trimmed);\n if (!type) {\n bucket.skippedSessionCount += 1;\n return;\n }\n bucket.findings.push({\n type,\n title: titleFromText(trimmed, type.replace(/_/g, \" \")),\n summary: trimmed,\n source_client: sourceClient,\n source_id: source.sourceId,\n source_label: source.sourceLabel,\n evidence_ref: `${source.sourceId}:native:${lineIndex + 1}`,\n confidence: nativeFindingConfidence(type, trimmed),\n occurred_at: generatedAt,\n redacted_verbatim: trimmed.slice(0, 420),\n privacy_state: \"redacted\",\n metadata: {\n episode_type: nativeEpisodeType(trimmed),\n related_entity_names: nativeRelatedEntityNames(trimmed),\n related_source_ids: [source.sourceId],\n state: type === \"blocker\" || type === \"missed_orchestration_opportunity\"\n ? \"blocked\"\n : type === \"outcome\" || type === \"artifact\"\n ? \"verified\"\n : \"observed\",\n },\n });\n });\n\n grouped.set(sourceClient, bucket);\n }\n\n return [...grouped.entries()]\n .filter(([, bucket]) => bucket.findings.length > 0)\n .map(([sourceClient, bucket]) => ({\n schema_version: WORK_GRAPH_EXTRACTION_SCHEMA_VERSION,\n extraction_id: `${sourceClient}:native-extraction:${shortHash({\n sources: bucket.searchedSources,\n findings: bucket.findings.map((finding) => finding.evidence_ref),\n }, 12)}`,\n source_client: sourceClient,\n source_label: `${labelForSourceClient(sourceClient)} native extraction`,\n searched_sources: sortedUnique(bucket.searchedSources),\n search_queries: [\n {\n id: \"native_session_episodes\",\n lens: `${labelForSourceClient(sourceClient)} episode extraction`,\n query: \"Extract decisions, artifacts, blockers, outcomes, handoffs, and missed OrgX writeback from local AI-client session lines.\",\n result_count: bucket.findings.length,\n },\n ],\n extraction_quality: {\n confidence: normalizeConfidence(\n bucket.findings.reduce((total, finding) => total + (finding.confidence ?? 0.72), 0) / bucket.findings.length,\n 0.74,\n ),\n searched_session_count: bucket.searchedSessionCount,\n skipped_session_count: bucket.skippedSessionCount,\n notes: [\n \"Auto-generated by orgx-wizard from local AI-client session imports.\",\n \"Raw transcripts are excluded; only redacted evidence snippets and source refs are retained.\",\n ],\n },\n findings: bucket.findings,\n }));\n}\n\nfunction buildDerivedFindings(imports: readonly FounderLoopImport[]): WorkGraphFinding[] {\n const findings: WorkGraphFinding[] = [];\n let derivedIndex = 0;\n\n for (const source of imports) {\n const sourceClient = sourceClientForImport(source);\n const lines = source.text.split(/\\r?\\n/).map((line) => line.trim()).filter(Boolean);\n\n for (const line of lines) {\n const lower = line.toLowerCase();\n\n if (includesAny(lower, [/\\b(owner|dri|founder|teammate|customer|user|stakeholder|buyer|reviewer)\\b/])) {\n findings.push({\n type: \"person\",\n title: titleFromText(line, \"Person or stakeholder signal\"),\n summary: line,\n source_client: sourceClient,\n source_id: source.sourceId,\n evidence_ref: evidenceRefFor(source.sourceId, derivedIndex++),\n confidence: 0.62,\n metadata: { source_label: source.sourceLabel },\n });\n }\n\n if (includesAny(lower, [/\\b(product surface|surface|live room|command center|dashboard|widget|plugin|wizard|audit|onboarding|mcp|slack|github|linear)\\b/])) {\n findings.push({\n type: \"product_surface\",\n title: titleFromText(line, \"Product surface signal\"),\n summary: line,\n source_client: sourceClient,\n source_id: source.sourceId,\n evidence_ref: evidenceRefFor(source.sourceId, derivedIndex++),\n confidence: 0.66,\n metadata: { source_label: source.sourceLabel },\n });\n }\n\n if (includesAny(lower, [/\\b(goal|objective|initiative|workstream|milestone|roadmap|launch)\\b/])) {\n findings.push({\n type: \"goal\",\n title: titleFromText(line, \"Goal signal\"),\n summary: line,\n source_client: sourceClient,\n source_id: source.sourceId,\n evidence_ref: evidenceRefFor(source.sourceId, derivedIndex++),\n confidence: 0.64,\n metadata: { source_label: source.sourceLabel },\n });\n }\n }\n }\n\n return findings;\n}\n\nexport function buildWorkGraphEvents(imports: readonly FounderLoopImport[]): WorkGraphSourceEvent[] {\n return imports.map((source, index) => ({\n schema_version: WORK_GRAPH_SCHEMA_VERSION,\n source_client: sourceClientForImport(source),\n source_id: source.sourceId,\n source_label: source.sourceLabel,\n event_type: \"session_excerpt\",\n text: source.text,\n evidence_ref: `${source.sourceId}:excerpt`,\n metadata: {\n import_index: index,\n line_count: source.text.split(/\\r?\\n/).filter(Boolean).length,\n raw_transcript_sent: false,\n },\n }));\n}\n\nexport function buildWorkGraphFindings(imports: readonly FounderLoopImport[]): WorkGraphFinding[] {\n const loopFindings = extractFounderLoopItems(imports).map((item) => {\n const source = imports.find((candidate) => candidate.sourceId === item.sourceId);\n const sourceClient = source ? sourceClientForImport(source) : \"unknown\";\n const type = findingTypeForItem(item);\n return {\n type,\n title: titleFromText(item.text, type),\n summary: item.text,\n source_client: sourceClient,\n source_id: item.sourceId,\n evidence_ref: item.evidenceRef,\n confidence: type === \"decision\" || type === \"artifact\" ? 0.82 : 0.72,\n metadata: {\n source_label: item.sourceLabel,\n founder_loop_type: item.type,\n line_number: item.lineNumber,\n },\n } satisfies WorkGraphFinding;\n });\n\n const seen = new Set<string>();\n return [...loopFindings, ...buildDerivedFindings(imports)].filter((finding) => {\n const key = `${finding.type}:${finding.source_id}:${finding.summary.toLowerCase()}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction buildMissedOpportunities(\n coverage: WorkGraphSourceCoverage,\n findings: readonly WorkGraphFinding[],\n): WorkGraphFinding[] {\n const opportunities: WorkGraphFinding[] = [];\n const hasActionableSignal = findings.some((finding) =>\n [\"decision\", \"artifact\", \"blocker\", \"action\"].includes(finding.type),\n );\n\n if (hasActionableSignal && !coverage.orgxMcpCalled) {\n opportunities.push({\n type: \"missed_orchestration_opportunity\",\n title: \"High-value work happened without an OrgX MCP write\",\n summary:\n \"The source contains decisions, artifacts, blockers, or actions, but no durable OrgX MCP call was detected.\",\n source_client: \"wizard\",\n source_id: \"work-graph\",\n evidence_ref: \"work-graph:coverage:orgx-mcp\",\n confidence: coverage.orgxObserved ? 0.78 : 0.7,\n metadata: {\n orgx_observed: coverage.orgxObserved,\n mcp_observed: coverage.mcpObserved,\n skill_only_signal: coverage.skillOnlySignal,\n },\n });\n }\n\n if (coverage.missing.length > 0) {\n opportunities.push({\n type: \"missed_orchestration_opportunity\",\n title: \"Source coverage is incomplete\",\n summary: `Missing sources: ${coverage.missing.join(\", \")}.`,\n source_client: \"wizard\",\n source_id: \"work-graph\",\n evidence_ref: \"work-graph:coverage:missing\",\n confidence: 0.76,\n metadata: { missing_sources: coverage.missing },\n });\n }\n\n return opportunities;\n}\n\nfunction scoreOpportunity(\n coverage: WorkGraphSourceCoverage,\n findings: readonly WorkGraphFinding[],\n): WorkGraphOpportunityScore {\n const count = (type: WorkGraphFindingType) => findings.filter((finding) => finding.type === type).length;\n const decisions = count(\"decision\");\n const artifacts = count(\"artifact\");\n const blockers = count(\"blocker\");\n const actions = count(\"action\");\n const people = count(\"person\");\n const business = count(\"business\");\n const surfaces = count(\"product_surface\");\n const goals = count(\"goal\");\n\n const evidenceQuality = clampScore(35 + Math.min(35, artifacts * 9 + decisions * 6) + Math.min(20, coverage.connected.length * 6) - coverage.missing.length * 8);\n const urgency = clampScore(20 + blockers * 18 + actions * 7 + decisions * 5);\n const ownerClarity = clampScore(25 + people * 18 + (findings.some((finding) => /\\b(owner|dri|responsible|founder)\\b/i.test(finding.summary)) ? 35 : 0));\n const automationPotential = clampScore(30 + actions * 10 + surfaces * 7 + (coverage.mcpObserved ? 12 : 0));\n const valuePotential = clampScore(25 + business * 20 + artifacts * 8 + goals * 10 + surfaces * 5);\n const orgxFit = clampScore(35 + decisions * 8 + blockers * 10 + artifacts * 7 + (coverage.orgxObserved ? 10 : 0) + (!coverage.orgxMcpCalled ? 10 : 0));\n\n return {\n overall: clampScore((valuePotential + evidenceQuality + urgency + ownerClarity + automationPotential + orgxFit) / 6),\n value_potential: valuePotential,\n evidence_quality: evidenceQuality,\n urgency,\n owner_clarity: ownerClarity,\n automation_potential: automationPotential,\n orgx_fit: orgxFit,\n };\n}\n\nfunction estimateImpactProjection(input: {\n coverage: WorkGraphSourceCoverage;\n findings: readonly WorkGraphFinding[];\n opportunityScore: WorkGraphOpportunityScore;\n patterns: readonly WorkGraphRecurringPattern[];\n trails: readonly WorkGraphTrail[];\n}): WorkGraphImpactProjection {\n const { coverage, findings, opportunityScore, patterns, trails } = input;\n const blockerEvents = trails\n .filter((trail) => trail.subject_entity_type === \"blocker\")\n .reduce((total, trail) => total + Math.max(1, trail.events.length), 0);\n const decisionEvents = trails\n .filter((trail) => trail.subject_entity_type === \"decision\")\n .reduce((total, trail) => total + Math.max(1, trail.events.length), 0);\n const artifactEvents = trails\n .filter((trail) => trail.subject_entity_type === \"artifact\")\n .reduce((total, trail) => total + Math.max(1, trail.events.length), 0);\n const missedCount = findings.filter((finding) => finding.type === \"missed_orchestration_opportunity\").length;\n const repeatedEvents = trails\n .filter((trail) => trail.events.length > 1)\n .reduce((total, trail) => total + trail.events.length, 0);\n const rawHours =\n blockerEvents * 0.75 +\n decisionEvents * 0.45 +\n artifactEvents * 0.25 +\n missedCount * 0.65 +\n repeatedEvents * 0.35 +\n coverage.missing.length * 0.4;\n const hours = Number(Math.max(0.5, Math.min(40, rawHours)).toFixed(1));\n const acceleration = clampScore(\n 6 +\n Math.round(opportunityScore.automation_potential * 0.22) +\n patterns.filter((pattern) => pattern.severity === \"critical\" || pattern.severity === \"high\").length * 5 +\n (coverage.manifests?.filter((manifest) => manifest.status === \"connected\").length ?? 0) * 2,\n );\n const confidenceInputs = [\n ...findings.map((finding) => finding.confidence),\n ...patterns.map((pattern) => pattern.confidence),\n coverage.coverage_score ? coverage.coverage_score / 100 : 0.55,\n ];\n const confidence = Number((\n confidenceInputs.reduce((total, value) => total + value, 0) / Math.max(1, confidenceInputs.length)\n ).toFixed(2));\n\n return {\n time_saved_hours_per_week: hours,\n acceleration_percent: Math.min(70, acceleration),\n estimated_monthly_value_usd: Math.round(hours * 4.33 * 200),\n confidence,\n basis: [\n `${blockerEvents} blocker event${blockerEvents === 1 ? \"\" : \"s\"} at 45 minutes of reconstruction/coordination each.`,\n `${decisionEvents} decision event${decisionEvents === 1 ? \"\" : \"s\"} at 27 minutes of rediscovery/promotion each.`,\n `${missedCount} missed orchestration signal${missedCount === 1 ? \"\" : \"s\"} at 39 minutes of manual writeback each.`,\n `${coverage.missing.length} missing source${coverage.missing.length === 1 ? \"\" : \"s\"} reducing attribution confidence.`,\n ],\n assumptions: [\n \"Uses a conservative $200/hour blended founder/operator cost for public-safe value estimates.\",\n \"Acceleration estimates the execution lift from turning repeated trails into automated attribution, decisions, and source connections.\",\n \"Impact is directional until the user claims the fingerprint and confirms or corrects trail evidence.\",\n ],\n };\n}\n\nfunction scoreExecutionQuality(input: {\n coverage: WorkGraphSourceCoverage;\n findings: readonly WorkGraphFinding[];\n impact: WorkGraphImpactProjection;\n patterns: readonly WorkGraphRecurringPattern[];\n recommendations: readonly WorkGraphTrailRecommendation[];\n trails: readonly WorkGraphTrail[];\n}): WorkGraphExecutionQualityScore {\n const { coverage, findings, impact, patterns, recommendations, trails } = input;\n const uniqueClients = sortedUnique(findings.map((finding) => finding.source_client));\n const unknownCount = findings.filter((finding) => finding.source_client === \"unknown\").length;\n const multiEventTrails = trails.filter((trail) => trail.events.length > 1).length;\n const evidenceCoverage = clampScore(\n (coverage.coverage_score ?? 50) +\n Math.min(18, coverage.connected.length * 3) -\n coverage.missing.length * 4,\n );\n const sourceAttribution = clampScore(\n 34 +\n uniqueClients.filter((client) => client !== \"unknown\").length * 10 +\n (coverage.manifests?.filter((manifest) => manifest.status === \"connected\").length ?? 0) * 6 -\n unknownCount * 8,\n );\n const trailDepth = clampScore(\n 25 +\n (trails.length > 0 ? Math.round((multiEventTrails / trails.length) * 45) : 0) +\n Math.min(20, trails.reduce((total, trail) => total + trail.events.length, 0) * 2),\n );\n const insightDepth = clampScore(\n 30 +\n Math.min(28, patterns.length * 8) +\n Math.min(18, findings.filter((finding) => [\"blocker\", \"decision\", \"outcome\", \"missed_orchestration_opportunity\"].includes(finding.type)).length * 3),\n );\n const actionability = clampScore(\n 30 +\n Math.min(35, recommendations.length * 10) +\n Math.min(20, recommendations.filter((recommendation) => recommendation.priority === \"p0\").length * 10),\n );\n const impactConfidence = clampScore(impact.confidence * 100);\n const overall = clampScore(\n evidenceCoverage * 0.22 +\n sourceAttribution * 0.18 +\n trailDepth * 0.18 +\n insightDepth * 0.18 +\n actionability * 0.14 +\n impactConfidence * 0.1,\n );\n\n return {\n overall,\n evidence_coverage: evidenceCoverage,\n source_attribution: sourceAttribution,\n trail_depth: trailDepth,\n insight_depth: insightDepth,\n actionability,\n impact_confidence: impactConfidence,\n notes: [\n \"10/10 requires client-native extraction per source, multi-event trails, source-specific evidence, and action recommendations tied to impact.\",\n multiEventTrails === trails.length\n ? \"Every trail has multiple evidence events.\"\n : `${trails.length - multiEventTrails} trail${trails.length - multiEventTrails === 1 ? \"\" : \"s\"} still need more chronology before they should be called recurring.`,\n coverage.missing.length > 0\n ? `Missing source coverage: ${coverage.missing.join(\", \")}.`\n : \"No required source gaps were declared for this run.\",\n ],\n };\n}\n\nfunction inferFinalState(findings: readonly WorkGraphFinding[]): WorkGraphFinalState {\n if (findings.some((finding) => finding.type === \"blocker\")) return \"blocked\";\n if (findings.some((finding) => finding.type === \"artifact\" || finding.type === \"outcome\" || /\\b(shipped|completed|done|verified)\\b/i.test(finding.summary))) {\n return \"completed\";\n }\n if (findings.some((finding) => finding.type === \"action\" || finding.type === \"decision\")) return \"in_progress\";\n return \"unknown\";\n}\n\nfunction buildKickoffs(\n findings: readonly WorkGraphFinding[],\n missed: readonly WorkGraphFinding[],\n score: WorkGraphOpportunityScore,\n): WorkGraphKickoffCandidate[] {\n const blockers = findings.filter((finding) => finding.type === \"blocker\").slice(0, 3);\n const decisions = findings.filter((finding) => finding.type === \"decision\").slice(0, 3);\n const artifacts = findings.filter((finding) => finding.type === \"artifact\").slice(0, 3);\n const kickoffs: WorkGraphKickoffCandidate[] = [];\n\n if (missed.length > 0) {\n kickoffs.push({\n title: \"Install continuous OrgX writeback\",\n summary: \"Turn detected work into live OrgX activity, retro, outcome, and decision records.\",\n reason: missed[0]?.summary ?? \"A source produced work without durable OrgX orchestration.\",\n finding_refs: missed.map((finding) => finding.evidence_ref).slice(0, 4),\n priority: score.overall >= 75 ? \"p0\" : \"p1\",\n });\n }\n\n if (blockers.length > 0 || decisions.length > 0) {\n kickoffs.push({\n title: \"Resolve the hidden decision queue\",\n summary: \"Convert unresolved decisions and blockers into owner-visible OrgX decision cards.\",\n reason: \"The Work Graph found decisions or blockers that can slow execution if they stay buried in transcripts.\",\n finding_refs: [...blockers, ...decisions].map((finding) => finding.evidence_ref).slice(0, 5),\n priority: blockers.length > 0 ? \"p0\" : \"p1\",\n });\n }\n\n if (artifacts.length > 0) {\n kickoffs.push({\n title: \"Attach proof to the operating loop\",\n summary: \"Promote completed work into artifacts with owners, evidence refs, and next actions.\",\n reason: \"Completed work was detected; OrgX can make it queryable and reusable.\",\n finding_refs: artifacts.map((finding) => finding.evidence_ref),\n priority: \"p1\",\n });\n }\n\n if (kickoffs.length === 0) {\n kickoffs.push({\n title: \"Connect first work source\",\n summary: \"Add AI client, Slack, or MCP source coverage so OrgX can build a useful Work Graph.\",\n reason: \"The scan did not find enough structured work to recommend a specific operating initiative.\",\n finding_refs: [],\n priority: \"p2\",\n });\n }\n\n return kickoffs.slice(0, 3);\n}\n\nfunction entityTypeForFinding(finding: WorkGraphFinding): WorkGraphEntityType {\n switch (finding.type) {\n case \"decision\":\n return \"decision\";\n case \"artifact\":\n return \"artifact\";\n case \"blocker\":\n return \"blocker\";\n case \"person\":\n return \"person\";\n case \"business\":\n return \"business\";\n case \"product_surface\":\n return \"surface\";\n case \"goal\":\n case \"initiative_candidate\":\n return \"initiative\";\n case \"outcome\":\n return \"outcome\";\n case \"action\":\n return /\\b(outcome|shipped|completed|verified)\\b/i.test(finding.summary) ? \"outcome\" : \"task\";\n case \"missed_orchestration_opportunity\":\n return \"source\";\n }\n}\n\nfunction trailKindForEntity(entityType: WorkGraphEntityType): WorkGraphTrailKind {\n switch (entityType) {\n case \"decision\":\n return \"decision_trail\";\n case \"artifact\":\n return \"artifact_trail\";\n case \"person\":\n return \"person_trail\";\n case \"business\":\n return \"business_trail\";\n case \"blocker\":\n return \"blocker_trail\";\n case \"agent\":\n return \"agent_trail\";\n case \"tool\":\n case \"source\":\n return \"source_trail\";\n case \"outcome\":\n return \"outcome_trail\";\n case \"idea\":\n return \"idea_trail\";\n case \"initiative\":\n case \"workstream\":\n case \"milestone\":\n case \"task\":\n case \"surface\":\n return \"initiative_trail\";\n }\n}\n\nfunction eventTypeForFinding(finding: WorkGraphFinding): WorkGraphTrailEvent[\"event_type\"] {\n switch (finding.type) {\n case \"decision\":\n return \"decision_inferred\";\n case \"artifact\":\n return /\\b(verified|proof|tested|passed)\\b/i.test(finding.summary)\n ? \"artifact_verified\"\n : \"artifact_created\";\n case \"blocker\":\n return \"blocker_detected\";\n case \"person\":\n return \"owner_assigned\";\n case \"business\":\n return \"signal_detected\";\n case \"product_surface\":\n return \"signal_detected\";\n case \"goal\":\n case \"initiative_candidate\":\n return \"initiative_created\";\n case \"outcome\":\n return \"outcome_recorded\";\n case \"action\":\n return /\\b(outcome|result|impact|roi)\\b/i.test(finding.summary)\n ? \"outcome_recorded\"\n : \"recommendation_generated\";\n case \"missed_orchestration_opportunity\":\n return \"source_connected\";\n }\n}\n\nfunction trailStateForFindings(findings: readonly WorkGraphFinding[]): WorkGraphTrailState {\n if (findings.some((finding) => finding.type === \"blocker\")) return \"blocked\";\n if (findings.some((finding) => finding.type === \"missed_orchestration_opportunity\")) return \"missing_evidence\";\n if (findings.some((finding) => /\\b(contradict|conflict)\\b/i.test(finding.summary))) return \"contradicted\";\n if (findings.some((finding) => finding.type === \"outcome\" || /\\b(verified|proof|passed|complete_with_proof)\\b/i.test(finding.summary))) return \"verified\";\n if (findings.some((finding) => finding.type === \"decision\")) return \"inferred\";\n return \"observed\";\n}\n\nfunction trailValenceForFindings(findings: readonly WorkGraphFinding[], recurrence: number): WorkGraphTrailValence {\n if (findings.some((finding) => finding.type === \"blocker\")) return recurrence > 1 ? \"escalating\" : \"risk\";\n if (findings.some((finding) => finding.type === \"missed_orchestration_opportunity\")) return \"leak\";\n if (findings.some((finding) => finding.type === \"decision\") && recurrence > 1) return \"wasteful_recurrence\";\n if (findings.some((finding) => finding.type === \"outcome\")) return \"healthy\";\n if (findings.some((finding) => finding.type === \"business\")) return \"opportunity\";\n if (findings.some((finding) => finding.type === \"artifact\")) return \"healthy\";\n return recurrence > 1 ? \"useful_recurrence\" : \"opportunity\";\n}\n\nfunction trailShapeForFindings(findings: readonly WorkGraphFinding[], recurrence: number): WorkGraphTrail[\"shape\"] {\n const decisions = findings.filter((finding) => finding.type === \"decision\").length;\n const artifacts = findings.filter((finding) => finding.type === \"artifact\").length;\n if (recurrence <= 1) return \"single_signal\";\n if (decisions > artifacts && decisions > 0) return \"decision_heavy_artifact_light\";\n if (artifacts > decisions && artifacts > 0 && decisions === 0) return \"artifact_heavy_decision_light\";\n if (findings.some((finding) => finding.type === \"blocker\")) return recurrence >= 3 ? \"accelerating_issue\" : \"dense_recent_cluster\";\n if (recurrence >= 3) return \"chronic_recurrence\";\n if (findings.some((finding) => /\\b(resurface|again|back|revived|reappeared)\\b/i.test(finding.summary))) return \"zombie_revival\";\n if (findings.some((finding) => finding.type === \"outcome\" || /\\b(verified|passed|shipped|completed)\\b/i.test(finding.summary))) return \"healthy_execution\";\n return \"dense_recent_cluster\";\n}\n\nfunction findingTimestamp(finding: WorkGraphFinding, fallback: string): string {\n const occurredAt = finding.metadata.occurred_at;\n return isIsoTimestamp(occurredAt) ? occurredAt : fallback;\n}\n\nfunction canonicalRelatedToken(finding: WorkGraphFinding): string | null {\n const candidates = [\n ...arrayOfStrings(finding.metadata.related_source_ids),\n ...arrayOfStrings(finding.metadata.related_entity_names),\n finding.source_id,\n finding.title,\n ];\n const scored = candidates\n .map((candidate) => candidate.trim())\n .filter(Boolean)\n .map((candidate) => {\n const normalized = candidate.toLowerCase();\n let score = 0;\n if (/_/.test(candidate)) score += 6;\n if (/orgx|mcp|wizard|plugin|runtime|hook|work graph|profile|trace|scaffold|ship|spawn|record|submit|list/i.test(candidate)) score += 5;\n if (/session|jsonl|rollout|line|current-release/i.test(normalized)) score -= 4;\n if (candidate.length > 80) score -= 2;\n return { candidate, score };\n })\n .filter((item) => item.score > 0)\n .sort((left, right) => right.score - left.score);\n return scored[0]?.candidate ?? null;\n}\n\nfunction groupingKeyForFinding(finding: WorkGraphFinding): string {\n const entityType = entityTypeForFinding(finding);\n const token = canonicalRelatedToken(finding);\n if (token && [\"blocker\", \"source\", \"surface\", \"initiative\", \"outcome\", \"task\"].includes(entityType)) {\n return `${entityType}:${slugPart(token)}`;\n }\n return `${entityType}:${slugPart(finding.title)}`;\n}\n\nfunction trailTitleForGroup(entityType: WorkGraphEntityType, group: readonly WorkGraphFinding[]): string {\n const token = canonicalRelatedToken(group[0]!);\n if (group.length > 1 && token) {\n const label = token.replace(/[-_]/g, \" \").replace(/\\b\\w/g, (char) => char.toUpperCase());\n if (entityType === \"blocker\") return `${label} is recurring as an execution blocker`;\n if (entityType === \"source\") return `${label} is an attribution coverage gap`;\n if (entityType === \"surface\") return `${label} is becoming a product surface trail`;\n if (entityType === \"outcome\") return `${label} is becoming outcome evidence`;\n return `${label} is becoming durable work`;\n }\n return group[0]!.title;\n}\n\nfunction trailSummaryForGroup(group: readonly WorkGraphFinding[]): string {\n if (group.length === 1) return group[0]!.summary;\n const sources = sortedUnique(group.map((finding) => labelForSourceClient(finding.source_client)));\n const states = sortedUnique(\n group\n .map((finding) => typeof finding.metadata.state === \"string\" ? finding.metadata.state : \"\")\n .filter(Boolean),\n );\n return [\n `${group.length} evidence events connect this trail across ${sources.join(\", \")}.`,\n states.length > 0 ? `Observed states: ${states.join(\", \")}.` : \"\",\n group[0]?.summary ?? \"\",\n ].filter(Boolean).join(\" \");\n}\n\nexport function buildWorkGraphTrails(\n findings: readonly WorkGraphFinding[],\n generatedAt: string,\n): WorkGraphTrail[] {\n const grouped = new Map<string, WorkGraphFinding[]>();\n\n for (const finding of findings) {\n const key = groupingKeyForFinding(finding);\n grouped.set(key, [...(grouped.get(key) ?? []), finding]);\n }\n\n return [...grouped.entries()].map(([key, group], index) => {\n const sortedGroup = [...group].sort((left, right) =>\n findingTimestamp(left, generatedAt).localeCompare(findingTimestamp(right, generatedAt))\n );\n const first = sortedGroup[0]!;\n const entityType = entityTypeForFinding(first);\n const entityId = `${entityType}:${shortHash(key, 12)}`;\n const trailId = `trail:${shortHash({ key, evidence: sortedGroup.map((finding) => finding.evidence_ref) }, 14)}`;\n const recurrence = sortedGroup.length;\n const evidenceRefs = sortedUnique(sortedGroup.map((finding) => finding.evidence_ref));\n const events: WorkGraphTrailEvent[] = sortedGroup.map((finding, eventIndex) => ({\n id: `${trailId}:event:${eventIndex + 1}`,\n trail_id: trailId,\n event_type: eventTypeForFinding(finding),\n entity_id: entityId,\n entity_type: entityType,\n timestamp: findingTimestamp(finding, generatedAt),\n ...(typeof finding.metadata.actor_id === \"string\" ? { actor_id: finding.metadata.actor_id } : {}),\n source_id: finding.source_id,\n source_type: finding.source_client,\n redacted_verbatim: finding.summary.slice(0, 320),\n confidence: finding.confidence,\n evidence_refs: [finding.evidence_ref],\n privacy_state: \"redacted\",\n }));\n const edges: WorkGraphTrailEdge[] = events.slice(1).map((event, edgeIndex) => ({\n id: `${trailId}:edge:${edgeIndex + 1}`,\n from_event_id: events[edgeIndex]!.id,\n to_event_id: event.id,\n relation: group.some((finding) => finding.type === \"blocker\") ? \"blocked\" : \"informed\",\n state: recurrence > 1 ? \"captured\" : \"inferred\",\n confidence: Math.min(0.92, Math.max(0.58, event.confidence - 0.04)),\n evidence_refs: event.evidence_refs,\n }));\n const confidence =\n sortedGroup.reduce((total, finding) => total + finding.confidence, 0) / sortedGroup.length;\n const createdAt = events[0]?.timestamp ?? generatedAt;\n const updatedAt = events[events.length - 1]?.timestamp ?? generatedAt;\n\n return {\n id: trailId,\n kind: trailKindForEntity(entityType),\n title: trailTitleForGroup(entityType, sortedGroup),\n summary: trailSummaryForGroup(sortedGroup),\n subject_entity_id: entityId,\n subject_entity_type: entityType,\n state: trailStateForFindings(sortedGroup),\n valence: trailValenceForFindings(sortedGroup, recurrence),\n confidence: Number(confidence.toFixed(2)),\n recurrence_score: recurrence <= 1 ? Math.min(24, evidenceRefs.length * 8 + 10) : Math.min(100, recurrence * 24 + evidenceRefs.length * 7),\n impact_score: Math.min(100, Math.round(first.confidence * 70) + recurrence * 8 + (index < 4 ? 10 : 0)),\n privacy_state: \"redacted\",\n events,\n edges,\n evidence_refs: evidenceRefs,\n blocker_ids: sortedGroup.filter((finding) => finding.type === \"blocker\").map((finding) => finding.evidence_ref),\n recommendation_ids: [],\n created_at: createdAt,\n updated_at: updatedAt,\n shape: trailShapeForFindings(sortedGroup, recurrence),\n };\n });\n}\n\nfunction severityFor(count: number): WorkGraphRecurringPattern[\"severity\"] {\n if (count >= 6) return \"critical\";\n if (count >= 3) return \"high\";\n if (count >= 2) return \"medium\";\n return \"low\";\n}\n\nfunction trailsForType(trails: readonly WorkGraphTrail[], entityType: WorkGraphEntityType): WorkGraphTrail[] {\n return trails.filter((trail) => trail.subject_entity_type === entityType);\n}\n\nexport function buildRecurringPatterns(\n coverage: WorkGraphSourceCoverage,\n findings: readonly WorkGraphFinding[],\n trails: readonly WorkGraphTrail[],\n): WorkGraphRecurringPattern[] {\n const patterns: WorkGraphRecurringPattern[] = [];\n const decisionTrails = trailsForType(trails, \"decision\");\n const artifactTrails = trailsForType(trails, \"artifact\");\n const blockerTrails = trailsForType(trails, \"blocker\");\n const personTrails = trailsForType(trails, \"person\");\n const businessTrails = trailsForType(trails, \"business\");\n const highRecurrence = trails.filter((trail) => trail.recurrence_score >= 56);\n\n if (decisionTrails.length > 0 && !coverage.orgxMcpCalled) {\n patterns.push({\n id: \"pattern:trapped-decision\",\n title: \"Decisions are being made without durable OrgX writeback\",\n description: `${decisionTrails.length} decision trail${decisionTrails.length === 1 ? \"\" : \"s\"} appeared while no OrgX MCP write was detected.`,\n pattern_type: \"trapped_decision\",\n affected_trail_ids: decisionTrails.map((trail) => trail.id),\n affected_entity_ids: decisionTrails.map((trail) => trail.subject_entity_id),\n recurrence_count: decisionTrails.length,\n severity: severityFor(decisionTrails.length + 1),\n confidence: coverage.orgxObserved ? 0.82 : 0.74,\n valence: \"leak\",\n root_cause_hypothesis: \"Agents and humans are making useful choices, but the runtime is not promoting those choices into organizational memory.\",\n recommended_runtime_action_id: \"recommendation:promote-decisions\",\n });\n }\n\n if (artifactTrails.length > 0 && personTrails.length === 0) {\n patterns.push({\n id: \"pattern:orphaned-artifact\",\n title: \"Artifacts do not have visible ownership\",\n description: `${artifactTrails.length} artifact trail${artifactTrails.length === 1 ? \"\" : \"s\"} appeared without a clear owner trail.`,\n pattern_type: \"orphaned_artifact\",\n affected_trail_ids: artifactTrails.map((trail) => trail.id),\n affected_entity_ids: artifactTrails.map((trail) => trail.subject_entity_id),\n recurrence_count: artifactTrails.length,\n severity: severityFor(artifactTrails.length),\n confidence: 0.72,\n valence: \"risk\",\n root_cause_hypothesis: \"Work is becoming concrete, but downstream accountability is not being attached at creation time.\",\n recommended_runtime_action_id: \"recommendation:assign-owner\",\n });\n }\n\n if (coverage.missing.length > 0) {\n const sourceTrails = trailsForType(trails, \"source\");\n patterns.push({\n id: \"pattern:missing-source\",\n title: \"Important source coverage is missing\",\n description: `Missing sources: ${coverage.missing.join(\", \")}.`,\n pattern_type: \"missing_source\",\n affected_trail_ids: sourceTrails.map((trail) => trail.id),\n affected_entity_ids: sourceTrails.map((trail) => trail.subject_entity_id),\n recurrence_count: coverage.missing.length,\n severity: severityFor(coverage.missing.length),\n confidence: 0.78,\n valence: \"leak\",\n root_cause_hypothesis: \"The scan can see work happening, but coordination and proof sources are not fully connected.\",\n recommended_runtime_action_id: \"recommendation:connect-source\",\n });\n }\n\n if (coverage.mcpObserved && !coverage.orgxMcpCalled) {\n patterns.push({\n id: \"pattern:tooling-mismatch\",\n title: \"MCP was present, but OrgX was not called\",\n description: \"The session mentions MCP/tooling activity, but no durable OrgX MCP call was detected.\",\n pattern_type: \"tooling_mismatch\",\n affected_trail_ids: trails.map((trail) => trail.id).slice(0, 6),\n affected_entity_ids: trails.map((trail) => trail.subject_entity_id).slice(0, 6),\n recurrence_count: findings.filter((finding) => /\\bmcp|tool\\b/i.test(finding.summary)).length || 1,\n severity: \"high\",\n confidence: 0.8,\n valence: \"leak\",\n root_cause_hypothesis: \"The available tool layer is not automatically closing the loop when work finishes.\",\n recommended_runtime_action_id: \"recommendation:install-runtime-hooks\",\n });\n }\n\n if (highRecurrence.length > 0) {\n patterns.push({\n id: \"pattern:repeated-work\",\n title: \"The same work shape is recurring\",\n description: `${highRecurrence.length} trail${highRecurrence.length === 1 ? \"\" : \"s\"} repeat strongly enough to deserve durable operating memory.`,\n pattern_type: \"repeated_work\",\n affected_trail_ids: highRecurrence.map((trail) => trail.id),\n affected_entity_ids: highRecurrence.map((trail) => trail.subject_entity_id),\n recurrence_count: highRecurrence.reduce((total, trail) => total + trail.events.length, 0),\n severity: severityFor(highRecurrence.length),\n confidence: 0.7,\n valence: \"useful_recurrence\",\n root_cause_hypothesis: \"Repeated work is creating a reusable operating pattern, but it is still only implicit.\",\n recommended_runtime_action_id: \"recommendation:launch-initiative\",\n });\n }\n\n if (businessTrails.length > 0 && findings.every((finding) => finding.type !== \"initiative_candidate\")) {\n patterns.push({\n id: \"pattern:business-signal-unclaimed\",\n title: \"Business signal has not become a launchable initiative\",\n description: `${businessTrails.length} business trail${businessTrails.length === 1 ? \"\" : \"s\"} appeared without a matching initiative candidate.`,\n pattern_type: \"business_signal_unclaimed\",\n affected_trail_ids: businessTrails.map((trail) => trail.id),\n affected_entity_ids: businessTrails.map((trail) => trail.subject_entity_id),\n recurrence_count: businessTrails.length,\n severity: severityFor(businessTrails.length),\n confidence: 0.68,\n valence: \"opportunity\",\n root_cause_hypothesis: \"Revenue or ROI signal exists, but the operating graph has not turned it into an account or initiative loop.\",\n recommended_runtime_action_id: \"recommendation:launch-initiative\",\n });\n }\n\n if (blockerTrails.length > 0) {\n const topBlockerTrail = [...blockerTrails].sort((left, right) =>\n right.events.length - left.events.length || right.impact_score - left.impact_score\n )[0];\n patterns.push({\n id: \"pattern:handoff-friction\",\n title: topBlockerTrail && topBlockerTrail.events.length > 1\n ? `${topBlockerTrail.title} and needs owner-visible resolution`\n : \"Blockers are becoming handoff friction\",\n description: `${blockerTrails.length} blocker trail${blockerTrails.length === 1 ? \"\" : \"s\"} need owner-visible resolution.`,\n pattern_type: \"handoff_friction\",\n affected_trail_ids: blockerTrails.map((trail) => trail.id),\n affected_entity_ids: blockerTrails.map((trail) => trail.subject_entity_id),\n recurrence_count: blockerTrails.length,\n severity: severityFor(blockerTrails.length + 1),\n confidence: 0.76,\n valence: \"risk\",\n root_cause_hypothesis: \"Execution is producing unresolved edges that need to become assigned decisions or tasks.\",\n recommended_runtime_action_id: \"recommendation:assign-owner\",\n });\n }\n\n return patterns.slice(0, 8);\n}\n\nexport function buildTrailRecommendations(\n patterns: readonly WorkGraphRecurringPattern[],\n trails: readonly WorkGraphTrail[],\n): WorkGraphTrailRecommendation[] {\n const recommendations: WorkGraphTrailRecommendation[] = [];\n const add = (recommendation: WorkGraphTrailRecommendation) => {\n if (!recommendations.some((existing) => existing.id === recommendation.id)) {\n recommendations.push(recommendation);\n }\n };\n\n for (const pattern of patterns) {\n const evidenceRefs = sortedUnique(\n trails\n .filter((trail) => pattern.affected_trail_ids.includes(trail.id))\n .flatMap((trail) => trail.evidence_refs),\n ).slice(0, 8);\n if (pattern.pattern_type === \"trapped_decision\") {\n add({\n id: \"recommendation:promote-decisions\",\n title: \"Promote trapped decisions\",\n summary: \"Turn inferred decisions into reviewed OrgX decision records with owners and downstream artifact links.\",\n action_type: \"promote_decision\",\n trail_ids: pattern.affected_trail_ids,\n evidence_refs: evidenceRefs,\n priority: pattern.severity === \"critical\" || pattern.severity === \"high\" ? \"p0\" : \"p1\",\n expected_lift: \"+decision durability\",\n confidence: pattern.confidence,\n });\n } else if (pattern.pattern_type === \"orphaned_artifact\") {\n add({\n id: \"recommendation:assign-owner\",\n title: \"Assign ownership to orphaned artifacts\",\n summary: \"Attach owners and next actions to artifacts before they decay into unqueryable receipts.\",\n action_type: \"assign_owner\",\n trail_ids: pattern.affected_trail_ids,\n evidence_refs: evidenceRefs,\n priority: \"p1\",\n expected_lift: \"+owner clarity\",\n confidence: pattern.confidence,\n });\n } else if (pattern.pattern_type === \"missing_source\") {\n add({\n id: \"recommendation:connect-source\",\n title: \"Connect missing source coverage\",\n summary: \"Close the evidence gap by connecting the coordination or proof sources where trails terminate.\",\n action_type: \"connect_source\",\n trail_ids: pattern.affected_trail_ids,\n evidence_refs: evidenceRefs,\n priority: \"p1\",\n expected_lift: \"+source confidence\",\n confidence: pattern.confidence,\n });\n } else if (pattern.pattern_type === \"tooling_mismatch\") {\n add({\n id: \"recommendation:install-runtime-hooks\",\n title: \"Install runtime writeback hooks\",\n summary: \"Use post-session reconciliation so useful work becomes OrgX activity even when the agent forgets.\",\n action_type: \"verify_outcome\",\n trail_ids: pattern.affected_trail_ids,\n evidence_refs: evidenceRefs,\n priority: \"p0\",\n expected_lift: \"+continuous attribution\",\n confidence: pattern.confidence,\n });\n } else if (pattern.pattern_type === \"handoff_friction\") {\n add({\n id: \"recommendation:resolve-blocker-handoff\",\n title: \"Resolve the blocker handoff trail\",\n summary: \"Promote the recurring blocker path into assigned work with proof requirements and a clear owner.\",\n action_type: \"assign_owner\",\n trail_ids: pattern.affected_trail_ids,\n evidence_refs: evidenceRefs,\n priority: pattern.severity === \"critical\" || pattern.severity === \"high\" ? \"p0\" : \"p1\",\n expected_lift: \"+execution continuity\",\n confidence: pattern.confidence,\n });\n } else if (pattern.pattern_type === \"business_signal_unclaimed\" || pattern.pattern_type === \"repeated_work\") {\n add({\n id: \"recommendation:launch-initiative\",\n title: \"Launch from this trail\",\n summary: \"Convert the highest-recurring evidence path into an OrgX initiative with proof requirements.\",\n action_type: \"launch_initiative\",\n trail_ids: pattern.affected_trail_ids,\n evidence_refs: evidenceRefs,\n priority: pattern.severity === \"critical\" || pattern.severity === \"high\" ? \"p0\" : \"p1\",\n expected_lift: \"+initiative readiness\",\n confidence: pattern.confidence,\n });\n }\n }\n\n if (recommendations.length === 0 && trails.length > 0) {\n const topTrail = [...trails].sort((a, b) => b.impact_score - a.impact_score)[0]!;\n add({\n id: \"recommendation:inspect-top-trail\",\n title: \"Inspect the strongest trail\",\n summary: \"Review the highest-confidence evidence path and decide whether it should become durable OrgX memory.\",\n action_type: \"launch_initiative\",\n trail_ids: [topTrail.id],\n evidence_refs: topTrail.evidence_refs,\n priority: \"p2\",\n expected_lift: \"+operating memory\",\n confidence: topTrail.confidence,\n });\n }\n\n const priorityRank = { p0: 0, p1: 1, p2: 2 };\n return recommendations\n .sort((left, right) =>\n priorityRank[left.priority] - priorityRank[right.priority] ||\n right.confidence - left.confidence\n )\n .slice(0, 5);\n}\n\nexport function buildWorkGraphMirror(input: {\n coverage: WorkGraphSourceCoverage;\n generatedAt: string;\n impact?: WorkGraphImpactProjection;\n patterns: readonly WorkGraphRecurringPattern[];\n recommendations: readonly WorkGraphTrailRecommendation[];\n trails: readonly WorkGraphTrail[];\n}): WorkGraphMirror {\n const { coverage, generatedAt, impact, patterns, recommendations, trails } = input;\n const topTrail = [...trails].sort((a, b) => b.impact_score - a.impact_score)[0];\n const topPattern = [...patterns].sort((a, b) => b.recurrence_count - a.recurrence_count)[0];\n const decisionCount = trailsForType(trails, \"decision\").length;\n const artifactCount = trailsForType(trails, \"artifact\").length;\n const blockerCount = trailsForType(trails, \"blocker\").length;\n const sourceGapCount = coverage.missing.length;\n const sourceClients = sortedUnique(\n trails.flatMap((trail) => trail.events.map((event) => event.source_type)),\n );\n const sourcePhrase = sourceClients.length > 0\n ? sourceClients.map(labelForSourceClient).join(\", \")\n : coverage.connected.join(\", \") || \"local sources\";\n const headline = blockerCount > 0\n ? \"Your AI work is shipping, but the execution trail is breaking\"\n : sourceGapCount > 0\n ? \"Your work leaves trails, but the proof chain is still incomplete\"\n : topPattern\n ? \"Your work has a recurring operating pattern worth preserving\"\n : topTrail\n ? \"Your work is becoming an operating profile\"\n : \"Your work is leaving an operating trail\";\n const primaryClaimRefs = topTrail?.evidence_refs ?? [];\n const claims: WorkGraphMirrorClaim[] = [\n {\n id: \"mirror:trail-count\",\n text: `${trails.length} trails were detected across ${coverage.connected.length} connected source${coverage.connected.length === 1 ? \"\" : \"s\"}.`,\n evidence_refs: trails.flatMap((trail) => trail.evidence_refs).slice(0, 6),\n confidence: trails.length > 0 ? 0.82 : 0.55,\n },\n {\n id: \"mirror:decision-artifact-balance\",\n text: `${decisionCount} decision trail${decisionCount === 1 ? \"\" : \"s\"} and ${artifactCount} artifact trail${artifactCount === 1 ? \"\" : \"s\"} were found.`,\n evidence_refs: trails\n .filter((trail) => trail.subject_entity_type === \"decision\" || trail.subject_entity_type === \"artifact\")\n .flatMap((trail) => trail.evidence_refs)\n .slice(0, 6),\n confidence: 0.78,\n },\n {\n id: \"mirror:missing-sources\",\n text: sourceGapCount > 0\n ? `${sourceGapCount} source gap${sourceGapCount === 1 ? \"\" : \"s\"} still limit attribution depth.`\n : \"The connected sources are enough for a first operating profile, pending human review.\",\n evidence_refs: trailsForType(trails, \"source\").flatMap((trail) => trail.evidence_refs).slice(0, 4),\n confidence: sourceGapCount > 0 ? 0.76 : 0.66,\n },\n ...(impact ? [{\n id: \"mirror:impact\",\n text: `${impact.time_saved_hours_per_week} hours/week and +${impact.acceleration_percent}% execution acceleration are recoverable if the top trails become durable.`,\n evidence_refs: trails.flatMap((trail) => trail.evidence_refs).slice(0, 6),\n confidence: impact.confidence,\n }] : []),\n ];\n const body = [\n `You have real work moving across ${sourcePhrase}: OrgX found ${trails.length} evidence trail${trails.length === 1 ? \"\" : \"s\"} without requiring OrgX tool calls to be present.`,\n topPattern\n ? `The strongest recurring pattern is ${topPattern.title.toLowerCase()}, with ${topPattern.recurrence_count} appearance${topPattern.recurrence_count === 1 ? \"\" : \"s\"} still needing durable writeback.`\n : topTrail\n ? `The clearest trail is ${topTrail.title.toLowerCase()}, but it still needs stronger chronology before it becomes durable operating memory.`\n : \"The first profile is forming from sparse evidence and should be reviewed before promotion.\",\n blockerCount > 0\n ? `${blockerCount} blocker trail${blockerCount === 1 ? \"\" : \"s\"} keep work returning as new work instead of becoming owner-visible resolution.`\n : `${decisionCount} decision trail${decisionCount === 1 ? \"\" : \"s\"} and ${artifactCount} artifact trail${artifactCount === 1 ? \"\" : \"s\"} already show where work can be preserved.`,\n sourceGapCount > 0\n ? `${sourceGapCount} source gap${sourceGapCount === 1 ? \"\" : \"s\"} still limit trust, especially ownership, handoffs, and later verification.`\n : \"The connected sources are enough for a first public-safe profile, pending human review.\",\n impact\n ? `Left unresolved, the profile estimates ${impact.time_saved_hours_per_week} recoverable hours/week, +${impact.acceleration_percent}% acceleration, and about $${impact.estimated_monthly_value_usd.toLocaleString(\"en-US\")}/month in operator leverage.`\n : \"\",\n recommendations[0]\n ? `The next repair is concrete: ${recommendations[0].title}.`\n : \"The next move is to inspect the highest-confidence trail before publishing it.\",\n ].filter(Boolean).join(\" \");\n\n return {\n headline,\n body,\n lens: \"all\",\n claims,\n ...(topTrail ? { primary_trail_id: topTrail.id } : {}),\n generated_at: generatedAt,\n };\n}\n\nexport function buildTensionMetrics(input: {\n coverage: WorkGraphSourceCoverage;\n impact?: WorkGraphImpactProjection;\n patterns: readonly WorkGraphRecurringPattern[];\n quality?: WorkGraphExecutionQualityScore;\n trails: readonly WorkGraphTrail[];\n}): WorkGraphTensionMetric[] {\n const { coverage, impact, patterns, quality, trails } = input;\n const decisionTrails = trailsForType(trails, \"decision\");\n const blockerTrails = trailsForType(trails, \"blocker\");\n const artifactTrails = trailsForType(trails, \"artifact\");\n const missingSourceTrails = trailsForType(trails, \"source\");\n const topReady = trails.filter((trail) => trail.impact_score >= 70 && trail.confidence >= 0.75);\n\n return [\n ...(quality ? [{\n id: \"tension:quality-score\",\n label: \"quality score\",\n value: `${quality.overall}/100`,\n tone: quality.overall >= 82 ? \"good\" as const : quality.overall >= 65 ? \"warning\" as const : \"danger\" as const,\n trail_ids: trails.slice(0, 8).map((trail) => trail.id),\n evidence_refs: trails.flatMap((trail) => trail.evidence_refs).slice(0, 8),\n explanation: \"Weighted audit quality across evidence coverage, attribution, trail depth, insight depth, actionability, and impact confidence.\",\n }] : []),\n ...(impact ? [{\n id: \"tension:time-saved\",\n label: \"hours recoverable\",\n value: `${impact.time_saved_hours_per_week}h/wk`,\n tone: impact.time_saved_hours_per_week >= 4 ? \"warning\" as const : \"muted\" as const,\n trail_ids: patterns.flatMap((pattern) => pattern.affected_trail_ids).slice(0, 8),\n evidence_refs: trails.flatMap((trail) => trail.evidence_refs).slice(0, 8),\n explanation: \"Estimated time recovered by promoting repeated decisions, blockers, artifacts, and writeback gaps into durable operating memory.\",\n }, {\n id: \"tension:acceleration\",\n label: \"acceleration\",\n value: `+${impact.acceleration_percent}%`,\n tone: impact.acceleration_percent >= 30 ? \"good\" as const : \"muted\" as const,\n trail_ids: patterns.flatMap((pattern) => pattern.affected_trail_ids).slice(0, 8),\n evidence_refs: trails.flatMap((trail) => trail.evidence_refs).slice(0, 8),\n explanation: \"Directional execution lift from connecting source evidence, writeback, owners, and action recommendations.\",\n }] : []),\n {\n id: \"tension:work-leaks\",\n label: \"work leaks\",\n value: String(patterns.filter((pattern) => pattern.valence === \"leak\" || pattern.valence === \"risk\").length),\n tone: patterns.some((pattern) => pattern.severity === \"critical\" || pattern.severity === \"high\") ? \"danger\" : \"warning\",\n trail_ids: patterns.flatMap((pattern) => pattern.affected_trail_ids).slice(0, 8),\n evidence_refs: trails.flatMap((trail) => trail.evidence_refs).slice(0, 8),\n explanation: \"Patterns where evidence exists but ownership, source coverage, or writeback is incomplete.\",\n },\n {\n id: \"tension:decisions-decaying\",\n label: \"decisions decaying\",\n value: String(decisionTrails.filter((trail) => trail.state === \"inferred\" || trail.state === \"missing_evidence\").length),\n tone: decisionTrails.length > 0 && !coverage.orgxMcpCalled ? \"danger\" : \"muted\",\n trail_ids: decisionTrails.map((trail) => trail.id),\n evidence_refs: decisionTrails.flatMap((trail) => trail.evidence_refs).slice(0, 8),\n explanation: \"Decision trails that have not been promoted into durable OrgX records.\",\n },\n {\n id: \"tension:artifacts-orphaned\",\n label: \"artifacts orphaned\",\n value: String(artifactTrails.filter((trail) => trail.state !== \"verified\").length),\n tone: artifactTrails.some((trail) => trail.shape === \"artifact_heavy_decision_light\") ? \"warning\" : \"muted\",\n trail_ids: artifactTrails.map((trail) => trail.id),\n evidence_refs: artifactTrails.flatMap((trail) => trail.evidence_refs).slice(0, 8),\n explanation: \"Artifacts that exist without complete decision, verification, or owner context.\",\n },\n {\n id: \"tension:sources-missing\",\n label: \"sources missing\",\n value: String(coverage.missing.length),\n tone: coverage.missing.length > 0 ? \"warning\" : \"good\",\n trail_ids: missingSourceTrails.map((trail) => trail.id),\n evidence_refs: missingSourceTrails.flatMap((trail) => trail.evidence_refs).slice(0, 6),\n explanation: \"Disconnected coordination or proof sources that limit attribution confidence.\",\n },\n {\n id: \"tension:launch-ready\",\n label: \"launch ready\",\n value: String(topReady.length),\n tone: topReady.length > 0 && blockerTrails.length === 0 ? \"good\" : \"muted\",\n trail_ids: topReady.map((trail) => trail.id).slice(0, 6),\n evidence_refs: topReady.flatMap((trail) => trail.evidence_refs).slice(0, 8),\n explanation: \"High-confidence trails that can become initiatives, decisions, artifacts, or owner-visible follow-ups.\",\n },\n ];\n}\n\nfunction countFindingsByType(\n findings: readonly WorkGraphFinding[],\n): Partial<Record<WorkGraphFindingType, number>> {\n const counts: Partial<Record<WorkGraphFindingType, number>> = {};\n for (const finding of findings) {\n counts[finding.type] = (counts[finding.type] ?? 0) + 1;\n }\n return Object.fromEntries(\n Object.entries(counts).sort(([left], [right]) => left.localeCompare(right)),\n ) as Partial<Record<WorkGraphFindingType, number>>;\n}\n\nfunction isIsoTimestamp(value: unknown): value is string {\n return typeof value === \"string\" && !Number.isNaN(Date.parse(value));\n}\n\nfunction redactionStateForFinding(finding: WorkGraphFinding): WorkGraphRedactionState {\n const privacy = typeof finding.metadata.privacy_state === \"string\"\n ? finding.metadata.privacy_state\n : \"\";\n if (privacy === \"private\") return \"private\";\n if (privacy === \"redacted\") return \"redacted\";\n return \"public_summary\";\n}\n\nfunction attributionKindForFinding(\n type: WorkGraphFindingType,\n): WorkGraphAttributionKind | null {\n switch (type) {\n case \"action\":\n case \"blocker\":\n case \"outcome\":\n return \"action\";\n case \"decision\":\n case \"artifact\":\n case \"person\":\n case \"business\":\n case \"product_surface\":\n case \"goal\":\n return type;\n case \"initiative_candidate\":\n return \"goal\";\n case \"missed_orchestration_opportunity\":\n return \"source\";\n default:\n return null;\n }\n}\n\nfunction attributionEventTypeForFinding(\n finding: WorkGraphFinding,\n): WorkGraphAttributionSourceEvent[\"event_type\"] {\n if (finding.source_client === \"slack\") return \"slack_message\";\n if (finding.source_client === \"github\") return \"github_event\";\n if (finding.source_client === \"linear\") return \"linear_event\";\n if (finding.source_client === \"gmail\") return \"gmail_message\";\n if (finding.source_client === \"calendar\") return \"calendar_event\";\n if (finding.source_client === \"notion\" || finding.source_client === \"docs\") return \"doc_signal\";\n if (finding.source_client === \"mcp\") return \"mcp_call\";\n if (finding.type === \"artifact\") return \"repo_artifact\";\n if (finding.type === \"missed_orchestration_opportunity\") return \"source_coverage\";\n if (/\\b(mcp|tool|hook|runtime)\\b/i.test(`${finding.title} ${finding.summary}`)) return \"tool_signal\";\n return \"client_extraction\";\n}\n\nfunction nodeBucketForKind(\n kind: WorkGraphAttributionKind,\n): keyof Pick<\n WorkGraphAttributionSpine,\n | \"actions\"\n | \"decisions\"\n | \"artifacts\"\n | \"people\"\n | \"agents\"\n | \"tools\"\n | \"businesses\"\n | \"product_surfaces\"\n | \"goals\"\n | \"sources\"\n | \"initiative_candidates\"\n> {\n switch (kind) {\n case \"decision\":\n return \"decisions\";\n case \"artifact\":\n return \"artifacts\";\n case \"person\":\n return \"people\";\n case \"agent\":\n return \"agents\";\n case \"tool\":\n return \"tools\";\n case \"business\":\n return \"businesses\";\n case \"product_surface\":\n return \"product_surfaces\";\n case \"goal\":\n return \"goals\";\n case \"source\":\n return \"sources\";\n case \"action\":\n default:\n return \"actions\";\n }\n}\n\nfunction nodeIdForFinding(kind: WorkGraphAttributionKind, finding: WorkGraphFinding): string {\n const dedupeSource = finding.metadata.dedupe_key ?? finding.evidence_ref ?? finding.title;\n return `${kind}:${slugPart(finding.title)}:${shortHash(dedupeSource, 8)}`;\n}\n\nfunction buildFindingNode(\n finding: WorkGraphFinding,\n kind: WorkGraphAttributionKind,\n): WorkGraphAttributionNode {\n const id = nodeIdForFinding(kind, finding);\n return {\n id,\n kind,\n label: finding.title,\n summary: finding.summary,\n source_client: finding.source_client,\n evidence_refs: [finding.evidence_ref],\n linked_node_ids: [],\n confidence: finding.confidence,\n weight: clampScore(finding.confidence * 100),\n review_state: \"unreviewed\",\n dedupe_key: `${kind}:${slugPart(finding.title)}`,\n metadata: {\n source_id: finding.source_id,\n finding_type: finding.type,\n ...finding.metadata,\n },\n };\n}\n\nfunction mergeNodes(nodes: WorkGraphAttributionNode[]): WorkGraphAttributionNode[] {\n const merged = new Map<string, WorkGraphAttributionNode>();\n for (const node of nodes) {\n const key = node.dedupe_key ?? node.id;\n const previous = merged.get(key);\n if (!previous) {\n merged.set(key, node);\n continue;\n }\n merged.set(key, {\n ...previous,\n confidence: Math.max(previous.confidence, node.confidence),\n evidence_refs: sortedUnique([...previous.evidence_refs, ...node.evidence_refs]),\n linked_node_ids: sortedUnique([...previous.linked_node_ids, ...node.linked_node_ids]),\n weight: Math.max(previous.weight, node.weight),\n });\n }\n return [...merged.values()].sort((left, right) => right.weight - left.weight);\n}\n\nfunction sourceNode(source: string, connected: boolean): WorkGraphAttributionNode {\n const label = source.trim() || \"Unknown source\";\n return {\n id: `source:${slugPart(label)}:${connected ? \"connected\" : \"missing\"}`,\n kind: \"source\",\n label,\n summary: connected\n ? `${label} contributed evidence to this Work Graph.`\n : `${label} was not connected, so related attribution remains incomplete.`,\n evidence_refs: [],\n linked_node_ids: [],\n confidence: connected ? 0.8 : 0.52,\n weight: connected ? 70 : 62,\n review_state: connected ? \"unreviewed\" : \"important\",\n dedupe_key: `source:${slugPart(label)}`,\n metadata: { connected },\n };\n}\n\nfunction buildToolNodes(coverage: WorkGraphSourceCoverage, findings: readonly WorkGraphFinding[]): WorkGraphAttributionNode[] {\n const mentionsOrgxTool =\n coverage.mcpObserved ||\n findings.some((finding) => /\\b(orgx[_-]?mcp|orgx_emit|mcp__orgx|tool call)\\b/i.test(`${finding.title} ${finding.summary}`));\n if (!mentionsOrgxTool) return [];\n return [\n {\n id: \"tool:orgx-mcp\",\n kind: \"tool\",\n label: \"OrgX MCP\",\n summary: coverage.orgxMcpCalled\n ? \"OrgX MCP was observed as a durable writeback surface in the audited work.\"\n : \"OrgX MCP was available or mentioned, but the audit found incomplete durable writeback.\",\n source_client: \"mcp\",\n evidence_refs: findings\n .filter((finding) => /\\b(orgx|mcp|tool)\\b/i.test(`${finding.title} ${finding.summary}`))\n .map((finding) => finding.evidence_ref)\n .slice(0, 12),\n linked_node_ids: [],\n confidence: coverage.orgxMcpCalled ? 0.86 : 0.72,\n weight: coverage.orgxMcpCalled ? 88 : 76,\n review_state: \"unreviewed\",\n dedupe_key: \"tool:orgx-mcp\",\n metadata: {\n mcp_observed: coverage.mcpObserved,\n orgx_observed: coverage.orgxObserved,\n orgx_mcp_called: coverage.orgxMcpCalled,\n skill_only_signal: coverage.skillOnlySignal,\n },\n },\n ];\n}\n\nfunction buildAgentNodes(findings: readonly WorkGraphFinding[]): WorkGraphAttributionNode[] {\n const actorIds = sortedUnique(\n findings\n .map((finding) => typeof finding.metadata.actor_id === \"string\" ? finding.metadata.actor_id.trim() : \"\")\n .filter(Boolean),\n );\n const sourceAgents = sortedUnique(\n findings\n .map((finding) =>\n [\"codex\", \"claude\", \"claude-code\", \"cursor\", \"openclaw\"].includes(finding.source_client)\n ? finding.source_client\n : \"\",\n )\n .filter(Boolean) as WorkGraphSourceClient[],\n );\n return [...actorIds, ...sourceAgents].slice(0, 20).map((agent) => ({\n id: `agent:${slugPart(agent)}`,\n kind: \"agent\",\n label: agent,\n summary: `${agent} contributed evidence to the Work Graph audit.`,\n source_client: sourceAgents.includes(agent as WorkGraphSourceClient)\n ? agent as WorkGraphSourceClient\n : \"manual\",\n evidence_refs: findings\n .filter((finding) => finding.metadata.actor_id === agent || finding.source_client === agent)\n .map((finding) => finding.evidence_ref)\n .slice(0, 12),\n linked_node_ids: [],\n confidence: 0.72,\n weight: 64,\n review_state: \"unreviewed\",\n dedupe_key: `agent:${slugPart(agent)}`,\n metadata: {},\n }));\n}\n\nexport function buildWorkGraphAttributionSpine(input: {\n coverage: WorkGraphSourceCoverage;\n events: readonly WorkGraphSourceEvent[];\n findings: readonly WorkGraphFinding[];\n}): WorkGraphAttributionSpine {\n const evidence_refs: WorkGraphEvidenceRef[] = input.findings.map((finding) => ({\n id: finding.evidence_ref,\n source_client: finding.source_client,\n source_id: finding.source_id,\n label: finding.title,\n summary: finding.summary.slice(0, 1200),\n ...(isIsoTimestamp(finding.metadata.occurred_at) ? { occurred_at: finding.metadata.occurred_at } : {}),\n confidence: finding.confidence,\n redaction_state: redactionStateForFinding(finding),\n metadata: {\n raw_transcript_sent: false,\n source_label: finding.metadata.source_label ?? null,\n },\n }));\n\n const source_events: WorkGraphAttributionSourceEvent[] = [\n ...input.events.map((event) => ({\n source_client: event.source_client,\n source_id: event.source_id,\n source_label: event.source_label,\n event_type: event.event_type === \"client_extraction\"\n ? \"client_extraction\" as const\n : event.event_type,\n evidence_ref: event.evidence_ref,\n confidence: 0.7,\n metadata: {\n ...event.metadata,\n raw_transcript_sent: false,\n },\n })),\n ...input.findings.map((finding) => ({\n source_client: finding.source_client,\n source_id: finding.source_id,\n source_label:\n typeof finding.metadata.source_label === \"string\"\n ? finding.metadata.source_label\n : finding.source_id,\n event_type: attributionEventTypeForFinding(finding),\n ...(isIsoTimestamp(finding.metadata.occurred_at) ? { occurred_at: finding.metadata.occurred_at } : {}),\n evidence_ref: finding.evidence_ref,\n ...(typeof finding.metadata.actor_id === \"string\" ? { actor_ref: finding.metadata.actor_id } : {}),\n confidence: finding.confidence,\n metadata: {\n finding_type: finding.type,\n raw_transcript_sent: false,\n },\n })),\n ];\n\n const buckets = {\n actions: [] as WorkGraphAttributionNode[],\n decisions: [] as WorkGraphAttributionNode[],\n artifacts: [] as WorkGraphAttributionNode[],\n people: [] as WorkGraphAttributionNode[],\n agents: buildAgentNodes(input.findings),\n tools: buildToolNodes(input.coverage, input.findings),\n businesses: [] as WorkGraphAttributionNode[],\n product_surfaces: [] as WorkGraphAttributionNode[],\n goals: [] as WorkGraphAttributionNode[],\n sources: [\n ...input.coverage.connected.map((source) => sourceNode(source, true)),\n ...input.coverage.missing.map((source) => sourceNode(source, false)),\n ],\n initiative_candidates: [] as WorkGraphAttributionNode[],\n };\n\n for (const finding of input.findings) {\n const kind = attributionKindForFinding(finding.type);\n if (!kind) continue;\n const node = buildFindingNode(finding, kind);\n const bucket = finding.type === \"initiative_candidate\"\n ? \"initiative_candidates\"\n : nodeBucketForKind(kind);\n buckets[bucket].push(node);\n }\n\n const normalized = {\n source_events: source_events.filter((event, index, all) =>\n all.findIndex((candidate) =>\n [\n candidate.source_client,\n candidate.source_id,\n candidate.event_type,\n candidate.evidence_ref,\n ].join(\":\") === [\n event.source_client,\n event.source_id,\n event.event_type,\n event.evidence_ref,\n ].join(\":\")\n ) === index\n ).slice(0, 1000),\n actions: mergeNodes(buckets.actions).slice(0, 500),\n decisions: mergeNodes(buckets.decisions).slice(0, 500),\n artifacts: mergeNodes(buckets.artifacts).slice(0, 500),\n people: mergeNodes(buckets.people).slice(0, 500),\n agents: mergeNodes(buckets.agents).slice(0, 200),\n tools: mergeNodes(buckets.tools).slice(0, 300),\n businesses: mergeNodes(buckets.businesses).slice(0, 200),\n product_surfaces: mergeNodes(buckets.product_surfaces).slice(0, 500),\n goals: mergeNodes(buckets.goals).slice(0, 500),\n sources: mergeNodes(buckets.sources).slice(0, 300),\n initiative_candidates: mergeNodes(buckets.initiative_candidates).slice(0, 50),\n evidence_refs: mergeByEvidenceId(evidence_refs).slice(0, 1000),\n };\n\n const nodeCount =\n normalized.actions.length +\n normalized.decisions.length +\n normalized.artifacts.length +\n normalized.people.length +\n normalized.agents.length +\n normalized.tools.length +\n normalized.businesses.length +\n normalized.product_surfaces.length +\n normalized.goals.length +\n normalized.sources.length +\n normalized.initiative_candidates.length;\n const confidenceInputs = [\n ...normalized.evidence_refs.map((evidence) => evidence.confidence),\n ...normalized.source_events.map((event) => event.confidence),\n ];\n const confidence = confidenceInputs.length\n ? Number((confidenceInputs.reduce((total, value) => total + value, 0) / confidenceInputs.length).toFixed(2))\n : 0;\n\n return {\n ...normalized,\n confidence,\n dedupe_keys: sortedUnique([\n ...Object.values(normalized)\n .flat()\n .map((item) => typeof item === \"object\" && item && \"dedupe_key\" in item ? String(item.dedupe_key ?? \"\") : \"\")\n .filter(Boolean),\n ]).slice(0, 1000),\n privacy: {\n redaction_state: \"public_summary\",\n raw_transcripts_included: false,\n public_summary_only: true,\n },\n review: {\n pending_count: nodeCount,\n correction_affordances: [\n \"confirm\",\n \"merge\",\n \"hide\",\n \"mark_important\",\n \"launch_or_dismiss\",\n ],\n },\n };\n}\n\nfunction mergeByEvidenceId(evidenceRefs: WorkGraphEvidenceRef[]): WorkGraphEvidenceRef[] {\n const merged = new Map<string, WorkGraphEvidenceRef>();\n for (const evidence of evidenceRefs) {\n const previous = merged.get(evidence.id);\n if (!previous || evidence.confidence > previous.confidence) {\n merged.set(evidence.id, evidence);\n }\n }\n return [...merged.values()].sort((left, right) => right.confidence - left.confidence);\n}\n\nexport function buildWorkGraphFingerprint(input: {\n connectedSources: readonly string[];\n findings: readonly WorkGraphFinding[];\n kickoffs: readonly WorkGraphKickoffCandidate[];\n missingSources: readonly string[];\n recurringPatterns: readonly WorkGraphRecurringPattern[];\n trails: readonly WorkGraphTrail[];\n workspace: WorkGraphWorkspaceRef;\n}): { fingerprint: string; basis: WorkGraphFingerprintBasis; hydration: WorkGraphSignupHydration } {\n const sourceClients = sortedUnique(input.findings.map((finding) => finding.source_client));\n const patternHashes = input.findings\n .map((finding) =>\n shortHash({\n type: finding.type,\n title: normalizeFingerprintText(finding.title),\n summary: normalizeFingerprintText(finding.summary),\n source_client: finding.source_client,\n }),\n )\n .sort();\n const kickoffHashes = input.kickoffs\n .map((kickoff) =>\n shortHash({\n title: normalizeFingerprintText(kickoff.title),\n summary: normalizeFingerprintText(kickoff.summary),\n priority: kickoff.priority,\n }),\n )\n .sort();\n const trailShapeHashes = input.trails\n .map((trail) =>\n shortHash({\n kind: trail.kind,\n subject_entity_type: trail.subject_entity_type,\n state: trail.state,\n valence: trail.valence,\n shape: trail.shape,\n title: normalizeFingerprintText(trail.title),\n }),\n )\n .sort();\n const recurringPatternHashes = input.recurringPatterns\n .map((pattern) =>\n shortHash({\n pattern_type: pattern.pattern_type,\n severity: pattern.severity,\n title: normalizeFingerprintText(pattern.title),\n recurrence_count: pattern.recurrence_count,\n }),\n )\n .sort();\n\n const basis: WorkGraphFingerprintBasis = {\n schema_version: WORK_GRAPH_SCHEMA_VERSION,\n fingerprint_version: WORK_GRAPH_FINGERPRINT_VERSION,\n workspace_hash: shortHash({\n id: normalizeFingerprintText(input.workspace.id),\n name: normalizeFingerprintText(input.workspace.name),\n }),\n source_clients: sourceClients,\n connected_source_hashes: sortedUnique(\n input.connectedSources.map((source) => shortHash(normalizeFingerprintText(source))),\n ),\n missing_source_hashes: sortedUnique(\n input.missingSources.map((source) => shortHash(normalizeFingerprintText(source))),\n ),\n finding_type_counts: countFindingsByType(input.findings),\n pattern_hashes: patternHashes,\n trail_shape_hashes: trailShapeHashes,\n recurring_pattern_hashes: recurringPatternHashes,\n kickoff_hashes: kickoffHashes,\n raw_transcripts_included: false,\n };\n const fingerprint = `wgf_${hashJson(basis).slice(0, 24)}`;\n\n return {\n fingerprint,\n basis,\n hydration: {\n strategy: \"work_graph_fingerprint_claim\",\n hydration_key: `orgx:work-graph:${fingerprint}`,\n eligible: input.findings.length > 0,\n notes: [\n \"Use this fingerprint to claim the pre-signup Work Graph after account creation.\",\n \"The fingerprint is derived from normalized patterns, source coverage, and kickoff shapes, not raw transcripts.\",\n ],\n },\n };\n}\n\nexport function buildSessionReconciliationReport(\n input: BuildSessionReconciliationReportInput,\n): SessionReconciliationReport {\n const clientExtractions = input.clientExtractions ?? [];\n if (input.imports.length === 0 && clientExtractions.length === 0) {\n throw new Error(\"At least one source import or AI-client extraction is required to build a Work Graph report.\");\n }\n\n const generatedAt = input.generatedAt ?? new Date().toISOString();\n const clientExtractionSummaries = summarizeClientExtractions(clientExtractions);\n const connectedSources = sortedUnique([\n ...(input.connectedSources ?? input.imports.map((source) => source.sourceLabel)),\n ...clientExtractionSummaries.map((summary) => summary.source_label),\n ]);\n const missingSources = input.missingSources ?? [];\n const coverage = buildCoverage(input.imports, connectedSources, missingSources, clientExtractions);\n const events = [...buildWorkGraphEvents(input.imports), ...buildClientExtractionEvents(clientExtractions)];\n const findings = [...buildWorkGraphFindings(input.imports), ...buildClientExtractionFindings(clientExtractions)];\n const autoMissed = buildMissedOpportunities(coverage, findings);\n const extractedMissed = findings.filter((finding) => finding.type === \"missed_orchestration_opportunity\");\n const missed = [...extractedMissed, ...autoMissed].filter((finding, index, all) =>\n all.findIndex((candidate) => candidate.evidence_ref === finding.evidence_ref) === index\n );\n const allFindings = [...findings, ...autoMissed];\n const trails = buildWorkGraphTrails(allFindings, generatedAt);\n const recurringPatterns = buildRecurringPatterns(coverage, allFindings, trails);\n const opportunityScore = scoreOpportunity(coverage, allFindings);\n const initiativeKickoffs = buildKickoffs(allFindings, missed, opportunityScore);\n const recommendations = buildTrailRecommendations(recurringPatterns, trails);\n const impactProjection = estimateImpactProjection({\n coverage,\n findings: allFindings,\n opportunityScore,\n patterns: recurringPatterns,\n trails,\n });\n const executionQuality = scoreExecutionQuality({\n coverage,\n findings: allFindings,\n impact: impactProjection,\n patterns: recurringPatterns,\n recommendations,\n trails,\n });\n const mirror = buildWorkGraphMirror({\n coverage,\n generatedAt,\n impact: impactProjection,\n patterns: recurringPatterns,\n recommendations,\n trails,\n });\n const tensionMetrics = buildTensionMetrics({\n coverage,\n impact: impactProjection,\n patterns: recurringPatterns,\n quality: executionQuality,\n trails,\n });\n const attributionSpine = buildWorkGraphAttributionSpine({\n coverage,\n events,\n findings: allFindings,\n });\n const fingerprint = buildWorkGraphFingerprint({\n connectedSources,\n findings: allFindings,\n kickoffs: initiativeKickoffs,\n missingSources,\n recurringPatterns,\n trails,\n workspace: input.workspace,\n });\n const reportSeed = {\n generatedAt,\n clientExtractions: clientExtractions.map((extraction, index) => ({\n extractionId: normalizeClientExtractionId(extraction, index),\n findingHash: hashJson(extraction.findings),\n })),\n imports: input.imports.map((source) => ({\n sourceId: source.sourceId,\n textHash: hashJson(source.text),\n })),\n workspace: input.workspace,\n };\n const reportHash = hashJson(reportSeed);\n const sessionId = input.sessionId ?? `work-graph-${reportHash.slice(0, 16)}`;\n\n return {\n schema_version: WORK_GRAPH_SCHEMA_VERSION,\n report_id: reportHash.slice(0, 24),\n idempotency_key: `work-graph:${sessionId}:${reportHash.slice(0, 16)}`,\n work_graph_fingerprint: fingerprint.fingerprint,\n fingerprint_version: WORK_GRAPH_FINGERPRINT_VERSION,\n fingerprint_basis: fingerprint.basis,\n signup_hydration: fingerprint.hydration,\n generated_at: generatedAt,\n source_client: \"wizard\",\n session_id: sessionId,\n workspace: input.workspace,\n extraction_protocol: buildWorkGraphExtractionProtocol(),\n client_extractions: clientExtractionSummaries,\n source_coverage: coverage,\n final_state: inferFinalState(allFindings),\n events,\n findings: allFindings,\n missed_orchestration_opportunities: missed,\n trails,\n recurring_patterns: recurringPatterns,\n recommendations,\n mirror,\n tension_metrics: tensionMetrics,\n attribution_spine: attributionSpine,\n opportunity_score: opportunityScore,\n execution_quality: executionQuality,\n impact_projection: impactProjection,\n initiative_kickoffs: initiativeKickoffs,\n redaction_level: \"summary_only\",\n raw_transcripts_sent: false,\n };\n}\n\nexport function renderWorkGraphExtractionProtocolMarkdown(\n protocol: WorkGraphExtractionProtocol = buildWorkGraphExtractionProtocol(),\n): string {\n const lines: string[] = [];\n lines.push(\"# OrgX Work Graph AI-Client Extraction Schema\");\n lines.push(\"\");\n lines.push(`Schema version: ${protocol.schema_version}`);\n lines.push(`Mode: ${protocol.mode}`);\n lines.push(\"\");\n lines.push(\"## Prompt\");\n lines.push(\"\");\n lines.push(protocol.prompt);\n lines.push(\"\");\n lines.push(\"## Objective\");\n lines.push(\"\");\n lines.push(protocol.schema.objective);\n lines.push(\"\");\n lines.push(\"## Search Lenses\");\n lines.push(\"\");\n for (const lens of protocol.schema.source_search_strategy) {\n lines.push(`- ${lens.lens}: ${lens.query} Return when: ${lens.return_when}`);\n }\n lines.push(\"\");\n lines.push(\"## Quality Bar\");\n lines.push(\"\");\n for (const item of protocol.schema.quality_bar) {\n lines.push(`- ${item}`);\n }\n lines.push(\"\");\n lines.push(\"## Reject As Noise\");\n lines.push(\"\");\n for (const item of protocol.schema.reject_as_noise) {\n lines.push(`- ${item}`);\n }\n lines.push(\"\");\n lines.push(\"## Required JSON Shape\");\n lines.push(\"\");\n lines.push(\"```json\");\n lines.push(JSON.stringify(protocol.schema.required_output, null, 2));\n lines.push(\"```\");\n\n return lines.join(\"\\n\");\n}\n\nexport function renderWorkGraphMarkdown(report: SessionReconciliationReport): string {\n const lines: string[] = [];\n lines.push(\"# OrgX Work Graph Reconciliation\");\n lines.push(\"\");\n lines.push(`Generated: ${report.generated_at}`);\n lines.push(`Workspace: ${report.workspace.name} (${report.workspace.id})`);\n lines.push(`Report ID: ${report.report_id}`);\n lines.push(`Work graph fingerprint: ${report.work_graph_fingerprint}`);\n lines.push(`Hydration key: ${report.signup_hydration.hydration_key}`);\n lines.push(`Final state: ${report.final_state}`);\n lines.push(\"\");\n lines.push(\"## AI-Client Search Protocol\");\n lines.push(\"\");\n lines.push(`Schema: ${report.extraction_protocol.schema_version}`);\n lines.push(report.extraction_protocol.prompt);\n lines.push(\"\");\n lines.push(\"Search lenses:\");\n for (const lens of report.extraction_protocol.schema.source_search_strategy) {\n lines.push(`- ${lens.lens}: ${lens.return_when}`);\n }\n lines.push(\"\");\n lines.push(\"## Client Extractions\");\n lines.push(\"\");\n if (report.client_extractions.length === 0) {\n lines.push(\"- No structured AI-client extraction files were provided; fallback local session import was used.\");\n } else {\n for (const extraction of report.client_extractions) {\n lines.push(`- ${extraction.source_label}: ${extraction.finding_count} findings, ${extraction.query_count} queries, ${extraction.searched_source_count} source groups, confidence ${extraction.confidence}`);\n }\n }\n lines.push(\"\");\n lines.push(\"## Opportunity Score\");\n lines.push(\"\");\n lines.push(`Overall: ${report.opportunity_score.overall}/100`);\n lines.push(`Value potential: ${report.opportunity_score.value_potential}/100`);\n lines.push(`Evidence quality: ${report.opportunity_score.evidence_quality}/100`);\n lines.push(`Urgency: ${report.opportunity_score.urgency}/100`);\n lines.push(`Owner clarity: ${report.opportunity_score.owner_clarity}/100`);\n lines.push(`Automation potential: ${report.opportunity_score.automation_potential}/100`);\n lines.push(`OrgX fit: ${report.opportunity_score.orgx_fit}/100`);\n lines.push(\"\");\n lines.push(\"## Execution Quality\");\n lines.push(\"\");\n lines.push(`Overall: ${report.execution_quality.overall}/100`);\n lines.push(`Evidence coverage: ${report.execution_quality.evidence_coverage}/100`);\n lines.push(`Source attribution: ${report.execution_quality.source_attribution}/100`);\n lines.push(`Trail depth: ${report.execution_quality.trail_depth}/100`);\n lines.push(`Insight depth: ${report.execution_quality.insight_depth}/100`);\n lines.push(`Actionability: ${report.execution_quality.actionability}/100`);\n lines.push(`Impact confidence: ${report.execution_quality.impact_confidence}/100`);\n for (const note of report.execution_quality.notes) {\n lines.push(`- ${note}`);\n }\n lines.push(\"\");\n lines.push(\"## Impact Projection\");\n lines.push(\"\");\n lines.push(`Time saved: ${report.impact_projection.time_saved_hours_per_week}h/week`);\n lines.push(`Acceleration: +${report.impact_projection.acceleration_percent}%`);\n lines.push(`Estimated monthly value: $${report.impact_projection.estimated_monthly_value_usd.toLocaleString(\"en-US\")}`);\n lines.push(`Confidence: ${report.impact_projection.confidence}`);\n for (const item of report.impact_projection.basis) {\n lines.push(`- ${item}`);\n }\n lines.push(\"\");\n lines.push(\"## Source Coverage\");\n lines.push(\"\");\n lines.push(`Connected: ${report.source_coverage.connected.join(\", \") || \"none\"}`);\n lines.push(`Missing: ${report.source_coverage.missing.join(\", \") || \"none\"}`);\n lines.push(`Coverage score: ${report.source_coverage.coverage_score ?? 0}/100`);\n lines.push(`MCP observed: ${report.source_coverage.mcpObserved ? \"yes\" : \"no\"}`);\n lines.push(`OrgX observed: ${report.source_coverage.orgxObserved ? \"yes\" : \"no\"}`);\n lines.push(`OrgX MCP called: ${report.source_coverage.orgxMcpCalled ? \"yes\" : \"no\"}`);\n if (report.source_coverage.manifests?.length) {\n lines.push(\"\");\n lines.push(\"Source manifests:\");\n for (const manifest of report.source_coverage.manifests) {\n lines.push(`- [${manifest.status}] ${manifest.source_label}: ${manifest.finding_count} findings, ${manifest.searched_session_count} searched / ${manifest.skipped_session_count} skipped sessions, confidence ${manifest.confidence}`);\n }\n }\n lines.push(\"\");\n lines.push(\"## Mirror\");\n lines.push(\"\");\n lines.push(`### ${report.mirror.headline}`);\n lines.push(\"\");\n lines.push(report.mirror.body);\n lines.push(\"\");\n for (const claim of report.mirror.claims) {\n lines.push(`- ${claim.text} (${claim.evidence_refs.join(\", \") || \"no evidence refs\"})`);\n }\n lines.push(\"\");\n lines.push(\"## Live Tension\");\n lines.push(\"\");\n for (const metric of report.tension_metrics) {\n lines.push(`- ${metric.value} ${metric.label}: ${metric.explanation}`);\n }\n lines.push(\"\");\n lines.push(\"## Work Graph Trails\");\n lines.push(\"\");\n for (const trail of report.trails.slice(0, 12)) {\n lines.push(`- [${trail.kind}] ${trail.title} — ${trail.state}, ${trail.valence}, ${trail.shape} (${trail.evidence_refs.join(\", \")})`);\n }\n lines.push(\"\");\n lines.push(\"## Recurring Patterns\");\n lines.push(\"\");\n if (report.recurring_patterns.length === 0) {\n lines.push(\"- No recurring patterns detected yet.\");\n } else {\n for (const pattern of report.recurring_patterns) {\n lines.push(`- [${pattern.severity}] ${pattern.title}: ${pattern.root_cause_hypothesis}`);\n }\n }\n lines.push(\"\");\n lines.push(\"## Top Findings\");\n lines.push(\"\");\n for (const finding of report.findings.slice(0, 12)) {\n lines.push(`- [${finding.type}] ${finding.title} (${finding.evidence_ref})`);\n }\n lines.push(\"\");\n lines.push(\"## Missed Orchestration\");\n lines.push(\"\");\n if (report.missed_orchestration_opportunities.length === 0) {\n lines.push(\"- No missed orchestration opportunities detected.\");\n } else {\n for (const finding of report.missed_orchestration_opportunities) {\n lines.push(`- ${finding.title}: ${finding.summary}`);\n }\n }\n lines.push(\"\");\n lines.push(\"## Initiative Kickoffs\");\n lines.push(\"\");\n for (const kickoff of report.initiative_kickoffs) {\n lines.push(`- [${kickoff.priority}] ${kickoff.title}: ${kickoff.summary}`);\n }\n lines.push(\"\");\n lines.push(\"## Eject Bay Recommendations\");\n lines.push(\"\");\n for (const recommendation of report.recommendations) {\n lines.push(`- [${recommendation.priority}] ${recommendation.title}: ${recommendation.summary}`);\n }\n lines.push(\"\");\n lines.push(\"## Attribution Spine\");\n lines.push(\"\");\n lines.push(`Source events: ${report.attribution_spine.source_events.length}`);\n lines.push(`Evidence refs: ${report.attribution_spine.evidence_refs.length}`);\n lines.push(`Review nodes: ${report.attribution_spine.review.pending_count}`);\n lines.push(`Confidence: ${report.attribution_spine.confidence}`);\n lines.push(\"\");\n const attributionGroups: Array<[string, WorkGraphAttributionNode[]]> = [\n [\"Actions\", report.attribution_spine.actions],\n [\"Decisions\", report.attribution_spine.decisions],\n [\"Artifacts\", report.attribution_spine.artifacts],\n [\"People\", report.attribution_spine.people],\n [\"Businesses\", report.attribution_spine.businesses],\n [\"Surfaces\", report.attribution_spine.product_surfaces],\n [\"Sources\", report.attribution_spine.sources],\n ];\n for (const [label, nodes] of attributionGroups) {\n if (nodes.length === 0) continue;\n lines.push(`${label}:`);\n for (const node of nodes.slice(0, 5)) {\n lines.push(`- ${node.label} (${node.evidence_refs.join(\", \") || \"source coverage\"})`);\n }\n lines.push(\"\");\n }\n lines.push(\"## Signup Hydration\");\n lines.push(\"\");\n lines.push(`- Strategy: ${report.signup_hydration.strategy}`);\n lines.push(`- Eligible: ${report.signup_hydration.eligible ? \"yes\" : \"no\"}`);\n for (const note of report.signup_hydration.notes) {\n lines.push(`- ${note}`);\n }\n lines.push(\"\");\n lines.push(\"## Privacy\");\n lines.push(\"\");\n lines.push(\"- Raw transcripts were not sent.\");\n lines.push(\"- This report contains summaries, hashes, and evidence refs only.\");\n\n return lines.join(\"\\n\");\n}\n","import { buildOrgxApiUrl, resolveOrgxAuth } from \"./auth.js\";\nimport type { SessionReconciliationReport } from \"./work-graph.js\";\n\nexport interface PublishWorkGraphReportOptions {\n artifactUrl?: string;\n attachArtifact?: boolean;\n entityId?: string;\n entityType?: \"project\" | \"initiative\" | \"milestone\" | \"task\" | \"decision\";\n initiativeId?: string;\n publicShare?: boolean;\n signal?: AbortSignal;\n workspaceId?: string;\n}\n\nexport interface PublishWorkGraphReportResult {\n ok: boolean;\n status: number;\n url: string;\n data: unknown;\n}\n\nexport interface PublishWorkGraphEventsOptions {\n signal?: AbortSignal;\n}\n\nasync function parseResponse(response: Response): Promise<unknown> {\n const text = await response.text();\n if (!text) return null;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\nexport async function publishWorkGraphReport(\n report: SessionReconciliationReport,\n options: PublishWorkGraphReportOptions = {},\n): Promise<PublishWorkGraphReportResult> {\n const auth = await resolveOrgxAuth();\n if (!auth) {\n throw new Error(\"OrgX auth is required to publish a Work Graph. Run `orgx-wizard auth login` or set ORGX_API_KEY.\");\n }\n\n const url = buildOrgxApiUrl(\"/client/work-graph/reports\", auth.baseUrl);\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n report,\n ...(options.workspaceId ? { workspace_id: options.workspaceId } : {}),\n ...(options.initiativeId ? { initiative_id: options.initiativeId } : {}),\n ...(options.entityType ? { entity_type: options.entityType } : {}),\n ...(options.entityId ? { entity_id: options.entityId } : {}),\n ...(options.artifactUrl ? { artifact_url: options.artifactUrl } : {}),\n attach_artifact: Boolean(options.attachArtifact),\n public_share: Boolean(options.publicShare),\n }),\n signal: options.signal ?? AbortSignal.timeout(15_000),\n });\n\n return {\n ok: response.ok,\n status: response.status,\n url,\n data: await parseResponse(response),\n };\n}\n\nexport async function publishWorkGraphEvents(\n fingerprint: string,\n patch: Record<string, unknown>,\n options: PublishWorkGraphEventsOptions = {},\n): Promise<PublishWorkGraphReportResult> {\n const auth = await resolveOrgxAuth();\n if (!auth) {\n throw new Error(\"OrgX auth is required to replay Work Graph hook events. Run `orgx-wizard auth login` or set ORGX_API_KEY.\");\n }\n\n const url = buildOrgxApiUrl(\"/client/work-graph/events\", auth.baseUrl);\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${auth.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n work_graph_fingerprint: fingerprint,\n patch,\n }),\n signal: options.signal ?? AbortSignal.timeout(15_000),\n });\n\n return {\n ok: response.ok,\n status: response.status,\n url,\n data: await parseResponse(response),\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\n\nimport type { WorkGraphSourceClient } from \"./work-graph.js\";\n\nconst SOURCE_CLIENTS: readonly WorkGraphSourceClient[] = [\n \"codex\",\n \"claude\",\n \"claude-code\",\n \"cursor\",\n \"openclaw\",\n \"slack\",\n \"mcp\",\n \"github\",\n \"linear\",\n \"gmail\",\n \"calendar\",\n \"notion\",\n \"docs\",\n \"manual\",\n \"wizard\",\n \"api\",\n \"unknown\",\n];\n\nexport interface RuntimeHookOutboxRecord {\n schema_version?: string;\n source?: string;\n source_client?: string;\n event?: string;\n session_id?: string;\n turn_id?: string;\n cwd?: string;\n transcript_path?: string;\n timestamp?: string;\n summary?: {\n tool_name?: string;\n prompt_chars?: number;\n payload_keys?: string[];\n };\n}\n\nexport interface RuntimeHookOutboxReadResult {\n path: string;\n records: RuntimeHookOutboxRecord[];\n skipped: number;\n}\n\nexport interface WorkGraphHookReplayPatchResult {\n patch: Record<string, unknown>;\n records: number;\n skipped: number;\n sources: WorkGraphSourceClient[];\n evidenceRefs: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction asNumber(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction asStringArray(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined;\n return value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction stableHash(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\").slice(0, 20);\n}\n\nfunction normalizeSourceClient(value: unknown): WorkGraphSourceClient {\n const raw = asString(value)?.toLowerCase();\n if (!raw) return \"unknown\";\n if (SOURCE_CLIENTS.includes(raw as WorkGraphSourceClient)) return raw as WorkGraphSourceClient;\n if (raw === \"claude_code\") return \"claude-code\";\n return \"unknown\";\n}\n\nfunction safeTimestamp(value: unknown): string {\n const raw = asString(value);\n if (raw && !Number.isNaN(Date.parse(raw))) return new Date(raw).toISOString();\n return new Date(0).toISOString();\n}\n\nfunction sourceLabel(sourceClient: WorkGraphSourceClient): string {\n switch (sourceClient) {\n case \"claude-code\":\n return \"Claude Code\";\n case \"codex\":\n return \"Codex\";\n case \"openclaw\":\n return \"OpenClaw\";\n case \"cursor\":\n return \"Cursor\";\n default:\n return sourceClient.replace(/[-_]/g, \" \").replace(/\\b\\w/g, (char) => char.toUpperCase());\n }\n}\n\nfunction readHookRecord(line: string): RuntimeHookOutboxRecord | null {\n try {\n const parsed = JSON.parse(line);\n if (!isRecord(parsed)) return null;\n const record: RuntimeHookOutboxRecord = {};\n const schemaVersion = asString(parsed.schema_version);\n const source = asString(parsed.source);\n const sourceClient = asString(parsed.source_client);\n const event = asString(parsed.event);\n const sessionId = asString(parsed.session_id);\n const turnId = asString(parsed.turn_id);\n const cwd = asString(parsed.cwd);\n const transcriptPath = asString(parsed.transcript_path);\n const timestamp = asString(parsed.timestamp);\n\n if (schemaVersion) record.schema_version = schemaVersion;\n if (source) record.source = source;\n if (sourceClient) record.source_client = sourceClient;\n if (event) record.event = event;\n if (sessionId) record.session_id = sessionId;\n if (turnId) record.turn_id = turnId;\n if (cwd) record.cwd = cwd;\n if (transcriptPath) record.transcript_path = transcriptPath;\n if (timestamp) record.timestamp = timestamp;\n\n if (isRecord(parsed.summary)) {\n const summary: NonNullable<RuntimeHookOutboxRecord[\"summary\"]> = {};\n const toolName = asString(parsed.summary.tool_name);\n const promptChars = asNumber(parsed.summary.prompt_chars);\n const payloadKeys = asStringArray(parsed.summary.payload_keys);\n if (toolName) summary.tool_name = toolName;\n if (promptChars !== undefined) summary.prompt_chars = promptChars;\n if (payloadKeys) summary.payload_keys = payloadKeys;\n record.summary = summary;\n }\n\n return record;\n } catch {\n return null;\n }\n}\n\nexport function readRuntimeHookOutbox(path: string, limit = 200): RuntimeHookOutboxReadResult {\n if (!existsSync(path)) return { path, records: [], skipped: 0 };\n const lines = readFileSync(path, \"utf8\").split(/\\r?\\n/).filter((line) => line.trim().length > 0);\n const selected = lines.slice(Math.max(0, lines.length - Math.max(1, limit)));\n const records: RuntimeHookOutboxRecord[] = [];\n let skipped = Math.max(0, lines.length - selected.length);\n for (const line of selected) {\n const record = readHookRecord(line);\n if (record) {\n records.push(record);\n } else {\n skipped += 1;\n }\n }\n return { path, records, skipped };\n}\n\nexport function buildWorkGraphHookReplayPatch(\n readResult: RuntimeHookOutboxReadResult,\n): WorkGraphHookReplayPatchResult {\n const sourceEvents: Record<string, unknown>[] = [];\n const evidenceRefs: Record<string, unknown>[] = [];\n const sources = new Map<WorkGraphSourceClient, string[]>();\n const agents = new Map<string, Record<string, unknown>>();\n const tools = new Map<string, Record<string, unknown>>();\n const dedupeKeys = new Set<string>();\n\n readResult.records.forEach((record, index) => {\n const sourceClient = normalizeSourceClient(record.source_client);\n const event = record.event ?? \"runtime_hook\";\n const timestamp = safeTimestamp(record.timestamp);\n const sourceId =\n record.session_id ??\n record.transcript_path ??\n record.cwd ??\n `${sourceClient}:hook:${index}`;\n const evidenceId = `hook:${stableHash(`${sourceClient}:${sourceId}:${event}:${timestamp}:${index}`)}`;\n const toolName = record.summary?.tool_name;\n const hasMcpTool = Boolean(toolName && /(mcp|orgx)/i.test(toolName));\n const label = `${sourceLabel(sourceClient)} ${event}`;\n const summary = hasMcpTool\n ? `${sourceLabel(sourceClient)} hook observed tool activity through ${toolName}.`\n : `${sourceLabel(sourceClient)} hook observed ${event} in the local runtime.`;\n\n evidenceRefs.push({\n id: evidenceId,\n source_client: sourceClient,\n source_id: sourceId,\n label,\n summary,\n occurred_at: timestamp,\n confidence: hasMcpTool ? 0.82 : 0.68,\n redaction_state: \"public_summary\",\n metadata: {\n raw_transcript_sent: false,\n hook_source: record.source ?? \"runtime_hook\",\n cwd: record.cwd ?? null,\n transcript_path: record.transcript_path ?? null,\n },\n });\n\n sourceEvents.push({\n source_client: sourceClient,\n source_id: sourceId,\n source_label: sourceLabel(sourceClient),\n event_type: hasMcpTool ? \"mcp_call\" : \"runtime_hook\",\n occurred_at: timestamp,\n evidence_ref: evidenceId,\n confidence: hasMcpTool ? 0.82 : 0.68,\n metadata: {\n hook_event: event,\n raw_transcript_sent: false,\n prompt_chars: record.summary?.prompt_chars ?? null,\n payload_keys: record.summary?.payload_keys ?? [],\n },\n });\n\n const sourceEvidence = sources.get(sourceClient) ?? [];\n sourceEvidence.push(evidenceId);\n sources.set(sourceClient, sourceEvidence.slice(0, 30));\n dedupeKeys.add(`hook:${sourceClient}:${sourceId}:${event}`);\n\n if (sourceClient !== \"unknown\") {\n const agentId = `agent:${sourceClient}`;\n agents.set(agentId, {\n id: agentId,\n kind: \"agent\",\n label: sourceLabel(sourceClient),\n summary: `${sourceLabel(sourceClient)} is emitting passive runtime hook evidence into this Work Graph.`,\n source_client: sourceClient,\n evidence_refs: sourceEvidence.slice(0, 30),\n linked_node_ids: [`source:${sourceClient}`],\n confidence: 0.7,\n weight: 62,\n review_state: \"unreviewed\",\n dedupe_key: agentId,\n metadata: { runtime_hook_replay: true },\n });\n }\n\n if (toolName) {\n const toolId = `tool:${stableHash(toolName.toLowerCase())}`;\n const previous = tools.get(toolId);\n const previousEvidence = Array.isArray(previous?.evidence_refs)\n ? previous.evidence_refs.filter((item): item is string => typeof item === \"string\")\n : [];\n tools.set(toolId, {\n id: toolId,\n kind: \"tool\",\n label: toolName,\n summary: hasMcpTool\n ? `Runtime hook evidence shows ${toolName} participating in OrgX/MCP work.`\n : `Runtime hook evidence shows ${toolName} participating in local work.`,\n source_client: sourceClient,\n evidence_refs: [...previousEvidence, evidenceId].slice(0, 30),\n linked_node_ids: [`source:${sourceClient}`],\n confidence: hasMcpTool ? 0.82 : 0.66,\n weight: hasMcpTool ? 78 : 54,\n review_state: \"unreviewed\",\n dedupe_key: toolId,\n metadata: { runtime_hook_replay: true },\n });\n }\n });\n\n const sourceNodes = [...sources.entries()].map(([sourceClient, refs]) => ({\n id: `source:${sourceClient}`,\n kind: \"source\",\n label: sourceLabel(sourceClient),\n summary: `${sourceLabel(sourceClient)} hook events have been replayed into this Work Graph profile.`,\n source_client: sourceClient,\n evidence_refs: refs.slice(0, 30),\n linked_node_ids: [],\n confidence: 0.7,\n weight: 65,\n review_state: \"unreviewed\",\n dedupe_key: `source:${sourceClient}`,\n metadata: { runtime_hook_replay: true },\n }));\n\n const patch = {\n source_events: sourceEvents,\n evidence_refs: evidenceRefs,\n sources: sourceNodes,\n agents: [...agents.values()],\n tools: [...tools.values()],\n dedupe_keys: [...dedupeKeys].slice(0, 200),\n confidence: evidenceRefs.length > 0 ? 0.7 : 0,\n };\n\n return {\n patch,\n records: readResult.records.length,\n skipped: readResult.skipped,\n sources: [...sources.keys()],\n evidenceRefs: evidenceRefs.length,\n };\n}\n","import { copyFileSync, existsSync, mkdirSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport {\n CLAUDE_DIR,\n CODEX_CONFIG_PATH,\n CODEX_DIR,\n ORGX_WIZARD_CONFIG_HOME,\n} from \"../constants.js\";\nimport { isRecord, parseJsonObject, readTextIfExists, writeJsonFile, writeTextFile } from \"./fs.js\";\n\nconst HOOK_MARKER = \"orgx-session-hook.mjs\";\nconst HOOK_EVENTS = [\"SessionStart\", \"UserPromptSubmit\", \"PreToolUse\", \"PostToolUse\", \"PermissionRequest\", \"Stop\"] as const;\nconst CLAUDE_HOOK_EVENTS = [\"SessionStart\", \"UserPromptSubmit\", \"PreToolUse\", \"PostToolUse\", \"SubagentStop\", \"Stop\", \"SessionEnd\"] as const;\n\nexport type RuntimeHookTarget = \"codex\" | \"claude-code\";\n\nexport interface RuntimeHookPaths {\n claudeSettingsPath: string;\n codexConfigPath: string;\n codexHooksPath: string;\n hookScriptPath: string;\n outboxPath: string;\n}\n\nexport interface RuntimeHookInspection {\n paths: RuntimeHookPaths;\n installed: {\n claudeCode: boolean;\n codex: boolean;\n hookScript: boolean;\n };\n codex: {\n configExists: boolean;\n hooksEnabled: boolean;\n hasNotify: boolean;\n notifyPreserved: boolean;\n };\n outboxEvents: number;\n}\n\nexport interface RuntimeHookInstallResult extends RuntimeHookInspection {\n changed: {\n claudeCode: boolean;\n codex: boolean;\n codexConfig: boolean;\n hookScript: boolean;\n };\n backups: string[];\n}\n\nexport interface RuntimeHookOptions {\n claudeSettingsPath?: string;\n codexConfigPath?: string;\n codexHooksPath?: string;\n hookScriptPath?: string;\n now?: Date;\n outboxPath?: string;\n}\n\nfunction defaultPaths(options: RuntimeHookOptions = {}): RuntimeHookPaths {\n const hookDir = join(ORGX_WIZARD_CONFIG_HOME, \"hooks\");\n return {\n claudeSettingsPath: options.claudeSettingsPath ?? join(CLAUDE_DIR, \"settings.json\"),\n codexConfigPath: options.codexConfigPath ?? CODEX_CONFIG_PATH ?? join(CODEX_DIR, \"config.toml\"),\n codexHooksPath: options.codexHooksPath ?? join(CODEX_DIR, \"hooks.json\"),\n hookScriptPath: options.hookScriptPath ?? join(hookDir, HOOK_MARKER),\n outboxPath: options.outboxPath ?? join(hookDir, \"events.jsonl\"),\n };\n}\n\nfunction countJsonlLines(path: string): number {\n const raw = readTextIfExists(path);\n if (!raw) return 0;\n return raw.split(/\\r?\\n/).filter((line) => line.trim().length > 0).length;\n}\n\nfunction backupPath(path: string, now: Date): string {\n const timestamp = now.toISOString().replace(/[:.]/g, \"-\");\n return `${path}.bak.${timestamp}`;\n}\n\nfunction backupExisting(path: string, now: Date): string | null {\n if (!existsSync(path)) return null;\n const backup = backupPath(path, now);\n copyFileSync(path, backup);\n return backup;\n}\n\nfunction hasOrgxHook(raw: string | null): boolean {\n return Boolean(raw?.includes(HOOK_MARKER));\n}\n\nfunction codexHooksEnabled(raw: string | null): boolean {\n return Boolean(raw && /^\\s*codex_hooks\\s*=\\s*true\\s*$/m.test(raw));\n}\n\nfunction codexHasNotify(raw: string | null): boolean {\n return Boolean(raw && /^\\s*notify\\s*=/m.test(raw));\n}\n\nexport function buildRuntimeHookScriptContent(): string {\n return `#!/usr/bin/env node\nimport { appendFileSync, mkdirSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nfunction parseArgs(argv) {\n const args = {};\n for (const arg of argv) {\n if (!arg.startsWith(\"--\")) continue;\n const [key, ...rest] = arg.slice(2).split(\"=\");\n args[key] = rest.length > 0 ? rest.join(\"=\") : \"true\";\n }\n return args;\n}\n\nfunction pickString(...values) {\n for (const value of values) {\n if (typeof value !== \"string\") continue;\n const trimmed = value.trim();\n if (trimmed) return trimmed;\n }\n return undefined;\n}\n\nasync function readStdin() {\n const chunks = [];\n for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nfunction parseJson(value) {\n try {\n const parsed = JSON.parse(value || \"{}\");\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nfunction summarize(payload) {\n const toolName = pickString(payload.tool_name, payload.toolName, payload.tool?.name, payload.name);\n const prompt = pickString(payload.prompt);\n return {\n tool_name: toolName,\n prompt_chars: prompt ? prompt.length : undefined,\n payload_keys: Object.keys(payload).slice(0, 40),\n };\n}\n\nconst args = parseArgs(process.argv.slice(2));\nconst raw = await readStdin();\nconst payload = parseJson(raw);\nconst outbox = pickString(\n process.env.ORGX_WIZARD_HOOK_OUTBOX,\n args.outbox,\n join(homedir(), \".config\", \"useorgx\", \"wizard\", \"hooks\", \"events.jsonl\")\n);\nconst event = pickString(args.event, payload.hook_event_name, payload.hookEventName, payload.event, payload.eventName, \"unknown\");\nconst sourceClient = pickString(args.source_client, args[\"source-client\"], \"unknown\");\n\nconst record = {\n schema_version: \"2026-05-07\",\n source: \"orgx_wizard_runtime_hook\",\n source_client: sourceClient,\n event,\n session_id: pickString(payload.session_id, payload.sessionId, payload.conversation_id, payload.conversationId),\n turn_id: pickString(payload.turn_id, payload.turnId),\n cwd: pickString(payload.cwd, payload.working_directory, payload.workspace, process.cwd()),\n transcript_path: pickString(payload.transcript_path, payload.transcriptPath),\n timestamp: new Date().toISOString(),\n summary: summarize(payload),\n};\n\ntry {\n mkdirSync(dirname(outbox), { recursive: true, mode: 0o700 });\n appendFileSync(outbox, JSON.stringify(record) + \"\\\\n\", { encoding: \"utf8\", mode: 0o600 });\n} catch {\n // Hooks must never break the user's agent runtime.\n}\n\nprocess.exit(0);\n`;\n}\n\nfunction buildHookCommand(params: {\n event: string;\n hookScriptPath: string;\n outboxPath: string;\n sourceClient: RuntimeHookTarget;\n}): string {\n return [\n \"node\",\n JSON.stringify(params.hookScriptPath),\n `--event=${params.event}`,\n `--source_client=${params.sourceClient}`,\n `--outbox=${params.outboxPath}`,\n ].join(\" \");\n}\n\nfunction mergeCodexHooks(raw: string | null, paths: RuntimeHookPaths): { changed: boolean; value: Record<string, unknown> } {\n const value = parseJsonObject(raw);\n const hooks = isRecord(value.hooks) ? value.hooks : {};\n let changed = false;\n\n for (const event of HOOK_EVENTS) {\n const existing = Array.isArray(hooks[event]) ? hooks[event] as Array<unknown> : [];\n const command = buildHookCommand({\n event,\n hookScriptPath: paths.hookScriptPath,\n outboxPath: paths.outboxPath,\n sourceClient: \"codex\",\n });\n const already = existing.some((entry) =>\n isRecord(entry) && typeof entry.command === \"string\" && entry.command.includes(HOOK_MARKER)\n );\n if (!already) {\n hooks[event] = [...existing, { command }];\n changed = true;\n }\n }\n\n value.hooks = hooks;\n return { changed: changed || !raw, value };\n}\n\nfunction mergeClaudeHooks(raw: string | null, paths: RuntimeHookPaths): { changed: boolean; value: Record<string, unknown> } {\n const value = parseJsonObject(raw);\n const hooksRoot = isRecord(value.hooks) ? value.hooks : {};\n let changed = false;\n\n for (const event of CLAUDE_HOOK_EVENTS) {\n const list = Array.isArray(hooksRoot[event]) ? hooksRoot[event] as Array<Record<string, unknown>> : [];\n const matcher = event === \"PreToolUse\" || event === \"PostToolUse\" ? \"Bash|Write|Edit|MultiEdit|mcp__.*\" : \"\";\n const command = buildHookCommand({\n event,\n hookScriptPath: paths.hookScriptPath,\n outboxPath: paths.outboxPath,\n sourceClient: \"claude-code\",\n });\n let rule = list.find((entry) => isRecord(entry) && entry.matcher === matcher);\n if (!rule) {\n rule = { matcher, hooks: [] };\n list.push(rule);\n changed = true;\n }\n\n const hooks = Array.isArray(rule.hooks) ? rule.hooks as Array<Record<string, unknown>> : [];\n const already = hooks.some((entry) =>\n isRecord(entry) &&\n entry.type === \"command\" &&\n typeof entry.command === \"string\" &&\n entry.command.includes(HOOK_MARKER)\n );\n if (!already) {\n hooks.push({ type: \"command\", command });\n rule.hooks = hooks;\n changed = true;\n }\n hooksRoot[event] = list;\n }\n\n value.hooks = hooksRoot;\n return { changed: changed || !raw, value };\n}\n\nfunction ensureCodexHooksFeature(raw: string | null): { changed: boolean; value: string } {\n const current = raw ?? \"\";\n if (codexHooksEnabled(current)) {\n return { changed: false, value: current };\n }\n\n if (/^\\s*codex_hooks\\s*=\\s*false\\s*$/m.test(current)) {\n return {\n changed: true,\n value: current.replace(/^\\s*codex_hooks\\s*=\\s*false\\s*$/m, \"codex_hooks = true\"),\n };\n }\n\n if (/^\\s*\\[features\\]\\s*$/m.test(current)) {\n return {\n changed: true,\n value: current.replace(/^(\\s*\\[features\\]\\s*)$/m, \"$1\\ncodex_hooks = true\"),\n };\n }\n\n const suffix = current.trimEnd().length > 0 ? \"\\n\\n\" : \"\";\n return {\n changed: true,\n value: `${current.trimEnd()}${suffix}[features]\\ncodex_hooks = true\\n`,\n };\n}\n\nexport function inspectRuntimeHooks(options: RuntimeHookOptions = {}): RuntimeHookInspection {\n const paths = defaultPaths(options);\n const codexConfigRaw = readTextIfExists(paths.codexConfigPath);\n const codexHooksRaw = readTextIfExists(paths.codexHooksPath);\n const claudeSettingsRaw = readTextIfExists(paths.claudeSettingsPath);\n return {\n paths,\n installed: {\n claudeCode: hasOrgxHook(claudeSettingsRaw),\n codex: hasOrgxHook(codexHooksRaw),\n hookScript: existsSync(paths.hookScriptPath),\n },\n codex: {\n configExists: Boolean(codexConfigRaw),\n hooksEnabled: codexHooksEnabled(codexConfigRaw),\n hasNotify: codexHasNotify(codexConfigRaw),\n notifyPreserved: !codexHasNotify(codexConfigRaw) || !hasOrgxHook(codexConfigRaw),\n },\n outboxEvents: countJsonlLines(paths.outboxPath),\n };\n}\n\nexport function installRuntimeHooks(\n targets: readonly RuntimeHookTarget[],\n options: RuntimeHookOptions = {},\n): RuntimeHookInstallResult {\n const now = options.now ?? new Date();\n const paths = defaultPaths(options);\n const backups: string[] = [];\n const changed = {\n claudeCode: false,\n codex: false,\n codexConfig: false,\n hookScript: false,\n };\n\n mkdirSync(dirname(paths.hookScriptPath), { recursive: true, mode: 0o700 });\n const scriptContent = buildRuntimeHookScriptContent();\n if (readTextIfExists(paths.hookScriptPath) !== scriptContent) {\n const backup = backupExisting(paths.hookScriptPath, now);\n if (backup) backups.push(backup);\n writeTextFile(paths.hookScriptPath, scriptContent, { mode: 0o700 });\n changed.hookScript = true;\n }\n\n if (targets.includes(\"codex\")) {\n const rawConfig = readTextIfExists(paths.codexConfigPath);\n const nextConfig = ensureCodexHooksFeature(rawConfig);\n if (nextConfig.changed) {\n const backup = backupExisting(paths.codexConfigPath, now);\n if (backup) backups.push(backup);\n writeTextFile(paths.codexConfigPath, nextConfig.value, { mode: 0o600 });\n changed.codexConfig = true;\n }\n\n const rawHooks = readTextIfExists(paths.codexHooksPath);\n const nextHooks = mergeCodexHooks(rawHooks, paths);\n if (nextHooks.changed) {\n const backup = backupExisting(paths.codexHooksPath, now);\n if (backup) backups.push(backup);\n writeJsonFile(paths.codexHooksPath, nextHooks.value, { mode: 0o600 });\n changed.codex = true;\n }\n }\n\n if (targets.includes(\"claude-code\")) {\n const rawSettings = readTextIfExists(paths.claudeSettingsPath);\n const nextSettings = mergeClaudeHooks(rawSettings, paths);\n if (nextSettings.changed) {\n const backup = backupExisting(paths.claudeSettingsPath, now);\n if (backup) backups.push(backup);\n writeJsonFile(paths.claudeSettingsPath, nextSettings.value, { mode: 0o600 });\n changed.claudeCode = true;\n }\n }\n\n return {\n ...inspectRuntimeHooks(options),\n changed,\n backups,\n };\n}\n\nexport function parseRuntimeHookTargets(value?: string): RuntimeHookTarget[] {\n if (!value?.trim()) return [\"codex\", \"claude-code\"];\n const requested = value.split(\",\").map((item) => item.trim().toLowerCase()).filter(Boolean);\n const expanded = requested.includes(\"all\") ? [\"codex\", \"claude-code\"] : requested;\n const normalized = expanded.map((target) => {\n if (target === \"claude\" || target === \"claude_code\") return \"claude-code\";\n return target;\n });\n const invalid = normalized.filter((target) => target !== \"codex\" && target !== \"claude-code\");\n if (invalid.length > 0) {\n throw new Error(`Unsupported hook target: ${invalid.join(\", \")}. Use codex, claude-code, or all.`);\n }\n return [...new Set(normalized)] as RuntimeHookTarget[];\n}\n\nexport function runtimeHookPathsForHome(home = homedir()): RuntimeHookPaths {\n const configHome = process.env.XDG_CONFIG_HOME?.trim() || join(home, \".config\");\n const hookDir = join(configHome, \"useorgx\", \"wizard\", \"hooks\");\n return {\n claudeSettingsPath: join(home, \".claude\", \"settings.json\"),\n codexConfigPath: join(home, \".codex\", \"config.toml\"),\n codexHooksPath: join(home, \".codex\", \"hooks.json\"),\n hookScriptPath: join(hookDir, HOOK_MARKER),\n outboxPath: join(hookDir, \"events.jsonl\"),\n };\n}\n","import ora, { type Ora } from \"ora\";\nimport pc from \"picocolors\";\n\nconst frames = [\"[ ]\", \"[= ]\", \"[== ]\", \"[=== ]\", \"[ ===]\", \"[ ==]\", \"[ =]\"];\n\nexport function createOrgxSpinner(text: string): Ora {\n return ora({\n text: pc.cyan(text),\n spinner: {\n interval: 90,\n frames,\n },\n });\n}\n\n"],"mappings":";;;AAAA,YAAY,WAAW;AACvB,SAAS,aAAAA,kBAAiB;AAC1B,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,OAAOC,SAAQ;;;ACNf,OAAO,QAAQ;AAER,SAAS,aAAa,SAA0B;AACrD,QAAM,QAAQ;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,QAAM,MAAM,MAAM,IAAI,CAAC,SAAS,GAAG,KAAK,IAAI,CAAC,EAAE,KAAK,IAAI;AACxD,QAAM,MAAM,UAAU,KAAK,GAAG,IAAI,IAAI,OAAO,EAAE,CAAC,KAAK;AACrD,SAAO,GAAG,GAAG,GAAG,GAAG;AACrB;;;ACdA,SAAS,eAAe;AACxB,SAAS,YAAY;AAEd,IAAM,sBAAsB;AAC5B,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB;AAC5B,IAAM,6BAA6B;AACnC,IAAM,6BAA6B;AACnC,IAAM,kCAAkC,GAAG,0BAA0B;AACrE,IAAM,8BAA8B,GAAG,0BAA0B;AACjE,IAAM,iCAAiC,GAAG,0BAA0B;AACpE,IAAM,+BAA+B;AACrC,IAAM,wBAAwB;AAC9B,IAAM,gCAAgC;AACtC,IAAM,wBACX,QAAQ,IAAI,eAAe,KAAK,KAAK;AAEhC,IAAM,kCAAkC;AACxC,IAAM,mCAAmC;AACzC,IAAM,2BAA2B;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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D;AAChF,UAAM,SAAS,yBAAyB;AAAA,MACtC,SAAS;AAAA,MACT,SAAS;AAAA,MACT,GAAI,QAAQ,UAAU,SAAY,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;AAAA,IAChE,CAAC;AACD,6BAAyB,MAAM;AAC/B,YAAQ;AAAA,MACN,KAAK,KAAK,IAAI,KAAKA,IAAG,IAAI,OAAO,OAAO,CAAC,+CAA+C,CAAC;AAAA,IAC3F;AAAA,EACF,CAAC;AAEH,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAMA,IAAG,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,CAAC;AAC5E,UAAQ,WAAW;AACrB,CAAC;","names":["spawnSync","readFileSync","pc","hostname","text","text","resolve","hostname","resolve","text","isNonEmptyString","spawnSync","spawnSync","text","text","parseResponseBody","text","existsSync","mkdirSync","readFileSync","readdirSync","statSync","writeFileSync","dirname","join","existsSync","dirname","dirname","existsSync","createHash","existsSync","join","createHash","join","existsSync","extension","encodeRepoPath","basename","buildContentsUrl","resolveGitHubError","fetchDirectoryEntries","join","existsSync","statSync","readFileSync","mkdirSync","dirname","writeFileSync","readdirSync","resolve","inspection","parseResponseBody","text","formatHttpError","requireOrgxAuth","parse","text","parseResponseBody","formatHttpError","requireOrgxAuth","text","text","existsSync","readdirSync","readFileSync","statSync","basename","join","relative","text","existsSync","readdirSync","join","statSync","readFileSync","relative","basename","createHash","createHash","parseResponseBody","text","formatHttpError","createHash","clampScore","createHash","text","includesAny","sourceLabel","text","createHash","existsSync","readFileSync","isRecord","asString","normalizeSourceClient","existsSync","mkdirSync","homedir","dirname","join","join","existsSync","mkdirSync","dirname","pc","text","pc","readFileSync","text","pc","spawnSync","pc","resolve","text","handoff","spinner","doctor","assessment","verification"]}