@thecorporation/cli 26.3.39 → 26.3.41

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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/animation.ts","../src/spinner.ts","../src/config.ts","../src/references.ts","../src/output.ts","../src/api-client.ts","../src/registry/workspace.ts","../src/registry/entities.ts","../src/formation-automation.ts","../src/commands/form.ts","../src/registry/formation.ts","../src/registry/cap-table.ts","../src/registry/finance.ts","../src/registry/governance.ts","../src/registry/documents.ts","../src/registry/compliance.ts","../src/registry/agents.ts","../src/registry/work-items.ts","../src/registry/services.ts","../src/commands/setup.ts","../src/commands/config.ts","../src/commands/serve.ts","../src/commands/demo.ts","../src/llm.ts","../src/tools.ts","../src/chat.ts","../src/commands/api-keys.ts","../src/commands/link.ts","../src/commands/claim.ts","../src/commands/feedback.ts","../src/commands/resolve.ts","../src/commands/find.ts","../src/registry/admin.ts","../src/registry/execution.ts","../src/registry/secret-proxies.ts","../src/registry/treasury.ts","../src/registry/branches.ts","../src/registry/index.ts","../src/index.ts","../src/cli.ts","../src/generic-executor.ts","../src/writer.ts"],"sourcesContent":["/**\n * Rising cityscape boot animation — ported from packages/cli/corp/tui/widgets/mascot.py\n */\n\n// prettier-ignore\nconst BUILDINGS: string[][] = [\n [\n \" ┌┐ \",\n \" ││ \",\n \" ││ \",\n \" ┌┤├┐ \",\n \" │││││\",\n \" │││││\",\n ],\n [\n \" ╔══╗ \",\n \" ║▪▪║ \",\n \" ║▪▪║ \",\n \" ║▪▪║ \",\n \" ║▪▪║ \",\n \" ║▪▪║ \",\n \" ║▪▪║ \",\n \" ║▪▪║ \",\n ],\n [\n \" /\\\\ \",\n \" / \\\\ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n ],\n [\n \" ┌──┐ \",\n \" │≋≋│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n ],\n [\n \" ╻ \",\n \" ┃ \",\n \" ┌┤┐ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n ],\n [\n \" ┌┐ \",\n \" ├┤ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n ],\n [\n \" ╔═══╗\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n ],\n [\n \" ┬─┬ \",\n \" │~│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n ],\n];\n\nconst MAX_HEIGHT = Math.max(...BUILDINGS.map((b) => b.length));\nconst TOTAL_FRAMES = MAX_HEIGHT + 4; // 15 frames, ~1.5s at 100ms\n\nconst GOLD = \"\\x1b[38;2;212;160;23m\";\nconst RESET = \"\\x1b[0m\";\n\nexport function renderFrame(frame: number): string {\n const cols: string[][] = [];\n for (let i = 0; i < BUILDINGS.length; i++) {\n const building = BUILDINGS[i];\n const h = building.length;\n const visible = Math.max(0, Math.min(h, frame - i));\n const width = building[0]?.length ?? 6;\n const blank = \" \".repeat(width);\n const col: string[] = Array(MAX_HEIGHT - visible).fill(blank);\n col.push(...building.slice(h - visible));\n cols.push(col);\n }\n\n const lines: string[] = [];\n for (let row = 0; row < MAX_HEIGHT; row++) {\n lines.push(cols.map((col) => col[row]).join(\"\"));\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Run an async function while displaying the rising cityscape animation.\n * No-ops when stdout is not a TTY (piped, CI, etc.).\n */\nexport async function withAnimation<T>(fn: () => Promise<T>): Promise<T> {\n if (!process.stdout.isTTY) {\n return fn();\n }\n\n let frame = 0;\n let animDone = false;\n const spinChars = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\n let spinIdx = 0;\n let lastLineCount = 0;\n\n const clearPrev = () => {\n if (lastLineCount > 0) {\n process.stdout.write(`\\x1b[${lastLineCount}A\\x1b[0J`);\n }\n };\n\n const drawFrame = () => {\n clearPrev();\n if (!animDone) {\n const art = renderFrame(frame);\n const output = `${GOLD}${art}${RESET}\\n`;\n process.stdout.write(output);\n lastLineCount = MAX_HEIGHT + 1;\n frame++;\n if (frame >= TOTAL_FRAMES) {\n animDone = true;\n }\n } else {\n // Dot spinner fallback after animation finishes\n const line = `${GOLD}${spinChars[spinIdx % spinChars.length]} Loading...${RESET}\\n`;\n process.stdout.write(line);\n lastLineCount = 1;\n spinIdx++;\n }\n };\n\n drawFrame();\n const timer = setInterval(drawFrame, 100);\n\n try {\n const result = await fn();\n return result;\n } finally {\n clearInterval(timer);\n clearPrev();\n }\n}\n","import { withAnimation } from \"./animation.js\";\n\n/**\n * Run an async function with a loading animation.\n * Silently skipped when `json` is truthy (pure JSON output) or non-TTY.\n */\nexport async function withSpinner<T>(\n _label: string,\n fn: () => Promise<T>,\n json?: boolean,\n): Promise<T> {\n if (json) {\n return fn();\n }\n return withAnimation(fn);\n}\n","import {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { CorpConfig } from \"./types.js\";\n\nconst CONFIG_DIR = process.env.CORP_CONFIG_DIR || join(homedir(), \".corp\");\nconst CONFIG_FILE = join(CONFIG_DIR, \"config.json\");\nconst AUTH_FILE = join(CONFIG_DIR, \"auth.json\");\nconst CONFIG_LOCK_DIR = join(CONFIG_DIR, \"config.lock\");\nconst CONFIG_LOCK_TIMEOUT_MS = 5000;\nconst CONFIG_LOCK_RETRY_MS = 25;\nconst CONFIG_STALE_LOCK_MS = 60_000;\nconst MAX_LAST_REFERENCES = 4096;\nconst TRUSTED_API_HOST_SUFFIXES = [\"thecorporation.ai\"];\n\nconst CONFIG_WAIT_BUFFER = new SharedArrayBuffer(4);\nconst CONFIG_WAIT_SIGNAL = new Int32Array(CONFIG_WAIT_BUFFER);\n\nconst ALLOWED_CONFIG_KEYS = new Set([\n \"api_url\",\n \"api_key\",\n \"workspace_id\",\n \"hosting_mode\",\n \"llm.provider\",\n \"llm.api_key\",\n \"llm.model\",\n \"llm.base_url\",\n \"user.name\",\n \"user.email\",\n \"active_entity_id\",\n \"data_dir\",\n]);\n\nconst SENSITIVE_CONFIG_KEYS = new Set([\"api_url\", \"api_key\", \"workspace_id\"]);\n\ntype CorpAuthConfig = {\n api_url?: string;\n api_key?: string;\n workspace_id?: string;\n llm?: {\n api_key?: string;\n };\n server_secrets?: {\n jwt_secret: string;\n secrets_master_key: string;\n internal_worker_token: string;\n };\n};\n\nconst DEFAULTS: CorpConfig = {\n api_url: process.env.CORP_API_URL || \"https://api.thecorporation.ai\",\n api_key: process.env.CORP_API_KEY || \"\",\n workspace_id: process.env.CORP_WORKSPACE_ID || \"\",\n hosting_mode: \"\",\n llm: {\n provider: \"anthropic\",\n api_key: process.env.CORP_LLM_API_KEY || \"\",\n model: \"claude-sonnet-4-6\",\n base_url: process.env.CORP_LLM_BASE_URL || undefined,\n },\n user: { name: \"\", email: \"\" },\n active_entity_id: \"\",\n data_dir: \"\",\n};\n\nfunction sleepSync(ms: number): void {\n Atomics.wait(CONFIG_WAIT_SIGNAL, 0, 0, ms);\n}\n\nfunction withConfigLock<T>(fn: () => T): T {\n mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });\n const startedAt = Date.now();\n while (true) {\n try {\n mkdirSync(CONFIG_LOCK_DIR, { mode: 0o700 });\n break;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw err;\n }\n try {\n const ageMs = Date.now() - statSync(CONFIG_LOCK_DIR).mtimeMs;\n if (ageMs >= CONFIG_STALE_LOCK_MS) {\n rmSync(CONFIG_LOCK_DIR, { recursive: true, force: true });\n continue;\n }\n } catch {\n // Ignore lock-stat failures and continue waiting.\n }\n if (Date.now() - startedAt >= CONFIG_LOCK_TIMEOUT_MS) {\n throw new Error(\"timed out waiting for the corp config lock\");\n }\n sleepSync(CONFIG_LOCK_RETRY_MS);\n }\n }\n\n try {\n return fn();\n } finally {\n rmSync(CONFIG_LOCK_DIR, { recursive: true, force: true });\n }\n}\n\nfunction ensureSecurePermissions(): void {\n mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });\n try {\n chmodSync(CONFIG_DIR, 0o700);\n } catch {\n // Ignore chmod failures on filesystems without POSIX permission support.\n }\n if (existsSync(CONFIG_FILE)) {\n try {\n chmodSync(CONFIG_FILE, 0o600);\n } catch {\n // Ignore chmod failures on filesystems without POSIX permission support.\n }\n }\n if (existsSync(AUTH_FILE)) {\n try {\n chmodSync(AUTH_FILE, 0o600);\n } catch {\n // Ignore chmod failures on filesystems without POSIX permission support.\n }\n }\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isLoopbackHost(hostname: string): boolean {\n return hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"::1\";\n}\n\nfunction isTrustedCorpHost(hostname: string): boolean {\n return TRUSTED_API_HOST_SUFFIXES.some(\n (suffix) => hostname === suffix || hostname.endsWith(`.${suffix}`),\n );\n}\n\nfunction allowUnsafeApiUrl(): boolean {\n return process.env.CORP_UNSAFE_API_URL === \"1\";\n}\n\nexport function validateApiUrl(value: string): string {\n const trimmed = value.trim();\n\n // Process transport: process:// or process:///path/to/binary\n if (trimmed.startsWith(\"process://\")) {\n return trimmed;\n }\n\n let parsed: URL;\n try {\n parsed = new URL(trimmed);\n } catch {\n throw new Error(\"api_url must be a valid absolute URL\");\n }\n\n if (parsed.username || parsed.password) {\n throw new Error(\"api_url must not include embedded credentials\");\n }\n\n const protocol = parsed.protocol.toLowerCase();\n const hostname = parsed.hostname.toLowerCase();\n if (protocol !== \"https:\" && !(protocol === \"http:\" && isLoopbackHost(hostname))) {\n throw new Error(\"api_url must use https, or http only for localhost/loopback development\");\n }\n if (protocol === \"https:\" && !isLoopbackHost(hostname) && !isTrustedCorpHost(hostname) && !allowUnsafeApiUrl()) {\n throw new Error(\n \"api_url must point to a trusted TheCorporation host or localhost; set CORP_UNSAFE_API_URL=1 to allow a custom self-hosted URL\",\n );\n }\n\n parsed.hash = \"\";\n return parsed.toString().replace(/\\/+$/, \"\");\n}\n\nexport function validateLlmBaseUrl(value: string): string {\n let parsed: URL;\n try {\n parsed = new URL(value.trim());\n } catch {\n throw new Error(\"llm.base_url must be a valid absolute URL\");\n }\n\n if (parsed.username || parsed.password) {\n throw new Error(\"llm.base_url must not include embedded credentials\");\n }\n\n const protocol = parsed.protocol.toLowerCase();\n const hostname = parsed.hostname.toLowerCase();\n if (protocol !== \"https:\" && !(protocol === \"http:\" && isLoopbackHost(hostname))) {\n throw new Error(\"llm.base_url must use https, or http only for localhost/loopback development\");\n }\n\n parsed.hash = \"\";\n return parsed.toString().replace(/\\/+$/, \"\");\n}\n\nfunction normalizeString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction normalizeActiveEntityMap(value: unknown): Record<string, string> | undefined {\n if (!isObject(value)) {\n return undefined;\n }\n const entries = Object.entries(value).filter(\n (entry): entry is [string, string] =>\n typeof entry[0] === \"string\" && typeof entry[1] === \"string\" && entry[1].length > 0,\n );\n if (entries.length === 0) {\n return undefined;\n }\n return Object.fromEntries(entries) as Record<string, string>;\n}\n\nfunction trimReferenceEntries(\n entries: Array<[string, string]>,\n): Array<[string, string]> {\n if (entries.length <= MAX_LAST_REFERENCES) {\n return entries;\n }\n return entries.slice(entries.length - MAX_LAST_REFERENCES);\n}\n\nfunction normalizeReferenceMap(value: unknown): Record<string, string> | undefined {\n if (!isObject(value)) {\n return undefined;\n }\n const entries = Object.entries(value).filter(\n (entry): entry is [string, string] => typeof entry[0] === \"string\" && typeof entry[1] === \"string\" && (entry[1] as string).trim().length > 0,\n );\n if (entries.length === 0) {\n return undefined;\n }\n return Object.fromEntries(\n trimReferenceEntries(entries.map(([key, val]) => [key, val.trim()])),\n );\n}\n\nfunction mergeConfigAndAuth(\n configRaw: unknown,\n authRaw: unknown,\n): Record<string, unknown> {\n const merged: Record<string, unknown> = isObject(configRaw) ? { ...configRaw } : {};\n if (!isObject(authRaw)) {\n return merged;\n }\n for (const key of [\"api_url\", \"api_key\", \"workspace_id\"]) {\n const value = authRaw[key];\n if (typeof value === \"string\") {\n merged[key] = value;\n }\n }\n if (isObject(authRaw.llm)) {\n const llm = isObject(merged.llm) ? { ...merged.llm } : {};\n if (typeof authRaw.llm.api_key === \"string\") {\n llm.api_key = authRaw.llm.api_key;\n }\n merged.llm = llm;\n }\n return merged;\n}\n\nfunction readJsonFile(path: string): unknown {\n if (!existsSync(path)) {\n return {};\n }\n return JSON.parse(readFileSync(path, \"utf-8\")) as unknown;\n}\n\nfunction hasLegacySensitiveConfig(raw: unknown): boolean {\n if (!isObject(raw)) {\n return false;\n }\n if (typeof raw.api_url === \"string\" || typeof raw.api_key === \"string\" || typeof raw.workspace_id === \"string\") {\n return true;\n }\n return isObject(raw.llm) && typeof raw.llm.api_key === \"string\";\n}\n\nfunction normalizeConfig(raw: unknown): CorpConfig {\n const cfg = structuredClone(DEFAULTS) as CorpConfig;\n if (!isObject(raw)) {\n return cfg;\n }\n\n const savedApiUrl = normalizeString(raw.api_url);\n if (savedApiUrl) {\n try {\n cfg.api_url = validateApiUrl(savedApiUrl);\n } catch {\n cfg.api_url = DEFAULTS.api_url;\n }\n }\n cfg.api_key = normalizeString(raw.api_key) ?? cfg.api_key;\n cfg.workspace_id = normalizeString(raw.workspace_id) ?? cfg.workspace_id;\n cfg.hosting_mode = normalizeString(raw.hosting_mode) ?? cfg.hosting_mode;\n cfg.active_entity_id = normalizeString(raw.active_entity_id) ?? cfg.active_entity_id;\n cfg.data_dir = normalizeString(raw.data_dir) ?? cfg.data_dir;\n\n if (isObject(raw.llm)) {\n cfg.llm.provider = normalizeString(raw.llm.provider) ?? cfg.llm.provider;\n cfg.llm.api_key = normalizeString(raw.llm.api_key) ?? cfg.llm.api_key;\n cfg.llm.model = normalizeString(raw.llm.model) ?? cfg.llm.model;\n const baseUrl = normalizeString(raw.llm.base_url);\n if (baseUrl && baseUrl.trim()) {\n try {\n cfg.llm.base_url = validateLlmBaseUrl(baseUrl);\n } catch {\n cfg.llm.base_url = undefined;\n }\n }\n }\n\n if (isObject(raw.user)) {\n cfg.user.name = normalizeString(raw.user.name) ?? cfg.user.name;\n cfg.user.email = normalizeString(raw.user.email) ?? cfg.user.email;\n }\n\n const activeEntityIds = normalizeActiveEntityMap(raw.active_entity_ids);\n if (activeEntityIds) {\n cfg.active_entity_ids = activeEntityIds;\n }\n const lastReferences = normalizeReferenceMap(raw.last_references);\n if (lastReferences) {\n cfg.last_references = lastReferences;\n }\n if (cfg.workspace_id && cfg.active_entity_id) {\n cfg.active_entity_ids = {\n ...(cfg.active_entity_ids ?? {}),\n [cfg.workspace_id]: cfg.active_entity_id,\n };\n }\n\n return cfg;\n}\n\nfunction serializeConfig(cfg: CorpConfig): string {\n const normalized = normalizeConfig(cfg);\n const serialized: Record<string, unknown> = {\n hosting_mode: normalized.hosting_mode,\n llm: {\n provider: normalized.llm.provider,\n model: normalized.llm.model,\n ...(normalized.llm.base_url ? { base_url: normalized.llm.base_url } : {}),\n },\n user: {\n name: normalized.user.name,\n email: normalized.user.email,\n },\n active_entity_id: normalized.active_entity_id,\n ...(normalized.data_dir ? { data_dir: normalized.data_dir } : {}),\n };\n if (normalized.active_entity_ids && Object.keys(normalized.active_entity_ids).length > 0) {\n serialized.active_entity_ids = normalized.active_entity_ids;\n }\n if (normalized.last_references && Object.keys(normalized.last_references).length > 0) {\n serialized.last_references = normalized.last_references;\n }\n return JSON.stringify(serialized, null, 2) + \"\\n\";\n}\n\nfunction serializeAuth(cfg: CorpConfig): string {\n const normalized = normalizeConfig(cfg);\n const serialized: CorpAuthConfig = {\n api_url: normalized.api_url,\n api_key: normalized.api_key,\n workspace_id: normalized.workspace_id,\n };\n if (normalized.llm.api_key) {\n serialized.llm = { api_key: normalized.llm.api_key };\n }\n // Preserve server_secrets from existing auth file\n const existingAuth = readJsonFile(AUTH_FILE);\n if (isObject(existingAuth) && isObject(existingAuth.server_secrets)) {\n const ss = existingAuth.server_secrets;\n if (typeof ss.jwt_secret === \"string\" && typeof ss.secrets_master_key === \"string\" && typeof ss.internal_worker_token === \"string\") {\n serialized.server_secrets = {\n jwt_secret: ss.jwt_secret,\n secrets_master_key: ss.secrets_master_key,\n internal_worker_token: ss.internal_worker_token,\n };\n }\n }\n // Allow overriding via cfg._server_secrets (used by setup to write new secrets)\n if ((cfg as Record<string, unknown>)._server_secrets) {\n serialized.server_secrets = (cfg as Record<string, unknown>)._server_secrets as CorpAuthConfig[\"server_secrets\"];\n }\n return JSON.stringify(serialized, null, 2) + \"\\n\";\n}\n\nfunction requireSupportedConfigKey(dotPath: string): void {\n if (!ALLOWED_CONFIG_KEYS.has(dotPath)) {\n throw new Error(`unsupported config key: ${dotPath}`);\n }\n}\n\nfunction validateSensitiveConfigUpdate(dotPath: string, forceSensitive = false): void {\n if (SENSITIVE_CONFIG_KEYS.has(dotPath) && !forceSensitive) {\n throw new Error(\n `refusing to update security-sensitive key '${dotPath}' without --force; ` +\n \"this key controls authentication or API routing, so explicit confirmation is required\",\n );\n }\n}\n\nfunction setKnownConfigValue(cfg: CorpConfig, dotPath: string, value: string): void {\n switch (dotPath) {\n case \"api_url\":\n cfg.api_url = validateApiUrl(value);\n return;\n case \"api_key\":\n cfg.api_key = value.trim();\n return;\n case \"workspace_id\":\n cfg.workspace_id = value.trim();\n return;\n case \"hosting_mode\":\n cfg.hosting_mode = value.trim();\n return;\n case \"data_dir\":\n cfg.data_dir = value.trim();\n return;\n case \"llm.provider\":\n cfg.llm.provider = value.trim();\n return;\n case \"llm.api_key\":\n cfg.llm.api_key = value.trim();\n return;\n case \"llm.model\":\n cfg.llm.model = value.trim();\n return;\n case \"llm.base_url\":\n cfg.llm.base_url = value.trim() ? validateLlmBaseUrl(value) : undefined;\n return;\n case \"user.name\":\n cfg.user.name = value.trim();\n return;\n case \"user.email\":\n cfg.user.email = value.trim();\n return;\n case \"active_entity_id\":\n setActiveEntityId(cfg, value.trim());\n return;\n default:\n throw new Error(`unsupported config key: ${dotPath}`);\n }\n}\n\nfunction readConfigUnlocked(): CorpConfig {\n ensureSecurePermissions();\n const configRaw = readJsonFile(CONFIG_FILE);\n const authRaw = readJsonFile(AUTH_FILE);\n return normalizeConfig(mergeConfigAndAuth(configRaw, authRaw));\n}\n\nfunction writeConfigUnlocked(cfg: CorpConfig): void {\n ensureSecurePermissions();\n const configTempFile = `${CONFIG_FILE}.${process.pid}.tmp`;\n const authTempFile = `${AUTH_FILE}.${process.pid}.tmp`;\n writeFileSync(configTempFile, serializeConfig(cfg), { mode: 0o600 });\n writeFileSync(authTempFile, serializeAuth(cfg), { mode: 0o600 });\n renameSync(configTempFile, CONFIG_FILE);\n renameSync(authTempFile, AUTH_FILE);\n ensureSecurePermissions();\n}\n\nfunction migrateLegacySensitiveConfigIfNeeded(): void {\n withConfigLock(() => {\n ensureSecurePermissions();\n const configRaw = readJsonFile(CONFIG_FILE);\n if (!hasLegacySensitiveConfig(configRaw)) {\n return;\n }\n const authRaw = readJsonFile(AUTH_FILE);\n const migrated = normalizeConfig(mergeConfigAndAuth(configRaw, authRaw));\n writeConfigUnlocked(migrated);\n });\n}\n\nexport function loadConfig(): CorpConfig {\n migrateLegacySensitiveConfigIfNeeded();\n return readConfigUnlocked();\n}\n\nexport interface ServerSecrets {\n jwt_secret: string;\n secrets_master_key: string;\n internal_worker_token: string;\n}\n\nexport function loadServerSecrets(): ServerSecrets | null {\n const authRaw = readJsonFile(AUTH_FILE);\n if (!isObject(authRaw) || !isObject(authRaw.server_secrets)) {\n return null;\n }\n const ss = authRaw.server_secrets;\n if (typeof ss.jwt_secret !== \"string\" || typeof ss.secrets_master_key !== \"string\" || typeof ss.internal_worker_token !== \"string\") {\n return null;\n }\n return {\n jwt_secret: ss.jwt_secret,\n secrets_master_key: ss.secrets_master_key,\n internal_worker_token: ss.internal_worker_token,\n };\n}\n\nexport function saveConfig(cfg: CorpConfig): void {\n withConfigLock(() => {\n writeConfigUnlocked(cfg);\n });\n}\n\nexport function updateConfig(mutator: (cfg: CorpConfig) => void): CorpConfig {\n return withConfigLock(() => {\n const cfg = readConfigUnlocked();\n mutator(cfg);\n writeConfigUnlocked(cfg);\n return cfg;\n });\n}\n\nexport function getValue(cfg: Record<string, unknown>, dotPath: string): unknown {\n const keys = dotPath.split(\".\");\n let current: unknown = cfg;\n for (const key of keys) {\n if (typeof current === \"object\" && current !== null && key in current) {\n current = (current as Record<string, unknown>)[key];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\nexport function setValue(\n cfg: Record<string, unknown>,\n dotPath: string,\n value: string,\n options: { forceSensitive?: boolean } = {},\n): void {\n requireSupportedConfigKey(dotPath);\n validateSensitiveConfigUpdate(dotPath, options.forceSensitive);\n setKnownConfigValue(cfg as CorpConfig, dotPath, value);\n}\n\nexport function requireConfig(...fields: string[]): CorpConfig {\n const cfg = loadConfig();\n const missing = fields.filter((f) => !getValue(cfg as unknown as Record<string, unknown>, f));\n if (missing.length > 0) {\n console.error(`Missing config: ${missing.join(\", \")}`);\n console.error(\"Run 'corp setup' to configure.\");\n process.exit(1);\n }\n return cfg;\n}\n\nexport function maskKey(value: string): string {\n if (!value || value.length < 8) return \"***\";\n return \"***\" + value.slice(-4);\n}\n\nexport function configForDisplay(cfg: CorpConfig): Record<string, unknown> {\n const display = { ...cfg } as Record<string, unknown>;\n if (display.api_key) display.api_key = maskKey(display.api_key as string);\n delete display.last_references;\n if (typeof display.llm === \"object\" && display.llm !== null) {\n const llm = { ...(display.llm as Record<string, unknown>) };\n if (llm.api_key) llm.api_key = maskKey(llm.api_key as string);\n display.llm = llm;\n }\n return display;\n}\n\nexport function getActiveEntityId(cfg: CorpConfig): string {\n if (cfg.workspace_id && cfg.active_entity_ids?.[cfg.workspace_id]) {\n return cfg.active_entity_ids[cfg.workspace_id];\n }\n return cfg.active_entity_id;\n}\n\nexport function setActiveEntityId(cfg: CorpConfig, entityId: string): void {\n cfg.active_entity_id = entityId;\n if (!cfg.workspace_id) {\n return;\n }\n cfg.active_entity_ids = {\n ...(cfg.active_entity_ids ?? {}),\n [cfg.workspace_id]: entityId,\n };\n}\n\nfunction referenceScopeKey(workspaceId: string, entityId?: string): string {\n if (workspaceId && entityId) {\n return `workspace:${workspaceId}:entity:${entityId}`;\n }\n if (workspaceId) {\n return `workspace:${workspaceId}`;\n }\n return \"global\";\n}\n\nexport function getLastReference(\n cfg: CorpConfig,\n kind: string,\n entityId?: string,\n): string | undefined {\n const normalizedKind = kind.trim().toLowerCase();\n const entityScopedKey = `${referenceScopeKey(cfg.workspace_id, entityId)}:${normalizedKind}`;\n if (entityId) {\n return cfg.last_references?.[entityScopedKey];\n }\n const workspaceScopedKey = `${referenceScopeKey(cfg.workspace_id)}:${normalizedKind}`;\n return cfg.last_references?.[workspaceScopedKey];\n}\n\nexport function setLastReference(\n cfg: CorpConfig,\n kind: string,\n referenceId: string,\n entityId?: string,\n): void {\n const normalizedKind = kind.trim().toLowerCase();\n const scopedKey = `${referenceScopeKey(cfg.workspace_id, entityId)}:${normalizedKind}`;\n const nextEntries = Object.entries({\n ...(cfg.last_references ?? {}),\n [scopedKey]: referenceId.trim(),\n });\n cfg.last_references = Object.fromEntries(trimReferenceEntries(nextEntries));\n}\n\nexport function resolveEntityId(cfg: CorpConfig, explicitId?: string): string {\n const eid = explicitId || getActiveEntityId(cfg);\n if (!eid) {\n console.error(\n \"No entity specified. Use --entity-id or set active_entity_id via 'corp config set active_entity_id <id>'.\"\n );\n process.exit(1);\n }\n return eid;\n}\n","import {\n getActiveEntityId,\n getLastReference,\n setLastReference,\n updateConfig,\n} from \"./config.js\";\nimport { CorpAPIClient } from \"./api-client.js\";\nimport type { ApiRecord, CorpConfig } from \"./types.js\";\n\n// Re-export types and pure functions from the shared core so existing\n// consumers in cli-ts can keep importing from \"./references.js\".\nexport type { ResourceKind, MatchRecord, ReferenceMatch } from \"@thecorporation/corp-tools\";\nexport {\n shortId,\n slugify,\n describeReferenceRecord,\n getReferenceId,\n getReferenceLabel,\n getReferenceAlias,\n RESOURCE_KINDS,\n} from \"@thecorporation/corp-tools\";\n\nimport {\n type ResourceKind,\n type MatchRecord,\n type ReferenceStorage,\n ReferenceTracker,\n shortId,\n normalize,\n validateReferenceInput,\n describeReferenceRecord,\n getReferenceAlias,\n isOpaqueUuid,\n isShortIdCandidate,\n parseLastReference,\n kindLabel,\n isEntityScopedKind,\n extractId,\n matchRank,\n} from \"@thecorporation/corp-tools\";\n\n// ---------------------------------------------------------------------------\n// Node-specific storage adapter\n// ---------------------------------------------------------------------------\n\nclass NodeReferenceStorage implements ReferenceStorage {\n constructor(private cfg: CorpConfig) {}\n\n getLastReference(kind: ResourceKind, entityId?: string): string | undefined {\n return getLastReference(this.cfg, kind, entityId);\n }\n\n setLastReference(kind: ResourceKind, id: string, entityId?: string): void {\n setLastReference(this.cfg, kind, id, entityId);\n }\n\n getActiveEntityId(): string | undefined {\n return getActiveEntityId(this.cfg);\n }\n}\n\n// ---------------------------------------------------------------------------\n// ReferenceResolver — Node/CLI-specific resolver with API calls and caching\n// ---------------------------------------------------------------------------\n\ntype Scope = { entityId?: string; bodyId?: string; meetingId?: string };\n\nexport class ReferenceResolver {\n private readonly client: CorpAPIClient;\n private readonly cfg: CorpConfig;\n private readonly tracker: ReferenceTracker;\n private entityCache?: ApiRecord[];\n private readonly contactsCache = new Map<string, ApiRecord[]>();\n private readonly shareTransfersCache = new Map<string, ApiRecord[]>();\n private readonly invoicesCache = new Map<string, ApiRecord[]>();\n private readonly bankAccountsCache = new Map<string, ApiRecord[]>();\n private readonly paymentsCache = new Map<string, ApiRecord[]>();\n private readonly payrollRunsCache = new Map<string, ApiRecord[]>();\n private readonly distributionsCache = new Map<string, ApiRecord[]>();\n private readonly reconciliationsCache = new Map<string, ApiRecord[]>();\n private readonly taxFilingsCache = new Map<string, ApiRecord[]>();\n private readonly deadlinesCache = new Map<string, ApiRecord[]>();\n private readonly classificationsCache = new Map<string, ApiRecord[]>();\n private readonly bodiesCache = new Map<string, ApiRecord[]>();\n private readonly meetingsCache = new Map<string, ApiRecord[]>();\n private readonly seatsCache = new Map<string, ApiRecord[]>();\n private readonly agendaCache = new Map<string, ApiRecord[]>();\n private readonly resolutionsCache = new Map<string, ApiRecord[]>();\n private readonly documentsCache = new Map<string, ApiRecord[]>();\n private readonly workItemsCache = new Map<string, ApiRecord[]>();\n private readonly valuationsCache = new Map<string, ApiRecord[]>();\n private readonly safeNotesCache = new Map<string, ApiRecord[]>();\n private readonly roundsCache = new Map<string, ApiRecord[]>();\n private readonly serviceRequestsCache = new Map<string, ApiRecord[]>();\n private readonly capTableCache = new Map<string, ApiRecord>();\n private agentsCache?: ApiRecord[];\n\n constructor(client: CorpAPIClient, cfg: CorpConfig) {\n this.client = client;\n this.cfg = cfg;\n this.tracker = new ReferenceTracker(new NodeReferenceStorage(cfg));\n }\n\n async resolveEntity(ref?: string): Promise<string> {\n if (ref !== undefined && ref !== null && !ref.trim()) {\n // An explicit but empty/whitespace-only ref is likely a bug in a script\n throw new Error(\n \"Entity reference is empty or whitespace. If you want the active entity, omit --entity-id entirely.\",\n );\n }\n if (!ref || !ref.trim()) {\n const activeEntityId = getActiveEntityId(this.cfg);\n if (!activeEntityId) {\n throw new Error(\n \"No entity specified. Use --entity-id or set active_entity_id via 'corp config set active_entity_id <ref>'.\",\n );\n }\n this.remember(\"entity\", activeEntityId);\n return activeEntityId;\n }\n return this.resolve(\"entity\", ref);\n }\n\n async resolveContact(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"contact\", ref, { entityId });\n }\n\n async resolveWorkItemActor(\n entityId: string,\n ref: string,\n ): Promise<{ actor_type: \"contact\" | \"agent\"; actor_id: string }> {\n const trimmed = validateReferenceInput(ref, \"actor reference\");\n const [contactResult, agentResult] = await Promise.allSettled([\n this.resolveContact(entityId, trimmed),\n this.resolveAgent(trimmed),\n ]);\n\n const contactId =\n contactResult.status === \"fulfilled\" ? contactResult.value : undefined;\n const agentId =\n agentResult.status === \"fulfilled\" ? agentResult.value : undefined;\n\n if (contactId && agentId && contactId !== agentId) {\n throw new Error(\n `Actor reference '${trimmed}' is ambiguous between a contact and an agent. Use a unique ref or explicit @last:contact / @last:agent.`,\n );\n }\n if (contactId) {\n return { actor_type: \"contact\", actor_id: contactId };\n }\n if (agentId) {\n return { actor_type: \"agent\", actor_id: agentId };\n }\n\n throw new Error(\n `No matching contact or agent found for '${trimmed}'. Try 'corp find contact <query>' or 'corp find agent <query>'.`,\n );\n }\n\n async resolveShareTransfer(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"share_transfer\", ref, { entityId });\n }\n\n async resolveInvoice(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"invoice\", ref, { entityId });\n }\n\n async resolveBankAccount(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"bank_account\", ref, { entityId });\n }\n\n async resolvePayment(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"payment\", ref, { entityId });\n }\n\n async resolvePayrollRun(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"payroll_run\", ref, { entityId });\n }\n\n async resolveDistribution(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"distribution\", ref, { entityId });\n }\n\n async resolveReconciliation(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"reconciliation\", ref, { entityId });\n }\n\n async resolveTaxFiling(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"tax_filing\", ref, { entityId });\n }\n\n async resolveDeadline(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"deadline\", ref, { entityId });\n }\n\n async resolveClassification(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"classification\", ref, { entityId });\n }\n\n async resolveBody(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"body\", ref, { entityId });\n }\n\n async resolveMeeting(entityId: string, ref: string, bodyId?: string): Promise<string> {\n return this.resolve(\"meeting\", ref, { entityId, bodyId });\n }\n\n async resolveSeat(entityId: string, ref: string, bodyId?: string): Promise<string> {\n return this.resolve(\"seat\", ref, { entityId, bodyId });\n }\n\n async resolveAgendaItem(entityId: string, meetingId: string, ref: string): Promise<string> {\n return this.resolve(\"agenda_item\", ref, { entityId, meetingId });\n }\n\n async resolveResolution(\n entityId: string,\n ref: string,\n meetingId?: string,\n ): Promise<string> {\n return this.resolve(\"resolution\", ref, { entityId, meetingId });\n }\n\n async resolveDocument(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"document\", ref, { entityId });\n }\n\n async resolveWorkItem(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"work_item\", ref, { entityId });\n }\n\n async resolveAgent(ref: string): Promise<string> {\n return this.resolve(\"agent\", ref);\n }\n\n async resolveValuation(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"valuation\", ref, { entityId });\n }\n\n async resolveSafeNote(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"safe_note\", ref, { entityId });\n }\n\n async resolveInstrument(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"instrument\", ref, { entityId });\n }\n\n async resolveShareClass(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"share_class\", ref, { entityId });\n }\n\n async resolveRound(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"round\", ref, { entityId });\n }\n\n async resolveServiceRequest(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"service_request\", ref, { entityId });\n }\n\n async find(\n kind: ResourceKind,\n query: string,\n scope: Scope = {},\n ): Promise<{ kind: ResourceKind; id: string; short_id: string; label: string; alias?: string; raw: ApiRecord }[]> {\n const records = await this.listRecords(kind, scope);\n return this.tracker.findMatches(kind, query, records);\n }\n\n getLastId(kind: ResourceKind, entityId?: string): string | undefined {\n return getLastReference(this.cfg, kind, entityId);\n }\n\n remember(kind: ResourceKind, referenceId: string, entityId?: string): void {\n setLastReference(this.cfg, kind, referenceId, entityId);\n updateConfig((cfg) => {\n setLastReference(cfg, kind, referenceId, entityId);\n });\n }\n\n rememberFromRecord(kind: ResourceKind, record: ApiRecord, entityId?: string): void {\n const described = describeReferenceRecord(kind, record);\n if (described) {\n this.remember(kind, described.id, entityId);\n }\n }\n\n async stabilizeRecord(kind: ResourceKind, record: ApiRecord, entityId?: string): Promise<ApiRecord> {\n const described = describeReferenceRecord(kind, record);\n if (!described) return record;\n if (typeof record.handle === \"string\" && record.handle.trim().length > 0) {\n return record;\n }\n const response = await this.client.syncReferences(\n kind,\n [{ resource_id: described.id, label: described.label }],\n isEntityScopedKind(kind) ? entityId : undefined,\n );\n const handle = response.references[0]?.handle;\n if (typeof handle === \"string\" && handle.trim().length > 0) {\n record.handle = handle.trim();\n }\n return record;\n }\n\n async stabilizeRecords(kind: ResourceKind, records: ApiRecord[], entityId?: string): Promise<ApiRecord[]> {\n return this.attachStableHandles(kind, records, entityId);\n }\n\n referenceAlias(kind: ResourceKind, record: ApiRecord): string | undefined {\n return getReferenceAlias(kind, record);\n }\n\n private async resolve(kind: ResourceKind, ref: string, scope: Scope = {}): Promise<string> {\n const last = parseLastReference(ref);\n if (last.isLast) {\n const lastKind = last.kind ?? kind;\n if (lastKind !== kind) {\n throw new Error(`@last:${lastKind} cannot be used where a ${kindLabel(kind)} reference is required.`);\n }\n const remembered = getLastReference(this.cfg, lastKind, scope.entityId);\n if (!remembered) {\n throw new Error(`No ${kindLabel(lastKind)} is recorded for @last.`);\n }\n this.remember(kind, remembered, scope.entityId);\n return remembered;\n }\n\n const trimmed = validateReferenceInput(ref, `${kindLabel(kind)} reference`);\n if (isOpaqueUuid(trimmed)) {\n this.remember(kind, trimmed, scope.entityId);\n return trimmed;\n }\n\n const records = await this.listRecords(kind, scope);\n const match = this.matchRecords(kind, trimmed, records);\n this.remember(kind, match.id, scope.entityId);\n return match.id;\n }\n\n private matchRecords(kind: ResourceKind, ref: string, records: ApiRecord[]): MatchRecord {\n const described = records\n .map((record) => describeReferenceRecord(kind, record))\n .filter((record): record is MatchRecord => record !== null);\n const normalizedRef = normalize(ref);\n\n const exactIdMatches = described.filter((record) => normalize(record.id) === normalizedRef);\n if (exactIdMatches.length === 1) {\n return exactIdMatches[0];\n }\n\n const exactTokenMatches = described.filter((record) => record.tokens.has(normalizedRef));\n if (exactTokenMatches.length === 1) {\n return exactTokenMatches[0];\n }\n if (exactTokenMatches.length > 1) {\n throw new Error(this.ambiguousMessage(kind, ref, exactTokenMatches));\n }\n\n if (isShortIdCandidate(ref)) {\n const prefixMatches = described.filter((record) => normalize(record.id).startsWith(normalizedRef));\n if (prefixMatches.length === 1) {\n return prefixMatches[0];\n }\n if (prefixMatches.length > 1) {\n throw new Error(this.ambiguousMessage(kind, ref, prefixMatches));\n }\n }\n\n throw new Error(\n `No ${kindLabel(kind)} found for reference \"${ref}\". Try: corp find ${kind} ${JSON.stringify(ref)}`,\n );\n }\n\n private ambiguousMessage(kind: ResourceKind, ref: string, matches: MatchRecord[]): string {\n const previews = matches\n .slice(0, 5)\n .map((match) => `${match.label} [${shortId(match.id)}]`)\n .join(\", \");\n return `Ambiguous ${kindLabel(kind)} reference \"${ref}\". Matches: ${previews}. Try: corp find ${kind} ${JSON.stringify(ref)}`;\n }\n\n private async listRecords(kind: ResourceKind, scope: Scope): Promise<ApiRecord[]> {\n const records = await (async () => {\n switch (kind) {\n case \"entity\":\n return this.listEntities();\n case \"contact\":\n return this.listContacts(scope.entityId);\n case \"share_transfer\":\n return this.listShareTransfers(scope.entityId);\n case \"invoice\":\n return this.listInvoices(scope.entityId);\n case \"bank_account\":\n return this.listBankAccounts(scope.entityId);\n case \"payment\":\n return this.listPayments(scope.entityId);\n case \"payroll_run\":\n return this.listPayrollRuns(scope.entityId);\n case \"distribution\":\n return this.listDistributions(scope.entityId);\n case \"reconciliation\":\n return this.listReconciliations(scope.entityId);\n case \"tax_filing\":\n return this.listTaxFilings(scope.entityId);\n case \"deadline\":\n return this.listDeadlines(scope.entityId);\n case \"classification\":\n return this.listClassifications(scope.entityId);\n case \"body\":\n return this.listBodies(scope.entityId);\n case \"meeting\":\n return this.listMeetings(scope.entityId, scope.bodyId);\n case \"seat\":\n return this.listSeats(scope.entityId, scope.bodyId);\n case \"agenda_item\":\n return this.listAgendaItems(scope.entityId, scope.meetingId);\n case \"resolution\":\n return this.listResolutions(scope.entityId, scope.meetingId);\n case \"document\":\n return this.listDocuments(scope.entityId);\n case \"work_item\":\n return this.listWorkItems(scope.entityId);\n case \"agent\":\n return this.listAgents();\n case \"valuation\":\n return this.listValuations(scope.entityId);\n case \"safe_note\":\n return this.listSafeNotes(scope.entityId);\n case \"instrument\":\n return this.listInstruments(scope.entityId);\n case \"share_class\":\n return this.listShareClasses(scope.entityId);\n case \"round\":\n return this.listRounds(scope.entityId);\n case \"service_request\":\n return this.listServiceRequestRecords(scope.entityId);\n }\n })();\n return this.attachStableHandles(kind, records, scope.entityId);\n }\n\n private async attachStableHandles(\n kind: ResourceKind,\n records: ApiRecord[],\n entityId?: string,\n ): Promise<ApiRecord[]> {\n const missing = records\n .map((record) => ({ record, described: describeReferenceRecord(kind, record) }))\n .filter(\n (entry): entry is { record: ApiRecord; described: MatchRecord } =>\n entry.described !== null\n && !(typeof entry.record.handle === \"string\" && entry.record.handle.trim().length > 0),\n );\n if (missing.length === 0) {\n return records;\n }\n\n // Chunk into batches of 400 to stay under the API's 500-item limit\n const SYNC_BATCH_SIZE = 400;\n const handleById = new Map<string, string>();\n const scopeEntityId = isEntityScopedKind(kind) ? entityId : undefined;\n\n for (let i = 0; i < missing.length; i += SYNC_BATCH_SIZE) {\n const batch = missing.slice(i, i + SYNC_BATCH_SIZE);\n const response = await this.client.syncReferences(\n kind,\n batch.map(({ described }) => ({\n resource_id: described.id,\n label: described.label,\n })),\n scopeEntityId,\n );\n for (const reference of response.references) {\n if (typeof reference.resource_id === \"string\" && typeof reference.handle === \"string\") {\n handleById.set(reference.resource_id, reference.handle);\n }\n }\n }\n\n for (const { record, described } of missing) {\n const handle = handleById.get(described.id);\n if (handle) {\n record.handle = handle;\n }\n }\n return records;\n }\n\n private async listEntities(): Promise<ApiRecord[]> {\n if (!this.entityCache) {\n this.entityCache = await this.client.listEntities();\n }\n return this.entityCache;\n }\n\n private async listContacts(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve contacts.\");\n const cached = this.contactsCache.get(entityId);\n if (cached) return cached;\n const contacts = await this.client.listContacts(entityId);\n this.contactsCache.set(entityId, contacts);\n return contacts;\n }\n\n private async listShareTransfers(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve share transfers.\");\n const cached = this.shareTransfersCache.get(entityId);\n if (cached) return cached;\n const transfers = await this.client.listShareTransfers(entityId);\n this.shareTransfersCache.set(entityId, transfers);\n return transfers;\n }\n\n private async listInvoices(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve invoices.\");\n const cached = this.invoicesCache.get(entityId);\n if (cached) return cached;\n const invoices = await this.client.listInvoices(entityId);\n this.invoicesCache.set(entityId, invoices);\n return invoices;\n }\n\n private async listBankAccounts(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve bank accounts.\");\n const cached = this.bankAccountsCache.get(entityId);\n if (cached) return cached;\n const bankAccounts = await this.client.listBankAccounts(entityId);\n this.bankAccountsCache.set(entityId, bankAccounts);\n return bankAccounts;\n }\n\n private async listPayments(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve payments.\");\n const cached = this.paymentsCache.get(entityId);\n if (cached) return cached;\n const payments = await this.client.listPayments(entityId);\n this.paymentsCache.set(entityId, payments);\n return payments;\n }\n\n private async listPayrollRuns(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve payroll runs.\");\n const cached = this.payrollRunsCache.get(entityId);\n if (cached) return cached;\n const payrollRuns = await this.client.listPayrollRuns(entityId);\n this.payrollRunsCache.set(entityId, payrollRuns);\n return payrollRuns;\n }\n\n private async listDistributions(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve distributions.\");\n const cached = this.distributionsCache.get(entityId);\n if (cached) return cached;\n const distributions = await this.client.listDistributions(entityId);\n this.distributionsCache.set(entityId, distributions);\n return distributions;\n }\n\n private async listReconciliations(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve reconciliations.\");\n const cached = this.reconciliationsCache.get(entityId);\n if (cached) return cached;\n const reconciliations = await this.client.listReconciliations(entityId);\n this.reconciliationsCache.set(entityId, reconciliations);\n return reconciliations;\n }\n\n private async listTaxFilings(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve tax filings.\");\n const cached = this.taxFilingsCache.get(entityId);\n if (cached) return cached;\n const filings = await this.client.listTaxFilings(entityId);\n this.taxFilingsCache.set(entityId, filings);\n return filings;\n }\n\n private async listDeadlines(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve deadlines.\");\n const cached = this.deadlinesCache.get(entityId);\n if (cached) return cached;\n const deadlines = await this.client.listDeadlines(entityId);\n this.deadlinesCache.set(entityId, deadlines);\n return deadlines;\n }\n\n private async listClassifications(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve contractor classifications.\");\n const cached = this.classificationsCache.get(entityId);\n if (cached) return cached;\n const classifications = await this.client.listContractorClassifications(entityId);\n this.classificationsCache.set(entityId, classifications);\n return classifications;\n }\n\n private async listBodies(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve governance bodies.\");\n const cached = this.bodiesCache.get(entityId);\n if (cached) return cached;\n const bodies = await this.client.listGovernanceBodies(entityId);\n this.bodiesCache.set(entityId, bodies as ApiRecord[]);\n return bodies as ApiRecord[];\n }\n\n private async listMeetings(entityId?: string, bodyId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve meetings.\");\n const cacheKey = `${entityId}:${bodyId ?? \"*\"}`;\n const cached = this.meetingsCache.get(cacheKey);\n if (cached) return cached;\n\n const meetings: ApiRecord[] = [];\n if (bodyId) {\n meetings.push(...((await this.client.listMeetings(bodyId, entityId)) as ApiRecord[]));\n } else {\n const bodies = await this.listBodies(entityId);\n for (const body of bodies) {\n const resolvedBodyId = extractId(body, [\"body_id\", \"id\"]);\n if (!resolvedBodyId) continue;\n meetings.push(...((await this.client.listMeetings(resolvedBodyId, entityId)) as ApiRecord[]));\n }\n }\n this.meetingsCache.set(cacheKey, meetings);\n return meetings;\n }\n\n private async listSeats(entityId?: string, bodyId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve seats.\");\n const cacheKey = `${entityId}:${bodyId ?? \"*\"}`;\n const cached = this.seatsCache.get(cacheKey);\n if (cached) return cached;\n\n const seats: ApiRecord[] = [];\n if (bodyId) {\n seats.push(...((await this.client.getGovernanceSeats(bodyId, entityId)) as ApiRecord[]));\n } else {\n const bodies = await this.listBodies(entityId);\n for (const body of bodies) {\n const resolvedBodyId = extractId(body, [\"body_id\", \"id\"]);\n if (!resolvedBodyId) continue;\n seats.push(...((await this.client.getGovernanceSeats(resolvedBodyId, entityId)) as ApiRecord[]));\n }\n }\n this.seatsCache.set(cacheKey, seats);\n return seats;\n }\n\n private async listAgendaItems(entityId?: string, meetingId?: string): Promise<ApiRecord[]> {\n if (!entityId || !meetingId) {\n throw new Error(\"Entity and meeting context are required to resolve agenda items.\");\n }\n const cached = this.agendaCache.get(`${entityId}:${meetingId}`);\n if (cached) return cached;\n const items = (await this.client.listAgendaItems(meetingId, entityId)) as ApiRecord[];\n this.agendaCache.set(`${entityId}:${meetingId}`, items);\n return items;\n }\n\n private async listResolutions(entityId?: string, meetingId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve resolutions.\");\n const cacheKey = `${entityId}:${meetingId ?? \"*\"}`;\n const cached = this.resolutionsCache.get(cacheKey);\n if (cached) return cached;\n\n const resolutions: ApiRecord[] = [];\n if (meetingId) {\n resolutions.push(...((await this.client.getMeetingResolutions(meetingId, entityId)) as ApiRecord[]));\n } else {\n const meetings = await this.listMeetings(entityId);\n for (const meeting of meetings) {\n const resolvedMeetingId = extractId(meeting, [\"meeting_id\", \"id\"]);\n if (!resolvedMeetingId) continue;\n resolutions.push(...((await this.client.getMeetingResolutions(resolvedMeetingId, entityId)) as ApiRecord[]));\n }\n }\n this.resolutionsCache.set(cacheKey, resolutions);\n return resolutions;\n }\n\n private async listDocuments(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve documents.\");\n const cached = this.documentsCache.get(entityId);\n if (cached) return cached;\n const docs = (await this.client.getEntityDocuments(entityId)) as ApiRecord[];\n this.documentsCache.set(entityId, docs);\n return docs;\n }\n\n private async listWorkItems(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve work items.\");\n const cached = this.workItemsCache.get(entityId);\n if (cached) return cached;\n const items = (await this.client.listWorkItems(entityId)) as ApiRecord[];\n this.workItemsCache.set(entityId, items);\n return items;\n }\n\n private async listAgents(): Promise<ApiRecord[]> {\n if (!this.agentsCache) {\n this.agentsCache = (await this.client.listAgents()) as ApiRecord[];\n }\n return this.agentsCache;\n }\n\n private async listValuations(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve valuations.\");\n const cached = this.valuationsCache.get(entityId);\n if (cached) return cached;\n const valuations = (await this.client.getValuations(entityId)) as ApiRecord[];\n this.valuationsCache.set(entityId, valuations);\n return valuations;\n }\n\n private async listSafeNotes(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve SAFE notes.\");\n const cached = this.safeNotesCache.get(entityId);\n if (cached) return cached;\n const safeNotes = (await this.client.getSafeNotes(entityId)) as ApiRecord[];\n this.safeNotesCache.set(entityId, safeNotes);\n return safeNotes;\n }\n\n private async listRounds(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve rounds.\");\n const cached = this.roundsCache.get(entityId);\n if (cached) return cached;\n const rounds = (await this.client.listEquityRounds(entityId)) as ApiRecord[];\n this.roundsCache.set(entityId, rounds);\n return rounds;\n }\n\n private async getCapTable(entityId?: string): Promise<ApiRecord> {\n if (!entityId) throw new Error(\"An entity context is required to resolve cap table resources.\");\n const cached = this.capTableCache.get(entityId);\n if (cached) return cached;\n const capTable = (await this.client.getCapTable(entityId)) as ApiRecord;\n this.capTableCache.set(entityId, capTable);\n return capTable;\n }\n\n private async listInstruments(entityId?: string): Promise<ApiRecord[]> {\n const capTable = await this.getCapTable(entityId);\n return Array.isArray(capTable.instruments) ? (capTable.instruments as ApiRecord[]) : [];\n }\n\n private async listShareClasses(entityId?: string): Promise<ApiRecord[]> {\n const capTable = await this.getCapTable(entityId);\n return Array.isArray(capTable.share_classes) ? (capTable.share_classes as ApiRecord[]) : [];\n }\n\n private async listServiceRequestRecords(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve service requests.\");\n const cached = this.serviceRequestsCache.get(entityId);\n if (cached) return cached;\n const requests = (await this.client.listServiceRequests(entityId)) as ApiRecord[];\n this.serviceRequestsCache.set(entityId, requests);\n return requests;\n }\n}\n","import chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport type { ApiRecord } from \"./types.js\";\nimport type { NextStepItem, NextStepsSummary } from \"@thecorporation/corp-tools\";\nimport {\n getReferenceAlias,\n getReferenceId,\n shortId,\n type ResourceKind,\n} from \"./references.js\";\n\nconst URGENCY_COLORS: Record<string, (s: string) => string> = {\n overdue: chalk.red.bold,\n due_today: chalk.yellow.bold,\n d1: chalk.yellow,\n d7: chalk.cyan,\n d14: chalk.blue,\n d30: chalk.dim,\n upcoming: chalk.dim,\n};\n\nconst NEXT_STEP_COLORS: Record<string, (s: string) => string> = {\n critical: chalk.red.bold,\n high: chalk.yellow,\n medium: chalk.cyan,\n low: chalk.dim,\n};\n\nexport function printError(msg: string): void {\n console.error(chalk.red(\"Error:\"), msg);\n}\n\nexport function printSuccess(msg: string): void {\n console.log(chalk.green(msg));\n}\n\nexport function printWarning(msg: string): void {\n console.log(chalk.yellow(msg));\n}\n\nexport function printJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2));\n}\n\nexport function printDryRun(operation: string, payload: unknown): void {\n printJson({\n dry_run: true,\n operation,\n payload,\n });\n}\n\nexport function printQuietId(record: unknown, ...idFields: string[]): void {\n if (typeof record !== \"object\" || record === null) return;\n const rec = record as Record<string, unknown>;\n for (const field of idFields) {\n if (typeof rec[field] === \"string\" && rec[field]) {\n console.log(rec[field]);\n return;\n }\n }\n}\n\ntype WriteResultOptions =\n | boolean\n | {\n jsonOnly?: boolean;\n quiet?: boolean;\n referenceKind?: ResourceKind;\n referenceLabel?: string;\n showReuseHint?: boolean;\n idFields?: string[];\n };\n\nfunction normalizeWriteResultOptions(options?: WriteResultOptions): {\n jsonOnly?: boolean;\n quiet?: boolean;\n referenceKind?: ResourceKind;\n referenceLabel?: string;\n showReuseHint?: boolean;\n idFields?: string[];\n} {\n if (typeof options === \"boolean\") {\n return { jsonOnly: options };\n }\n return options ?? {};\n}\n\nfunction formatReferenceCell(kind: ResourceKind, record: ApiRecord): string {\n const id = getReferenceId(kind, record);\n if (!id) return \"\";\n const alias = getReferenceAlias(kind, record);\n return alias ? `${alias} [${shortId(id)}]` : shortId(id);\n}\n\nexport function printReferenceSummary(\n kind: ResourceKind,\n record: ApiRecord,\n opts: { label?: string; showReuseHint?: boolean } = {},\n): void {\n const id = getReferenceId(kind, record);\n if (!id) return;\n const alias = getReferenceAlias(kind, record);\n const token = alias ? `${alias} [${shortId(id)}]` : shortId(id);\n console.log(` ${chalk.bold(opts.label ?? \"Ref:\")} ${token}`);\n console.log(` ${chalk.bold(\"ID:\")} ${id}`);\n if (opts.showReuseHint) {\n console.log(` ${chalk.bold(\"Reuse:\")} @last:${kind}`);\n }\n}\n\nexport function printWriteResult(\n result: unknown,\n successMessage: string,\n options?: WriteResultOptions,\n): void {\n const normalized = normalizeWriteResultOptions(options);\n if (normalized.jsonOnly) {\n printJson(result);\n return;\n }\n if (normalized.quiet) {\n const defaultIdFields = [\n \"entity_id\", \"agent_id\", \"meeting_id\", \"body_id\", \"seat_id\",\n \"work_item_id\", \"document_id\", \"invoice_id\", \"payment_id\",\n \"safe_note_id\", \"valuation_id\", \"round_id\", \"instrument_id\",\n \"transfer_workflow_id\", \"distribution_id\", \"deadline_id\",\n \"filing_id\", \"bank_account_id\", \"classification_id\",\n \"resolution_id\", \"agenda_item_id\", \"contact_id\",\n \"request_id\", \"service_request_id\", \"key_id\",\n \"formation_id\", \"execution_id\", \"incident_id\",\n \"id\",\n ];\n printQuietId(result, ...(normalized.idFields ?? defaultIdFields));\n return;\n }\n printSuccess(successMessage);\n if (\n normalized.referenceKind\n && typeof result === \"object\"\n && result !== null\n && !Array.isArray(result)\n ) {\n printReferenceSummary(normalized.referenceKind, result as ApiRecord, {\n label: normalized.referenceLabel,\n showReuseHint: normalized.showReuseHint,\n });\n }\n}\n\n// --- Status Panel ---\n\nexport function printStatusPanel(data: ApiRecord): void {\n console.log(chalk.blue(\"─\".repeat(50)));\n console.log(chalk.blue.bold(\" Corp Status\"));\n console.log(chalk.blue(\"─\".repeat(50)));\n console.log(` ${chalk.bold(\"Workspace:\")} ${data.workspace_id ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Entities:\")} ${data.entity_count ?? 0}`);\n\n const urgency = (data.urgency_counts ?? {}) as Record<string, number>;\n if (Object.keys(urgency).length > 0) {\n console.log(`\\n ${chalk.bold(\"Obligations:\")}`);\n for (const [tier, count] of Object.entries(urgency)) {\n const colorFn = URGENCY_COLORS[tier] ?? ((s: string) => s);\n console.log(` ${colorFn(`${tier}:`)} ${count}`);\n }\n }\n\n if (data.next_deadline) {\n console.log(`\\n ${chalk.bold(\"Next deadline:\")} ${data.next_deadline}`);\n }\n console.log(chalk.blue(\"─\".repeat(50)));\n}\n\nexport function printFinanceSummaryPanel(data: ApiRecord): void {\n const invoices = (data.invoices ?? {}) as ApiRecord;\n const bankAccounts = (data.bank_accounts ?? {}) as ApiRecord;\n const payments = (data.payments ?? {}) as ApiRecord;\n const payrollRuns = (data.payroll_runs ?? {}) as ApiRecord;\n const distributions = (data.distributions ?? {}) as ApiRecord;\n const reconciliations = (data.reconciliations ?? {}) as ApiRecord;\n const classifications = (data.contractor_classifications ?? {}) as ApiRecord;\n\n console.log(chalk.green(\"─\".repeat(54)));\n console.log(chalk.green.bold(\" Finance Summary\"));\n console.log(chalk.green(\"─\".repeat(54)));\n console.log(` ${chalk.bold(\"Entity:\")} ${s(data.entity_id) || \"N/A\"}`);\n console.log(` ${chalk.bold(\"Invoices:\")} ${s(invoices.count)} total, ${s(invoices.open_count)} open, ${money(invoices.total_amount_cents)}`);\n if (invoices.latest_due_date) {\n console.log(` ${chalk.bold(\"Invoice Horizon:\")} next due ${date(invoices.latest_due_date)}`);\n }\n console.log(` ${chalk.bold(\"Bank Accounts:\")} ${s(bankAccounts.active_count)}/${s(bankAccounts.count)} active`);\n console.log(` ${chalk.bold(\"Payments:\")} ${s(payments.count)} total, ${s(payments.pending_count)} pending, ${money(payments.total_amount_cents)}`);\n console.log(` ${chalk.bold(\"Payroll Runs:\")} ${s(payrollRuns.count)} total${payrollRuns.latest_period_end ? `, latest ${date(payrollRuns.latest_period_end)}` : \"\"}`);\n console.log(` ${chalk.bold(\"Distributions:\")} ${s(distributions.count)} total, ${money(distributions.total_amount_cents)}`);\n console.log(` ${chalk.bold(\"Reconciliations:\")} ${s(reconciliations.balanced_count)}/${s(reconciliations.count)} balanced`);\n console.log(` ${chalk.bold(\"Contractors:\")} ${s(classifications.count)} classifications, ${s(classifications.high_risk_count)} high risk`);\n console.log(chalk.green(\"─\".repeat(54)));\n}\n\nconst CATEGORY_LABELS: Record<string, string> = {\n setup: \"Setup\",\n formation: \"Formation\",\n documents: \"Documents\",\n governance: \"Governance\",\n cap_table: \"Cap Table\",\n compliance: \"Compliance\",\n finance: \"Finance\",\n agents: \"Agents\",\n};\n\nexport function printNextSteps(data: {\n top: NextStepItem | null;\n backlog: NextStepItem[];\n summary: NextStepsSummary;\n}): void {\n if (!data.top) {\n console.log(chalk.green.bold(\"\\n All caught up! No pending actions.\\n\"));\n return;\n }\n\n // Top recommendation\n console.log();\n console.log(chalk.bold(\" Next up:\"));\n const topColor = NEXT_STEP_COLORS[data.top.urgency] ?? ((x: string) => x);\n console.log(` ${topColor(data.top.title)}`);\n if (data.top.description) {\n console.log(` ${chalk.dim(data.top.description)}`);\n }\n console.log(` ${chalk.green(\"→\")} ${chalk.green(data.top.command)}`);\n\n // Backlog grouped by category\n if (data.backlog.length > 0) {\n console.log();\n console.log(chalk.bold(\" More to do:\"));\n\n const groups = new Map<string, NextStepItem[]>();\n for (const item of data.backlog) {\n const cat = item.category || \"other\";\n if (!groups.has(cat)) groups.set(cat, []);\n groups.get(cat)!.push(item);\n }\n\n for (const [cat, items] of groups) {\n const label = CATEGORY_LABELS[cat] ?? cat;\n console.log(`\\n ${chalk.bold(`${label} (${items.length})`)}`);\n for (const item of items) {\n const color = NEXT_STEP_COLORS[item.urgency] ?? ((x: string) => x);\n console.log(` ${color(\"•\")} ${item.title}`);\n if (item.description) {\n console.log(` ${chalk.dim(item.description)}`);\n }\n console.log(` ${chalk.green(\"→\")} ${chalk.green(item.command)}`);\n }\n }\n }\n\n // Summary footer\n const { critical = 0, high = 0, medium = 0, low = 0 } = data.summary;\n const total = critical + high + medium + low;\n const parts: string[] = [];\n if (critical > 0) parts.push(chalk.red.bold(`${critical} critical`));\n if (high > 0) parts.push(chalk.yellow(`${high} high`));\n if (medium > 0) parts.push(chalk.cyan(`${medium} medium`));\n if (low > 0) parts.push(chalk.dim(`${low} low`));\n console.log(`\\n ${total} item${total === 1 ? \"\" : \"s\"} total (${parts.join(\", \")})\\n`);\n}\n\n// --- Generic table helper ---\n\nfunction makeTable(title: string, columns: string[]): Table.Table {\n console.log(`\\n${chalk.bold(title)}`);\n return new Table({ head: columns.map((c) => chalk.dim(c)) });\n}\n\nfunction s(val: unknown, maxLen?: number): string {\n const str = val == null ? \"\" : String(val);\n if (maxLen && str.length > maxLen) return str.slice(0, maxLen);\n return str;\n}\n\nfunction money(val: unknown, cents = true): string {\n if (typeof val === \"number\") {\n const dollars = cents ? val / 100 : val;\n return `$${dollars.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;\n }\n return String(val ?? \"\");\n}\n\nfunction date(val: unknown): string {\n const str = s(val);\n if (!str) return \"\";\n const parsed = new Date(str);\n return Number.isNaN(parsed.getTime()) ? str : parsed.toISOString().slice(0, 10);\n}\n\nfunction actorLabel(record: ApiRecord, field: \"claimed_by\" | \"completed_by\" | \"created_by\"): string {\n const actor = record[`${field}_actor`];\n if (actor && typeof actor === \"object\" && !Array.isArray(actor)) {\n const label = s((actor as ApiRecord).label);\n const actorType = s((actor as ApiRecord).actor_type);\n if (label) {\n return actorType ? `${label} (${actorType})` : label;\n }\n }\n return s(record[field]);\n}\n\n// --- Domain tables ---\n\nexport function printEntitiesTable(entities: ApiRecord[]): void {\n const table = makeTable(\"Entities\", [\"Ref\", \"Name\", \"Type\", \"Jurisdiction\", \"Status\"]);\n for (const e of entities) {\n table.push([\n formatReferenceCell(\"entity\", e),\n s(e.legal_name ?? e.name),\n s(e.entity_type),\n s(e.jurisdiction),\n s(e.formation_status ?? e.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printObligationsTable(obligations: ApiRecord[]): void {\n const table = makeTable(\"Obligations\", [\"ID\", \"Type\", \"Urgency\", \"Due\", \"Status\"]);\n for (const o of obligations) {\n const urg = s(o.urgency) || \"upcoming\";\n const colorFn = URGENCY_COLORS[urg] ?? ((x: string) => x);\n table.push([s(o.obligation_id, 12), s(o.obligation_type), colorFn(urg), s(o.due_at), s(o.status)]);\n }\n console.log(table.toString());\n}\n\nexport function printContactsTable(contacts: ApiRecord[]): void {\n const table = makeTable(\"Contacts\", [\"Ref\", \"Name\", \"Email\", \"Category\", \"Entity\"]);\n for (const c of contacts) {\n table.push([\n formatReferenceCell(\"contact\", c),\n s(c.name),\n s(c.email),\n s(c.category),\n s(c.entity_name ?? c.entity_id),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printCapTable(data: ApiRecord): void {\n const accessLevel = s(data.access_level) || \"admin\";\n const instruments = (data.instruments ?? []) as ApiRecord[];\n if (instruments.length > 0) {\n const table = makeTable(\"Cap Table — Instruments\", [\"Ref\", \"Symbol\", \"Kind\", \"Authorized\", \"Issued\", \"Diluted\"]);\n for (const instrument of instruments) {\n table.push([\n formatReferenceCell(\"instrument\", instrument),\n s(instrument.symbol),\n s(instrument.kind),\n s(instrument.authorized_units ?? \"unlimited\"),\n s(instrument.issued_units),\n s(instrument.diluted_units),\n ]);\n }\n console.log(table.toString());\n }\n\n const holders = (data.holders ?? []) as ApiRecord[];\n if (holders.length > 0 && accessLevel !== \"summary\") {\n const table = makeTable(\n \"Ownership Breakdown\",\n [\"Holder\", \"Outstanding\", \"As Converted\", \"Fully Diluted\", \"Fully Diluted %\"],\n );\n for (const holder of holders) {\n const dilutedBps = typeof holder.fully_diluted_bps === \"number\"\n ? `${(holder.fully_diluted_bps / 100).toFixed(2)}%`\n : \"\";\n table.push([\n s(holder.name),\n s(holder.outstanding_units),\n s(holder.as_converted_units),\n s(holder.fully_diluted_units),\n dilutedBps,\n ]);\n }\n console.log(table.toString());\n }\n\n const shareClasses = (data.share_classes ?? []) as ApiRecord[];\n if (shareClasses.length > 0) {\n const cols = [\"Ref\", \"Class\", \"Authorized\", \"Outstanding\"];\n if (accessLevel !== \"summary\") cols.push(\"Holders\");\n const table = makeTable(\"Cap Table — Share Classes\", cols);\n for (const sc of shareClasses) {\n const row = [\n formatReferenceCell(\"share_class\", sc),\n s(sc.class_code ?? sc.name),\n s(sc.authorized),\n s(sc.outstanding),\n ];\n if (accessLevel !== \"summary\") {\n const holders = (sc.holders ?? []) as ApiRecord[];\n row.push(holders.map((h) => `${h.name ?? \"?\"}(${h.percentage ?? \"?\"}%)`).join(\", \"));\n }\n table.push(row);\n }\n console.log(table.toString());\n }\n\n const ownership = (data.ownership ?? []) as ApiRecord[];\n if (ownership.length > 0 && accessLevel !== \"summary\") {\n const table = makeTable(\"Ownership Breakdown\", [\"Holder\", \"Shares\", \"Percentage\", \"Class\"]);\n for (const o of ownership) {\n table.push([s(o.holder_name ?? o.name), s(o.shares), `${o.percentage ?? \"\"}%`, s(o.share_class)]);\n }\n console.log(table.toString());\n }\n\n const pools = (data.option_pools ?? []) as ApiRecord[];\n if (pools.length > 0) {\n const table = makeTable(\"Option Pools\", [\"Name\", \"Authorized\", \"Granted\", \"Available\"]);\n for (const p of pools) {\n table.push([s(p.name), s(p.authorized), s(p.granted), s(p.available)]);\n }\n console.log(table.toString());\n }\n\n if (data.fully_diluted_shares != null) {\n const fd = data.fully_diluted_shares;\n console.log(`\\n${chalk.bold(\"Fully Diluted Shares:\")} ${typeof fd === \"number\" ? fd.toLocaleString() : fd}`);\n }\n if (data.total_units != null) {\n console.log(`\\n${chalk.bold(\"Cap Table Basis:\")} ${s(data.basis) || \"outstanding\"}`);\n console.log(`${chalk.bold(\"Total Units:\")} ${typeof data.total_units === \"number\" ? data.total_units.toLocaleString() : data.total_units}`);\n }\n}\n\nexport function printSafesTable(safes: ApiRecord[]): void {\n const table = makeTable(\"SAFE Notes\", [\"Ref\", \"Investor\", \"Amount\", \"Cap\", \"Discount\", \"Date\"]);\n for (const s_ of safes) {\n table.push([\n formatReferenceCell(\"safe_note\", s_),\n s(s_.investor_name ?? s_.investor),\n money(s_.principal_amount_cents ?? s_.investment_amount ?? s_.amount),\n money(s_.valuation_cap_cents ?? s_.valuation_cap ?? s_.cap),\n s(s_.discount_rate ?? s_.discount),\n s(s_.issued_at ?? s_.date ?? s_.created_at),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printTransfersTable(transfers: ApiRecord[]): void {\n const table = makeTable(\"Share Transfers\", [\"Ref\", \"From\", \"To\", \"Shares\", \"Type\", \"Status\"]);\n for (const t of transfers) {\n table.push([\n formatReferenceCell(\"share_transfer\", t),\n s(t.from_holder ?? t.from),\n s(t.to_holder ?? t.to),\n s(t.shares ?? t.share_count),\n s(t.transfer_type),\n s(t.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printInstrumentsTable(instruments: ApiRecord[]): void {\n const table = makeTable(\"Instruments\", [\"Ref\", \"Symbol\", \"Kind\", \"Authorized\", \"Issued\", \"Status\"]);\n for (const instrument of instruments) {\n table.push([\n formatReferenceCell(\"instrument\", instrument),\n s(instrument.symbol),\n s(instrument.kind),\n s(instrument.authorized_units ?? \"unlimited\"),\n s(instrument.issued_units),\n s(instrument.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printShareClassesTable(shareClasses: ApiRecord[]): void {\n const table = makeTable(\"Share Classes\", [\"Ref\", \"Class\", \"Authorized\", \"Outstanding\"]);\n for (const shareClass of shareClasses) {\n table.push([\n formatReferenceCell(\"share_class\", shareClass),\n s(shareClass.class_code ?? shareClass.name ?? shareClass.share_class),\n s(shareClass.authorized),\n s(shareClass.outstanding),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printRoundsTable(rounds: ApiRecord[]): void {\n const table = makeTable(\"Equity Rounds\", [\"Ref\", \"Name\", \"Status\", \"Issuer\", \"Created\"]);\n for (const round of rounds) {\n table.push([\n formatReferenceCell(\"round\", round),\n s(round.name),\n s(round.status),\n s(round.issuer_legal_entity_id),\n date(round.created_at),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printInvoicesTable(invoices: ApiRecord[]): void {\n const table = makeTable(\"Invoices\", [\"Ref\", \"Customer\", \"Amount\", \"Due\", \"Status\"]);\n for (const invoice of invoices) {\n table.push([\n formatReferenceCell(\"invoice\", invoice),\n s(invoice.customer_name),\n money(invoice.amount_cents),\n date(invoice.due_date),\n s(invoice.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printBankAccountsTable(accounts: ApiRecord[]): void {\n const table = makeTable(\"Bank Accounts\", [\"Ref\", \"Bank\", \"Type\", \"Status\", \"Created\"]);\n for (const account of accounts) {\n table.push([\n formatReferenceCell(\"bank_account\", account),\n s(account.bank_name),\n s(account.account_type),\n s(account.status),\n date(account.created_at),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printPaymentsTable(payments: ApiRecord[]): void {\n const table = makeTable(\"Payments\", [\"Ref\", \"Recipient\", \"Amount\", \"Method\", \"Status\"]);\n for (const payment of payments) {\n table.push([\n formatReferenceCell(\"payment\", payment),\n s(payment.recipient),\n money(payment.amount_cents),\n s(payment.payment_method),\n s(payment.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printPayrollRunsTable(runs: ApiRecord[]): void {\n const table = makeTable(\"Payroll Runs\", [\"Ref\", \"Start\", \"End\", \"Status\", \"Created\"]);\n for (const run of runs) {\n table.push([\n formatReferenceCell(\"payroll_run\", run),\n date(run.pay_period_start),\n date(run.pay_period_end),\n s(run.status),\n date(run.created_at),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printDistributionsTable(distributions: ApiRecord[]): void {\n const table = makeTable(\"Distributions\", [\"Ref\", \"Type\", \"Amount\", \"Status\", \"Description\"]);\n for (const distribution of distributions) {\n table.push([\n formatReferenceCell(\"distribution\", distribution),\n s(distribution.distribution_type),\n money(distribution.total_amount_cents),\n s(distribution.status),\n s(distribution.description),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printReconciliationsTable(reconciliations: ApiRecord[]): void {\n const table = makeTable(\"Reconciliations\", [\"Ref\", \"As Of\", \"Debits\", \"Credits\", \"Status\"]);\n for (const reconciliation of reconciliations) {\n table.push([\n formatReferenceCell(\"reconciliation\", reconciliation),\n date(reconciliation.as_of_date),\n money(reconciliation.total_debits_cents),\n money(reconciliation.total_credits_cents),\n s(reconciliation.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printValuationsTable(valuations: ApiRecord[]): void {\n const table = makeTable(\"Valuations\", [\"Ref\", \"Date\", \"Type\", \"Valuation\", \"PPS\"]);\n for (const v of valuations) {\n table.push([\n formatReferenceCell(\"valuation\", v),\n date(v.effective_date ?? v.valuation_date ?? v.date),\n s(v.valuation_type ?? v.type),\n money(v.enterprise_value_cents ?? v.enterprise_value ?? v.valuation),\n money(v.fmv_per_share_cents ?? v.price_per_share ?? v.pps ?? v.fmv_per_share),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printTaxFilingsTable(filings: ApiRecord[]): void {\n const table = makeTable(\"Tax Filings\", [\"Ref\", \"Type\", \"Year\", \"Status\", \"Document\"]);\n for (const filing of filings) {\n table.push([\n formatReferenceCell(\"tax_filing\", filing),\n s(filing.document_type),\n s(filing.tax_year),\n s(filing.status),\n s(filing.document_id, 12),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printDeadlinesTable(deadlines: ApiRecord[]): void {\n const table = makeTable(\"Deadlines\", [\"Ref\", \"Type\", \"Due\", \"Status\", \"Description\"]);\n for (const deadline of deadlines) {\n table.push([\n formatReferenceCell(\"deadline\", deadline),\n s(deadline.deadline_type),\n date(deadline.due_date),\n s(deadline.status),\n s(deadline.description),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printClassificationsTable(classifications: ApiRecord[]): void {\n const table = makeTable(\"Contractor Classifications\", [\"Ref\", \"Contractor\", \"State\", \"Risk\", \"Result\"]);\n for (const classification of classifications) {\n table.push([\n formatReferenceCell(\"classification\", classification),\n s(classification.contractor_name),\n s(classification.state),\n s(classification.risk_level),\n s(classification.classification),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printGovernanceTable(bodies: ApiRecord[]): void {\n const table = makeTable(\"Governance Bodies\", [\"Ref\", \"Body\", \"Type\", \"Seats\", \"Meetings\"]);\n for (const b of bodies) {\n table.push([\n formatReferenceCell(\"body\", b),\n s(b.name),\n s(b.body_type ?? b.type),\n s(b.seat_count ?? b.seats),\n s(b.meeting_count ?? b.meetings),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printSeatsTable(seats: ApiRecord[]): void {\n const table = makeTable(\"Seats\", [\"Ref\", \"Holder\", \"Role\", \"Status\"]);\n for (const st of seats) {\n table.push([\n formatReferenceCell(\"seat\", st),\n s(st.holder_name ?? st.holder ?? st.holder_id),\n s(st.role),\n s(st.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printMeetingsTable(meetings: ApiRecord[]): void {\n const table = makeTable(\"Meetings\", [\"Ref\", \"Title\", \"Date\", \"Status\", \"Resolutions\"]);\n for (const m of meetings) {\n table.push([\n formatReferenceCell(\"meeting\", m),\n s(m.title ?? m.name),\n s(m.scheduled_date ?? m.meeting_date ?? m.date),\n s(m.status),\n s(m.resolution_count ?? m.resolutions),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printResolutionsTable(resolutions: ApiRecord[]): void {\n const table = makeTable(\"Resolutions\", [\"Ref\", \"Title\", \"Type\", \"Status\", \"For\", \"Against\"]);\n for (const r of resolutions) {\n table.push([\n formatReferenceCell(\"resolution\", r),\n s(r.title),\n s(r.resolution_type ?? r.type),\n s(r.status),\n s(r.votes_for),\n s(r.votes_against),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printAgendaItemsTable(items: ApiRecord[]): void {\n const table = makeTable(\"Agenda Items\", [\"Ref\", \"Title\", \"Status\", \"Type\"]);\n for (const item of items) {\n table.push([\n formatReferenceCell(\"agenda_item\", item),\n s(item.title),\n s(item.status),\n s(item.item_type ?? item.type),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printDocumentsTable(docs: ApiRecord[]): void {\n const table = makeTable(\"Documents\", [\"Ref\", \"Title\", \"Type\", \"Date\", \"Status\", \"Signatures\"]);\n for (const d of docs) {\n const sigs = d.signatures;\n const sigStr = Array.isArray(sigs) ? `${sigs.length} signed` : s(sigs);\n table.push([\n formatReferenceCell(\"document\", d),\n s(d.title ?? d.name),\n s(d.document_type ?? d.type),\n s(d.date ?? d.created_at),\n s(d.status),\n sigStr,\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printWorkItemsTable(items: ApiRecord[]): void {\n const table = makeTable(\"Work Items\", [\"Ref\", \"Title\", \"Category\", \"Status\", \"Deadline\", \"Claimed By\"]);\n for (const w of items) {\n const status = s(w.effective_status ?? w.status);\n const colored =\n status === \"completed\" ? chalk.green(status) :\n status === \"claimed\" ? chalk.yellow(status) :\n status === \"cancelled\" ? chalk.dim(status) :\n status;\n table.push([\n formatReferenceCell(\"work_item\", w),\n s(w.title),\n s(w.category),\n colored,\n w.asap ? chalk.red.bold(\"ASAP\") : s(w.deadline ?? \"\"),\n actorLabel(w, \"claimed_by\"),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printAgentsTable(agents: ApiRecord[]): void {\n const table = makeTable(\"Agents\", [\"Ref\", \"Name\", \"Status\", \"Model\"]);\n for (const a of agents) {\n const status = s(a.status);\n const colored =\n status === \"active\" ? chalk.green(status) : status === \"paused\" ? chalk.yellow(status) : status;\n table.push([formatReferenceCell(\"agent\", a), s(a.name), colored, s(a.model)]);\n }\n console.log(table.toString());\n}\n\nexport function printApprovalsTable(approvals: ApiRecord[]): void {\n const table = makeTable(\"Pending Approvals\", [\"ID\", \"Type\", \"Requested By\", \"Description\", \"Created\"]);\n for (const a of approvals) {\n let desc = s(a.description ?? a.summary);\n if (desc.length > 60) desc = desc.slice(0, 57) + \"...\";\n table.push([\n s(a.approval_id ?? a.id, 12),\n s(a.approval_type ?? a.type),\n s(a.requested_by ?? a.requester),\n desc,\n s(a.created_at),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printServiceCatalogTable(items: ApiRecord[]): void {\n const table = makeTable(\"Service Catalog\", [\"Slug\", \"Name\", \"Price\", \"Type\"]);\n for (const item of items) {\n table.push([\n s(item.slug),\n s(item.name),\n money(item.amount_cents),\n s(item.price_type),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printServiceRequestsTable(requests: ApiRecord[]): void {\n const table = makeTable(\"Service Requests\", [\"Ref\", \"Service\", \"Amount\", \"Status\", \"Created\"]);\n for (const r of requests) {\n const status = s(r.status);\n const colored =\n status === \"fulfilled\" ? chalk.green(status) :\n status === \"paid\" ? chalk.cyan(status) :\n status === \"checkout\" ? chalk.yellow(status) :\n status === \"failed\" ? chalk.dim(status) :\n status;\n table.push([\n formatReferenceCell(\"service_request\", r),\n s(r.service_slug),\n money(r.amount_cents),\n colored,\n date(r.created_at),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printBillingPanel(status: ApiRecord, plans: ApiRecord[]): void {\n const plan = s(status.plan ?? status.tier) || \"free\";\n const subStatus = s(status.status) || \"active\";\n const periodEnd = s(status.current_period_end);\n const explanation = s(status.status_explanation);\n\n console.log(chalk.green(\"─\".repeat(50)));\n console.log(chalk.green.bold(\" Billing Status\"));\n console.log(chalk.green(\"─\".repeat(50)));\n console.log(` ${chalk.bold(\"Plan:\")} ${plan}`);\n console.log(` ${chalk.bold(\"Status:\")} ${subStatus}`);\n if (periodEnd) console.log(` ${chalk.bold(\"Current Period End:\")} ${periodEnd}`);\n if (explanation) console.log(` ${chalk.bold(\"Explanation:\")} ${explanation}`);\n console.log(chalk.dim(\" Manage: corp billing portal\"));\n console.log(chalk.dim(\" Upgrade: corp billing upgrade --plan <plan>\"));\n console.log(chalk.green(\"─\".repeat(50)));\n\n if (plans.length > 0) {\n const table = makeTable(\"Available Plans\", [\"Plan\", \"Price\", \"Features\"]);\n for (const p of plans) {\n const amount = (p.price_cents ?? p.amount ?? 0) as number;\n const interval = s(p.interval);\n let priceStr = \"Free\";\n if (amount > 0) {\n priceStr = interval ? `$${Math.round(amount / 100)}/${interval}` : `$${Math.round(amount / 100)}`;\n }\n const name = s(p.name ?? p.plan_id ?? p.tier);\n const features = Array.isArray(p.features) ? (p.features as string[]).join(\", \") : s(p.description);\n table.push([name, priceStr, features]);\n }\n console.log(table.toString());\n }\n}\n","export { CorpAPIClient, SessionExpiredError, provisionWorkspace } from \"@thecorporation/corp-tools\";\n","import chalk from \"chalk\";\nimport type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n loadConfig,\n requireConfig,\n resolveEntityId,\n getActiveEntityId,\n saveConfig,\n setActiveEntityId,\n} from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { ReferenceResolver, getReferenceAlias } from \"../references.js\";\nimport {\n printError,\n printJson,\n printStatusPanel,\n printNextSteps,\n printBillingPanel,\n printReferenceSummary,\n printSuccess,\n printWarning,\n} from \"../output.js\";\nimport { withSpinner } from \"../spinner.js\";\nimport type { NextStepsResponse, NextStepItem } from \"@thecorporation/corp-tools\";\nimport type { ApiRecord } from \"../types.js\";\n\n// ---------------------------------------------------------------------------\n// Local helpers (relocated from individual command files)\n// ---------------------------------------------------------------------------\n\n/** Pre-flight local checks for `next` (runs before any API call). */\nfunction localChecks(): NextStepItem[] {\n const items: NextStepItem[] = [];\n let cfg;\n try {\n cfg = loadConfig();\n } catch {\n items.push({\n category: \"setup\",\n title: \"Run initial setup\",\n description: \"No configuration found\",\n command: \"npx corp setup\",\n urgency: \"critical\",\n });\n return items;\n }\n\n if (!cfg.api_key) {\n items.push({\n category: \"setup\",\n title: \"Run setup to configure API key\",\n description: \"No API key configured\",\n command: \"npx corp setup\",\n urgency: \"critical\",\n });\n return items;\n }\n\n if (!cfg.workspace_id) {\n items.push({\n category: \"setup\",\n title: \"Claim a workspace\",\n description: \"No workspace configured\",\n command: \"npx corp claim <code>\",\n urgency: \"critical\",\n });\n return items;\n }\n\n if (!getActiveEntityId(cfg)) {\n items.push({\n category: \"setup\",\n title: \"Set an active entity\",\n description: \"No active entity — set one to get entity-specific recommendations\",\n command: \"npx corp use <entity-name>\",\n urgency: \"high\",\n });\n }\n\n return items;\n}\n\n/** Enrich billing status with explanation when pending_checkout. */\nfunction enrichBillingStatus(status: ApiRecord): ApiRecord {\n if (typeof status.status_explanation === \"string\" && status.status_explanation.trim()) {\n return status;\n }\n\n const plan = String(status.plan ?? status.tier ?? \"\").trim();\n const subStatus = String(status.status ?? \"\").trim();\n if (subStatus !== \"pending_checkout\") {\n return status;\n }\n\n const statusExplanation = plan\n ? `Checkout for the ${plan} plan has started, but billing will not become active until Stripe checkout is completed.`\n : \"Checkout has started, but billing will not become active until Stripe checkout is completed.\";\n\n return { ...status, status_explanation: statusExplanation };\n}\n\n// ---------------------------------------------------------------------------\n// Registry entries\n// ---------------------------------------------------------------------------\n\nexport const workspaceCommands: CommandDef[] = [\n // --- status ---\n {\n name: \"status\",\n description: \"Workspace summary\",\n route: { method: \"GET\", path: \"/v1/workspaces/{wid}/status\" },\n display: { title: \"Corp Status\" },\n handler: async (ctx) => {\n try {\n const data = await withSpinner(\"Loading\", () => ctx.client.getStatus());\n if (ctx.opts.json) {\n ctx.writer.json(data);\n } else {\n printStatusPanel(data);\n }\n } catch (err) {\n ctx.writer.error(`Failed to fetch status: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp status\"],\n },\n\n // --- context / whoami ---\n {\n name: \"context\",\n description: \"Show the active workspace, user, and entity context\",\n aliases: [\"whoami\"],\n display: { title: \"Corp Context\" },\n handler: async (ctx) => {\n const rawCfg = loadConfig();\n const resolver = new ReferenceResolver(ctx.client, rawCfg);\n\n try {\n const [status, entities] = await Promise.all([\n ctx.client.getStatus(),\n ctx.client.listEntities(),\n ]);\n await resolver.stabilizeRecords(\"entity\", entities);\n\n const activeEntityId = getActiveEntityId(rawCfg);\n const activeEntity = activeEntityId\n ? entities.find((entity) => entity.entity_id === activeEntityId) ?? null\n : null;\n\n const [contactsResult, documentsResult, workItemsResult] = activeEntity\n ? await Promise.allSettled([\n ctx.client.listContacts(String(activeEntity.entity_id)),\n ctx.client.getEntityDocuments(String(activeEntity.entity_id)),\n ctx.client.listWorkItems(String(activeEntity.entity_id)),\n ])\n : [null, null, null];\n\n const payload = {\n user: {\n name: rawCfg.user?.name ?? \"\",\n email: rawCfg.user?.email ?? \"\",\n },\n workspace: {\n workspace_id: rawCfg.workspace_id,\n api_url: rawCfg.api_url,\n status,\n },\n active_entity: activeEntity\n ? {\n entity: activeEntity,\n summary: {\n contact_count:\n contactsResult && contactsResult.status === \"fulfilled\"\n ? contactsResult.value.length\n : null,\n document_count:\n documentsResult && documentsResult.status === \"fulfilled\"\n ? documentsResult.value.length\n : null,\n work_item_count:\n workItemsResult && workItemsResult.status === \"fulfilled\"\n ? workItemsResult.value.length\n : null,\n },\n }\n : null,\n entity_count: entities.length,\n };\n\n if (ctx.opts.json) {\n ctx.writer.json(payload);\n return;\n }\n\n console.log(chalk.blue(\"\\u2500\".repeat(50)));\n console.log(chalk.blue.bold(\" Corp Context\"));\n console.log(chalk.blue(\"\\u2500\".repeat(50)));\n console.log(` ${chalk.bold(\"User:\")} ${payload.user.name || \"N/A\"} <${payload.user.email || \"N/A\"}>`);\n console.log(` ${chalk.bold(\"Workspace:\")} ${rawCfg.workspace_id}`);\n console.log(` ${chalk.bold(\"API URL:\")} ${rawCfg.api_url}`);\n console.log(` ${chalk.bold(\"Entities:\")} ${entities.length}`);\n if (payload.active_entity) {\n console.log(` ${chalk.bold(\"Active Entity:\")} ${payload.active_entity.entity.legal_name ?? payload.active_entity.entity.entity_id}`);\n printReferenceSummary(\"entity\", payload.active_entity.entity, { label: \"Active Entity Ref:\" });\n console.log(` ${chalk.bold(\"Contacts:\")} ${payload.active_entity.summary.contact_count ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Documents:\")} ${payload.active_entity.summary.document_count ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Work Items:\")} ${payload.active_entity.summary.work_item_count ?? \"N/A\"}`);\n } else {\n console.log(` ${chalk.bold(\"Active Entity:\")} none`);\n }\n if ((status as Record<string, unknown>).next_deadline) {\n console.log(` ${chalk.bold(\"Next Deadline:\")} ${(status as Record<string, unknown>).next_deadline}`);\n }\n console.log(chalk.blue(\"\\u2500\".repeat(50)));\n } catch (err) {\n ctx.writer.error(`Failed to fetch context: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp context\", \"corp context --json\"],\n },\n\n // --- use <entity-ref> ---\n {\n name: \"use\",\n description: \"Set the active entity by name, short ID, or reference\",\n args: [{ name: \"entity-ref\", required: true, description: \"Entity name, short ID, or reference\" }],\n handler: async (ctx) => {\n const entityRef = ctx.positional[0];\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n try {\n const entityId = await resolver.resolveEntity(entityRef);\n setActiveEntityId(cfg, entityId);\n saveConfig(cfg);\n const alias = getReferenceAlias(\"entity\", { entity_id: entityId }) ?? entityId;\n ctx.writer.success(`Active entity set to ${alias} (${entityId})`);\n } catch (err) {\n ctx.writer.error(`Failed to resolve entity: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp use\", \"corp use --json\"],\n },\n\n // --- next ---\n {\n name: \"next\",\n description: \"See what to do next — your recommended actions\",\n options: [\n { flags: \"--entity-id <ref>\", description: \"Entity to check (default: active entity)\" },\n { flags: \"--workspace\", description: \"Show recommendations across all entities\" },\n ],\n examples: [\n \"$ corp next # Next steps for active entity\",\n \"$ corp next --workspace # Next steps across all entities\",\n \"$ corp next --entity-id ent_abc123 # Next steps for specific entity\",\n \"$ corp next --json # JSON output for scripting\",\n ],\n handler: async (ctx) => {\n const opts = ctx.opts as { entityId?: string; workspace?: boolean; json?: boolean };\n\n if (opts.entityId && opts.workspace) {\n ctx.writer.error(\"--entity-id and --workspace are mutually exclusive\");\n process.exit(1);\n }\n\n const localItems = localChecks();\n const hasCriticalLocal = localItems.some((i) => i.urgency === \"critical\");\n\n if (hasCriticalLocal) {\n const top = localItems[0];\n const backlog = localItems.slice(1);\n const summary = { critical: 0, high: 0, medium: 0, low: 0 };\n for (const item of [top, ...backlog]) {\n const key = item.urgency as keyof typeof summary;\n if (key in summary) summary[key]++;\n }\n const response = { top, backlog, summary };\n if (opts.json) {\n ctx.writer.json(response);\n } else {\n printNextSteps(response);\n }\n return;\n }\n\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n\n try {\n let data: NextStepsResponse;\n if (opts.workspace) {\n data = await withSpinner(\"Loading\", () => client.getWorkspaceNextSteps(), opts.json);\n } else {\n const entityId = resolveEntityId(cfg, opts.entityId);\n data = await withSpinner(\"Loading\", () => client.getEntityNextSteps(entityId), opts.json);\n }\n\n // Merge non-critical local items into backlog\n if (localItems.length > 0) {\n data.backlog.push(...localItems);\n const all = [data.top, ...data.backlog].filter(Boolean) as NextStepItem[];\n data.summary = { critical: 0, high: 0, medium: 0, low: 0 };\n for (const item of all) {\n const key = item.urgency as keyof typeof data.summary;\n if (key in data.summary) data.summary[key]++;\n }\n }\n\n if (opts.json) {\n ctx.writer.json(data);\n } else {\n printNextSteps(data);\n }\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"Not found\") || msg.includes(\"404\")) {\n // Entity store may not exist yet (e.g. formation not finalized)\n if (localItems.length > 0) {\n const top = localItems[0];\n const backlog = localItems.slice(1);\n const summary = { critical: 0, high: 0, medium: 0, low: 0 };\n for (const item of [top, ...backlog]) {\n const key = item.urgency as keyof typeof summary;\n if (key in summary) summary[key]++;\n }\n const response = { top, backlog, summary };\n if (opts.json) { ctx.writer.json(response); } else { printNextSteps(response); }\n } else {\n console.log(\"No entities found yet. Get started:\\n\");\n console.log(' corp form --type c_corp --name \"My Company\" --member \"Name,email,director,100,street|city|state|zip,ceo,true\"');\n console.log(\"\\n Or use the staged flow:\");\n console.log(' corp form create --type llc --name \"My LLC\"');\n console.log(' corp form add-founder @last --name \"Alice\" --email \"a@co.com\" --role member --ownership-pct 100');\n console.log(\" corp form finalize @last\");\n }\n } else {\n ctx.writer.error(`Failed to fetch next steps: ${err}`);\n process.exit(1);\n }\n }\n },\n },\n\n // --- obligations (pure read) ---\n {\n name: \"obligations\",\n description: \"List obligations with urgency tiers\",\n route: { method: \"GET\", path: \"/v1/obligations/summary\" },\n display: {\n title: \"Obligations\",\n listKey: \"obligations\",\n cols: [\n \"obligation_type>Type\",\n \"urgency>Urgency\",\n \"@due_at>Due\",\n \"status>Status\",\n \"#obligation_id>ID\",\n ],\n },\n optQP: [\"tier\"],\n options: [{ flags: \"--tier <tier>\", description: \"Filter by urgency tier\" }],\n examples: [\"corp obligations\"],\n },\n\n // --- digest ---\n {\n name: \"digest\",\n description: \"View or trigger daily digests\",\n route: { method: \"GET\", path: \"/v1/digests\" },\n display: { title: \"Digests\" },\n options: [\n { flags: \"--trigger\", description: \"Trigger digest now\" },\n { flags: \"--key <key>\", description: \"Get specific digest by key\" },\n { flags: \"--entity-id <ref>\", description: \"Entity reference (ID, short ID, @last, or unique name)\" },\n ],\n handler: async (ctx) => {\n const opts = ctx.opts as { trigger?: boolean; key?: string; entityId?: string; json?: boolean };\n try {\n if (opts.trigger) {\n const result = await ctx.client.triggerDigest();\n const message = (() => {\n const value = (result as Record<string, unknown>).message;\n return typeof value === \"string\" && value.trim() ? value : null;\n })();\n if (!opts.json) {\n ctx.writer.success(result.digest_count > 0 ? \"Digest triggered.\" : \"Digest trigger accepted.\");\n }\n if (message && !opts.json) {\n ctx.writer.warning(message);\n }\n ctx.writer.json(result);\n } else if (opts.key) {\n const result = await ctx.client.getDigest(opts.key);\n ctx.writer.json(result);\n } else {\n const digests = await ctx.client.listDigests();\n if (digests.length === 0) {\n if (opts.json) {\n ctx.writer.json([]);\n } else {\n ctx.writer.writeln(\"No digest history found.\");\n }\n } else {\n ctx.writer.json(digests);\n }\n }\n } catch (err) {\n ctx.writer.error(`Failed: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp digest\"],\n },\n\n // --- billing ---\n {\n name: \"billing\",\n description: \"Billing status, plans, and subscription management\",\n display: { title: \"Billing\" },\n handler: async (ctx) => {\n try {\n const [status, plans] = await Promise.all([\n ctx.client.getBillingStatus(),\n ctx.client.getBillingPlans(),\n ]);\n const enrichedStatus = enrichBillingStatus(status);\n if (ctx.opts.json) {\n ctx.writer.json({ status: enrichedStatus, plans });\n } else {\n printBillingPanel(enrichedStatus, plans);\n }\n } catch (err) {\n ctx.writer.error(`Failed to fetch billing info: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp billing\"],\n },\n\n // --- billing portal ---\n {\n name: \"billing portal\",\n description: \"Open Stripe Customer Portal\",\n route: { method: \"POST\", path: \"/v1/billing/portal\" },\n handler: async (ctx) => {\n try {\n const result = await ctx.client.createBillingPortal();\n const url = result.portal_url as string;\n if (!url) {\n ctx.writer.error(\"No portal URL returned. Ensure you have an active subscription.\");\n process.exit(1);\n }\n ctx.writer.success(\"Stripe Customer Portal URL:\");\n ctx.writer.writeln(url);\n } catch (err) {\n ctx.writer.error(`Failed to create portal session: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp billing portal\"],\n },\n\n // --- billing upgrade ---\n {\n name: \"billing upgrade\",\n description: \"Open Stripe Checkout to upgrade your plan\",\n route: { method: \"POST\", path: \"/v1/billing/checkout\" },\n options: [\n {\n flags: \"--plan <plan>\",\n description: \"Plan ID to upgrade to (free, pro, enterprise)\",\n default: \"pro\",\n choices: [\"free\", \"pro\", \"enterprise\"],\n },\n ],\n handler: async (ctx) => {\n const opts = ctx.opts as { plan: string };\n try {\n const result = await ctx.client.createBillingCheckout(opts.plan);\n const url = result.checkout_url as string;\n if (!url) {\n ctx.writer.error(\"No checkout URL returned.\");\n process.exit(1);\n }\n ctx.writer.success(`Stripe Checkout URL for ${opts.plan}:`);\n ctx.writer.writeln(url);\n } catch (err) {\n ctx.writer.error(`Failed to create checkout session: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp billing upgrade\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"entities next-steps\",\n description: \"View recommended next actions for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/next-steps\" },\n entity: true,\n display: { title: \"Entities Next Steps\", cols: [\"backlog>Backlog\", \"summary>Summary\", \"top>Top\"] },\n examples: [\"corp entities next-steps\", \"corp entities next-steps --json\"],\n },\n {\n name: \"workspaces next-steps\",\n description: \"View recommended next actions across the workspace\",\n route: { method: \"GET\", path: \"/v1/workspaces/{workspace_id}/next-steps\" },\n display: { title: \"Workspaces Next Steps\", cols: [\"backlog>Backlog\", \"summary>Summary\", \"top>Top\"] },\n examples: [\"corp workspaces next-steps\"],\n },\n\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport { printEntitiesTable, printContactsTable, printError, printJson, printReferenceSummary, printSuccess, printWriteResult } from \"../output.js\";\nimport { withSpinner } from \"../spinner.js\";\nimport { confirm } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport type { ApiRecord } from \"../types.js\";\n\n// ── Entity handlers ────────────────────────────────────────────\n\nasync function entitiesHandler(ctx: CommandContext): Promise<void> {\n const jsonOutput = !!ctx.opts.json;\n try {\n const entities = await withSpinner(\"Loading\", () => ctx.client.listEntities(), jsonOutput);\n await ctx.resolver.stabilizeRecords(\"entity\", entities);\n if (jsonOutput) {\n printJson(entities);\n } else if (entities.length === 0) {\n console.log(\"No entities found.\");\n } else {\n printEntitiesTable(entities);\n }\n } catch (err) {\n printError(`Failed to fetch entities: ${err}`);\n process.exit(1);\n }\n}\n\nasync function entitiesShowHandler(ctx: CommandContext): Promise<void> {\n const entityRef = ctx.positional[0];\n const jsonOutput = !!ctx.opts.json;\n const quiet = !!ctx.opts.quiet;\n try {\n const resolvedEntityId = await ctx.resolver.resolveEntity(entityRef);\n const entities = await ctx.client.listEntities();\n const entity = entities.find((e: ApiRecord) => e.entity_id === resolvedEntityId);\n if (!entity) {\n printError(`Entity not found: ${entityRef}`);\n process.exit(1);\n }\n await ctx.resolver.stabilizeRecord(\"entity\", entity);\n if (quiet) {\n console.log(String(entity.entity_id ?? resolvedEntityId));\n return;\n }\n if (jsonOutput) {\n printJson(entity);\n } else {\n console.log(chalk.blue(\"\\u2500\".repeat(40)));\n console.log(chalk.blue.bold(\" Entity Detail\"));\n console.log(chalk.blue(\"\\u2500\".repeat(40)));\n console.log(` ${chalk.bold(\"Name:\")} ${entity.legal_name ?? entity.name ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Type:\")} ${entity.entity_type ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Jurisdiction:\")} ${entity.jurisdiction ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Status:\")} ${entity.formation_status ?? entity.status ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"State:\")} ${entity.formation_state ?? \"N/A\"}`);\n printReferenceSummary(\"entity\", entity, { showReuseHint: true });\n if (entity.formation_date) console.log(` ${chalk.bold(\"Formation Date:\")} ${entity.formation_date}`);\n if (entity.ein) console.log(` ${chalk.bold(\"EIN:\")} ${entity.ein}`);\n console.log(chalk.blue(\"\\u2500\".repeat(40)));\n }\n } catch (err) {\n printError(`Failed to fetch entities: ${err}`);\n process.exit(1);\n }\n}\n\nasync function entitiesConvertHandler(ctx: CommandContext): Promise<void> {\n const entityRef = ctx.positional[0];\n try {\n const resolvedEntityId = await ctx.resolver.resolveEntity(entityRef);\n const data: Record<string, string> = { target_type: ctx.opts.to as string };\n if (ctx.opts.jurisdiction) data.new_jurisdiction = ctx.opts.jurisdiction as string;\n const result = await ctx.client.convertEntity(resolvedEntityId, data);\n printSuccess(`Entity conversion initiated: ${result.conversion_id ?? \"OK\"}`);\n printJson(result);\n } catch (err) {\n printError(`Failed to convert entity: ${err}`);\n process.exit(1);\n }\n}\n\nasync function entitiesDissolveHandler(ctx: CommandContext): Promise<void> {\n const entityRef = ctx.positional[0];\n try {\n const resolvedEntityId = await ctx.resolver.resolveEntity(entityRef);\n if (!ctx.opts.yes) {\n const ok = await confirm({\n message: `Dissolve entity ${entityRef}? This cannot be undone.`,\n default: false,\n });\n if (!ok) {\n console.log(\"Cancelled.\");\n return;\n }\n }\n const data: Record<string, string> = { reason: ctx.opts.reason as string };\n if (ctx.opts.effectiveDate) data.effective_date = ctx.opts.effectiveDate as string;\n const result = await ctx.client.dissolveEntity(resolvedEntityId, data);\n printSuccess(`Dissolution initiated: ${result.dissolution_id ?? \"OK\"}`);\n printJson(result);\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"InvalidTransition\") || msg.includes(\"422\")) {\n printError(`Cannot dissolve entity: only entities with 'active' status can be dissolved. Check the entity's current status with: corp entities show ${entityRef}`);\n } else {\n printError(`Failed to dissolve entity: ${err}`);\n }\n process.exit(1);\n }\n}\n\n// ── Contact handlers ───────────────────────────────────────────\n\nasync function contactsHandler(ctx: CommandContext): Promise<void> {\n const jsonOutput = !!ctx.opts.json;\n try {\n const eid = await ctx.resolver.resolveEntity(ctx.entityId);\n const contacts = await ctx.client.listContacts(eid);\n await ctx.resolver.stabilizeRecords(\"contact\", contacts, eid);\n if (jsonOutput) printJson(contacts);\n else if (contacts.length === 0) console.log(\"No contacts found.\");\n else printContactsTable(contacts);\n } catch (err) {\n printError(`Failed to fetch contacts: ${err}`);\n process.exit(1);\n }\n}\n\nasync function contactsShowHandler(ctx: CommandContext): Promise<void> {\n const contactRef = ctx.positional[0];\n const jsonOutput = !!ctx.opts.json;\n try {\n const eid = await ctx.resolver.resolveEntity(ctx.entityId);\n const resolvedContactId = await ctx.resolver.resolveContact(eid, contactRef);\n const profile = await ctx.client.getContactProfile(resolvedContactId, eid);\n const contact = await ctx.resolver.stabilizeRecord(\"contact\", (profile.contact ?? profile) as ApiRecord, eid);\n if (jsonOutput) {\n printJson(profile);\n } else {\n console.log(chalk.cyan(\"\\u2500\".repeat(40)));\n console.log(chalk.cyan.bold(\" Contact Profile\"));\n console.log(chalk.cyan(\"\\u2500\".repeat(40)));\n console.log(` ${chalk.bold(\"Name:\")} ${contact.name ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Email:\")} ${contact.email ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Category:\")} ${contact.category ?? \"N/A\"}`);\n printReferenceSummary(\"contact\", contact, { showReuseHint: true });\n if (contact.phone) console.log(` ${chalk.bold(\"Phone:\")} ${contact.phone}`);\n if (contact.notes) console.log(` ${chalk.bold(\"Notes:\")} ${contact.notes}`);\n const holdings = profile.equity_holdings as ApiRecord[] | undefined;\n if (holdings?.length) {\n console.log(`\\n ${chalk.bold(\"Equity Holdings:\")}`);\n for (const h of holdings) console.log(` ${h.share_class ?? \"?\"}: ${h.shares ?? \"?\"} shares`);\n }\n const obls = profile.obligations as unknown[];\n if (obls?.length) console.log(`\\n ${chalk.bold(\"Obligations:\")} ${obls.length}`);\n console.log(chalk.cyan(\"\\u2500\".repeat(40)));\n }\n } catch (err) {\n printError(`Failed to fetch contact: ${err}`);\n process.exit(1);\n }\n}\n\nasync function contactsAddHandler(ctx: CommandContext): Promise<void> {\n const jsonOutput = !!ctx.opts.json;\n try {\n const eid = await ctx.resolver.resolveEntity(ctx.entityId);\n const data: ApiRecord = {\n entity_id: eid,\n contact_type: (ctx.opts.type as string) ?? \"individual\",\n name: ctx.opts.name as string,\n email: ctx.opts.email as string,\n category: (ctx.opts.category as string) ?? \"employee\",\n };\n if (ctx.opts.phone) data.phone = ctx.opts.phone;\n if (ctx.opts.notes) data.notes = ctx.opts.notes;\n if (ctx.opts.mailingAddress ?? ctx.opts.address) data.mailing_address = ctx.opts.mailingAddress ?? ctx.opts.address;\n if (ctx.opts.capTableAccess) data.cap_table_access = ctx.opts.capTableAccess;\n const result = await ctx.client.createContact(data);\n await ctx.resolver.stabilizeRecord(\"contact\", result, eid);\n ctx.resolver.rememberFromRecord(\"contact\", result, eid);\n printWriteResult(\n result,\n `Contact created: ${result.contact_id ?? result.id ?? \"OK\"}`,\n { jsonOnly: jsonOutput, referenceKind: \"contact\", showReuseHint: true },\n );\n } catch (err) {\n printError(`Failed to create contact: ${err}`);\n process.exit(1);\n }\n}\n\nasync function contactsEditHandler(ctx: CommandContext): Promise<void> {\n const contactRef = ctx.positional[0];\n const jsonOutput = !!ctx.opts.json;\n try {\n const eid = await ctx.resolver.resolveEntity(ctx.entityId);\n const resolvedContactId = await ctx.resolver.resolveContact(eid, contactRef);\n const data: ApiRecord = { entity_id: eid };\n let hasUpdates = false;\n if (ctx.opts.name != null) { data.name = ctx.opts.name; hasUpdates = true; }\n if (ctx.opts.email != null) { data.email = ctx.opts.email; hasUpdates = true; }\n if (ctx.opts.category != null) { data.category = ctx.opts.category; hasUpdates = true; }\n if (ctx.opts.phone != null) { data.phone = ctx.opts.phone; hasUpdates = true; }\n if (ctx.opts.notes != null) { data.notes = ctx.opts.notes; hasUpdates = true; }\n if (ctx.opts.capTableAccess != null) { data.cap_table_access = ctx.opts.capTableAccess; hasUpdates = true; }\n if (ctx.opts.mailingAddress != null || ctx.opts.address != null) {\n data.mailing_address = ctx.opts.mailingAddress ?? ctx.opts.address;\n hasUpdates = true;\n }\n if (!hasUpdates) {\n console.log(\"No fields to update.\");\n return;\n }\n const result = await ctx.client.updateContact(resolvedContactId, data);\n ctx.resolver.remember(\"contact\", resolvedContactId, eid);\n printWriteResult(result, \"Contact updated.\", jsonOutput);\n } catch (err) {\n printError(`Failed to update contact: ${err}`);\n process.exit(1);\n }\n}\n\n// ── Command definitions ────────────────────────────────────────\n\nexport const entityCommands: CommandDef[] = [\n // ── entities ──\n {\n name: \"entities\",\n description: \"List all entities\",\n handler: entitiesHandler,\n examples: [\"corp entities\"],\n },\n {\n name: \"entities show\",\n description: \"Show entity detail\",\n args: [{ name: \"entity-ref\", required: true }],\n handler: entitiesShowHandler,\n examples: [\"corp entities show\"],\n },\n {\n name: \"entities convert\",\n description: \"Convert entity to a different type\",\n route: { method: \"POST\", path: \"/v1/entities/{pos}/convert\" },\n args: [{ name: \"entity-ref\", required: true }],\n options: [\n { flags: \"--to <type>\", description: \"Target entity type (llc, c_corp)\", required: true },\n { flags: \"--jurisdiction <jurisdiction>\", description: \"New jurisdiction\" },\n ],\n handler: entitiesConvertHandler,\n examples: [\"corp entities convert <entity-ref> --to 'type'\", \"corp entities convert --json\"],\n },\n {\n name: \"entities dissolve\",\n description: \"Dissolve an entity\",\n route: { method: \"POST\", path: \"/v1/entities/{pos}/dissolve\" },\n args: [{ name: \"entity-ref\", required: true }],\n options: [\n { flags: \"--reason <reason>\", description: \"Dissolution reason\", required: true },\n { flags: \"--effective-date <date>\", description: \"Effective date (ISO 8601)\" },\n { flags: \"--yes, -y\", description: \"Skip confirmation prompt\" },\n ],\n handler: entitiesDissolveHandler,\n examples: [\"corp entities dissolve <entity-ref> --reason 'reason'\", \"corp entities dissolve --json\"],\n },\n\n // ── contacts ──\n {\n name: \"contacts\",\n description: \"Contact management\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/contacts\" },\n entity: true,\n display: {\n title: \"Contacts\",\n cols: [\"name>Name\", \"email>Email\", \"category>Category\", \"#contact_id>ID\"],\n },\n handler: contactsHandler,\n examples: [\"corp contacts\", \"corp contacts --json\"],\n },\n {\n name: \"contacts show\",\n description: \"Show contact detail/profile\",\n route: { method: \"GET\", path: \"/v1/contacts/{pos}/profile\" },\n entity: \"query\",\n display: { title: \"Contact Profile\" },\n args: [{ name: \"contact-ref\", required: true }],\n handler: contactsShowHandler,\n examples: [\"corp contacts show\", \"corp contacts show --json\"],\n },\n {\n name: \"contacts add\",\n description: \"Add a new contact\",\n route: { method: \"POST\", path: \"/v1/contacts\" },\n entity: true,\n options: [\n { flags: \"--name <name>\", description: \"Contact name\", required: true },\n { flags: \"--email <email>\", description: \"Contact email\", required: true },\n { flags: \"--type <type>\", description: \"Contact type (individual, organization)\", default: \"individual\" },\n { flags: \"--category <category>\", description: \"Category (employee, contractor, board_member, investor, law_firm, valuation_firm, accounting_firm, officer, founder, member, other)\" },\n { flags: \"--cap-table-access <level>\", description: \"Cap table access (none, summary, detailed)\" },\n { flags: \"--address <address>\", description: \"Mailing address\" },\n { flags: \"--mailing-address <address>\", description: \"Alias for --address\" },\n { flags: \"--phone <phone>\", description: \"Phone number\" },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n ],\n handler: contactsAddHandler,\n produces: { kind: \"contact\" },\n successTemplate: \"Contact created: {name}\",\n examples: [\"corp contacts add --name 'name' --email 'email'\", \"corp contacts add --json\"],\n },\n {\n name: \"contacts edit\",\n description: \"Edit an existing contact\",\n route: { method: \"PATCH\", path: \"/v1/contacts/{pos}\" },\n entity: true,\n args: [{ name: \"contact-ref\", required: true }],\n options: [\n { flags: \"--name <name>\", description: \"Contact name\" },\n { flags: \"--email <email>\", description: \"Contact email\" },\n { flags: \"--category <category>\", description: \"Contact category\" },\n { flags: \"--cap-table-access <level>\", description: \"Cap table access (none, summary, detailed)\" },\n { flags: \"--address <address>\", description: \"Mailing address\" },\n { flags: \"--mailing-address <address>\", description: \"Alias for --address\" },\n { flags: \"--phone <phone>\", description: \"Phone number\" },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n ],\n handler: contactsEditHandler,\n examples: [\"corp contacts edit <contact-ref>\", \"corp contacts edit --json\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"contacts notification-prefs\",\n description: \"View notification preferences for a contact\",\n route: { method: \"GET\", path: \"/v1/contacts/{pos}/notification-prefs\" },\n args: [{ name: \"contact-id\", required: true, description: \"Contact ID\" }],\n display: { title: \"Contacts Notification Prefs\", cols: [\"#contact_id>ID\", \"email_enabled>Email Enabled\", \"sms_enabled>Sms Enabled\", \"@updated_at>Updated At\", \"webhook_enabled>Webhook Enabled\"] },\n examples: [\"corp contacts notification-prefs\"],\n },\n {\n name: \"contacts update-notification-prefs\",\n description: \"View notification preferences for a contact\",\n route: { method: \"PATCH\", path: \"/v1/contacts/{pos}/notification-prefs\" },\n args: [{ name: \"contact-id\", required: true, description: \"Contact ID\" }],\n options: [\n { flags: \"--email-enabled <email-enabled>\", description: \"Email Enabled\" },\n { flags: \"--sms-enabled <sms-enabled>\", description: \"Sms Enabled\" },\n { flags: \"--webhook-enabled <webhook-enabled>\", description: \"Webhook Enabled\" },\n ],\n examples: [\"corp contacts notification-prefs <contact-id>\", \"corp contacts notification-prefs --json\"],\n successTemplate: \"Notification Prefs updated\",\n },\n\n];","import { CorpAPIClient } from \"./api-client.js\";\nimport { ReferenceResolver } from \"./references.js\";\nimport type { ApiRecord } from \"./types.js\";\n\nconst DEFAULT_SIGNATURE_CONSENT = \"I agree to sign this document electronically.\";\nconst DEFAULT_ATTESTATION_CONSENT = \"I attest the filing information is accurate and authorized.\";\n\ntype SignatureRequirement = {\n role: string;\n signer_name: string;\n signer_email?: string;\n};\n\nexport type AutoSignSummary = {\n documents_seen: number;\n documents_signed: number;\n signatures_added: number;\n documents: ApiRecord[];\n};\n\nexport type ActivationSummary = {\n entity_id: string;\n initial_status: string;\n final_status: string;\n signatures_added: number;\n documents_signed: number;\n steps: string[];\n formation: ApiRecord;\n};\n\nfunction normalizeRole(value: unknown): string {\n return String(value ?? \"\").trim().toLowerCase();\n}\n\nfunction fallbackSignerEmail(requirement: SignatureRequirement): string {\n const slug = String(requirement.signer_name ?? \"signer\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \".\")\n .replace(/^\\.+|\\.+$/g, \"\");\n return `${slug || \"signer\"}@example.com`;\n}\n\nfunction getSignatureRequirements(document: ApiRecord): SignatureRequirement[] {\n const content = document.content;\n if (!content || typeof content !== \"object\" || Array.isArray(content)) {\n return [];\n }\n const requirements = (content as ApiRecord).signature_requirements;\n if (!Array.isArray(requirements)) {\n return [];\n }\n return requirements\n .filter((item): item is ApiRecord => typeof item === \"object\" && item !== null && !Array.isArray(item))\n .map((item) => ({\n role: String(item.role ?? \"\").trim(),\n signer_name: String(item.signer_name ?? \"\").trim(),\n signer_email:\n typeof item.signer_email === \"string\" && item.signer_email.trim()\n ? item.signer_email.trim()\n : undefined,\n }))\n .filter((item) => item.role.length > 0 && item.signer_name.length > 0);\n}\n\nfunction getSignedRoles(document: ApiRecord): Set<string> {\n const signatures = Array.isArray(document.signatures) ? document.signatures : [];\n return new Set(\n signatures\n .filter((item): item is ApiRecord => typeof item === \"object\" && item !== null && !Array.isArray(item))\n .map((item) => normalizeRole(item.signer_role))\n .filter(Boolean),\n );\n}\n\nfunction deterministicEin(entityId: string): string {\n const digits = entityId.replace(/\\D/g, \"\");\n const nineDigits = `${digits}123456789`.slice(0, 9).padEnd(9, \"0\");\n return `${nineDigits.slice(0, 2)}-${nineDigits.slice(2)}`;\n}\n\nfunction filingIdentifier(prefix: string, entityId: string): string {\n const token = entityId.replace(/[^a-zA-Z0-9]/g, \"\").slice(0, 12).toLowerCase() || \"formation\";\n return `${prefix}-${token}`;\n}\n\nexport async function autoSignFormationDocument(\n client: CorpAPIClient,\n entityId: string,\n documentId: string,\n): Promise<{ document: ApiRecord; signatures_added: number }> {\n const document = await client.getDocument(documentId, entityId) as ApiRecord;\n const requiredSignatures = getSignatureRequirements(document);\n if (requiredSignatures.length === 0) {\n return { document, signatures_added: 0 };\n }\n\n const signedRoles = getSignedRoles(document);\n let signaturesAdded = 0;\n for (const requirement of requiredSignatures) {\n if (signedRoles.has(normalizeRole(requirement.role))) {\n continue;\n }\n await client.signDocument(documentId, entityId, {\n signer_name: requirement.signer_name,\n signer_role: requirement.role,\n signer_email: requirement.signer_email ?? fallbackSignerEmail(requirement),\n signature_text: requirement.signer_name,\n consent_text: DEFAULT_SIGNATURE_CONSENT,\n });\n signedRoles.add(normalizeRole(requirement.role));\n signaturesAdded += 1;\n }\n\n const refreshed = await client.getDocument(documentId, entityId) as ApiRecord;\n return { document: refreshed, signatures_added: signaturesAdded };\n}\n\nexport async function autoSignFormationDocuments(\n client: CorpAPIClient,\n resolver: ReferenceResolver,\n entityId: string,\n): Promise<AutoSignSummary> {\n const summaries = await client.getEntityDocuments(entityId) as ApiRecord[];\n await resolver.stabilizeRecords(\"document\", summaries, entityId);\n\n let signaturesAdded = 0;\n let documentsSigned = 0;\n const documents: ApiRecord[] = [];\n\n for (const summary of summaries) {\n const documentId = String(summary.document_id ?? \"\");\n if (!documentId) {\n continue;\n }\n const { document, signatures_added } = await autoSignFormationDocument(\n client,\n entityId,\n documentId,\n );\n signaturesAdded += signatures_added;\n if (signatures_added > 0) {\n documentsSigned += 1;\n }\n documents.push(document);\n }\n\n return {\n documents_seen: summaries.length,\n documents_signed: documentsSigned,\n signatures_added: signaturesAdded,\n documents,\n };\n}\n\nexport async function activateFormationEntity(\n client: CorpAPIClient,\n resolver: ReferenceResolver,\n entityId: string,\n options: {\n evidenceUri?: string;\n evidenceType?: string;\n filingId?: string;\n receiptReference?: string;\n ein?: string;\n } = {},\n): Promise<ActivationSummary> {\n let formation = await client.getFormation(entityId) as ApiRecord;\n const initialStatus = String(formation.formation_status ?? \"\");\n const steps: string[] = [];\n let signaturesAdded = 0;\n let documentsSigned = 0;\n\n for (let i = 0; i < 10; i += 1) {\n const status = String(formation.formation_status ?? \"\");\n if (status === \"active\") {\n if (initialStatus === \"active\") {\n steps.push(\"entity is already active — no action needed\");\n }\n return {\n entity_id: entityId,\n initial_status: initialStatus,\n final_status: status,\n signatures_added: signaturesAdded,\n documents_signed: documentsSigned,\n steps,\n formation,\n };\n }\n\n if (status === \"pending\") {\n throw new Error(\n \"Formation is still pending — finalize before activation.\\n\" +\n \" Run: corp form finalize \" + entityId,\n );\n }\n\n if (status === \"documents_generated\") {\n const signed = await autoSignFormationDocuments(client, resolver, entityId);\n signaturesAdded += signed.signatures_added;\n documentsSigned += signed.documents_signed;\n await client.markFormationDocumentsSigned(entityId);\n steps.push(`signed ${signed.signatures_added} signatures across ${signed.documents_signed} documents`);\n formation = await client.getFormation(entityId) as ApiRecord;\n continue;\n }\n\n if (status === \"documents_signed\") {\n const gates = await client.getFormationGates(entityId);\n if (gates.requires_natural_person_attestation && !gates.attestation_recorded) {\n await client.recordFilingAttestation(entityId, {\n signer_name: gates.designated_attestor_name,\n signer_role: gates.designated_attestor_role,\n signer_email: gates.designated_attestor_email ?? fallbackSignerEmail({\n role: String(gates.designated_attestor_role ?? \"attestor\"),\n signer_name: String(gates.designated_attestor_name ?? \"attestor\"),\n }),\n consent_text: DEFAULT_ATTESTATION_CONSENT,\n notes: \"Recorded automatically by corp form activate\",\n });\n steps.push(\"recorded filing attestation\");\n }\n const gatesAfterAttestation = await client.getFormationGates(entityId);\n if (\n gatesAfterAttestation.requires_registered_agent_consent_evidence\n && Number(gatesAfterAttestation.registered_agent_consent_evidence_count ?? 0) === 0\n ) {\n await client.addRegisteredAgentConsentEvidence(entityId, {\n evidence_uri: options.evidenceUri ?? `generated://registered-agent-consent/${entityId}`,\n evidence_type: options.evidenceType ?? \"generated\",\n notes: \"Recorded automatically by corp form activate\",\n });\n steps.push(\"recorded registered-agent consent evidence\");\n }\n const finalGates = await client.getFormationGates(entityId);\n if (Array.isArray(finalGates.filing_submission_blockers) && finalGates.filing_submission_blockers.length > 0) {\n throw new Error(\n `Formation filing is still blocked: ${finalGates.filing_submission_blockers.join(\"; \")}`,\n );\n }\n await client.submitFiling(entityId);\n steps.push(\"submitted filing\");\n formation = await client.getFormation(entityId) as ApiRecord;\n continue;\n }\n\n if (status === \"filing_submitted\") {\n await client.confirmFiling(entityId, {\n external_filing_id: options.filingId ?? filingIdentifier(\"sim\", entityId),\n receipt_reference: options.receiptReference ?? filingIdentifier(\"receipt\", entityId),\n });\n steps.push(\"confirmed filing\");\n formation = await client.getFormation(entityId) as ApiRecord;\n continue;\n }\n\n if (status === \"filed\") {\n await client.applyEin(entityId);\n steps.push(\"submitted EIN application\");\n formation = await client.getFormation(entityId) as ApiRecord;\n continue;\n }\n\n if (status === \"ein_applied\") {\n await client.confirmEin(entityId, { ein: options.ein ?? deterministicEin(entityId) });\n steps.push(\"confirmed EIN\");\n formation = await client.getFormation(entityId) as ApiRecord;\n continue;\n }\n\n throw new Error(`Unsupported formation status for activation: ${status || \"unknown\"}`);\n }\n\n throw new Error(\"Formation activation did not converge within 10 steps.\");\n}\n","import { input, select, confirm, number } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport { relative, resolve } from \"node:path\";\nimport { requireConfig, setActiveEntityId, saveConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printDryRun, printError, printJson, printReferenceSummary, printSuccess } from \"../output.js\";\nimport { ReferenceResolver } from \"../references.js\";\nimport type { ApiRecord } from \"../types.js\";\nimport { EntityType, OfficerTitle } from \"@thecorporation/corp-tools\";\nimport { activateFormationEntity } from \"../formation-automation.js\";\n\n// ── Types ──────────────────────────────────────────────────────\n\ninterface FounderInfo {\n name: string;\n email: string;\n role: string;\n address?: { street: string; street2?: string; city: string; state: string; zip: string };\n officer_title?: string;\n is_incorporator?: boolean;\n shares_purchased?: number;\n ownership_pct?: number;\n vesting?: { total_months: number; cliff_months: number; acceleration?: string };\n ip_description?: string;\n}\n\ninterface FormOptions {\n type?: string;\n name?: string;\n jurisdiction?: string;\n member?: string[];\n memberJson?: string[];\n membersFile?: string;\n fiscalYearEnd?: string;\n sCorp?: boolean;\n transferRestrictions?: boolean;\n rofr?: boolean;\n address?: string;\n principalName?: string;\n json?: boolean;\n dryRun?: boolean;\n quiet?: boolean;\n}\n\n// ── Helpers ────────────────────────────────────────────────────\n\nfunction isCorp(entityType: string): boolean {\n return entityType === \"c_corp\" || entityType === \"s_corp\" || entityType === \"corporation\";\n}\n\nfunction sectionHeader(title: string): void {\n console.log();\n console.log(chalk.blue(\"─\".repeat(50)));\n console.log(chalk.blue.bold(` ${title}`));\n console.log(chalk.blue(\"─\".repeat(50)));\n}\n\nfunction officerTitleLabel(title: string): string {\n switch (title) {\n case \"ceo\":\n return \"CEO\";\n case \"cfo\":\n return \"CFO\";\n case \"cto\":\n return \"CTO\";\n case \"coo\":\n return \"COO\";\n case \"vp\":\n return \"VP\";\n default:\n return title.charAt(0).toUpperCase() + title.slice(1);\n }\n}\n\nfunction parseBoolean(value: unknown): boolean | undefined {\n if (typeof value === \"boolean\") return value;\n if (typeof value !== \"string\") return undefined;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n return undefined;\n}\n\nfunction parseAddressValue(raw: unknown): FounderInfo[\"address\"] {\n if (!raw) return undefined;\n if (typeof raw === \"string\") {\n const parts = raw.split(\"|\").map((part) => part.trim());\n if (parts.length === 4) {\n return { street: parts[0], city: parts[1], state: parts[2], zip: parts[3] };\n }\n throw new Error(`Invalid founder address: ${raw}. Expected street|city|state|zip.`);\n }\n if (typeof raw === \"object\" && raw !== null) {\n const value = raw as Record<string, unknown>;\n if (\n typeof value.street === \"string\" &&\n typeof value.city === \"string\" &&\n typeof value.state === \"string\" &&\n typeof value.zip === \"string\"\n ) {\n return {\n street: value.street,\n street2: typeof value.street2 === \"string\" ? value.street2 : undefined,\n city: value.city,\n state: value.state,\n zip: value.zip,\n };\n }\n }\n throw new Error(\"Founder address must be an object or street|city|state|zip string.\");\n}\n\nfunction normalizeFounderInfo(input: Record<string, unknown>): FounderInfo {\n const name = typeof input.name === \"string\" ? input.name.trim() : \"\";\n const email = typeof input.email === \"string\" ? input.email.trim() : \"\";\n const role = typeof input.role === \"string\" ? input.role.trim() : \"\";\n if (!name || !email || !role) {\n throw new Error(\"Founder JSON requires non-empty name, email, and role.\");\n }\n\n const founder: FounderInfo = { name, email, role };\n const ownershipPct = input.ownership_pct ?? input.membership_pct ?? input.pct;\n if (ownershipPct != null) founder.ownership_pct = Number(ownershipPct);\n const sharesPurchased = input.shares_purchased ?? input.shares;\n if (sharesPurchased != null) founder.shares_purchased = Number(sharesPurchased);\n if (typeof input.officer_title === \"string\") founder.officer_title = input.officer_title;\n const incorporator = parseBoolean(input.is_incorporator ?? input.incorporator);\n if (incorporator !== undefined) founder.is_incorporator = incorporator;\n if (input.address != null) founder.address = parseAddressValue(input.address);\n if (typeof input.ip_description === \"string\") founder.ip_description = input.ip_description;\n if (input.vesting && typeof input.vesting === \"object\") {\n const vesting = input.vesting as Record<string, unknown>;\n if (vesting.total_months != null && vesting.cliff_months != null) {\n founder.vesting = {\n total_months: Number(vesting.total_months),\n cliff_months: Number(vesting.cliff_months),\n acceleration:\n typeof vesting.acceleration === \"string\" ? vesting.acceleration : undefined,\n };\n }\n }\n return founder;\n}\n\nfunction parseLegacyMemberSpec(raw: string): FounderInfo {\n const parts = raw.split(\",\").map((p) => p.trim());\n if (parts.length < 3) {\n throw new Error(\n `Invalid member format: ${raw}. Expected: name,email,role[,pct[,street|city|state|zip[,officer_title[,is_incorporator]]]]`,\n );\n }\n const founder: FounderInfo = { name: parts[0], email: parts[1], role: parts[2] };\n if (parts.length >= 4) founder.ownership_pct = parseFloat(parts[3]);\n if (parts.length >= 5 && parts[4]) founder.address = parseAddressValue(parts[4]);\n if (parts.length >= 6 && parts[5]) founder.officer_title = parts[5];\n if (parts.length >= 7) {\n const incorporator = parseBoolean(parts[6]);\n if (incorporator !== undefined) founder.is_incorporator = incorporator;\n }\n return founder;\n}\n\nfunction parseKeyValueMemberSpec(raw: string): FounderInfo {\n const parsed: Record<string, unknown> = {};\n for (const segment of raw.split(\",\")) {\n const [key, ...rest] = segment.split(\"=\");\n if (!key || rest.length === 0) {\n throw new Error(`Invalid member format: ${raw}. Expected key=value pairs.`);\n }\n parsed[key.trim()] = rest.join(\"=\").trim();\n }\n return normalizeFounderInfo(parsed);\n}\n\nfunction readSafeJsonFile(filePath: string, label: string): string {\n if (process.env.CORP_ALLOW_UNSAFE_FILE_INPUT === \"1\") {\n return readFileSync(filePath, \"utf8\");\n }\n const resolvedFile = realpathSync(resolve(filePath));\n const workingTreeRoot = realpathSync(process.cwd());\n const rel = relative(workingTreeRoot, resolvedFile);\n if (rel === \"\" || (!rel.startsWith(\"..\") && !rel.startsWith(\"/\"))) {\n return readFileSync(resolvedFile, \"utf8\");\n }\n throw new Error(\n `--${label} must stay inside the current working directory unless CORP_ALLOW_UNSAFE_FILE_INPUT=1 is set.`,\n );\n}\n\nfunction validateFounders(founders: FounderInfo[]): void {\n // Check for duplicate emails\n const seenEmails = new Set<string>();\n for (const f of founders) {\n const email = f.email.toLowerCase().trim();\n if (seenEmails.has(email)) {\n throw new Error(`Duplicate founder email: ${email}. Each founder must have a unique email address.`);\n }\n seenEmails.add(email);\n }\n\n // Check total ownership doesn't exceed 100%\n let totalOwnership = 0;\n for (const f of founders) {\n if (f.ownership_pct != null) {\n if (f.ownership_pct <= 0 || f.ownership_pct > 100) {\n throw new Error(`Invalid ownership_pct ${f.ownership_pct} for ${f.name}. Must be between 0 and 100.`);\n }\n totalOwnership += f.ownership_pct;\n }\n }\n if (totalOwnership > 100.000001) {\n throw new Error(`Total ownership_pct is ${totalOwnership.toFixed(2)}%, which exceeds 100%. Reduce ownership percentages.`);\n }\n}\n\nfunction parseScriptedFounders(opts: FormOptions): FounderInfo[] {\n const founders: FounderInfo[] = [];\n for (const raw of opts.member ?? []) {\n founders.push(raw.includes(\"=\") ? parseKeyValueMemberSpec(raw) : parseLegacyMemberSpec(raw));\n }\n for (const raw of opts.memberJson ?? []) {\n founders.push(normalizeFounderInfo(JSON.parse(raw) as Record<string, unknown>));\n }\n if (opts.membersFile) {\n const parsed = JSON.parse(readSafeJsonFile(opts.membersFile, \"members-file\")) as unknown;\n let entries: unknown[];\n if (Array.isArray(parsed)) {\n entries = parsed;\n } else if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n \"members\" in parsed &&\n Array.isArray((parsed as { members?: unknown }).members)\n ) {\n entries = (parsed as { members: unknown[] }).members;\n } else {\n throw new Error(\"members file must be a JSON array or {\\\"members\\\": [...]}\");\n }\n for (const entry of entries) {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n throw new Error(\"each founder entry must be a JSON object\");\n }\n founders.push(normalizeFounderInfo(entry as Record<string, unknown>));\n }\n }\n validateFounders(founders);\n return founders;\n}\n\nasync function promptAddress(): Promise<{ street: string; city: string; state: string; zip: string }> {\n const street = await input({ message: \" Street address\" });\n const city = await input({ message: \" City\" });\n const state = await input({ message: \" State (2-letter)\", default: \"DE\" });\n const zip = await input({ message: \" ZIP code\" });\n return { street, city, state, zip };\n}\n\n// ── Phase 1: Entity Details ────────────────────────────────────\n\nasync function phaseEntityDetails(opts: FormOptions, serverCfg: ApiRecord, scripted: boolean) {\n if (!scripted) sectionHeader(\"Phase 1: Entity Details\");\n\n let entityType = opts.type;\n if (!entityType) {\n if (scripted) { entityType = \"llc\"; }\n else {\n entityType = await select({\n message: \"Entity type\",\n choices: [\n { value: \"llc\", name: \"LLC\" },\n { value: \"c_corp\", name: \"C-Corp\" },\n ],\n });\n }\n }\n\n let name = opts.name;\n if (!name) {\n if (scripted) { printError(\"--name is required in scripted mode\"); process.exit(1); }\n name = await input({ message: \"Legal name\" });\n }\n\n let jurisdiction = opts.jurisdiction;\n if (!jurisdiction) {\n const defaultJ = entityType === \"llc\" ? \"US-WY\" : \"US-DE\";\n if (scripted) { jurisdiction = defaultJ; }\n else { jurisdiction = await input({ message: \"Jurisdiction\", default: defaultJ }); }\n }\n\n let companyAddress: { street: string; city: string; state: string; zip: string } | undefined;\n if (opts.address) {\n const parts = opts.address.split(\",\").map((p) => p.trim());\n if (parts.length === 4) {\n companyAddress = { street: parts[0], city: parts[1], state: parts[2], zip: parts[3] };\n }\n }\n if (!companyAddress && !scripted) {\n const wantAddress = await confirm({ message: \"Add company address?\", default: false });\n if (wantAddress) {\n companyAddress = await promptAddress();\n }\n }\n\n const fiscalYearEnd = opts.fiscalYearEnd ?? \"12-31\";\n\n let sCorpElection = opts.sCorp ?? false;\n if (!scripted && isCorp(entityType) && opts.sCorp === undefined) {\n sCorpElection = await confirm({ message: \"S-Corp election?\", default: false });\n }\n\n return { entityType, name, jurisdiction, companyAddress, fiscalYearEnd, sCorpElection };\n}\n\n// ── Phase 2: People ────────────────────────────────────────────\n\nasync function phasePeople(\n opts: FormOptions,\n entityType: string,\n scripted: boolean,\n): Promise<FounderInfo[]> {\n if (!scripted) sectionHeader(\"Phase 2: Founders & Officers\");\n\n const founders: FounderInfo[] = [];\n\n // CLI-provided members (scripted mode)\n if (scripted) {\n try {\n return parseScriptedFounders(opts);\n } catch (err) {\n printError(String(err));\n process.exit(1);\n }\n }\n\n // Interactive mode\n const founderCount = (await number({ message: \"Number of founders (1-6)\", default: 1 })) ?? 1;\n\n for (let i = 0; i < founderCount; i++) {\n console.log(chalk.dim(`\\n Founder ${i + 1} of ${founderCount}:`));\n const name = await input({ message: ` Name` });\n const email = await input({ message: ` Email` });\n\n let role = \"member\";\n if (isCorp(entityType)) {\n role = await select({\n message: \" Role\",\n choices: [\n { value: \"director\", name: \"Director\" },\n { value: \"officer\", name: \"Officer\" },\n { value: \"member\", name: \"Shareholder only\" },\n ],\n });\n }\n\n const wantAddress = await confirm({ message: \" Add address?\", default: false });\n const address = wantAddress ? await promptAddress() : undefined;\n\n let officerTitle: string | undefined;\n if (isCorp(entityType)) {\n const wantOfficer = role === \"officer\" || await confirm({ message: \" Assign officer title?\", default: i === 0 });\n if (wantOfficer) {\n officerTitle = await select({\n message: \" Officer title\",\n choices: OfficerTitle.map((t) => ({\n value: t,\n name: officerTitleLabel(t),\n })),\n });\n }\n }\n\n let isIncorporator = false;\n if (isCorp(entityType) && i === 0 && founderCount === 1) {\n isIncorporator = true;\n } else if (isCorp(entityType)) {\n isIncorporator = await confirm({ message: \" Designate as sole incorporator?\", default: i === 0 });\n }\n\n founders.push({ name, email, role, address, officer_title: officerTitle, is_incorporator: isIncorporator });\n }\n\n return founders;\n}\n\n// ── Phase 3: Stock & Finalize ──────────────────────────────────\n\nasync function phaseStock(\n opts: FormOptions,\n entityType: string,\n founders: FounderInfo[],\n scripted: boolean,\n): Promise<{ founders: FounderInfo[]; transferRestrictions: boolean; rofr: boolean }> {\n if (!scripted) sectionHeader(\"Phase 3: Equity & Finalize\");\n\n const transferRestrictions = opts.transferRestrictions ?? (\n !scripted && isCorp(entityType)\n ? await confirm({ message: \"Transfer restrictions on shares?\", default: true })\n : isCorp(entityType)\n );\n\n const rofr = opts.rofr ?? (\n !scripted && isCorp(entityType)\n ? await confirm({ message: \"Right of first refusal?\", default: true })\n : isCorp(entityType)\n );\n\n if (!scripted) {\n for (const f of founders) {\n console.log(chalk.dim(`\\n Equity for ${f.name}:`));\n\n if (isCorp(entityType)) {\n const shares = await number({ message: ` Shares to purchase`, default: 0 });\n f.shares_purchased = shares ?? 0;\n if (f.shares_purchased === 0) {\n const pct = await number({ message: ` Ownership % (1-100)`, default: founders.length === 1 ? 100 : 0 });\n f.ownership_pct = pct ?? 0;\n }\n } else {\n const pct = await number({\n message: ` Ownership % (1-100)`,\n default: founders.length === 1 ? 100 : 0,\n });\n f.ownership_pct = pct ?? 0;\n }\n\n if (isCorp(entityType)) {\n const wantVesting = await confirm({ message: \" Add vesting schedule?\", default: false });\n if (wantVesting) {\n const totalMonths = (await number({ message: \" Total vesting months\", default: 48 })) ?? 48;\n const cliffMonths = (await number({ message: \" Cliff months\", default: 12 })) ?? 12;\n const acceleration = await select({\n message: \" Acceleration\",\n choices: [\n { value: \"none\", name: \"None\" },\n { value: \"single_trigger\", name: \"Single trigger\" },\n { value: \"double_trigger\", name: \"Double trigger\" },\n ],\n });\n f.vesting = {\n total_months: totalMonths,\n cliff_months: cliffMonths,\n acceleration: acceleration === \"none\" ? undefined : acceleration,\n };\n }\n }\n\n const wantIp = await confirm({ message: \" Contributing IP?\", default: false });\n if (wantIp) {\n f.ip_description = await input({ message: \" Describe IP being contributed\" });\n }\n }\n }\n\n return { founders, transferRestrictions, rofr };\n}\n\n// ── Summary Table ──────────────────────────────────────────────\n\nfunction printSummary(\n entityType: string,\n name: string,\n jurisdiction: string,\n fiscalYearEnd: string,\n sCorpElection: boolean,\n founders: FounderInfo[],\n transferRestrictions: boolean,\n rofr: boolean,\n): void {\n sectionHeader(\"Formation Summary\");\n\n console.log(` ${chalk.bold(\"Entity:\")} ${name}`);\n console.log(` ${chalk.bold(\"Type:\")} ${entityType}`);\n console.log(` ${chalk.bold(\"Jurisdiction:\")} ${jurisdiction}`);\n console.log(` ${chalk.bold(\"Fiscal Year End:\")} ${fiscalYearEnd}`);\n if (isCorp(entityType)) {\n console.log(` ${chalk.bold(\"S-Corp Election:\")} ${sCorpElection ? \"Yes\" : \"No\"}`);\n console.log(` ${chalk.bold(\"Transfer Restrictions:\")} ${transferRestrictions ? \"Yes\" : \"No\"}`);\n console.log(` ${chalk.bold(\"Right of First Refusal:\")} ${rofr ? \"Yes\" : \"No\"}`);\n }\n\n const table = new Table({\n head: [chalk.dim(\"Name\"), chalk.dim(\"Email\"), chalk.dim(\"Role\"), chalk.dim(\"Equity\"), chalk.dim(\"Officer\")],\n });\n for (const f of founders) {\n const equity = f.shares_purchased\n ? `${f.shares_purchased.toLocaleString()} shares`\n : f.ownership_pct\n ? `${f.ownership_pct}%`\n : \"—\";\n table.push([f.name, f.email, f.role, equity, f.officer_title ?? \"—\"]);\n }\n console.log(table.toString());\n}\n\n// ── Main Command ───────────────────────────────────────────────\n\nconst SUPPORTED_ENTITY_TYPES = [\"llc\", \"c_corp\", \"s_corp\", \"corporation\"];\n\nexport async function formCommand(opts: FormOptions): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n // Client-side type validation\n if (opts.type && !SUPPORTED_ENTITY_TYPES.includes(opts.type)) {\n printError(`Unsupported entity type '${opts.type}'. Supported types: ${SUPPORTED_ENTITY_TYPES.join(\", \")}`);\n process.exit(1);\n }\n // Client-side name validation\n if (opts.name != null && !opts.name.trim()) {\n printError(\"--name cannot be empty or whitespace\");\n process.exit(1);\n }\n\n let serverCfg: ApiRecord = {};\n try { serverCfg = await client.getConfig(); } catch { /* ignore */ }\n\n const hasMembers = Boolean(\n (opts.member && opts.member.length > 0) ||\n (opts.memberJson && opts.memberJson.length > 0) ||\n opts.membersFile,\n );\n const scripted = hasMembers || opts.json || opts.dryRun || !process.stdout.isTTY;\n\n // If non-TTY/json/dryRun and no members provided, error early instead of prompting\n if (scripted && !hasMembers) {\n printError(\"At least one --member, --member-json, or --members-file is required in non-interactive mode.\");\n process.exit(1);\n }\n\n // Phase 1: Entity Details\n const { entityType, name, jurisdiction, companyAddress, fiscalYearEnd, sCorpElection } =\n await phaseEntityDetails(opts, serverCfg, scripted);\n\n // Phase 2: People\n const founders = await phasePeople(opts, entityType, scripted);\n\n // C-Corp upfront validation — check all requirements at once\n if (isCorp(entityType) && scripted) {\n const missing: string[] = [];\n const hasAddress = founders.some((f) => f.address);\n const hasOfficer = founders.some((f) => f.officer_title);\n const hasIncorporator = founders.some((f) => f.is_incorporator);\n if (!hasAddress) missing.push(\"At least one member with an address (for incorporator filing)\");\n if (!hasOfficer) missing.push(\"At least one member with --officer-title (for initial board consent)\");\n if (!hasIncorporator && founders.length === 1) {\n // Single founder auto-marked as incorporator, no error needed\n } else if (!hasIncorporator && founders.length > 1) {\n missing.push(\"At least one member marked as --incorporator\");\n }\n if (missing.length > 0) {\n printError(\n \"C-Corp formation requires:\\n\" +\n missing.map((m) => ` - ${m}`).join(\"\\n\") + \"\\n\" +\n ' Example: --member \"Name,email,director,100,street|city|state|zip,ceo,true\"',\n );\n process.exit(1);\n }\n }\n\n // Phase 3: Stock & Finalize\n const { transferRestrictions, rofr } = await phaseStock(opts, entityType, founders, scripted);\n\n // Summary & Confirm (suppress for --json and --quiet to keep output clean)\n if (!opts.quiet && !opts.json) {\n printSummary(entityType, name, jurisdiction, fiscalYearEnd, sCorpElection, founders, transferRestrictions, rofr);\n }\n\n const shouldProceed = scripted\n ? true\n : await confirm({ message: \"Proceed with formation?\", default: true });\n\n if (!shouldProceed) {\n console.log(chalk.yellow(\"Formation cancelled.\"));\n return;\n }\n\n // Build members payload\n const members: ApiRecord[] = founders.map((f) => {\n const m: ApiRecord = {\n name: f.name,\n email: f.email,\n role: f.role,\n investor_type: \"natural_person\",\n };\n if (f.ownership_pct) m.ownership_pct = f.ownership_pct;\n if (f.shares_purchased) m.shares_purchased = f.shares_purchased;\n if (f.address) m.address = f.address;\n if (f.officer_title) m.officer_title = f.officer_title;\n if (f.is_incorporator) m.is_incorporator = true;\n if (f.vesting) m.vesting = f.vesting;\n if (f.ip_description) m.ip_description = f.ip_description;\n return m;\n });\n\n const payload: ApiRecord = {\n entity_type: entityType,\n legal_name: name,\n jurisdiction,\n members,\n workspace_id: cfg.workspace_id,\n fiscal_year_end: fiscalYearEnd,\n s_corp_election: sCorpElection,\n transfer_restrictions: transferRestrictions,\n right_of_first_refusal: rofr,\n };\n if (companyAddress) payload.company_address = companyAddress;\n // LLC: auto-set principal_name from first member if not explicitly provided\n if (entityType === \"llc\") {\n const principalName = opts.principalName ?? founders[0]?.name;\n if (principalName) payload.principal_name = principalName;\n }\n\n if (opts.dryRun) {\n printDryRun(\"formation.create_with_cap_table\", payload);\n return;\n }\n\n const result = await client.createFormationWithCapTable(payload);\n await resolver.stabilizeRecord(\"entity\", result);\n resolver.rememberFromRecord(\"entity\", result);\n\n if (result.entity_id) {\n setActiveEntityId(cfg, String(result.entity_id));\n saveConfig(cfg);\n }\n\n if (opts.quiet) {\n const id = result.entity_id ?? result.formation_id;\n if (id) console.log(String(id));\n return;\n }\n\n if (opts.json) {\n printJson(result);\n return;\n }\n\n if (result.entity_id) {\n console.log(chalk.dim(` Active entity set to ${result.entity_id}`));\n }\n\n // Output results\n printSuccess(`Formation created: ${result.formation_id ?? \"OK\"}`);\n if (result.entity_id) {\n printReferenceSummary(\"entity\", result, { showReuseHint: true });\n }\n if (result.legal_entity_id) console.log(` Legal Entity ID: ${result.legal_entity_id}`);\n if (result.instrument_id) console.log(` Instrument ID: ${result.instrument_id}`);\n\n const docIds = (result.document_ids ?? []) as string[];\n if (docIds.length > 0) {\n console.log(` Documents: ${docIds.length} generated`);\n }\n\n const holders = (result.holders ?? []) as ApiRecord[];\n if (holders.length > 0) {\n console.log();\n const table = new Table({\n head: [chalk.dim(\"Holder\"), chalk.dim(\"Shares\"), chalk.dim(\"Ownership %\")],\n });\n for (const h of holders) {\n const pct = typeof h.ownership_pct === \"number\" ? `${h.ownership_pct.toFixed(1)}%` : \"—\";\n table.push([String(h.name ?? \"?\"), String(h.shares ?? 0), pct]);\n }\n console.log(chalk.bold(\" Cap Table:\"));\n console.log(table.toString());\n }\n\n if (result.next_action) {\n const entityRef = result.entity_id ? `${result.entity_id}` : \"@last:entity\";\n const actionHint: Record<string, string> = {\n sign_documents: `corp form activate ${entityRef}`,\n submit_state_filing: `corp form activate ${entityRef}`,\n confirm_state_filing: `corp form activate ${entityRef} --filing-id \"...\"`,\n apply_for_ein: `corp form activate ${entityRef}`,\n confirm_ein: `corp form activate ${entityRef} --ein \"...\"`,\n };\n const hint = actionHint[result.next_action as string];\n if (hint) {\n console.log(chalk.yellow(`\\n Next step: ${hint}`));\n } else {\n console.log(chalk.yellow(`\\n Next: ${result.next_action}`));\n }\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes(\"exit\")) throw err;\n const msg = String(err);\n const hints: string[] = [];\n if (msg.includes(\"incorporator_address\")) {\n hints.push(\"Add an address to a founder: --member \\\"Name,email,director,100,street|city|state|zip,ceo,true\\\"\");\n }\n if (msg.includes(\"company_address\")) {\n hints.push(\"Add --address \\\"street,city,state,zip\\\" for the company address (required for C-Corps)\");\n }\n if (msg.includes(\"principal_name\")) {\n hints.push(\"Add --principal-name \\\"Manager Name\\\" (auto-set from first member for LLCs)\");\n }\n if (msg.includes(\"officers_list\") || msg.includes(\"officer\")) {\n hints.push(\"C-Corp directors need an officer_title: --member \\\"Name,email,director,100,,,ceo\\\"\");\n }\n if (hints.length > 0) {\n printError(\n `Formation failed: ${msg}\\n\\n` +\n \" Missing fields — fix all at once:\\n\" +\n hints.map((h) => ` - ${h}`).join(\"\\n\"),\n );\n } else {\n printError(`Failed to create formation: ${err}`);\n }\n process.exit(1);\n }\n}\n\n// ── Staged Formation Subcommands ─────────────────────────────\n\ninterface FormCreateOptions {\n type: string;\n name: string;\n jurisdiction?: string;\n registeredAgentName?: string;\n registeredAgentAddress?: string;\n formationDate?: string;\n fiscalYearEnd?: string;\n sCorp?: boolean;\n transferRestrictions?: boolean;\n rofr?: boolean;\n companyAddress?: string;\n dryRun?: boolean;\n json?: boolean;\n quiet?: boolean;\n}\n\nfunction parseCsvAddress(raw?: string): { street: string; city: string; state: string; zip: string } | undefined {\n if (!raw) return undefined;\n const parts = raw.split(\",\").map((p) => p.trim()).filter(Boolean);\n if (parts.length !== 4) {\n throw new Error(`Invalid address format: ${raw}. Expected 'street,city,state,zip'`);\n }\n return { street: parts[0], city: parts[1], state: parts[2], zip: parts[3] };\n}\n\nfunction shouldResolveEntityRefForDryRun(entityRef: string): boolean {\n const trimmed = entityRef.trim().toLowerCase();\n return trimmed === \"_\" || trimmed === \"@last\" || trimmed.startsWith(\"@last:\");\n}\n\nasync function resolveEntityRefForFormCommand(\n resolver: ReferenceResolver,\n entityRef: string,\n dryRun?: boolean,\n): Promise<string> {\n if (!dryRun || shouldResolveEntityRefForDryRun(entityRef)) {\n return resolver.resolveEntity(entityRef);\n }\n try {\n return await resolver.resolveEntity(entityRef);\n } catch (err) {\n if (String(err).includes(\"fetch failed\")) {\n return entityRef;\n }\n throw err;\n }\n}\n\nexport async function formCreateCommand(opts: FormCreateOptions): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n const entityType = opts.type === \"corporation\" ? \"c_corp\" : opts.type;\n const payload: ApiRecord = {\n entity_type: entityType,\n legal_name: opts.name,\n };\n if (opts.jurisdiction) payload.jurisdiction = opts.jurisdiction;\n if (opts.registeredAgentName) payload.registered_agent_name = opts.registeredAgentName;\n if (opts.registeredAgentAddress) payload.registered_agent_address = opts.registeredAgentAddress;\n if (opts.formationDate) payload.formation_date = opts.formationDate;\n if (opts.fiscalYearEnd) payload.fiscal_year_end = opts.fiscalYearEnd;\n if (opts.sCorp !== undefined) payload.s_corp_election = opts.sCorp;\n if (opts.transferRestrictions !== undefined) payload.transfer_restrictions = opts.transferRestrictions;\n if (opts.rofr !== undefined) payload.right_of_first_refusal = opts.rofr;\n const companyAddress = parseCsvAddress(opts.companyAddress);\n if (companyAddress) payload.company_address = companyAddress;\n\n if (opts.dryRun) {\n printDryRun(\"formation.create_pending\", payload);\n return;\n }\n\n const result = await client.createPendingEntity(payload);\n await resolver.stabilizeRecord(\"entity\", result);\n resolver.rememberFromRecord(\"entity\", result);\n\n if (result.entity_id) {\n setActiveEntityId(cfg, String(result.entity_id));\n saveConfig(cfg);\n }\n\n if (opts.quiet) {\n const id = result.entity_id;\n if (id) console.log(String(id));\n return;\n }\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(`Pending entity created: ${result.entity_id}`);\n printReferenceSummary(\"entity\", result, { showReuseHint: true });\n console.log(` Name: ${result.legal_name}`);\n console.log(` Type: ${result.entity_type}`);\n console.log(` Jurisdiction: ${result.jurisdiction}`);\n console.log(` Status: ${result.formation_status}`);\n console.log(chalk.yellow(`\\n Next: corp form add-founder @last:entity --name \"...\" --email \"...\" --role member --pct 50`));\n } catch (err) {\n printError(`Failed to create pending entity: ${err}`);\n process.exit(1);\n }\n}\n\ninterface FormAddFounderOptions {\n name: string;\n email: string;\n role: string;\n pct: string;\n officerTitle?: string;\n incorporator?: boolean;\n address?: string;\n dryRun?: boolean;\n json?: boolean;\n}\n\ninterface FormFinalizeOptions {\n authorizedShares?: string;\n parValue?: string;\n boardSize?: string;\n principalName?: string;\n registeredAgentName?: string;\n registeredAgentAddress?: string;\n formationDate?: string;\n fiscalYearEnd?: string;\n sCorp?: boolean;\n transferRestrictions?: boolean;\n rofr?: boolean;\n companyAddress?: string;\n incorporatorName?: string;\n incorporatorAddress?: string;\n dryRun?: boolean;\n json?: boolean;\n}\n\ninterface FormActivateOptions {\n evidenceUri?: string;\n evidenceType?: string;\n filingId?: string;\n receiptReference?: string;\n ein?: string;\n dryRun?: boolean;\n json?: boolean;\n}\n\nexport async function formAddFounderCommand(entityId: string, opts: FormAddFounderOptions): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n const resolvedEntityId = await resolveEntityRefForFormCommand(resolver, entityId, opts.dryRun);\n const payload: ApiRecord = {\n name: opts.name,\n email: opts.email,\n role: opts.role,\n ownership_pct: parseFloat(opts.pct),\n };\n if (opts.officerTitle) payload.officer_title = opts.officerTitle.toLowerCase();\n if (opts.incorporator) payload.is_incorporator = true;\n const address = parseCsvAddress(opts.address);\n if (address) payload.address = address;\n\n if (opts.dryRun) {\n printDryRun(\"formation.add_founder\", { entity_id: resolvedEntityId, ...payload });\n return;\n }\n\n const result = await client.addFounder(resolvedEntityId, payload);\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(`Founder added (${result.member_count} total)`);\n const members = (result.members ?? []) as ApiRecord[];\n for (const m of members) {\n const pct = typeof m.ownership_pct === \"number\" ? ` (${m.ownership_pct}%)` : \"\";\n console.log(` - ${m.name} <${m.email ?? \"no email\"}> [${m.role ?? \"member\"}]${pct}`);\n }\n console.log(chalk.yellow(`\\n Next: add more founders or run: corp form finalize @last:entity`));\n } catch (err) {\n printError(`Failed to add founder: ${err}`);\n process.exit(1);\n }\n}\n\nexport async function formFinalizeCommand(entityId: string, opts: FormFinalizeOptions): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n const resolvedEntityId = await resolveEntityRefForFormCommand(resolver, entityId, opts.dryRun);\n const payload: ApiRecord = {};\n if (opts.authorizedShares) {\n const authorizedShares = parseInt(opts.authorizedShares, 10);\n if (!Number.isFinite(authorizedShares)) {\n throw new Error(`Invalid authorized shares: ${opts.authorizedShares}`);\n }\n payload.authorized_shares = authorizedShares;\n }\n if (opts.parValue) payload.par_value = opts.parValue;\n if (opts.boardSize) {\n const boardSize = parseInt(opts.boardSize, 10);\n if (!Number.isFinite(boardSize) || boardSize <= 0) {\n throw new Error(`Invalid board size: ${opts.boardSize}`);\n }\n payload.board_size = boardSize;\n }\n if (opts.principalName) payload.principal_name = opts.principalName;\n if (opts.registeredAgentName) payload.registered_agent_name = opts.registeredAgentName;\n if (opts.registeredAgentAddress) payload.registered_agent_address = opts.registeredAgentAddress;\n if (opts.formationDate) payload.formation_date = opts.formationDate;\n if (opts.fiscalYearEnd) payload.fiscal_year_end = opts.fiscalYearEnd;\n if (opts.sCorp !== undefined) payload.s_corp_election = opts.sCorp;\n if (opts.transferRestrictions !== undefined) payload.transfer_restrictions = opts.transferRestrictions;\n if (opts.rofr !== undefined) payload.right_of_first_refusal = opts.rofr;\n const companyAddress = parseCsvAddress(opts.companyAddress);\n if (companyAddress) payload.company_address = companyAddress;\n if (opts.incorporatorName) payload.incorporator_name = opts.incorporatorName;\n if (opts.incorporatorAddress) payload.incorporator_address = opts.incorporatorAddress;\n\n if (opts.dryRun) {\n printDryRun(\"formation.finalize\", { entity_id: resolvedEntityId, ...payload });\n return;\n }\n\n const result = await client.finalizeFormation(resolvedEntityId, payload);\n await resolver.stabilizeRecord(\"entity\", result);\n resolver.rememberFromRecord(\"entity\", result);\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(`Formation finalized: ${result.entity_id}`);\n printReferenceSummary(\"entity\", result, { showReuseHint: true });\n if (result.legal_entity_id) console.log(` Legal Entity ID: ${result.legal_entity_id}`);\n if (result.instrument_id) console.log(` Instrument ID: ${result.instrument_id}`);\n\n const docIds = (result.document_ids ?? []) as string[];\n if (docIds.length > 0) {\n console.log(` Documents: ${docIds.length} generated`);\n }\n\n const holders = (result.holders ?? []) as ApiRecord[];\n if (holders.length > 0) {\n console.log();\n const table = new Table({\n head: [chalk.dim(\"Holder\"), chalk.dim(\"Shares\"), chalk.dim(\"Ownership %\")],\n });\n for (const h of holders) {\n const pct = typeof h.ownership_pct === \"number\" ? `${h.ownership_pct.toFixed(1)}%` : \"—\";\n table.push([String(h.name ?? \"?\"), String(h.shares ?? 0), pct]);\n }\n console.log(chalk.bold(\" Cap Table:\"));\n console.log(table.toString());\n }\n\n if (result.next_action) {\n console.log(chalk.yellow(`\\n Next: ${result.next_action}`));\n }\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"officers_list\") || msg.includes(\"officer\")) {\n printError(\n `Finalization failed: ${msg}\\n` +\n \" Hint: C-Corp entities require at least one founder with an officer_title.\\n\" +\n \" Add a founder with: corp form add-founder @last:entity --name '...' --email '...' --role director --pct 100 --officer-title ceo\",\n );\n } else {\n printError(`Failed to finalize formation: ${err}`);\n }\n process.exit(1);\n }\n}\n\nexport async function formActivateCommand(entityId: string, opts: FormActivateOptions): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n const resolvedEntityId = await resolveEntityRefForFormCommand(resolver, entityId, opts.dryRun);\n const payload: ApiRecord = { entity_id: resolvedEntityId };\n if (opts.evidenceUri) payload.evidence_uri = opts.evidenceUri;\n if (opts.evidenceType) payload.evidence_type = opts.evidenceType;\n if (opts.filingId) payload.filing_id = opts.filingId;\n if (opts.receiptReference) payload.receipt_reference = opts.receiptReference;\n if (opts.ein) payload.ein = opts.ein;\n\n if (opts.dryRun) {\n printDryRun(\"formation.activate\", payload);\n return;\n }\n\n const result = await activateFormationEntity(client, resolver, resolvedEntityId, {\n evidenceUri: opts.evidenceUri,\n evidenceType: opts.evidenceType,\n filingId: opts.filingId,\n receiptReference: opts.receiptReference,\n ein: opts.ein,\n });\n const formation = await client.getFormation(resolvedEntityId);\n await resolver.stabilizeRecord(\"entity\", formation as ApiRecord);\n resolver.rememberFromRecord(\"entity\", formation as ApiRecord);\n\n if (opts.json) {\n printJson({\n ...result,\n formation,\n });\n return;\n }\n\n printSuccess(`Formation advanced to ${result.final_status}.`);\n printReferenceSummary(\"entity\", formation as ApiRecord, { showReuseHint: true });\n if (result.steps.length > 0) {\n console.log(\" Steps:\");\n for (const step of result.steps) {\n console.log(` - ${step}`);\n }\n }\n console.log(` Signatures added: ${result.signatures_added}`);\n console.log(` Documents updated: ${result.documents_signed}`);\n } catch (err) {\n printError(`Failed to activate formation: ${err}`);\n process.exit(1);\n }\n}\n","import type { CommandDef, CommandContext } from \"./types.js\";\nimport { printDryRun, printError, printJson, printReferenceSummary, printSuccess } from \"../output.js\";\nimport { setActiveEntityId, saveConfig, requireConfig } from \"../config.js\";\nimport { activateFormationEntity } from \"../formation-automation.js\";\nimport chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport type { ApiRecord } from \"../types.js\";\n\n// ── form (one-shot formation) handler ──────────────────────────\n\nasync function formHandler(ctx: CommandContext): Promise<void> {\n const { formCommand } = await import(\"../commands/form.js\");\n // Map --entity-type / --legal-name aliases to --type / --name for formCommand\n const opts: Record<string, unknown> = { ...ctx.opts, quiet: ctx.quiet };\n if (opts.entityType && !opts.type) opts.type = opts.entityType;\n if (opts.legalName && !opts.name) opts.name = opts.legalName;\n await formCommand(opts as Parameters<typeof formCommand>[0]);\n}\n\n// ── form create handler ────────────────────────────────────────\n\nconst SUPPORTED_ENTITY_TYPES = [\"llc\", \"c_corp\", \"s_corp\", \"corporation\"];\n\nfunction parseCsvAddress(raw?: string): { street: string; city: string; state: string; zip: string } | undefined {\n if (!raw) return undefined;\n const parts = raw.split(\",\").map((p) => p.trim()).filter(Boolean);\n if (parts.length !== 4) {\n throw new Error(`Invalid address format: ${raw}. Expected 'street,city,state,zip'`);\n }\n return { street: parts[0], city: parts[1], state: parts[2], zip: parts[3] };\n}\n\nfunction shouldResolveEntityRefForDryRun(entityRef: string): boolean {\n const trimmed = entityRef.trim().toLowerCase();\n return trimmed === \"_\" || trimmed === \"@last\" || trimmed.startsWith(\"@last:\");\n}\n\nasync function resolveEntityRefForFormCommand(\n resolver: CommandContext[\"resolver\"],\n entityRef: string,\n dryRun?: boolean,\n): Promise<string> {\n if (!dryRun || shouldResolveEntityRefForDryRun(entityRef)) {\n return resolver.resolveEntity(entityRef);\n }\n try {\n return await resolver.resolveEntity(entityRef);\n } catch {\n // In dry-run mode, fall back to the raw ref if resolution fails\n // (e.g. fetch failed, auth error, network error, etc.)\n return entityRef;\n }\n}\n\nasync function formCreateHandler(ctx: CommandContext): Promise<void> {\n const opts = ctx.opts;\n // Reject options that belong to form finalize, not form create\n if (opts.shares || opts.authorizedShares) {\n ctx.writer.error(\n \"--shares / --authorized-shares is not accepted on form create.\\n\" +\n \" Set authorized shares during finalize:\\n\" +\n \" corp form finalize @last:entity --authorized-shares 10000000\",\n );\n process.exit(1);\n }\n const resolvedType = opts.type as string | undefined;\n const resolvedName = opts.name as string | undefined;\n if (!resolvedType) {\n ctx.writer.error(\"required option '--type <type>' not specified\");\n process.exit(1);\n }\n if (!SUPPORTED_ENTITY_TYPES.includes(resolvedType)) {\n ctx.writer.error(`unsupported entity type '${resolvedType}'. Supported types: ${SUPPORTED_ENTITY_TYPES.join(\", \")}`);\n process.exit(1);\n }\n if (!resolvedName) {\n ctx.writer.error(\"required option '--name <name>' not specified\");\n process.exit(1);\n }\n if (!resolvedName.trim()) {\n ctx.writer.error(\"--name cannot be empty or whitespace\");\n process.exit(1);\n }\n\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n try {\n const entityType = resolvedType === \"corporation\" ? \"c_corp\" : resolvedType;\n const payload: ApiRecord = {\n entity_type: entityType,\n legal_name: resolvedName,\n };\n if (opts.jurisdiction) payload.jurisdiction = opts.jurisdiction;\n if (opts.registeredAgentName) payload.registered_agent_name = opts.registeredAgentName;\n if (opts.registeredAgentAddress) payload.registered_agent_address = opts.registeredAgentAddress;\n if (opts.formationDate) payload.formation_date = opts.formationDate;\n if (opts.fiscalYearEnd) payload.fiscal_year_end = opts.fiscalYearEnd;\n if (opts.sCorp !== undefined) payload.s_corp_election = opts.sCorp;\n if (opts.transferRestrictions !== undefined) payload.transfer_restrictions = opts.transferRestrictions;\n if (opts.rofr !== undefined) payload.right_of_first_refusal = opts.rofr;\n const companyAddress = parseCsvAddress((opts.companyAddress ?? opts.address) as string | undefined);\n if (companyAddress) payload.company_address = companyAddress;\n\n if (ctx.dryRun) {\n printDryRun(\"formation.create_pending\", payload);\n return;\n }\n\n const result = await ctx.client.createPendingEntity(payload);\n await ctx.resolver.stabilizeRecord(\"entity\", result);\n ctx.resolver.rememberFromRecord(\"entity\", result);\n\n if (result.entity_id) {\n const newEntityId = String(result.entity_id);\n setActiveEntityId(cfg, newEntityId);\n // Ensure @last:entity points to the just-created entity\n ctx.resolver.remember(\"entity\", newEntityId);\n saveConfig(cfg);\n }\n\n if (ctx.quiet) {\n const id = result.entity_id;\n if (id) console.log(String(id));\n return;\n }\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(`Pending entity created: ${result.entity_id}`);\n printReferenceSummary(\"entity\", result, { showReuseHint: true });\n console.log(` Name: ${result.legal_name}`);\n console.log(` Type: ${result.entity_type}`);\n console.log(` Jurisdiction: ${result.jurisdiction}`);\n console.log(` Status: ${result.formation_status}`);\n console.log(chalk.yellow(`\\n Next: corp form add-founder @last:entity --name \"...\" --email \"...\" --role member --pct 50`));\n } catch (err) {\n printError(`Failed to create pending entity: ${err}`);\n process.exit(1);\n }\n}\n\n// ── form add-founder handler ───────────────────────────────────\n\nasync function formAddFounderHandler(ctx: CommandContext): Promise<void> {\n const entityRef = ctx.positional[0];\n const opts = ctx.opts;\n try {\n const resolvedEntityId = await resolveEntityRefForFormCommand(ctx.resolver, entityRef, ctx.dryRun);\n const rawPct = (opts.ownershipPct ?? opts.pct) as string | undefined;\n if (!rawPct) {\n ctx.writer.error(\"required option '--ownership-pct <percent>' not specified\");\n process.exit(1);\n }\n const pctValue = parseFloat(rawPct);\n if (isNaN(pctValue) || pctValue <= 0 || pctValue > 100) {\n ctx.writer.error(`--ownership-pct must be between 0 and 100 (e.g. 60 for 60%), got: ${rawPct}`);\n process.exit(1);\n }\n const payload: ApiRecord = {\n name: opts.name as string,\n email: opts.email as string,\n role: opts.role as string,\n ownership_pct: pctValue,\n };\n if (opts.officerTitle) payload.officer_title = (opts.officerTitle as string).toLowerCase();\n if (opts.incorporator) payload.is_incorporator = true;\n const address = parseCsvAddress(opts.address as string | undefined);\n if (address) payload.address = address;\n\n if (ctx.dryRun) {\n printDryRun(\"formation.add_founder\", { entity_id: resolvedEntityId, ...payload });\n return;\n }\n\n const result = await ctx.client.addFounder(resolvedEntityId, payload);\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(`Founder added (${result.member_count} total)`);\n const members = (result.members ?? []) as ApiRecord[];\n for (const m of members) {\n const pct = typeof m.ownership_pct === \"number\" ? ` (${m.ownership_pct}%)` : \"\";\n console.log(` - ${m.name} <${m.email ?? \"no email\"}> [${m.role ?? \"member\"}]${pct}`);\n }\n console.log(chalk.yellow(`\\n Next: add more founders or run: corp form finalize @last:entity`));\n } catch (err) {\n printError(`Failed to add founder: ${err}`);\n process.exit(1);\n }\n}\n\n// ── form finalize handler ──────────────────────────────────────\n\nasync function formFinalizeHandler(ctx: CommandContext): Promise<void> {\n const entityRef = ctx.positional[0];\n const opts = ctx.opts;\n try {\n const resolvedEntityId = await resolveEntityRefForFormCommand(ctx.resolver, entityRef, ctx.dryRun);\n const payload: ApiRecord = {};\n if (opts.authorizedShares) {\n const authorizedShares = parseInt(opts.authorizedShares as string, 10);\n if (!Number.isFinite(authorizedShares)) {\n throw new Error(`Invalid authorized shares: ${opts.authorizedShares}`);\n }\n payload.authorized_shares = authorizedShares;\n }\n if (opts.parValue) payload.par_value = opts.parValue;\n if (opts.boardSize) {\n const boardSize = parseInt(opts.boardSize as string, 10);\n if (!Number.isFinite(boardSize) || boardSize <= 0) {\n throw new Error(`Invalid board size: ${opts.boardSize}`);\n }\n payload.board_size = boardSize;\n }\n if (opts.principalName) payload.principal_name = opts.principalName;\n if (opts.registeredAgentName) payload.registered_agent_name = opts.registeredAgentName;\n if (opts.registeredAgentAddress) payload.registered_agent_address = opts.registeredAgentAddress;\n if (opts.formationDate) payload.formation_date = opts.formationDate;\n if (opts.fiscalYearEnd) payload.fiscal_year_end = opts.fiscalYearEnd;\n if (opts.sCorp !== undefined) payload.s_corp_election = opts.sCorp;\n if (opts.transferRestrictions !== undefined) payload.transfer_restrictions = opts.transferRestrictions;\n if (opts.rofr !== undefined) payload.right_of_first_refusal = opts.rofr;\n const companyAddress = parseCsvAddress(opts.companyAddress as string | undefined);\n if (companyAddress) payload.company_address = companyAddress;\n if (opts.incorporatorName) payload.incorporator_name = opts.incorporatorName;\n if (opts.incorporatorAddress) payload.incorporator_address = opts.incorporatorAddress;\n\n if (ctx.dryRun) {\n printDryRun(\"formation.finalize\", { entity_id: resolvedEntityId, ...payload });\n return;\n }\n\n const result = await ctx.client.finalizeFormation(resolvedEntityId, payload);\n await ctx.resolver.stabilizeRecord(\"entity\", result);\n ctx.resolver.rememberFromRecord(\"entity\", result);\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(`Formation finalized: ${result.entity_id}`);\n printReferenceSummary(\"entity\", result, { showReuseHint: true });\n if (result.legal_entity_id) console.log(` Legal Entity ID: ${result.legal_entity_id}`);\n if (result.instrument_id) console.log(` Instrument ID: ${result.instrument_id}`);\n\n const docIds = (result.document_ids ?? []) as string[];\n if (docIds.length > 0) {\n console.log(` Documents: ${docIds.length} generated`);\n }\n\n const holders = (result.holders ?? []) as ApiRecord[];\n if (holders.length > 0) {\n console.log();\n const table = new Table({\n head: [chalk.dim(\"Holder\"), chalk.dim(\"Shares\"), chalk.dim(\"Ownership %\")],\n });\n for (const h of holders) {\n const pct = typeof h.ownership_pct === \"number\" ? `${h.ownership_pct.toFixed(1)}%` : \"\\u2014\";\n table.push([String(h.name ?? \"?\"), String(h.shares ?? 0), pct]);\n }\n console.log(chalk.bold(\" Cap Table:\"));\n console.log(table.toString());\n }\n\n if (result.next_action) {\n console.log(chalk.yellow(`\\n Next: ${result.next_action}`));\n }\n } catch (err) {\n const msg = String(err);\n // Collect all missing-field hints and show them at once\n const hints: string[] = [];\n if (msg.includes(\"incorporator_address\")) {\n hints.push('--incorporator-address \"123 Main St,City,ST,12345\"');\n }\n if (msg.includes(\"company_address\")) {\n hints.push('--company-address \"123 Main St,City,ST,12345\"');\n }\n if (msg.includes(\"principal_name\")) {\n hints.push('--principal-name \"Managing Member Name\"');\n }\n if (msg.includes(\"officers_list\") || msg.includes(\"officer\")) {\n hints.push(\"Add a founder with --officer-title: corp form add-founder @last --role director --officer-title ceo ...\");\n }\n if (msg.includes(\"incorporator_name\")) {\n hints.push('--incorporator-name \"Incorporator Name\"');\n }\n if (hints.length > 0) {\n printError(\n `Finalization failed: ${msg}\\n\\n` +\n \" To fix, re-run finalize with the missing fields:\\n\" +\n hints.map((h) => ` ${h}`).join(\"\\n\") + \"\\n\\n\" +\n \" Example:\\n\" +\n ` corp form finalize @last ${hints.filter((h) => h.startsWith(\"--\")).join(\" \")}`,\n );\n } else {\n printError(`Failed to finalize formation: ${err}`);\n }\n process.exit(1);\n }\n}\n\n// ── form activate handler ──────────────────────────────────────\n\nasync function formActivateHandler(ctx: CommandContext): Promise<void> {\n const entityRef = ctx.positional[0];\n const opts = ctx.opts;\n try {\n const resolvedEntityId = await resolveEntityRefForFormCommand(ctx.resolver, entityRef, ctx.dryRun);\n const payload: ApiRecord = { entity_id: resolvedEntityId };\n if (opts.evidenceUri) payload.evidence_uri = opts.evidenceUri;\n if (opts.evidenceType) payload.evidence_type = opts.evidenceType;\n if (opts.filingId) payload.filing_id = opts.filingId;\n if (opts.receiptReference) payload.receipt_reference = opts.receiptReference;\n if (opts.ein) payload.ein = opts.ein;\n\n if (ctx.dryRun) {\n printDryRun(\"formation.activate\", payload);\n return;\n }\n\n const result = await activateFormationEntity(ctx.client, ctx.resolver, resolvedEntityId, {\n evidenceUri: opts.evidenceUri as string | undefined,\n evidenceType: opts.evidenceType as string | undefined,\n filingId: opts.filingId as string | undefined,\n receiptReference: opts.receiptReference as string | undefined,\n ein: opts.ein as string | undefined,\n });\n const formation = await ctx.client.getFormation(resolvedEntityId);\n await ctx.resolver.stabilizeRecord(\"entity\", formation as ApiRecord);\n ctx.resolver.rememberFromRecord(\"entity\", formation as ApiRecord);\n\n if (opts.json) {\n printJson({\n ...result,\n formation,\n });\n return;\n }\n\n printSuccess(`Formation advanced to ${result.final_status}.`);\n printReferenceSummary(\"entity\", formation as ApiRecord, { showReuseHint: true });\n if (result.steps.length > 0) {\n console.log(\" Steps:\");\n for (const step of result.steps) {\n console.log(` - ${step}`);\n }\n }\n console.log(` Signatures added: ${result.signatures_added}`);\n console.log(` Documents updated: ${result.documents_signed}`);\n if (result.final_status === \"active\") {\n console.log(chalk.yellow(\"\\n Next steps:\"));\n console.log(chalk.yellow(\" corp cap-table View your cap table\"));\n console.log(chalk.yellow(\" corp next See all recommended actions\"));\n }\n } catch (err) {\n printError(`Failed to activate formation: ${err}`);\n process.exit(1);\n }\n}\n\n// ── Command definitions ────────────────────────────────────────\n\nexport const formationCommands: CommandDef[] = [\n {\n name: \"form\",\n description: \"Form a new entity with founders and cap table\",\n passThroughOptions: true,\n dryRun: true,\n options: [\n { flags: \"--type <type>\", description: \"Entity type\", choices: [\"llc\", \"c_corp\", \"s_corp\"] },\n { flags: \"--entity-type <type>\", description: \"Entity type (alias for --type)\" },\n { flags: \"--name <name>\", description: \"Legal name\" },\n { flags: \"--legal-name <name>\", description: \"Legal name (alias for --name)\" },\n { flags: \"--jurisdiction <jurisdiction>\", description: \"Jurisdiction (e.g. US-DE, US-WY)\" },\n { flags: \"--member <member>\", description: \"Founder as 'name,email,role[,pct[,street|city|state|zip[,officer_title[,is_incorporator]]]]' (repeatable)\", type: \"array\", default: [] },\n { flags: \"--member-json <json>\", description: \"Founder JSON object (repeatable)\", type: \"array\", default: [] },\n { flags: \"--members-file <path>\", description: \"Path to a JSON array of founders or {\\\"members\\\": [...]}\" },\n { flags: \"--address <address>\", description: \"Company address as 'street,city,state,zip' (required for c_corp)\" },\n { flags: \"--fiscal-year-end <date>\", description: \"Fiscal year end (MM-DD)\", default: \"12-31\" },\n { flags: \"--s-corp\", description: \"Elect S-Corp status\" },\n { flags: \"--transfer-restrictions\", description: \"Enable transfer restrictions\" },\n { flags: \"--rofr\", description: \"Enable right of first refusal\" },\n { flags: \"--principal-name <name>\", description: \"Managing member name for LLCs (auto-set from first member if omitted)\" },\n ],\n handler: formHandler,\n produces: { kind: \"entity\", trackEntity: true },\n successTemplate: \"Entity formed: {legal_name}\",\n examples: [\n 'corp form --type llc --name \"My LLC\" --member \"Alice,alice@co.com,member,100\"',\n 'corp form --type c_corp --name \"Acme Inc\" --member \"Bob,bob@co.com,director,100,123 Main|City|DE|19801,ceo,true\"',\n \"corp form --type c_corp --name \\\"Acme Inc\\\" --jurisdiction US-DE --member-json '{\\\"name\\\":\\\"Bob\\\",\\\"email\\\":\\\"bob@acme.com\\\",\\\"role\\\":\\\"director\\\",\\\"pct\\\":100}'\",\n 'corp form create --type llc --name \"My LLC\"',\n 'corp form add-founder @last:entity --name \"Alice\" --email \"alice@co.com\" --role member --ownership-pct 100',\n \"corp form finalize @last:entity\",\n \"corp form activate @last:entity\",\n ],\n },\n {\n name: \"form create\",\n description: \"Create a pending entity (staged flow step 1)\",\n dryRun: true,\n options: [\n { flags: \"--type <type>\", description: \"Entity type\", choices: [\"llc\", \"c_corp\", \"s_corp\"] },\n { flags: \"--name <name>\", description: \"Legal name\" },\n { flags: \"--jurisdiction <jurisdiction>\", description: \"Jurisdiction (e.g. US-DE, US-WY)\" },\n { flags: \"--registered-agent-name <name>\", description: \"Registered agent legal name\" },\n { flags: \"--registered-agent-address <address>\", description: \"Registered agent address line\" },\n { flags: \"--formation-date <date>\", description: \"Formation date (RFC3339 or YYYY-MM-DD)\" },\n { flags: \"--fiscal-year-end <date>\", description: \"Fiscal year end (MM-DD)\" },\n { flags: \"--s-corp\", description: \"Elect S-Corp status\" },\n { flags: \"--transfer-restrictions\", description: \"Enable transfer restrictions\" },\n { flags: \"--rofr\", description: \"Enable right of first refusal\" },\n { flags: \"--company-address <address>\", description: \"Company address as 'street,city,state,zip'\" },\n { flags: \"--address <address>\", description: \"Company address (alias for --company-address)\" },\n { flags: \"--shares <count>\", description: \"\", hidden: true },\n { flags: \"--authorized-shares <count>\", description: \"\", hidden: true },\n ],\n handler: formCreateHandler,\n produces: { kind: \"entity\", trackEntity: true },\n successTemplate: \"Pending entity created: {legal_name}\",\n examples: [\n 'corp form create --type c_corp --name \"Acme Inc\" --jurisdiction US-DE --address \"123 Main,City,ST,12345\"',\n 'corp form create --type llc --name \"My LLC\" --jurisdiction US-WY --principal-name \"Carlos\"',\n ],\n },\n {\n name: \"form add-founder\",\n description: \"Add a founder to a pending entity (staged flow step 2)\",\n dryRun: true,\n args: [{ name: \"entity-ref\", required: true }],\n options: [\n { flags: \"--name <name>\", description: \"Founder name\", required: true },\n { flags: \"--email <email>\", description: \"Founder email\", required: true },\n { flags: \"--role <role>\", description: \"Founder role\", required: true, choices: [\"director\", \"officer\", \"manager\", \"member\", \"chair\"] },\n { flags: \"--ownership-pct <percent>\", description: \"Ownership percentage (e.g. 60 for 60%)\", required: true },\n { flags: \"--pct <percent>\", description: \"Alias for --ownership-pct\" },\n { flags: \"--officer-title <title>\", description: \"Officer title (corporations only)\", choices: [\"ceo\", \"cfo\", \"cto\", \"coo\", \"secretary\", \"treasurer\", \"president\", \"vp\", \"other\"] },\n { flags: \"--incorporator\", description: \"Mark as sole incorporator (corporations only)\" },\n { flags: \"--address <address>\", description: \"Founder address as 'street,city,state,zip'\" },\n ],\n handler: formAddFounderHandler,\n examples: [\n 'corp form add-founder @last --name \"Alice\" --email \"alice@co.com\" --role director --ownership-pct 60 --officer-title ceo --incorporator',\n 'corp form add-founder @last --name \"Bob\" --email \"bob@co.com\" --role member --ownership-pct 40 --address \"123 Main|City|ST|12345\"',\n ],\n },\n {\n name: \"form finalize\",\n description: \"Finalize formation and generate documents + cap table (staged flow step 3)\",\n dryRun: true,\n args: [{ name: \"entity-ref\", required: true }],\n options: [\n { flags: \"--authorized-shares <count>\", description: \"Authorized shares for corporations\" },\n { flags: \"--par-value <value>\", description: \"Par value per share, e.g. 0.0001\" },\n { flags: \"--board-size <count>\", description: \"Board size for corporations\" },\n { flags: \"--principal-name <name>\", description: \"Principal or manager name for LLCs\" },\n { flags: \"--registered-agent-name <name>\", description: \"Registered agent legal name\" },\n { flags: \"--registered-agent-address <address>\", description: \"Registered agent address line\" },\n { flags: \"--formation-date <date>\", description: \"Formation date (RFC3339 or YYYY-MM-DD)\" },\n { flags: \"--fiscal-year-end <date>\", description: \"Fiscal year end (MM-DD)\" },\n { flags: \"--s-corp\", description: \"Elect S-Corp status\" },\n { flags: \"--transfer-restrictions\", description: \"Enable transfer restrictions\" },\n { flags: \"--rofr\", description: \"Enable right of first refusal\" },\n { flags: \"--company-address <address>\", description: \"Company address as 'street,city,state,zip'\" },\n { flags: \"--incorporator-name <name>\", description: \"Incorporator legal name (overrides founder)\" },\n { flags: \"--incorporator-address <address>\", description: \"Incorporator mailing address (overrides founder)\" },\n ],\n handler: formFinalizeHandler,\n examples: [\"corp form finalize\"],\n },\n {\n name: \"form activate\",\n description: \"Programmatically sign formation documents and advance an entity to active\",\n dryRun: true,\n args: [{ name: \"entity-ref\", required: true }],\n options: [\n { flags: \"--evidence-uri <uri>\", description: \"Registered-agent consent evidence URI placeholder\" },\n { flags: \"--evidence-type <type>\", description: \"Registered-agent consent evidence type\", default: \"generated\" },\n { flags: \"--filing-id <id>\", description: \"External filing identifier to record\" },\n { flags: \"--receipt-reference <ref>\", description: \"External receipt reference to record\" },\n { flags: \"--ein <ein>\", description: \"EIN to confirm (defaults to a deterministic simulated EIN)\" },\n ],\n handler: formActivateHandler,\n examples: [\"corp form activate\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"contracts\",\n description: \"Generate a contract document\",\n route: { method: \"POST\", path: \"/v1/contracts\" },\n options: [\n { flags: \"--counterparty-name <counterparty-name>\", description: \"Counterparty Name\", required: true },\n { flags: \"--effective-date <effective-date>\", description: \"Effective Date\", required: true },\n { flags: \"--parameters <parameters>\", description: \"Parameters\" },\n { flags: \"--template-type <template-type>\", description: \"Template type for generated contracts.\", required: true, choices: [\"consulting_agreement\", \"employment_offer\", \"contractor_agreement\", \"nda\", \"safe_agreement\", \"custom\"] },\n ],\n examples: [\"corp contracts --counterparty-name 'counterparty-name' --effective-date 'effective-date' --template-type consulting_agreement\", \"corp contracts --json\"],\n successTemplate: \"Contracts created\",\n },\n {\n name: \"documents show\",\n description: \"View a document by ID\",\n route: { method: \"GET\", path: \"/v1/documents/{pos}\" },\n entity: true,\n args: [{ name: \"document-id\", required: true, description: \"Document ID\" }],\n display: { title: \"Document\", cols: [\"document_type>Type\", \"status>Status\", \"title>Title\", \"signature_count>Signatures\", \"@created_at>Created\", \"#document_id>ID\"] },\n examples: [\"corp documents show <document-id>\", \"corp documents show <document-id> --json\"],\n },\n {\n name: \"documents amendment-history\",\n description: \"View amendment history for a document\",\n route: { method: \"GET\", path: \"/v1/documents/{pos}/amendment-history\" },\n entity: true,\n args: [{ name: \"document-id\", required: true, description: \"Document ID\" }],\n display: { title: \"Documents Amendment History\", cols: [\"amended_at>Amended At\", \"description>Description\", \"version>Version\"] },\n examples: [\"corp documents amendment-history\", \"corp documents amendment-history --json\"],\n },\n {\n name: \"documents pdf\",\n description: \"Download a document as PDF\",\n route: { method: \"GET\", path: \"/v1/documents/{pos}/pdf\" },\n entity: true,\n args: [{ name: \"document-id\", required: true, description: \"Document ID\" }],\n examples: [\"corp documents pdf\", \"corp documents pdf --json\"],\n },\n {\n name: \"documents request-copy\",\n description: \"Request a certified copy of a document\",\n route: { method: \"POST\", path: \"/v1/documents/{pos}/request-copy\" },\n args: [{ name: \"document-id\", required: true, description: \"Document ID\" }],\n options: [\n { flags: \"--recipient-email <recipient-email>\", description: \"Recipient Email\" },\n ],\n examples: [\"corp documents request-copy <document-id>\", \"corp documents request-copy --json\"],\n successTemplate: \"Request Copy created\",\n },\n {\n name: \"entities list\",\n description: \"List all entities in the workspace\",\n route: { method: \"GET\", path: \"/v1/entities\" },\n display: { title: \"Entities\", cols: [\"legal_name>Name\", \"entity_type>Type\", \"formation_status>Status\", \"jurisdiction>Jurisdiction\", \"#entity_id>ID\"] },\n examples: [\"corp entities list\", \"corp entities list --json\"],\n },\n {\n name: \"entities governance-documents\",\n description: \"List governance documents for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance-documents\" },\n entity: true,\n display: { title: \"Entities Governance Documents\", cols: [\"@created_at>Created At\", \"#document_id>ID\", \"document_type>Document Type\", \"signature_count>Signature Count\", \"status>Status\", \"title>Title\"] },\n examples: [\"corp entities governance-documents\", \"corp entities governance-documents --json\"],\n },\n {\n name: \"entities governance-documents-current\",\n description: \"View current governance documents\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance-documents/current\" },\n entity: true,\n display: { title: \"Entities Governance Documents Current\", cols: [\"@created_at>Created At\", \"#document_id>ID\", \"document_type>Document Type\", \"signature_count>Signature Count\", \"status>Status\", \"title>Title\"] },\n examples: [\"corp entities governance-documents-current\", \"corp entities governance-documents-current --json\"],\n },\n {\n name: \"formations create\",\n description: \"View formation status for an entity\",\n route: { method: \"POST\", path: \"/v1/formations\" },\n options: [\n { flags: \"--authorized-shares <authorized-shares>\", description: \"Number of authorized shares\" },\n { flags: \"--company-address <company-address>\", description: \"Company mailing address\" },\n { flags: \"--entity-type <entity-type>\", description: \"The legal structure of a business entity.\", required: true, choices: [\"c_corp\", \"llc\"] },\n { flags: \"--fiscal-year-end <fiscal-year-end>\", description: \"Fiscal year end, e.g. \\\"12-31\\\". Defaults to \\\"12-31\\\".\" },\n { flags: \"--formation-date <formation-date>\", description: \"Optional formation date for importing pre-formed entities.\" },\n { flags: \"--jurisdiction <jurisdiction>\", description: \"Jurisdiction (e.g. Delaware, US-DE)\", required: true },\n { flags: \"--legal-name <legal-name>\", description: \"Legal name of the entity\", required: true },\n { flags: \"--members <members>\", description: \"LLC member entries\", required: true, type: \"array\" },\n { flags: \"--par-value <par-value>\", description: \"Par value per share\" },\n { flags: \"--registered-agent-address <registered-agent-address>\", description: \"Registered agent mailing address\" },\n { flags: \"--registered-agent-name <registered-agent-name>\", description: \"Registered agent name\" },\n { flags: \"--right-of-first-refusal <right-of-first-refusal>\", description: \"Include right of first refusal in bylaws (corp). Default true.\" },\n { flags: \"--s-corp-election <s-corp-election>\", description: \"Whether the company will elect S-Corp tax treatment.\" },\n { flags: \"--transfer-restrictions <transfer-restrictions>\", description: \"Include transfer restrictions in bylaws (corp). Default true.\" },\n ],\n examples: [\"corp formations --entity-type c_corp --jurisdiction 'jurisdiction' --legal-name 'legal-name' --members 'members'\", \"corp formations --json\"],\n successTemplate: \"Formations created\",\n },\n {\n name: \"formations pending\",\n description: \"List entities with pending formations\",\n route: { method: \"POST\", path: \"/v1/formations/pending\" },\n options: [\n { flags: \"--company-address <company-address>\", description: \"Company mailing address\" },\n { flags: \"--entity-type <entity-type>\", description: \"The legal structure of a business entity.\", required: true, choices: [\"c_corp\", \"llc\"] },\n { flags: \"--fiscal-year-end <fiscal-year-end>\", description: \"Fiscal year end (e.g. 12-31)\" },\n { flags: \"--formation-date <formation-date>\", description: \"Date of formation (ISO 8601)\" },\n { flags: \"--jurisdiction <jurisdiction>\", description: \"Jurisdiction (e.g. Delaware, US-DE)\" },\n { flags: \"--legal-name <legal-name>\", description: \"Legal name of the entity\", required: true },\n { flags: \"--registered-agent-address <registered-agent-address>\", description: \"Registered agent mailing address\" },\n { flags: \"--registered-agent-name <registered-agent-name>\", description: \"Registered agent name\" },\n { flags: \"--right-of-first-refusal <right-of-first-refusal>\", description: \"Include ROFR in bylaws (true/false)\" },\n { flags: \"--s-corp-election <s-corp-election>\", description: \"S Corp Election\" },\n { flags: \"--transfer-restrictions <transfer-restrictions>\", description: \"Transfer Restrictions\" },\n ],\n examples: [\"corp formations pending --entity-type c_corp --legal-name 'legal-name'\", \"corp formations pending --json\"],\n successTemplate: \"Pending created\",\n },\n {\n name: \"formations with-cap-table\",\n description: \"Create entity with formation and initial cap table\",\n route: { method: \"POST\", path: \"/v1/formations/with-cap-table\" },\n options: [\n { flags: \"--authorized-shares <authorized-shares>\", description: \"Number of authorized shares\" },\n { flags: \"--company-address <company-address>\", description: \"Company mailing address\" },\n { flags: \"--entity-type <entity-type>\", description: \"The legal structure of a business entity.\", required: true, choices: [\"c_corp\", \"llc\"] },\n { flags: \"--fiscal-year-end <fiscal-year-end>\", description: \"Fiscal year end, e.g. \\\"12-31\\\". Defaults to \\\"12-31\\\".\" },\n { flags: \"--formation-date <formation-date>\", description: \"Optional formation date for importing pre-formed entities.\" },\n { flags: \"--jurisdiction <jurisdiction>\", description: \"Jurisdiction (e.g. Delaware, US-DE)\", required: true },\n { flags: \"--legal-name <legal-name>\", description: \"Legal name of the entity\", required: true },\n { flags: \"--members <members>\", description: \"LLC member entries\", required: true, type: \"array\" },\n { flags: \"--par-value <par-value>\", description: \"Par value per share\" },\n { flags: \"--registered-agent-address <registered-agent-address>\", description: \"Registered agent mailing address\" },\n { flags: \"--registered-agent-name <registered-agent-name>\", description: \"Registered agent name\" },\n { flags: \"--right-of-first-refusal <right-of-first-refusal>\", description: \"Include right of first refusal in bylaws (corp). Default true.\" },\n { flags: \"--s-corp-election <s-corp-election>\", description: \"Whether the company will elect S-Corp tax treatment.\" },\n { flags: \"--transfer-restrictions <transfer-restrictions>\", description: \"Include transfer restrictions in bylaws (corp). Default true.\" },\n ],\n examples: [\"corp formations with-cap-table --entity-type c_corp --jurisdiction 'jurisdiction' --legal-name 'legal-name' --members 'members'\", \"corp formations with-cap-table --json\"],\n successTemplate: \"With Cap Table created\",\n },\n {\n name: \"formations\",\n description: \"View formation status for an entity\",\n route: { method: \"GET\", path: \"/v1/formations/{eid}\" },\n entity: true,\n display: { title: \"Formations\", cols: [\"entity_type>Entity Type\", \"formation_date>Formation Date\", \"formation_state>Formation State\", \"formation_status>Formation Status\", \"#entity_id>ID\"] },\n examples: [\"corp formations\", \"corp formations --json\"],\n },\n {\n name: \"formations apply-ein\",\n description: \"Submit EIN application\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/apply-ein\" },\n entity: true,\n examples: [\"corp formations apply-ein\"],\n successTemplate: \"Apply Ein created\",\n },\n {\n name: \"formations ein-confirmation\",\n description: \"Confirm EIN received from IRS\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/ein-confirmation\" },\n entity: true,\n options: [\n { flags: \"--ein <ein>\", description: \"Employer Identification Number\", required: true },\n ],\n examples: [\"corp formations ein-confirmation --ein 'ein'\"],\n successTemplate: \"Ein Confirmation created\",\n },\n {\n name: \"formations filing-attestation\",\n description: \"Attest to filing accuracy\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/filing-attestation\" },\n entity: true,\n options: [\n { flags: \"--consent-text <consent-text>\", description: \"Consent Text\" },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n { flags: \"--signer-email <signer-email>\", description: \"Signer Email\", required: true },\n { flags: \"--signer-name <signer-name>\", description: \"Signer Name\", required: true },\n { flags: \"--signer-role <signer-role>\", description: \"Signer Role\", required: true },\n ],\n examples: [\"corp formations filing-attestation --signer-email 'signer-email' --signer-name 'signer-name' --signer-role 'signer-role'\", \"corp formations filing-attestation --json\"],\n successTemplate: \"Filing Attestation created\",\n },\n {\n name: \"formations filing-confirmation\",\n description: \"Confirm state filing received\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/filing-confirmation\" },\n entity: true,\n options: [\n { flags: \"--external-filing-id <external-filing-id>\", description: \"External Filing Id\", required: true },\n { flags: \"--receipt-reference <receipt-reference>\", description: \"Receipt Reference\" },\n ],\n examples: [\"corp formations filing-confirmation --external-filing-id 'external-filing-id'\", \"corp formations filing-confirmation --json\"],\n successTemplate: \"Filing Confirmation created\",\n },\n {\n name: \"formations finalize\",\n description: \"Finalize a formation (lock documents)\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/finalize\" },\n entity: true,\n options: [\n { flags: \"--authorized-shares <authorized-shares>\", description: \"Number of authorized shares\" },\n { flags: \"--board-size <board-size>\", description: \"Board Size\" },\n { flags: \"--company-address <company-address>\", description: \"Company mailing address\" },\n { flags: \"--fiscal-year-end <fiscal-year-end>\", description: \"Fiscal year end (e.g. 12-31)\" },\n { flags: \"--formation-date <formation-date>\", description: \"Date of formation (ISO 8601)\" },\n { flags: \"--incorporator-address <incorporator-address>\", description: \"Incorporator Address\" },\n { flags: \"--incorporator-name <incorporator-name>\", description: \"Incorporator Name\" },\n { flags: \"--par-value <par-value>\", description: \"Par value per share\" },\n { flags: \"--principal-name <principal-name>\", description: \"Principal Name\" },\n { flags: \"--registered-agent-address <registered-agent-address>\", description: \"Registered agent mailing address\" },\n { flags: \"--registered-agent-name <registered-agent-name>\", description: \"Registered agent name\" },\n { flags: \"--right-of-first-refusal <right-of-first-refusal>\", description: \"Include ROFR in bylaws (true/false)\" },\n { flags: \"--s-corp-election <s-corp-election>\", description: \"S Corp Election\" },\n { flags: \"--transfer-restrictions <transfer-restrictions>\", description: \"Transfer Restrictions\" },\n ],\n examples: [\"corp formations finalize\", \"corp formations finalize --json\"],\n successTemplate: \"Finalize created\",\n },\n {\n name: \"formations founders\",\n description: \"Add founders to a formation\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/founders\" },\n entity: true,\n options: [\n { flags: \"--address <address>\", description: \"Address\" },\n { flags: \"--email <email>\", description: \"Email\" },\n { flags: \"--is-incorporator <is-incorporator>\", description: \"Is Incorporator\" },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--officer-title <officer-title>\", description: \"Officer Title\", choices: [\"ceo\", \"cfo\", \"cto\", \"coo\", \"secretary\", \"treasurer\", \"president\", \"vp\", \"other\"] },\n { flags: \"--ownership-pct <ownership-pct>\", description: \"Ownership Pct\" },\n { flags: \"--role <role>\", description: \"Role\", choices: [\"director\", \"officer\", \"manager\", \"member\", \"chair\"] },\n ],\n examples: [\"corp formations founders --name ceo\", \"corp formations founders --json\"],\n successTemplate: \"Founders created\",\n },\n {\n name: \"formations gates\",\n description: \"View formation gate status (checklist)\",\n route: { method: \"GET\", path: \"/v1/formations/{eid}/gates\" },\n entity: true,\n display: { title: \"Formations Gates\", cols: [\"attestation_recorded>Attestation Recorded\", \"designated_attestor_email>Designated Attestor Email\", \"designated_attestor_name>Designated Attestor Name\", \"designated_attestor_role>Designated Attestor Role\", \"#entity_id>ID\"] },\n examples: [\"corp formations gates\", \"corp formations gates --json\"],\n },\n {\n name: \"formations mark-documents-signed\",\n description: \"Mark formation documents as signed\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/mark-documents-signed\" },\n entity: true,\n examples: [\"corp formations mark-documents-signed\"],\n successTemplate: \"Mark Documents Signed created\",\n },\n {\n name: \"formations registered-agent-consent-evidence\",\n description: \"Provide registered agent consent evidence\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/registered-agent-consent-evidence\" },\n entity: true,\n options: [\n { flags: \"--evidence-type <evidence-type>\", description: \"Evidence Type\" },\n { flags: \"--evidence-uri <evidence-uri>\", description: \"Evidence Uri\", required: true },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n ],\n examples: [\"corp formations registered-agent-consent-evidence --evidence-uri 'evidence-uri'\", \"corp formations registered-agent-consent-evidence --json\"],\n successTemplate: \"Registered Agent Consent Evidence created\",\n },\n {\n name: \"formations service-agreement-execute\",\n description: \"Execute the service agreement\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/service-agreement/execute\" },\n entity: true,\n options: [\n { flags: \"--contract-id <contract-id>\", description: \"Contract Id\" },\n { flags: \"--document-id <document-id>\", description: \"Document ID\" },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n ],\n examples: [\"corp formations service-agreement-execute\", \"corp formations service-agreement-execute --json\"],\n successTemplate: \"Service Agreement Execute created\",\n },\n {\n name: \"formations submit-filing\",\n description: \"Submit state filing for a formation\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/submit-filing\" },\n entity: true,\n examples: [\"corp formations submit-filing\"],\n successTemplate: \"Submit Filing created\",\n },\n {\n name: \"governance catalog\",\n description: \"Browse the governance document catalog\",\n route: { method: \"GET\", path: \"/v1/governance/catalog\" },\n display: { title: \"Governance Catalog\", cols: [\"categories>Categories\"] },\n examples: [\"corp governance catalog\"],\n },\n {\n name: \"governance catalog-markdown\",\n description: \"View a governance document in markdown\",\n route: { method: \"GET\", path: \"/v1/governance/catalog/{pos}/markdown\" },\n args: [{ name: \"document-id\", required: true, description: \"Document ID\" }],\n display: { title: \"Governance Catalog Markdown\", cols: [\"category>Category\", \"entity_scope>Entity Scope\", \"id>Id\", \"markdown>Markdown\", \"title>Title\", \"variants>Variants\"] },\n examples: [\"corp governance catalog-markdown\"],\n },\n\n];","import chalk from \"chalk\";\nimport type { CommandDef, CommandContext } from \"./types.js\";\nimport type { ApiRecord } from \"../types.js\";\nimport {\n printCapTable,\n printInstrumentsTable,\n printReferenceSummary,\n printRoundsTable,\n printSafesTable,\n printShareClassesTable,\n printTransfersTable,\n printValuationsTable,\n} from \"../output.js\";\nimport { shortId } from \"../references.js\";\nimport {\n entityHasActiveBoard,\n issueEquity,\n issueSafe,\n} from \"@thecorporation/corp-tools\";\n\n// Helpers (normalizedGrantType, expectedInstrumentKinds, grantRequiresCurrent409a,\n// buildInstrumentCreationHint, resolveInstrumentForGrant, entityHasActiveBoard,\n// ensureIssuancePreflight) are now imported from @thecorporation/corp-tools.\n\n// ---------------------------------------------------------------------------\n// Local output helper — 409A panel\n// ---------------------------------------------------------------------------\n\nfunction print409a(data: Record<string, unknown>): void {\n console.log(chalk.green(\"\\u2500\".repeat(40)));\n console.log(chalk.green.bold(\" 409A Valuation\"));\n console.log(chalk.green(\"\\u2500\".repeat(40)));\n const fmv = typeof data.fmv_per_share_cents === \"number\" ? (data.fmv_per_share_cents as number) / 100 : data.fmv_per_share;\n const enterpriseValue = typeof data.enterprise_value_cents === \"number\"\n ? (data.enterprise_value_cents as number) / 100\n : data.enterprise_value;\n console.log(` ${chalk.bold(\"FMV/Share:\")} $${fmv ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Enterprise Value:\")} $${enterpriseValue ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Valuation Date:\")} ${data.effective_date ?? data.valuation_date ?? \"N/A\"}`);\n if (data.provider) console.log(` ${chalk.bold(\"Provider:\")} ${data.provider}`);\n console.log(chalk.green(\"\\u2500\".repeat(40)));\n}\n\n// ---------------------------------------------------------------------------\n// Cap-table registry entries\n// ---------------------------------------------------------------------------\n\nexport const capTableCommands: CommandDef[] = [\n // --- cap-table (overview) ---\n {\n name: \"cap-table\",\n description: \"Cap table, equity grants, SAFEs, transfers, and valuations\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/cap-table\" },\n entity: true,\n display: {\n title: \"Cap Table\",\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n let data: ApiRecord;\n try {\n data = await ctx.client.getCapTable(eid);\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"no linked legal entity\") || msg.includes(\"Not found\")) {\n throw new Error(\"No cap table found. Finalize formation first: corp form finalize \" + eid);\n }\n throw err;\n }\n const instruments = Array.isArray(data.instruments) ? data.instruments as ApiRecord[] : [];\n const shareClasses = Array.isArray(data.share_classes) ? data.share_classes as ApiRecord[] : [];\n await ctx.resolver.stabilizeRecords(\"instrument\", instruments, eid);\n await ctx.resolver.stabilizeRecords(\"share_class\", shareClasses, eid);\n if (ctx.opts.json) { ctx.writer.json(data); return; }\n if ((data.access_level as string) === \"none\") {\n ctx.writer.error(\"You do not have access to this entity's cap table.\");\n process.exit(1);\n }\n printCapTable(data);\n try {\n const val = await ctx.client.getCurrent409a(eid);\n if (val) print409a(val);\n } catch { /* ignore */ }\n },\n examples: [\n \"corp cap-table\",\n 'corp cap-table issue-equity --grant-type common --shares 1000000 --recipient \"Alice Smith\"',\n 'corp cap-table issue-safe --investor \"Seed Fund\" --amount-dollars 500000 --valuation-cap-dollars 10000000',\n \"corp cap-table create-valuation --type four_oh_nine_a --date 2026-01-01 --methodology market\",\n \"corp cap-table transfer --from alice --to bob --shares 1000 --share-class-id COMMON --governing-doc-type bylaws --transferee-rights full_member\",\n ],\n },\n\n // --- cap-table safes ---\n {\n name: \"cap-table safes\",\n description: \"List SAFE notes\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/safe-notes\" },\n entity: true,\n display: {\n title: \"SAFE Notes\",\n cols: [\"investor_name|investor>Investor\", \"principal_amount_cents|investment_amount|amount>Amount\", \"valuation_cap_cents|valuation_cap|cap>Cap\", \"discount_rate|discount>Discount\", \"issued_at|date|created_at>Date\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const safes = await ctx.client.getSafeNotes(eid);\n await ctx.resolver.stabilizeRecords(\"safe_note\", safes, eid);\n if (ctx.opts.json) { ctx.writer.json(safes); return; }\n if (safes.length === 0) { ctx.writer.writeln(\"No SAFE notes found.\"); return; }\n printSafesTable(safes);\n },\n examples: [\"corp cap-table safes\", \"corp cap-table safes --json\"],\n },\n\n // --- cap-table transfers ---\n {\n name: \"cap-table transfers\",\n description: \"Share transfers\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/share-transfers\" },\n entity: true,\n display: {\n title: \"Share Transfers\",\n cols: [\"from_holder|from>From\", \"to_holder|to>To\", \"shares|share_count>Shares\", \"transfer_type>Type\", \"status>Status\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const transfers = await ctx.client.getShareTransfers(eid);\n await ctx.resolver.stabilizeRecords(\"share_transfer\", transfers, eid);\n if (ctx.opts.json) { ctx.writer.json(transfers); return; }\n if (transfers.length === 0) { ctx.writer.writeln(\"No share transfers found.\"); return; }\n printTransfersTable(transfers);\n },\n examples: [\"corp cap-table transfers\", \"corp cap-table transfers --json\"],\n },\n\n // --- cap-table instruments ---\n {\n name: \"cap-table instruments\",\n description: \"Cap table instruments\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/cap-table\" },\n entity: true,\n display: {\n title: \"Instruments\",\n listKey: \"instruments\",\n cols: [\"symbol>Symbol\", \"kind>Kind\", \"authorized_units>Authorized\", \"issued_units>Issued\", \"status>Status\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const capTable = await ctx.client.getCapTable(eid);\n const instruments = Array.isArray(capTable.instruments) ? capTable.instruments as ApiRecord[] : [];\n await ctx.resolver.stabilizeRecords(\"instrument\", instruments, eid);\n if (ctx.opts.json) { ctx.writer.json(instruments); return; }\n if (instruments.length === 0) { ctx.writer.writeln(\"No instruments found.\"); return; }\n printInstrumentsTable(instruments);\n },\n examples: [\"corp cap-table instruments\", \"corp cap-table instruments --json\"],\n },\n\n // --- cap-table share-classes ---\n {\n name: \"cap-table share-classes\",\n description: \"List share classes\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/cap-table\" },\n entity: true,\n display: {\n title: \"Share Classes\",\n listKey: \"share_classes\",\n cols: [\"class_code|name|share_class>Class\", \"authorized>Authorized\", \"outstanding>Outstanding\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const capTable = await ctx.client.getCapTable(eid);\n const shareClasses = Array.isArray(capTable.share_classes) ? capTable.share_classes as ApiRecord[] : [];\n await ctx.resolver.stabilizeRecords(\"share_class\", shareClasses, eid);\n if (ctx.opts.json) { ctx.writer.json(shareClasses); return; }\n if (shareClasses.length === 0) { ctx.writer.writeln(\"No share classes found.\"); return; }\n printShareClassesTable(shareClasses);\n },\n examples: [\"corp cap-table share-classes\", \"corp cap-table share-classes --json\"],\n },\n\n // --- cap-table rounds ---\n {\n name: \"cap-table rounds\",\n description: \"Staged equity rounds\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/equity-rounds\" },\n entity: true,\n display: {\n title: \"Equity Rounds\",\n cols: [\"name>Name\", \"status>Status\", \"issuer_legal_entity_id>Issuer\", \"@created_at>Created\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const rounds = await ctx.client.listEquityRounds(eid);\n await ctx.resolver.stabilizeRecords(\"round\", rounds, eid);\n if (ctx.opts.json) { ctx.writer.json(rounds); return; }\n if (rounds.length === 0) { ctx.writer.writeln(\"No rounds found.\"); return; }\n printRoundsTable(rounds);\n },\n examples: [\"corp cap-table rounds\", \"corp cap-table rounds --json\"],\n },\n\n // --- cap-table valuations ---\n {\n name: \"cap-table valuations\",\n description: \"Valuations history\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/valuations\" },\n entity: true,\n display: {\n title: \"Valuations\",\n cols: [\"@effective_date|valuation_date|date>Date\", \"valuation_type|type>Type\", \"enterprise_value_cents|enterprise_value|valuation>Valuation\", \"fmv_per_share_cents|price_per_share|pps|fmv_per_share>PPS\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const valuations = await ctx.client.getValuations(eid);\n await ctx.resolver.stabilizeRecords(\"valuation\", valuations, eid);\n if (ctx.opts.json) { ctx.writer.json(valuations); return; }\n if (valuations.length === 0) { ctx.writer.writeln(\"No valuations found.\"); return; }\n printValuationsTable(valuations);\n },\n examples: [\"corp cap-table valuations\", \"corp cap-table valuations --json\"],\n },\n\n // --- cap-table 409a ---\n {\n name: \"cap-table 409a\",\n description: \"Current 409A valuation\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/current-409a\" },\n entity: true,\n display: { title: \"409A Valuation\" },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n try {\n const data = await ctx.client.getCurrent409a(eid);\n await ctx.resolver.stabilizeRecord(\"valuation\", data, eid);\n if (ctx.opts.json) { ctx.writer.json(data); return; }\n if (!data || Object.keys(data).length === 0) { ctx.writer.writeln(\"No 409A valuation found.\"); return; }\n print409a(data);\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"404\") || msg.includes(\"Not found\") || msg.includes(\"not found\")) {\n try {\n const valuations = await ctx.client.getValuations(eid);\n const pending409a = valuations\n .filter((valuation) => valuation.valuation_type === \"four_oh_nine_a\")\n .find((valuation) => valuation.status === \"pending_approval\");\n if (pending409a) {\n const effectiveDate = pending409a.effective_date ?? \"unknown date\";\n ctx.writer.writeln(\n `No current approved 409A valuation found. A 409A valuation is pending approval (${effectiveDate}).\\n` +\n \" Complete board approval, then re-run: corp cap-table 409a\",\n );\n } else {\n ctx.writer.writeln(\n \"No 409A valuation found for this entity. Create one with:\\n\" +\n \" corp cap-table create-valuation --type four_oh_nine_a --date YYYY-MM-DD --methodology <method>\",\n );\n }\n } catch {\n ctx.writer.writeln(\n \"No 409A valuation found for this entity. Create one with:\\n\" +\n \" corp cap-table create-valuation --type four_oh_nine_a --date YYYY-MM-DD --methodology <method>\",\n );\n }\n } else {\n ctx.writer.error(`Failed to fetch 409A valuation: ${err}`);\n }\n process.exit(1);\n }\n },\n examples: [\"corp cap-table 409a\", \"corp cap-table 409a --json\"],\n },\n\n // --- cap-table control-map ---\n {\n name: \"cap-table control-map\",\n description: \"View entity control/ownership map\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/control-map\" },\n entity: \"query\",\n display: { title: \"Control Map\" },\n options: [\n { flags: \"--root-entity-id <ref>\", description: \"Root entity for ownership tree (defaults to active entity)\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const rootEntityId = (ctx.opts.rootEntityId as string | undefined)\n ? await ctx.resolver.resolveEntity(ctx.opts.rootEntityId as string)\n : eid;\n\n let result: ApiRecord;\n try {\n result = await ctx.client.getControlMap(eid, rootEntityId);\n } catch (firstErr) {\n const msg = String(firstErr);\n if (msg.includes(\"404\") && !ctx.opts.rootEntityId) {\n try {\n const capTable = await ctx.client.getCapTable(eid);\n const issuerLegalEntityId = capTable.issuer_legal_entity_id as string | undefined;\n if (issuerLegalEntityId && issuerLegalEntityId !== eid) {\n result = await ctx.client.getControlMap(eid, issuerLegalEntityId);\n } else {\n throw firstErr;\n }\n } catch {\n throw firstErr;\n }\n } else {\n throw firstErr;\n }\n }\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.json(result);\n },\n examples: [\"corp cap-table control-map\", \"corp cap-table control-map --json\"],\n },\n\n // --- cap-table dilution ---\n {\n name: \"cap-table dilution\",\n description: \"Preview dilution impact of a round\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/dilution-preview\" },\n entity: \"query\",\n display: { title: \"Dilution Preview\" },\n options: [\n { flags: \"--round-id <ref>\", description: \"Round reference to model dilution for\", required: true },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const roundId = await ctx.resolver.resolveRound(eid, ctx.opts.roundId as string);\n const result = await ctx.client.getDilutionPreview(eid, roundId);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n if (result.round_status === \"closed\" || result.round_status === \"issued\") {\n console.log(chalk.yellow(\"Note: This round is already closed. Dilution preview reflects the finalized state, not a scenario model.\"));\n console.log(chalk.dim(\" For scenario modeling, create a new round with: corp cap-table start-round --name '...' --issuer-legal-entity-id '...'\"));\n }\n ctx.writer.json(result);\n },\n examples: [\"corp cap-table dilution\", \"corp cap-table dilution --json\"],\n },\n\n // --- cap-table create-instrument ---\n {\n name: \"cap-table create-instrument\",\n description: \"Create a cap table instrument\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/instruments\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--kind <kind>\", description: \"Instrument kind (common_equity, preferred_equity, membership_unit, option_grant, safe)\", required: true },\n { flags: \"--symbol <symbol>\", description: \"Instrument symbol\", required: true },\n { flags: \"--issuer-legal-entity-id <ref>\", description: \"Issuer legal entity reference (ID, short ID, @last, or unique name)\" },\n { flags: \"--authorized-units <n>\", description: \"Authorized units\", type: \"int\" },\n { flags: \"--issue-price-cents <n>\", description: \"Issue price in cents\", type: \"int\" },\n { flags: \"--terms-json <json>\", description: \"JSON object of instrument terms\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n let issuerLegalEntityId = ctx.opts.issuerLegalEntityId as string | undefined;\n if (!issuerLegalEntityId) {\n const capTable = await ctx.client.getCapTable(eid);\n issuerLegalEntityId = capTable.issuer_legal_entity_id as string | undefined;\n }\n if (!issuerLegalEntityId) {\n throw new Error(\"No issuer legal entity found. Has this entity been formed with a cap table?\");\n }\n issuerLegalEntityId = await ctx.resolver.resolveEntity(issuerLegalEntityId);\n\n const terms = (ctx.opts.termsJson as string | undefined)\n ? JSON.parse(ctx.opts.termsJson as string) as Record<string, unknown>\n : {};\n const payload: Record<string, unknown> = {\n entity_id: eid,\n issuer_legal_entity_id: issuerLegalEntityId,\n kind: ctx.opts.kind as string,\n symbol: ctx.opts.symbol as string,\n terms,\n };\n if (ctx.opts.authorizedUnits != null) payload.authorized_units = ctx.opts.authorizedUnits;\n if (ctx.opts.issuePriceCents != null) payload.issue_price_cents = ctx.opts.issuePriceCents;\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.create_instrument\", payload);\n return;\n }\n const result = await ctx.client.createInstrument(payload);\n await ctx.resolver.stabilizeRecord(\"instrument\", result, eid);\n ctx.resolver.rememberFromRecord(\"instrument\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Instrument created: ${result.instrument_id ?? \"OK\"}`);\n printReferenceSummary(\"instrument\", result, { showReuseHint: true });\n },\n produces: { kind: \"instrument\" },\n successTemplate: \"Instrument created: {symbol}\",\n examples: [\"corp cap-table create-instrument --kind 'kind' --symbol 'symbol'\", \"corp cap-table create-instrument --json\"],\n },\n\n // --- cap-table issue-equity ---\n {\n name: \"cap-table issue-equity\",\n description: \"Issue an equity grant (creates a round, adds security, and issues it)\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/equity-rounds\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--grant-type <type>\", description: \"Grant type (common, preferred, membership_unit, stock_option, iso, nso, rsa)\", required: true },\n { flags: \"--shares <n>\", description: \"Number of shares\", required: true, type: \"int\" },\n { flags: \"--recipient <name>\", description: \"Recipient name\", required: true },\n { flags: \"--email <email>\", description: \"Recipient email (auto-creates contact if needed)\" },\n { flags: \"--instrument-id <ref>\", description: \"Instrument reference (ID, short ID, symbol, or @last)\" },\n { flags: \"--meeting-id <ref>\", description: \"Board meeting reference required when a board approval already exists or is being recorded\" },\n { flags: \"--resolution-id <ref>\", description: \"Board resolution reference required when issuing under a board-governed entity\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const grantType = ctx.opts.grantType as string;\n const shares = ctx.opts.shares as number;\n const recipient = ctx.opts.recipient as string;\n const email = ctx.opts.email as string | undefined;\n const optInstrumentId = ctx.opts.instrumentId as string | undefined;\n const optMeetingId = ctx.opts.meetingId as string | undefined;\n const optResolutionId = ctx.opts.resolutionId as string | undefined;\n\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.issue_equity\", {\n entity_id: eid,\n grant_type: grantType,\n shares,\n recipient,\n email,\n instrument_id: optInstrumentId,\n meeting_id: optMeetingId,\n resolution_id: optResolutionId,\n });\n return;\n }\n\n // Resolve references before passing to workflow\n const instrumentId = optInstrumentId\n ? await ctx.resolver.resolveInstrument(eid, optInstrumentId)\n : undefined;\n const meetingId = optMeetingId ? await ctx.resolver.resolveMeeting(eid, optMeetingId) : undefined;\n const resolutionId = optResolutionId\n ? await ctx.resolver.resolveResolution(eid, optResolutionId, meetingId)\n : undefined;\n\n const result = await issueEquity(ctx.client, {\n entityId: eid,\n grantType,\n shares,\n recipientName: recipient,\n recipientEmail: email,\n instrumentId,\n meetingId,\n resolutionId,\n });\n\n if (!result.success) {\n let errMsg = result.error!;\n if (errMsg.includes(\"already bound\") && !errMsg.includes(\"quick-approve\")) {\n errMsg += '\\n Each issuance needs its own board approval.\\n Run: corp governance quick-approve --text \"RESOLVED: authorize equity issuance\"';\n }\n ctx.writer.error(errMsg);\n return;\n }\n\n // Track references for the created round\n const round = result.data?.round as Record<string, unknown> | undefined;\n if (round) {\n await ctx.resolver.stabilizeRecord(\"round\", round, eid);\n ctx.resolver.rememberFromRecord(\"round\", round, eid);\n }\n\n // Show instrument selection detail\n const instrStep = result.steps.find((s) => s.name === \"resolve_instrument\");\n if (instrStep && !optInstrumentId) {\n console.log(instrStep.detail);\n }\n\n if (ctx.opts.json) { ctx.writer.json(result.data); return; }\n ctx.writer.success(`Equity issued: ${shares} shares (${grantType}) to ${recipient}`);\n if (round) {\n printReferenceSummary(\"round\", round, { label: \"Round Ref:\", showReuseHint: true });\n }\n },\n produces: { kind: \"round\" },\n successTemplate: \"Equity issued: {round_name}\",\n examples: [\n 'corp cap-table issue-equity --grant-type common --shares 50000 --recipient \"Alice Smith\"',\n 'corp cap-table issue-equity --grant-type iso --shares 10000 --recipient \"Bob\" --email \"bob@co.com\"',\n ],\n },\n\n // --- cap-table issue-safe ---\n {\n name: \"cap-table issue-safe\",\n description: \"Issue a SAFE note\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/safe-notes\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--investor <name>\", description: \"Investor name\", required: true },\n { flags: \"--amount-cents <n>\", description: \"Principal amount in cents (e.g. 50000000 = $500,000)\", type: \"int\" },\n { flags: \"--amount-dollars <n>\", description: \"Principal amount in dollars (e.g. 500000 = $500,000)\", type: \"int\" },\n { flags: \"--safe-type <type>\", description: \"SAFE type\", default: \"post_money\", choices: [\"post_money\", \"pre_money\", \"mfn\"] },\n { flags: \"--valuation-cap-cents <n>\", description: \"Valuation cap in cents (e.g. 100000000 = $1M)\", type: \"int\" },\n { flags: \"--valuation-cap-dollars <n>\", description: \"Valuation cap in dollars (e.g. 1000000 = $1M)\", type: \"int\" },\n { flags: \"--meeting-id <ref>\", description: \"Board meeting reference required when issuing under a board-governed entity\" },\n { flags: \"--resolution-id <ref>\", description: \"Board resolution reference required when issuing under a board-governed entity\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const investor = ctx.opts.investor as string;\n if (ctx.opts.amountCents != null && ctx.opts.amountDollars != null) {\n throw new Error(\"--amount-cents and --amount-dollars are mutually exclusive. Use one or the other.\");\n }\n const amountCents = ctx.opts.amountCents != null\n ? (ctx.opts.amountCents as number)\n : ctx.opts.amountDollars != null ? (ctx.opts.amountDollars as number) * 100 : undefined;\n if (amountCents == null) {\n throw new Error(\"required: --amount-cents <n> or --amount-dollars <n>\");\n }\n const safeType = (ctx.opts.safeType ?? \"post_money\") as string;\n if (ctx.opts.valuationCapCents != null && ctx.opts.valuationCapDollars != null) {\n throw new Error(\"--valuation-cap-cents and --valuation-cap-dollars are mutually exclusive. Use one or the other.\");\n }\n const valuationCapCents = ctx.opts.valuationCapCents != null\n ? (ctx.opts.valuationCapCents as number)\n : ctx.opts.valuationCapDollars != null ? (ctx.opts.valuationCapDollars as number) * 100 : undefined;\n if (valuationCapCents == null) {\n throw new Error(\"required: --valuation-cap-cents <n> or --valuation-cap-dollars <n>\");\n }\n const email = ctx.opts.email as string | undefined;\n const optMeetingId = ctx.opts.meetingId as string | undefined;\n const optResolutionId = ctx.opts.resolutionId as string | undefined;\n\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.issue_safe\", {\n entity_id: eid,\n investor,\n amount_cents: amountCents,\n safe_type: safeType,\n valuation_cap_cents: valuationCapCents,\n email,\n meeting_id: optMeetingId,\n resolution_id: optResolutionId,\n });\n return;\n }\n\n // Resolve references before passing to workflow\n const meetingId = optMeetingId ? await ctx.resolver.resolveMeeting(eid, optMeetingId) : undefined;\n const resolutionId = optResolutionId\n ? await ctx.resolver.resolveResolution(eid, optResolutionId, meetingId)\n : undefined;\n\n const result = await issueSafe(ctx.client, {\n entityId: eid,\n investorName: investor,\n amountCents,\n valuationCapCents,\n safeType,\n email,\n meetingId,\n resolutionId,\n });\n\n if (!result.success) {\n let errMsg = result.error!;\n if (errMsg.includes(\"already bound\") && !errMsg.includes(\"quick-approve\")) {\n errMsg += '\\n Each issuance needs its own board approval.\\n Run: corp governance quick-approve --text \"RESOLVED: authorize SAFE issuance\"';\n }\n ctx.writer.error(errMsg);\n return;\n }\n\n await ctx.resolver.stabilizeRecord(\"safe_note\", result.data!, eid);\n ctx.resolver.rememberFromRecord(\"safe_note\", result.data!, eid);\n if (ctx.opts.json) { ctx.writer.json(result.data); return; }\n ctx.writer.success(`SAFE issued: $${(amountCents / 100).toLocaleString()} to ${investor}`);\n printReferenceSummary(\"safe_note\", result.data!, { showReuseHint: true });\n },\n produces: { kind: \"safe_note\" },\n successTemplate: \"SAFE created: {investor_name}\",\n examples: [\n 'corp cap-table issue-safe --investor \"Seed Fund\" --amount-dollars 500000 --valuation-cap-dollars 10000000',\n \"corp cap-table issue-safe --investor \\\"Angel\\\" --amount-cents 50000000 --valuation-cap-cents 1000000000\",\n ],\n },\n\n // --- cap-table transfer ---\n {\n name: \"cap-table transfer\",\n description: \"Create a share transfer workflow\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/share-transfers\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--from <ref>\", description: \"Source contact reference (from_contact_id)\", required: true },\n { flags: \"--to <ref>\", description: \"Destination contact reference (to_contact_id)\", required: true },\n { flags: \"--shares <n>\", description: \"Number of shares to transfer\", required: true, type: \"int\" },\n { flags: \"--share-class-id <ref>\", description: \"Share class reference (auto-resolved if only one exists)\" },\n { flags: \"--governing-doc-type <type>\", description: \"Governing doc type (bylaws, operating_agreement, shareholder_agreement, other)\", default: \"bylaws\" },\n { flags: \"--transferee-rights <rights>\", description: \"Transferee rights (full_member, economic_only, limited)\", default: \"full_member\" },\n { flags: \"--prepare-intent-id <id>\", description: \"Prepare intent ID (auto-created if omitted)\" },\n { flags: \"--type <type>\", description: \"Transfer type (gift, trust_transfer, secondary_sale, estate, other)\", default: \"secondary_sale\" },\n { flags: \"--price-per-share-cents <n>\", description: \"Price per share in cents\", type: \"int\" },\n { flags: \"--relationship <rel>\", description: \"Relationship to holder\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const fromContactId = await ctx.resolver.resolveContact(eid, ctx.opts.from as string);\n const toContactId = await ctx.resolver.resolveContact(eid, ctx.opts.to as string);\n let shareClassId: string;\n if (ctx.opts.shareClassId) {\n shareClassId = await ctx.resolver.resolveShareClass(eid, ctx.opts.shareClassId as string);\n } else {\n // Auto-resolve: use the only share class if there's exactly one\n const capTable = await ctx.client.getCapTable(eid);\n const instruments = (capTable.instruments ?? []) as Array<{ share_class_id?: string }>;\n const classIds = [...new Set(instruments.map((i) => i.share_class_id).filter(Boolean))] as string[];\n if (classIds.length === 1) {\n shareClassId = classIds[0];\n } else if (classIds.length === 0) {\n throw new Error(\"No share classes found. Create one first or specify --share-class-id.\");\n } else {\n throw new Error(`Multiple share classes found (${classIds.length}). Specify --share-class-id to disambiguate.`);\n }\n }\n const shares = ctx.opts.shares as number;\n const pricePerShareCents = ctx.opts.pricePerShareCents as number | undefined;\n const relationship = ctx.opts.relationship as string | undefined;\n const transferType = (ctx.opts.type ?? \"secondary_sale\") as string;\n const prepareIntentId = ctx.opts.prepareIntentId as string | undefined;\n\n if (pricePerShareCents != null && pricePerShareCents < 0) {\n throw new Error(\"price-per-share-cents cannot be negative\");\n }\n if (fromContactId === toContactId) {\n throw new Error(\"--from and --to must be different contacts\");\n }\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.transfer_shares\", {\n entity_id: eid,\n from_contact_id: fromContactId,\n to_contact_id: toContactId,\n share_count: shares,\n transfer_type: transferType,\n share_class_id: shareClassId,\n governing_doc_type: ctx.opts.governingDocType as string,\n transferee_rights: ctx.opts.transfereeRights as string,\n prepare_intent_id: prepareIntentId,\n price_per_share_cents: pricePerShareCents,\n relationship_to_holder: relationship,\n });\n return;\n }\n\n let intentId = prepareIntentId;\n if (!intentId) {\n const intent = await ctx.client.createExecutionIntent({\n entity_id: eid,\n intent_type: \"equity.transfer.prepare\",\n description: `Transfer ${shares} shares from ${fromContactId} to ${toContactId}`,\n });\n intentId = (intent.intent_id ?? intent.id) as string;\n await ctx.client.evaluateIntent(intentId, eid);\n await ctx.client.authorizeIntent(intentId, eid);\n }\n const body: Record<string, unknown> = {\n entity_id: eid,\n share_class_id: shareClassId,\n from_contact_id: fromContactId,\n to_contact_id: toContactId,\n transfer_type: transferType,\n share_count: shares,\n governing_doc_type: ctx.opts.governingDocType as string,\n transferee_rights: ctx.opts.transfereeRights as string,\n prepare_intent_id: intentId,\n };\n if (pricePerShareCents != null) body.price_per_share_cents = pricePerShareCents;\n if (relationship) body.relationship_to_holder = relationship;\n const result = await ctx.client.transferShares(body);\n await ctx.resolver.stabilizeRecord(\"share_transfer\", result, eid);\n ctx.resolver.rememberFromRecord(\"share_transfer\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Transfer workflow created: ${result.transfer_workflow_id ?? \"OK\"}`);\n printReferenceSummary(\"share_transfer\", result, { label: \"Transfer Ref:\", showReuseHint: true });\n },\n produces: { kind: \"share_transfer\" },\n successTemplate: \"Transfer created\",\n examples: [\"corp cap-table transfer --from 'ref' --to 'ref' --shares 'n' --share-class-id 'ref' --governing-doc-type 'type' --transferee-rights 'rights'\", \"corp cap-table transfer --json\"],\n },\n\n // --- cap-table distribute ---\n {\n name: \"cap-table distribute\",\n description: \"Calculate a distribution\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/distributions\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--amount-cents <n>\", description: \"Total distribution amount in cents (e.g. 100000 = $1,000.00)\", required: true, type: \"int\" },\n { flags: \"--amount-dollars <n>\", description: \"Total distribution amount in dollars (e.g. 1000 = $1,000.00)\", type: \"int\" },\n { flags: \"--type <type>\", description: \"Distribution type (dividend, return, liquidation)\", default: \"dividend\" },\n { flags: \"--description <desc>\", description: \"Distribution description\", required: true },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n if (ctx.opts.amountCents != null && ctx.opts.amountDollars != null) {\n throw new Error(\"--amount-cents and --amount-dollars are mutually exclusive. Use one or the other.\");\n }\n const amountCents = ctx.opts.amountCents != null\n ? (ctx.opts.amountCents as number)\n : ctx.opts.amountDollars != null\n ? (ctx.opts.amountDollars as number) * 100\n : undefined;\n if (amountCents == null) {\n throw new Error(\"required: --amount-cents <n> or --amount-dollars <n>\");\n }\n const distributionType = (ctx.opts.type ?? \"dividend\") as string;\n const description = ctx.opts.description as string;\n const payload = {\n entity_id: eid,\n total_amount_cents: amountCents,\n distribution_type: distributionType,\n description,\n };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.distribute\", payload);\n return;\n }\n const result = await ctx.client.calculateDistribution(payload);\n await ctx.resolver.stabilizeRecord(\"distribution\", result, eid);\n ctx.resolver.rememberFromRecord(\"distribution\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Distribution calculated: ${result.distribution_id ?? \"OK\"}`);\n printReferenceSummary(\"distribution\", result, { showReuseHint: true });\n },\n examples: [\"corp cap-table distribute --amount-cents 'n' --description 'desc'\", \"corp cap-table distribute --json\"],\n },\n\n // --- cap-table start-round ---\n {\n name: \"cap-table start-round\",\n description: \"Start a staged equity round\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/equity-rounds\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--name <name>\", description: \"Round name\", required: true },\n { flags: \"--issuer-legal-entity-id <ref>\", description: \"Issuer legal entity reference (auto-resolved from cap table if omitted)\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n let issuerLegalEntityId = ctx.opts.issuerLegalEntityId as string | undefined;\n if (!issuerLegalEntityId) {\n const capTable = await ctx.client.getCapTable(eid);\n issuerLegalEntityId = capTable.issuer_legal_entity_id as string | undefined;\n }\n if (!issuerLegalEntityId) {\n throw new Error(\"No issuer legal entity found. Provide --issuer-legal-entity-id or ensure the entity has a cap table.\");\n }\n issuerLegalEntityId = await ctx.resolver.resolveEntity(issuerLegalEntityId);\n const payload = {\n entity_id: eid,\n name: ctx.opts.name as string,\n issuer_legal_entity_id: issuerLegalEntityId,\n };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.start_round\", payload);\n return;\n }\n const result = await ctx.client.startEquityRound(payload);\n await ctx.resolver.stabilizeRecord(\"round\", result, eid);\n ctx.resolver.rememberFromRecord(\"round\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Round started: ${result.round_id ?? \"OK\"}`);\n printReferenceSummary(\"round\", result, { showReuseHint: true });\n },\n produces: { kind: \"round\" },\n successTemplate: \"Round started: {round_name}\",\n examples: [\"corp cap-table start-round --name 'name' --issuer-legal-entity-id 'ref'\"],\n },\n\n // --- cap-table add-security ---\n {\n name: \"cap-table add-security\",\n description: \"Add a security to a staged equity round\",\n route: { method: \"POST\", path: \"/v1/equity-rounds/{pos}/securities\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--round-id <ref>\", description: \"Round reference\", required: true },\n { flags: \"--instrument-id <ref>\", description: \"Instrument reference\", required: true },\n { flags: \"--quantity <n>\", description: \"Number of shares/units\", required: true, type: \"int\" },\n { flags: \"--recipient-name <name>\", description: \"Recipient display name\", required: true },\n { flags: \"--holder-id <ref>\", description: \"Existing holder reference\" },\n { flags: \"--email <email>\", description: \"Recipient email (to find or create holder)\" },\n { flags: \"--principal-cents <n>\", description: \"Principal amount in cents\", type: \"int\" },\n { flags: \"--grant-type <type>\", description: \"Grant type\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const roundId = await ctx.resolver.resolveRound(eid, ctx.opts.roundId as string);\n const instrumentId = await ctx.resolver.resolveInstrument(eid, ctx.opts.instrumentId as string);\n const body: Record<string, unknown> = {\n entity_id: eid,\n instrument_id: instrumentId,\n quantity: ctx.opts.quantity as number,\n recipient_name: ctx.opts.recipientName as string,\n };\n if (ctx.opts.holderId) body.holder_id = await ctx.resolver.resolveContact(eid, ctx.opts.holderId as string);\n if (ctx.opts.email) body.email = ctx.opts.email as string;\n if (ctx.opts.principalCents) body.principal_cents = ctx.opts.principalCents as number;\n if (ctx.opts.grantType) body.grant_type = ctx.opts.grantType as string;\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.add_security\", { round_id: roundId, ...body });\n return;\n }\n const result = await ctx.client.addRoundSecurity(roundId, body);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Security added for ${ctx.opts.recipientName}`);\n },\n examples: [\"corp cap-table add-security --round-id 'ref' --instrument-id 'ref' --quantity 'n' --recipient-name 'name'\", \"corp cap-table add-security --json\"],\n },\n\n // --- cap-table issue-round ---\n {\n name: \"cap-table issue-round\",\n description: \"Issue all securities and close a staged round\",\n route: { method: \"POST\", path: \"/v1/equity-rounds/{pos}/issue\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--round-id <ref>\", description: \"Round reference\", required: true },\n { flags: \"--meeting-id <ref>\", description: \"Board meeting reference (required if entity has an active board)\" },\n { flags: \"--resolution-id <ref>\", description: \"Board resolution reference (required if entity has an active board)\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const roundId = await ctx.resolver.resolveRound(eid, ctx.opts.roundId as string);\n const meetingId = (ctx.opts.meetingId as string | undefined)\n ? await ctx.resolver.resolveMeeting(eid, ctx.opts.meetingId as string)\n : undefined;\n const resolutionId = (ctx.opts.resolutionId as string | undefined)\n ? await ctx.resolver.resolveResolution(eid, ctx.opts.resolutionId as string, meetingId)\n : undefined;\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.issue_round\", {\n entity_id: eid,\n round_id: roundId,\n meeting_id: meetingId,\n resolution_id: resolutionId,\n });\n return;\n }\n if ((!meetingId || !resolutionId) && await entityHasActiveBoard(ctx.client, eid)) {\n throw new Error(\n \"Board approval is required before issuing this round. Pass --meeting-id and --resolution-id from a passed board vote.\\n Tip: Use 'corp governance quick-approve --text \\\"RESOLVED: ...\\\"' for one-step approval.\",\n );\n }\n const body: Record<string, unknown> = { entity_id: eid };\n if (meetingId) body.meeting_id = meetingId;\n if (resolutionId) body.resolution_id = resolutionId;\n const result = await ctx.client.issueRound(roundId, body);\n ctx.resolver.remember(\"round\", roundId, eid);\n const roundMatch = (await ctx.resolver.find(\"round\", shortId(roundId), { entityId: eid }))\n .find((match) => match.id === roundId);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(\"Round issued and closed\");\n if (roundMatch) {\n printReferenceSummary(\"round\", roundMatch.raw, { showReuseHint: true });\n }\n },\n examples: [\"corp cap-table issue-round --round-id 'ref'\", \"corp cap-table issue-round --json\"],\n },\n\n // --- cap-table create-valuation ---\n {\n name: \"cap-table create-valuation\",\n description: \"Create a valuation\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/valuations\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--type <type>\", description: \"Valuation type (four_oh_nine_a, fair_market_value, etc.)\", required: true },\n { flags: \"--date <date>\", description: \"Effective date (ISO 8601)\", required: true },\n { flags: \"--methodology <method>\", description: \"Methodology\", required: true, choices: [\"income\", \"market\", \"asset\", \"backsolve\", \"hybrid\", \"other\"] },\n { flags: \"--fmv <cents>\", description: \"FMV per share in cents\", type: \"int\" },\n { flags: \"--enterprise-value <cents>\", description: \"Enterprise value in cents\", type: \"int\" },\n { flags: \"--auto-approve\", description: \"Automatically submit and approve the valuation (skips board workflow)\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const body: Record<string, unknown> = {\n entity_id: eid,\n valuation_type: ctx.opts.type as string,\n effective_date: ctx.opts.date as string,\n methodology: ctx.opts.methodology as string,\n };\n if (ctx.opts.fmv != null) body.fmv_per_share_cents = ctx.opts.fmv;\n if (ctx.opts.enterpriseValue != null) body.enterprise_value_cents = ctx.opts.enterpriseValue;\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.create_valuation\", body);\n return;\n }\n const result = await ctx.client.createValuation(body);\n await ctx.resolver.stabilizeRecord(\"valuation\", result, eid);\n ctx.resolver.rememberFromRecord(\"valuation\", result, eid);\n\n const valuationId = String(result.valuation_id ?? result.id);\n\n if (ctx.opts.autoApprove && valuationId) {\n try {\n await ctx.client.submitValuationForApproval(valuationId, eid);\n const approved = await ctx.client.approveValuation(valuationId, eid);\n await ctx.resolver.stabilizeRecord(\"valuation\", approved, eid);\n if (ctx.opts.json) { ctx.writer.json(approved); return; }\n ctx.writer.success(`Valuation created and approved: ${valuationId}`);\n printReferenceSummary(\"valuation\", approved, { showReuseHint: true });\n return;\n } catch (err) {\n // Fall through to normal output if auto-approve fails (e.g. board required)\n if (!ctx.opts.json) {\n ctx.writer.warning(`Auto-approve failed (board approval may be required): ${err}`);\n }\n }\n }\n\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Valuation created: ${result.valuation_id ?? \"OK\"}`);\n printReferenceSummary(\"valuation\", result, { showReuseHint: true });\n },\n produces: { kind: \"valuation\" },\n successTemplate: \"Valuation created\",\n examples: [\"corp cap-table create-valuation --type 'type' --date 'date' --methodology 'method'\", \"corp cap-table create-valuation --json\"],\n },\n\n // --- cap-table submit-valuation <valuation-ref> ---\n {\n name: \"cap-table submit-valuation\",\n description: \"Submit a valuation for board approval\",\n route: { method: \"POST\", path: \"/v1/valuations/{pos}/submit\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"valuation-ref\", required: true, description: \"Valuation reference\" }],\n handler: async (ctx) => {\n const valuationRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const valuationId = await ctx.resolver.resolveValuation(eid, valuationRef);\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.submit_valuation\", { entity_id: eid, valuation_id: valuationId });\n return;\n }\n try {\n const result = await ctx.client.submitValuationForApproval(valuationId, eid);\n await ctx.resolver.stabilizeRecord(\"valuation\", result, eid);\n ctx.resolver.remember(\"valuation\", valuationId, eid);\n if (result.meeting_id) ctx.resolver.remember(\"meeting\", String(result.meeting_id), eid);\n if (result.agenda_item_id) ctx.resolver.remember(\"agenda_item\", String(result.agenda_item_id), eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Valuation submitted for approval: ${result.valuation_id ?? valuationId ?? \"OK\"}`);\n printReferenceSummary(\"valuation\", result, { showReuseHint: true });\n if (result.meeting_id) {\n const meetingMatch = (await ctx.resolver.find(\"meeting\", shortId(String(result.meeting_id)), { entityId: eid }))\n .find((match) => match.id === String(result.meeting_id));\n if (meetingMatch) {\n printReferenceSummary(\"meeting\", meetingMatch.raw, { label: \"Meeting Ref:\" });\n } else {\n printReferenceSummary(\"meeting\", { meeting_id: result.meeting_id }, { label: \"Meeting Ref:\" });\n }\n }\n if (result.agenda_item_id) {\n const agendaMatch = (await ctx.resolver.find(\"agenda_item\", shortId(String(result.agenda_item_id)), {\n entityId: eid,\n meetingId: result.meeting_id ? String(result.meeting_id) : undefined,\n }))\n .find((match) => match.id === String(result.agenda_item_id));\n if (agendaMatch) {\n printReferenceSummary(\"agenda_item\", agendaMatch.raw, { label: \"Agenda Ref:\" });\n } else {\n printReferenceSummary(\"agenda_item\", { agenda_item_id: result.agenda_item_id }, { label: \"Agenda Ref:\" });\n }\n }\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"404\") || msg.includes(\"Not found\") || msg.includes(\"not found\")) {\n ctx.writer.error(`Valuation not found. List valuations with: corp cap-table valuations`);\n } else {\n ctx.writer.error(`Failed to submit valuation: ${err}`);\n }\n process.exit(1);\n }\n },\n examples: [\"corp cap-table submit-valuation <valuation-ref>\"],\n },\n\n // --- cap-table approve-valuation <valuation-ref> ---\n {\n name: \"cap-table approve-valuation\",\n description: \"Approve a valuation\",\n route: { method: \"POST\", path: \"/v1/valuations/{pos}/approve\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"valuation-ref\", required: true, description: \"Valuation reference\" }],\n options: [\n { flags: \"--resolution-id <ref>\", description: \"Resolution reference from the board vote\" },\n ],\n handler: async (ctx) => {\n const valuationRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const valuationId = await ctx.resolver.resolveValuation(eid, valuationRef);\n const resolutionId = (ctx.opts.resolutionId as string | undefined)\n ? await ctx.resolver.resolveResolution(eid, ctx.opts.resolutionId as string)\n : undefined;\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.approve_valuation\", {\n entity_id: eid,\n valuation_id: valuationId,\n resolution_id: resolutionId,\n });\n return;\n }\n try {\n const result = await ctx.client.approveValuation(valuationId, eid, resolutionId);\n await ctx.resolver.stabilizeRecord(\"valuation\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Valuation approved: ${result.valuation_id ?? valuationId ?? \"OK\"}`);\n printReferenceSummary(\"valuation\", result);\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"400\")) {\n ctx.writer.error(`Bad request \\u2014 a --resolution-id from a board vote may be required. Submit for approval first: corp cap-table submit-valuation <valuation-ref>`);\n } else {\n ctx.writer.error(`Failed to approve valuation: ${err}`);\n }\n process.exit(1);\n }\n },\n examples: [\"corp cap-table approve-valuation <valuation-ref>\", \"corp cap-table approve-valuation --json\"],\n },\n\n // --- cap-table preview-conversion ---\n {\n name: \"cap-table preview-conversion\",\n description: \"Preview SAFE-to-equity conversion\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/safe-conversion-preview\" },\n entity: true,\n options: [\n { flags: \"--safe-id <ref>\", description: \"SAFE note reference to convert\", required: true },\n { flags: \"--price-per-share-cents <n>\", description: \"Conversion price per share in cents\", required: true, type: \"int\" },\n ],\n display: { title: \"Conversion Preview\" },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const safeId = await ctx.resolver.resolveSafeNote(eid, ctx.opts.safeId as string);\n const result = await ctx.client.previewRoundConversion({\n entity_id: eid,\n safe_note_id: safeId,\n price_per_share_cents: ctx.opts.pricePerShareCents as number,\n } as unknown as Parameters<typeof ctx.client.previewRoundConversion>[0]);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(\"Conversion Preview:\");\n if (result.shares_issued) console.log(` Shares to issue: ${result.shares_issued}`);\n if (result.ownership_pct) console.log(` Post-conversion ownership: ${result.ownership_pct}%`);\n ctx.writer.json(result);\n },\n examples: [\"corp cap-table preview-conversion\", \"corp cap-table preview-conversion --json\"],\n },\n\n // --- cap-table convert ---\n {\n name: \"cap-table convert\",\n description: \"Execute SAFE-to-equity conversion\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/safe-conversions\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--safe-id <ref>\", description: \"SAFE note reference to convert\", required: true },\n { flags: \"--price-per-share-cents <n>\", description: \"Conversion price per share in cents\", required: true, type: \"int\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const safeId = await ctx.resolver.resolveSafeNote(eid, ctx.opts.safeId as string);\n const payload = {\n entity_id: eid,\n safe_note_id: safeId,\n price_per_share_cents: ctx.opts.pricePerShareCents as number,\n };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"equity.conversion.execute\", payload);\n return;\n }\n const result = await ctx.client.executeRoundConversion(\n payload as unknown as Parameters<typeof ctx.client.executeRoundConversion>[0],\n );\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Conversion executed for SAFE ${safeId}`);\n },\n examples: [\"corp cap-table convert --safe-id 'ref' --price-per-share-cents 'n'\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"equity control-links\",\n description: \"Create a control link between legal entities\",\n route: { method: \"POST\", path: \"/v1/equity/control-links\" },\n entity: true,\n options: [\n { flags: \"--child-legal-entity-id <child-legal-entity-id>\", description: \"Child entity in the control relationship\", required: true },\n { flags: \"--control-type <control-type>\", description: \"Type of control relationship.\", required: true, choices: [\"voting\", \"board\", \"economic\", \"contractual\"] },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n { flags: \"--parent-legal-entity-id <parent-legal-entity-id>\", description: \"Parent entity in the control relationship\", required: true },\n { flags: \"--voting-power-bps <voting-power-bps>\", description: \"Voting power in basis points (0-10000)\" },\n ],\n examples: [\"corp equity control-links --child-legal-entity-id voting --control-type voting --parent-legal-entity-id 'parent-legal-entity-id'\", \"corp equity control-links --json\"],\n successTemplate: \"Control Links created\",\n },\n {\n name: \"equity control-map\",\n description: \"View the equity control map\",\n route: { method: \"GET\", path: \"/v1/equity/control-map\" },\n entity: true,\n display: { title: \"Equity Control Map\", cols: [\"edges>Edges\", \"#root_entity_id>ID\", \"traversed_entities>Traversed Entities\"] },\n examples: [\"corp equity control-map\", \"corp equity control-map --json\"],\n },\n {\n name: \"equity conversions-execute\",\n description: \"Execute a SAFE/note conversion into equity\",\n route: { method: \"POST\", path: \"/v1/equity/conversions/execute\" },\n options: [\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n { flags: \"--round-id <round-id>\", description: \"Equity round ID\", required: true },\n { flags: \"--source-reference <source-reference>\", description: \"Source reference for the conversion\" },\n ],\n examples: [\"corp equity conversions-execute --intent-id 'intent-id' --round-id 'round-id'\", \"corp equity conversions-execute --json\"],\n successTemplate: \"Conversions Execute created\",\n },\n {\n name: \"equity conversions-preview\",\n description: \"Preview a SAFE/note conversion without executing\",\n route: { method: \"POST\", path: \"/v1/equity/conversions/preview\" },\n entity: true,\n options: [\n { flags: \"--round-id <round-id>\", description: \"Equity round ID\", required: true },\n { flags: \"--source-reference <source-reference>\", description: \"Source reference for the conversion\" },\n ],\n examples: [\"corp equity conversions-preview --round-id 'round-id'\", \"corp equity conversions-preview --json\"],\n successTemplate: \"Conversions Preview created\",\n },\n {\n name: \"equity dilution-preview\",\n description: \"Preview dilution impact of a potential issuance\",\n route: { method: \"GET\", path: \"/v1/equity/dilution/preview\" },\n entity: true,\n display: { title: \"Equity Dilution Preview\", cols: [\"#issuer_legal_entity_id>ID\", \"pre_round_outstanding_units>Pre Round Outstanding Units\", \"projected_dilution_bps>Projected Dilution Bps\", \"projected_new_units>Projected New Units\", \"projected_post_outstanding_units>Projected Post Outstanding Units\", \"#round_id>ID\"] },\n examples: [\"corp equity dilution-preview\", \"corp equity dilution-preview --json\"],\n },\n {\n name: \"equity entities\",\n description: \"Register a legal entity in the equity system\",\n route: { method: \"POST\", path: \"/v1/equity/entities\" },\n entity: true,\n options: [\n { flags: \"--linked-entity-id <linked-entity-id>\", description: \"ID of the entity to link\" },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--role <role>\", description: \"Role this legal entity plays in the ownership/control graph.\", required: true, choices: [\"operating\", \"control\", \"investment\", \"nonprofit\", \"spv\", \"other\"] },\n ],\n examples: [\"corp equity entities --name 'name' --role operating\", \"corp equity entities --json\"],\n successTemplate: \"Entities created\",\n },\n {\n name: \"equity create-fundraising-workflow\",\n description: \"Start or view a fundraising workflow\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows\" },\n options: [\n { flags: \"--conversion-target-instrument-id <conversion-target-instrument-id>\", description: \"Target instrument for conversion\" },\n { flags: \"--issuer-legal-entity-id <issuer-legal-entity-id>\", description: \"Legal entity issuing the securities\", required: true },\n { flags: \"--metadata <metadata>\", description: \"Additional metadata (JSON)\" },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--pre-money-cents <pre-money-cents>\", description: \"Pre-money valuation in cents\" },\n { flags: \"--prepare-intent-id <prepare-intent-id>\", description: \"Execution intent ID for preparation\", required: true },\n { flags: \"--round-price-cents <round-price-cents>\", description: \"Round share price in cents\" },\n { flags: \"--target-raise-cents <target-raise-cents>\", description: \"Target fundraising amount in cents\" },\n ],\n examples: [\"corp equity fundraising-workflows --issuer-legal-entity-id 'issuer-legal-entity-id' --name 'name' --prepare-intent-id 'prepare-intent-id'\", \"corp equity fundraising-workflows --json\"],\n successTemplate: \"Fundraising Workflows created\",\n },\n {\n name: \"equity fundraising-workflows\",\n description: \"Start or view a fundraising workflow\",\n route: { method: \"GET\", path: \"/v1/equity/fundraising-workflows/{pos}\" },\n entity: true,\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n display: { title: \"Equity Fundraising Workflows\", cols: [\"board_packet_documents>Board Packet Documents\", \"closing_packet_documents>Closing Packet Documents\", \"@created_at>Created At\", \"#accept_intent_id>ID\"] },\n examples: [\"corp equity fundraising-workflows\", \"corp equity fundraising-workflows --json\"],\n },\n {\n name: \"equity fundraising-workflows-apply-terms\",\n description: \"Apply term sheet to a fundraising round\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/apply-terms\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--anti-dilution-method <anti-dilution-method>\", description: \"Anti-dilution protection method\", required: true, choices: [\"none\", \"broad_based_weighted_average\", \"narrow_based_weighted_average\", \"full_ratchet\"] },\n { flags: \"--conversion-precedence <conversion-precedence>\", description: \"Conversion priority ordering\", type: \"array\" },\n { flags: \"--protective-provisions <protective-provisions>\", description: \"Protective provision terms\" },\n ],\n examples: [\"corp equity fundraising-workflows-apply-terms <workflow-id> --anti-dilution-method none\", \"corp equity fundraising-workflows-apply-terms --json\"],\n successTemplate: \"Fundraising Workflows Apply Terms created\",\n },\n {\n name: \"equity fundraising-workflows-compile-packet\",\n description: \"Compile the document packet for a fundraising round\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/compile-packet\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--phase <phase>\", description: \"Workflow phase\" },\n { flags: \"--required-signers <required-signers>\", description: \"List of required signers\", type: \"array\" },\n ],\n examples: [\"corp equity fundraising-workflows-compile-packet <workflow-id>\", \"corp equity fundraising-workflows-compile-packet --json\"],\n successTemplate: \"Fundraising Workflows Compile Packet created\",\n },\n {\n name: \"equity fundraising-workflows-finalize\",\n description: \"Finalize and close a fundraising workflow\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/finalize\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--phase <phase>\", description: \"Workflow phase\" },\n ],\n examples: [\"corp equity fundraising-workflows-finalize <workflow-id>\", \"corp equity fundraising-workflows-finalize --json\"],\n successTemplate: \"Fundraising Workflows Finalize created\",\n },\n {\n name: \"equity fundraising-workflows-generate-board-packet\",\n description: \"Generate board approval packet for fundraising\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/generate-board-packet\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--documents <documents>\", description: \"Document references or content\", type: \"array\" },\n ],\n examples: [\"corp equity fundraising-workflows-generate-board-packet <workflow-id>\", \"corp equity fundraising-workflows-generate-board-packet --json\"],\n successTemplate: \"Fundraising Workflows Generate Board Packet created\",\n },\n {\n name: \"equity fundraising-workflows-generate-closing-packet\",\n description: \"Generate closing documents for fundraising\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/generate-closing-packet\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--documents <documents>\", description: \"Document references or content\", type: \"array\" },\n ],\n examples: [\"corp equity fundraising-workflows-generate-closing-packet <workflow-id>\", \"corp equity fundraising-workflows-generate-closing-packet --json\"],\n successTemplate: \"Fundraising Workflows Generate Closing Packet created\",\n },\n {\n name: \"equity fundraising-workflows-prepare-execution\",\n description: \"Prepare fundraising for execution\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/prepare-execution\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--approval-artifact-id <approval-artifact-id>\", description: \"Approval artifact ID to bind\", required: true },\n { flags: \"--document-request-ids <document-request-ids>\", description: \"Comma-separated document request IDs\", type: \"array\" },\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n { flags: \"--phase <phase>\", description: \"Workflow phase\" },\n ],\n examples: [\"corp equity fundraising-workflows-prepare-execution <workflow-id> --approval-artifact-id 'approval-artifact-id' --intent-id 'intent-id'\", \"corp equity fundraising-workflows-prepare-execution --json\"],\n successTemplate: \"Fundraising Workflows Prepare Execution created\",\n },\n {\n name: \"equity fundraising-workflows-record-board-approval\",\n description: \"Record board approval for fundraising\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/record-board-approval\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\", required: true },\n { flags: \"--resolution-id <resolution-id>\", description: \"Resolution ID\", required: true },\n ],\n examples: [\"corp equity fundraising-workflows-record-board-approval <workflow-id> --meeting-id 'meeting-id' --resolution-id 'resolution-id'\"],\n successTemplate: \"Fundraising Workflows Record Board Approval created\",\n },\n {\n name: \"equity fundraising-workflows-record-close\",\n description: \"Record closing of a fundraising round\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/record-close\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n ],\n examples: [\"corp equity fundraising-workflows-record-close <workflow-id> --intent-id 'intent-id'\"],\n successTemplate: \"Fundraising Workflows Record Close created\",\n },\n {\n name: \"equity fundraising-workflows-record-investor-acceptance\",\n description: \"Record investor acceptance of terms\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/record-investor-acceptance\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--accepted-by-contact-id <accepted-by-contact-id>\", description: \"Contact ID of the accepting party\" },\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n ],\n examples: [\"corp equity fundraising-workflows-record-investor-acceptance <workflow-id> --intent-id 'intent-id'\", \"corp equity fundraising-workflows-record-investor-acceptance --json\"],\n successTemplate: \"Fundraising Workflows Record Investor Acceptance created\",\n },\n {\n name: \"equity fundraising-workflows-record-signature\",\n description: \"Record a signature on fundraising documents\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/record-signature\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--channel <channel>\", description: \"Approval channel (board_vote, written_consent, etc.)\" },\n { flags: \"--signer-identity <signer-identity>\", description: \"Identity of the signer\", required: true },\n ],\n examples: [\"corp equity fundraising-workflows-record-signature <workflow-id> --signer-identity 'signer-identity'\", \"corp equity fundraising-workflows-record-signature --json\"],\n successTemplate: \"Fundraising Workflows Record Signature created\",\n },\n {\n name: \"equity fundraising-workflows-start-signatures\",\n description: \"Start the signature collection process\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/start-signatures\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n examples: [\"corp equity fundraising-workflows-start-signatures <workflow-id>\"],\n successTemplate: \"Fundraising Workflows Start Signatures created\",\n },\n {\n name: \"equity grants\",\n description: \"Issue an equity grant (options, RSUs, etc.)\",\n route: { method: \"POST\", path: \"/v1/equity/grants\" },\n entity: true,\n options: [\n { flags: \"--grant-type <grant-type>\", description: \"The type of equity grant.\", required: true, choices: [\"common\", \"common_stock\", \"preferred\", \"preferred_stock\", \"membership_unit\", \"stock_option\", \"iso\", \"nso\", \"rsa\", \"svu\"] },\n { flags: \"--recipient-name <recipient-name>\", description: \"Payment recipient name\", required: true },\n { flags: \"--shares <shares>\", description: \"Shares\", required: true, type: \"int\" },\n ],\n examples: [\"corp equity grants --grant-type common_stock --recipient-name 'recipient-name' --shares 'shares'\"],\n successTemplate: \"Grants created\",\n },\n {\n name: \"equity holders\",\n description: \"Register a new equity holder\",\n route: { method: \"POST\", path: \"/v1/equity/holders\" },\n entity: true,\n options: [\n { flags: \"--contact-id <contact-id>\", description: \"Contact ID\", required: true },\n { flags: \"--external-reference <external-reference>\", description: \"External Reference\" },\n { flags: \"--holder-type <holder-type>\", description: \"Type of holder represented in the cap table.\", required: true, choices: [\"individual\", \"organization\", \"fund\", \"nonprofit\", \"trust\", \"other\"] },\n { flags: \"--linked-entity-id <linked-entity-id>\", description: \"ID of the entity to link\" },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n ],\n examples: [\"corp equity holders --contact-id 'contact-id' --holder-type individual --name 'name'\", \"corp equity holders --json\"],\n successTemplate: \"Holders created\",\n },\n {\n name: \"equity instruments\",\n description: \"Create a new equity instrument\",\n route: { method: \"POST\", path: \"/v1/equity/instruments\" },\n entity: true,\n options: [\n { flags: \"--authorized-units <authorized-units>\", description: \"Authorized Units\" },\n { flags: \"--issue-price-cents <issue-price-cents>\", description: \"Issue Price Cents\" },\n { flags: \"--issuer-legal-entity-id <issuer-legal-entity-id>\", description: \"Legal entity issuing the securities\", required: true },\n { flags: \"--kind <kind>\", description: \"Instrument kind in the ownership model.\", required: true, choices: [\"common_equity\", \"preferred_equity\", \"membership_unit\", \"option_grant\", \"safe\", \"convertible_note\", \"warrant\"] },\n { flags: \"--symbol <symbol>\", description: \"Symbol\", required: true },\n { flags: \"--terms <terms>\", description: \"Terms\" },\n ],\n examples: [\"corp equity instruments --issuer-legal-entity-id 'issuer-legal-entity-id' --kind common_equity --symbol 'symbol'\", \"corp equity instruments --json\"],\n successTemplate: \"Instruments created\",\n },\n {\n name: \"equity positions-adjust\",\n description: \"Adjust an equity position (split, correction)\",\n route: { method: \"POST\", path: \"/v1/equity/positions/adjust\" },\n entity: true,\n options: [\n { flags: \"--holder-id <holder-id>\", description: \"Equity holder ID\", required: true },\n { flags: \"--instrument-id <instrument-id>\", description: \"Instrument Id\", required: true },\n { flags: \"--issuer-legal-entity-id <issuer-legal-entity-id>\", description: \"Legal entity issuing the securities\", required: true },\n { flags: \"--principal-delta-cents <principal-delta-cents>\", description: \"Principal Delta Cents\", type: \"int\" },\n { flags: \"--quantity-delta <quantity-delta>\", description: \"Quantity Delta\", required: true, type: \"int\" },\n { flags: \"--source-reference <source-reference>\", description: \"Source reference for the conversion\" },\n ],\n examples: [\"corp equity positions-adjust --holder-id 'holder-id' --instrument-id 'instrument-id' --issuer-legal-entity-id 'issuer-legal-entity-id' --quantity-delta 'quantity-delta'\", \"corp equity positions-adjust --json\"],\n successTemplate: \"Positions Adjust created\",\n },\n {\n name: \"equity rounds\",\n description: \"Create a new equity round (prefer cap-table start-round which auto-resolves issuer)\",\n route: { method: \"POST\", path: \"/v1/equity/rounds\" },\n entity: true,\n options: [\n { flags: \"--conversion-target-instrument-id <conversion-target-instrument-id>\", description: \"Target instrument for conversion\" },\n { flags: \"--issuer-legal-entity-id <issuer-legal-entity-id>\", description: \"Issuer legal entity (run 'corp cap-table --json' to find this)\", required: true },\n { flags: \"--metadata <metadata>\", description: \"Additional metadata (JSON)\" },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--pre-money-cents <pre-money-cents>\", description: \"Pre-money valuation in cents\" },\n { flags: \"--round-price-cents <round-price-cents>\", description: \"Round share price in cents\" },\n { flags: \"--target-raise-cents <target-raise-cents>\", description: \"Target fundraising amount in cents\" },\n ],\n examples: [\"corp equity rounds --issuer-legal-entity-id 'issuer-legal-entity-id' --name 'name'\", \"corp equity rounds --json\"],\n successTemplate: \"Rounds created\",\n },\n {\n name: \"equity rounds-staged\",\n description: \"Create a staged (draft) equity round (prefer cap-table start-round which auto-resolves issuer)\",\n route: { method: \"POST\", path: \"/v1/equity/rounds/staged\" },\n entity: true,\n options: [\n { flags: \"--issuer-legal-entity-id <issuer-legal-entity-id>\", description: \"Issuer legal entity (run 'corp cap-table --json' to find this)\", required: true },\n { flags: \"--metadata <metadata>\", description: \"Additional metadata (JSON)\" },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--pre-money-cents <pre-money-cents>\", description: \"Pre-money valuation in cents\" },\n { flags: \"--round-price-cents <round-price-cents>\", description: \"Round share price in cents\" },\n { flags: \"--target-raise-cents <target-raise-cents>\", description: \"Target fundraising amount in cents\" },\n ],\n examples: [\"corp equity rounds-staged --issuer-legal-entity-id 'issuer-legal-entity-id' --name 'name'\", \"corp equity rounds-staged --json\"],\n successTemplate: \"Rounds Staged created\",\n },\n {\n name: \"equity rounds-accept\",\n description: \"Accept terms for an equity round\",\n route: { method: \"POST\", path: \"/v1/equity/rounds/{pos}/accept\" },\n entity: true,\n args: [{ name: \"round-id\", required: true, description: \"Equity round ID\" }],\n options: [\n { flags: \"--accepted-by-contact-id <accepted-by-contact-id>\", description: \"Contact ID of the accepting party\" },\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n ],\n examples: [\"corp equity rounds-accept <round-id> --intent-id 'intent-id'\", \"corp equity rounds-accept --json\"],\n successTemplate: \"Rounds Accept created\",\n },\n {\n name: \"equity rounds-apply-terms\",\n description: \"Apply term sheet to an equity round\",\n route: { method: \"POST\", path: \"/v1/equity/rounds/{pos}/apply-terms\" },\n entity: true,\n args: [{ name: \"round-id\", required: true, description: \"Equity round ID\" }],\n options: [\n { flags: \"--anti-dilution-method <anti-dilution-method>\", description: \"Anti-dilution protection method\", required: true, choices: [\"none\", \"broad_based_weighted_average\", \"narrow_based_weighted_average\", \"full_ratchet\"] },\n { flags: \"--conversion-precedence <conversion-precedence>\", description: \"Conversion priority ordering\", type: \"array\" },\n { flags: \"--protective-provisions <protective-provisions>\", description: \"Protective provision terms\" },\n ],\n examples: [\"corp equity rounds-apply-terms <round-id> --anti-dilution-method none\", \"corp equity rounds-apply-terms --json\"],\n successTemplate: \"Rounds Apply Terms created\",\n },\n {\n name: \"equity rounds-board-approve\",\n description: \"Record board approval for an equity round\",\n route: { method: \"POST\", path: \"/v1/equity/rounds/{pos}/board-approve\" },\n entity: true,\n args: [{ name: \"round-id\", required: true, description: \"Equity round ID\" }],\n options: [\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\", required: true },\n { flags: \"--resolution-id <resolution-id>\", description: \"Resolution ID\", required: true },\n ],\n examples: [\"corp equity rounds-board-approve <round-id> --meeting-id 'meeting-id' --resolution-id 'resolution-id'\"],\n successTemplate: \"Rounds Board Approve created\",\n },\n {\n name: \"equity rounds-issue\",\n description: \"Issue shares for an equity round\",\n route: { method: \"POST\", path: \"/v1/equity/rounds/{pos}/issue\" },\n entity: true,\n args: [{ name: \"round-id\", required: true, description: \"Equity round ID\" }],\n options: [\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\" },\n { flags: \"--resolution-id <resolution-id>\", description: \"Resolution ID\" },\n ],\n examples: [\"corp equity rounds-issue <round-id>\", \"corp equity rounds-issue --json\"],\n successTemplate: \"Rounds Issue created\",\n },\n {\n name: \"equity rounds-securities\",\n description: \"Add securities to an equity round\",\n route: { method: \"POST\", path: \"/v1/equity/rounds/{pos}/securities\" },\n entity: true,\n args: [{ name: \"round-id\", required: true, description: \"Equity round ID\" }],\n options: [\n { flags: \"--email <email>\", description: \"Email\" },\n { flags: \"--grant-type <grant-type>\", description: \"Grant Type\" },\n { flags: \"--holder-id <holder-id>\", description: \"Equity holder ID\" },\n { flags: \"--instrument-id <instrument-id>\", description: \"Instrument Id\", required: true },\n { flags: \"--principal-cents <principal-cents>\", description: \"Principal Cents\", type: \"int\" },\n { flags: \"--quantity <quantity>\", description: \"Quantity\", required: true, type: \"int\" },\n { flags: \"--recipient-name <recipient-name>\", description: \"Payment recipient name\", required: true },\n ],\n examples: [\"corp equity rounds-securities <round-id> --instrument-id 'instrument-id' --quantity 'quantity' --recipient-name 'recipient-name'\", \"corp equity rounds-securities --json\"],\n successTemplate: \"Rounds Securities created\",\n },\n {\n name: \"equity create-transfer-workflow\",\n description: \"Start or view a share transfer workflow\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows\" },\n options: [\n { flags: \"--from-contact-id <from-contact-id>\", description: \"From Contact Id\", required: true },\n { flags: \"--governing-doc-type <governing-doc-type>\", description: \"The type of governing document for a share transfer.\", required: true, choices: [\"bylaws\", \"operating_agreement\", \"shareholder_agreement\", \"other\"] },\n { flags: \"--prepare-intent-id <prepare-intent-id>\", description: \"Execution intent ID for preparation\", required: true },\n { flags: \"--price-per-share-cents <price-per-share-cents>\", description: \"Price Per Share Cents\" },\n { flags: \"--relationship-to-holder <relationship-to-holder>\", description: \"Relationship To Holder\" },\n { flags: \"--share-class-id <share-class-id>\", description: \"Share class ID\", required: true },\n { flags: \"--share-count <share-count>\", description: \"Number of shares\", required: true, type: \"int\" },\n { flags: \"--to-contact-id <to-contact-id>\", description: \"To Contact Id\", required: true },\n { flags: \"--transfer-type <transfer-type>\", description: \"Type of share transfer.\", required: true, choices: [\"gift\", \"trust_transfer\", \"secondary_sale\", \"estate\", \"other\"] },\n { flags: \"--transferee-rights <transferee-rights>\", description: \"Rights granted to the transferee.\", required: true, choices: [\"full_member\", \"economic_only\", \"limited\"] },\n ],\n examples: [\"corp equity transfer-workflows --from-contact-id 'from-contact-id' --governing-doc-type bylaws --prepare-intent-id 'prepare-intent-id' --share-class-id 'share-class-id' --share-count 'share-count' --to-contact-id gift --transfer-type gift --transferee-rights full_member\", \"corp equity transfer-workflows --json\"],\n successTemplate: \"Transfer Workflows created\",\n },\n {\n name: \"equity transfer-workflows\",\n description: \"Start or view a share transfer workflow\",\n route: { method: \"GET\", path: \"/v1/equity/transfer-workflows/{pos}\" },\n entity: true,\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n display: { title: \"Equity Transfer Workflows\", cols: [\"execution_status>Execution Status\", \"generated_documents>Generated Documents\", \"last_packet_hash>Last Packet Hash\", \"@created_at>Created At\", \"#active_packet_id>ID\"] },\n examples: [\"corp equity transfer-workflows\", \"corp equity transfer-workflows --json\"],\n },\n {\n name: \"equity transfer-workflows-compile-packet\",\n description: \"Compile documents for a share transfer\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/compile-packet\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--phase <phase>\", description: \"Workflow phase\" },\n { flags: \"--required-signers <required-signers>\", description: \"List of required signers\", type: \"array\" },\n ],\n examples: [\"corp equity transfer-workflows-compile-packet <workflow-id>\", \"corp equity transfer-workflows-compile-packet --json\"],\n successTemplate: \"Transfer Workflows Compile Packet created\",\n },\n {\n name: \"equity transfer-workflows-finalize\",\n description: \"Finalize a share transfer workflow\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/finalize\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--phase <phase>\", description: \"Workflow phase\" },\n ],\n examples: [\"corp equity transfer-workflows-finalize <workflow-id>\", \"corp equity transfer-workflows-finalize --json\"],\n successTemplate: \"Transfer Workflows Finalize created\",\n },\n {\n name: \"equity transfer-workflows-generate-docs\",\n description: \"Generate documents for a share transfer\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/generate-docs\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--documents <documents>\", description: \"Document references or content\", type: \"array\" },\n ],\n examples: [\"corp equity transfer-workflows-generate-docs <workflow-id>\", \"corp equity transfer-workflows-generate-docs --json\"],\n successTemplate: \"Transfer Workflows Generate Docs created\",\n },\n {\n name: \"equity transfer-workflows-prepare-execution\",\n description: \"Prepare transfer for execution\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/prepare-execution\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--approval-artifact-id <approval-artifact-id>\", description: \"Approval artifact ID to bind\", required: true },\n { flags: \"--document-request-ids <document-request-ids>\", description: \"Comma-separated document request IDs\", type: \"array\" },\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n { flags: \"--phase <phase>\", description: \"Workflow phase\" },\n ],\n examples: [\"corp equity transfer-workflows-prepare-execution <workflow-id> --approval-artifact-id 'approval-artifact-id' --intent-id 'intent-id'\", \"corp equity transfer-workflows-prepare-execution --json\"],\n successTemplate: \"Transfer Workflows Prepare Execution created\",\n },\n {\n name: \"equity transfer-workflows-record-board-approval\",\n description: \"Record board approval for a transfer\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/record-board-approval\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\", required: true },\n { flags: \"--resolution-id <resolution-id>\", description: \"Resolution ID\", required: true },\n ],\n examples: [\"corp equity transfer-workflows-record-board-approval <workflow-id> --meeting-id 'meeting-id' --resolution-id 'resolution-id'\"],\n successTemplate: \"Transfer Workflows Record Board Approval created\",\n },\n {\n name: \"equity transfer-workflows-record-execution\",\n description: \"Record execution of a share transfer\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/record-execution\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n ],\n examples: [\"corp equity transfer-workflows-record-execution <workflow-id> --intent-id 'intent-id'\"],\n successTemplate: \"Transfer Workflows Record Execution created\",\n },\n {\n name: \"equity transfer-workflows-record-review\",\n description: \"Record review of a share transfer\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/record-review\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--approved\", description: \"Approved\", required: true },\n { flags: \"--notes <notes>\", description: \"Additional notes\", required: true },\n { flags: \"--reviewer <reviewer>\", description: \"Reviewer\", required: true },\n ],\n examples: [\"corp equity transfer-workflows-record-review <workflow-id> --approved --notes 'notes' --reviewer 'reviewer'\"],\n successTemplate: \"Transfer Workflows Record Review created\",\n },\n {\n name: \"equity transfer-workflows-record-rofr\",\n description: \"Record right of first refusal waiver\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/record-rofr\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--offered\", description: \"Offered\", required: true },\n { flags: \"--waived\", description: \"Waived\", required: true },\n ],\n examples: [\"corp equity transfer-workflows-record-rofr <workflow-id> --offered --waived\"],\n successTemplate: \"Transfer Workflows Record Rofr created\",\n },\n {\n name: \"equity transfer-workflows-record-signature\",\n description: \"Record a signature on transfer documents\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/record-signature\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--channel <channel>\", description: \"Approval channel (board_vote, written_consent, etc.)\" },\n { flags: \"--signer-identity <signer-identity>\", description: \"Identity of the signer\", required: true },\n ],\n examples: [\"corp equity transfer-workflows-record-signature <workflow-id> --signer-identity 'signer-identity'\", \"corp equity transfer-workflows-record-signature --json\"],\n successTemplate: \"Transfer Workflows Record Signature created\",\n },\n {\n name: \"equity transfer-workflows-start-signatures\",\n description: \"Start signature collection for transfer\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/start-signatures\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n examples: [\"corp equity transfer-workflows-start-signatures <workflow-id>\"],\n successTemplate: \"Transfer Workflows Start Signatures created\",\n },\n {\n name: \"equity transfer-workflows-submit-review\",\n description: \"Submit a share transfer for review\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/submit-review\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n examples: [\"corp equity transfer-workflows-submit-review <workflow-id>\"],\n successTemplate: \"Transfer Workflows Submit Review created\",\n },\n {\n name: \"equity workflows-status\",\n description: \"Check status of an equity workflow\",\n route: { method: \"GET\", path: \"/v1/equity/workflows/{pos}/{pos2}/status\" },\n entity: true,\n args: [{ name: \"workflow-type\", required: true, description: \"Workflow Type\" }, { name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n display: { title: \"Equity Workflows Status\", cols: [\"execution_status>Execution Status\", \"fundraising_workflow>Fundraising Workflow\", \"packet>Packet\", \"transfer_workflow>Transfer Workflow\", \"#active_packet_id>ID\"] },\n examples: [\"corp equity workflows-status\", \"corp equity workflows-status --json\"],\n },\n {\n name: \"safe-notes\",\n description: \"Issue a new SAFE note\",\n route: { method: \"POST\", path: \"/v1/safe-notes\" },\n options: [\n { flags: \"--conversion-unit-type <conversion-unit-type>\", description: \"Conversion Unit Type\" },\n { flags: \"--discount-rate <discount-rate>\", description: \"SAFE discount rate (0-100)\" },\n { flags: \"--document-id <document-id>\", description: \"Document ID\" },\n { flags: \"--email <email>\", description: \"Email\" },\n { flags: \"--investor-contact-id <investor-contact-id>\", description: \"Investor Contact Id\" },\n { flags: \"--investor-name <investor-name>\", description: \"Investor name\", required: true },\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\" },\n { flags: \"--principal-amount-cents <principal-amount-cents>\", description: \"Principal Amount Cents\", required: true, type: \"int\" },\n { flags: \"--pro-rata-rights\", description: \"Pro Rata Rights\" },\n { flags: \"--resolution-id <resolution-id>\", description: \"Resolution ID\" },\n { flags: \"--safe-type <safe-type>\", description: \"Safe Type\", choices: [\"post_money\", \"pre_money\", \"mfn\"] },\n { flags: \"--valuation-cap-cents <valuation-cap-cents>\", description: \"Valuation Cap Cents\" },\n ],\n examples: [\"corp safe-notes --investor-name 'investor-name' --principal-amount-cents 'principal-amount-cents'\", \"corp safe-notes --json\"],\n successTemplate: \"Safe Notes created\",\n },\n {\n name: \"share-transfers\",\n description: \"Execute a share transfer between parties\",\n route: { method: \"POST\", path: \"/v1/share-transfers\" },\n options: [\n { flags: \"--from-holder <from-holder>\", description: \"From Holder\", required: true },\n { flags: \"--governing-doc-type <governing-doc-type>\", description: \"Governing Doc Type\", choices: [\"bylaws\", \"operating_agreement\", \"shareholder_agreement\", \"other\"] },\n { flags: \"--share-class-id <share-class-id>\", description: \"Share class ID\", required: true },\n { flags: \"--shares <shares>\", description: \"Shares\", required: true, type: \"int\" },\n { flags: \"--to-holder <to-holder>\", description: \"To Holder\", required: true },\n { flags: \"--transfer-type <transfer-type>\", description: \"Type of share transfer.\", required: true, choices: [\"gift\", \"trust_transfer\", \"secondary_sale\", \"estate\", \"other\"] },\n { flags: \"--transferee-rights <transferee-rights>\", description: \"Transferee Rights\", choices: [\"full_member\", \"economic_only\", \"limited\"] },\n ],\n examples: [\"corp share-transfers --from-holder bylaws --share-class-id 'share-class-id' --shares 'shares' --to-holder gift --transfer-type gift\", \"corp share-transfers --json\"],\n successTemplate: \"Share Transfers created\",\n },\n {\n name: \"valuations\",\n description: \"Create a new company valuation\",\n route: { method: \"POST\", path: \"/v1/valuations\" },\n options: [\n { flags: \"--dlom <dlom>\", description: \"Dlom\" },\n { flags: \"--effective-date <effective-date>\", description: \"Effective Date\", required: true },\n { flags: \"--enterprise-value-cents <enterprise-value-cents>\", description: \"Enterprise Value Cents\" },\n { flags: \"--fmv-per-share-cents <fmv-per-share-cents>\", description: \"Fmv Per Share Cents\" },\n { flags: \"--hurdle-amount-cents <hurdle-amount-cents>\", description: \"Hurdle Amount Cents\" },\n { flags: \"--methodology <methodology>\", description: \"Methodology used for a valuation.\", required: true, choices: [\"income\", \"market\", \"asset\", \"backsolve\", \"hybrid\", \"other\"] },\n { flags: \"--provider-contact-id <provider-contact-id>\", description: \"Provider Contact Id\" },\n { flags: \"--report-date <report-date>\", description: \"Report Date\" },\n { flags: \"--report-document-id <report-document-id>\", description: \"Report Document Id\" },\n { flags: \"--valuation-type <valuation-type>\", description: \"Type of 409A or equivalent valuation.\", required: true, choices: [\"four_oh_nine_a\", \"llc_profits_interest\", \"fair_market_value\", \"gift\", \"estate\", \"other\"] },\n ],\n examples: [\"corp valuations --effective-date 'effective-date' --methodology income --valuation-type four_oh_nine_a\", \"corp valuations --json\"],\n successTemplate: \"Valuations created\",\n },\n {\n name: \"valuations submit-for-approval\",\n description: \"Submit a valuation for board approval\",\n route: { method: \"POST\", path: \"/v1/valuations/{pos}/submit-for-approval\" },\n args: [{ name: \"valuation-id\", required: true, description: \"Valuation ID\" }],\n examples: [\"corp valuations submit-for-approval <valuation-id>\"],\n successTemplate: \"Submit For Approval created\",\n },\n\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n printBankAccountsTable,\n printClassificationsTable,\n printDistributionsTable,\n printError,\n printFinanceSummaryPanel,\n printInvoicesTable,\n printJson,\n printPaymentsTable,\n printPayrollRunsTable,\n printReconciliationsTable,\n printWriteResult,\n} from \"../output.js\";\nimport type { ApiRecord } from \"../types.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers (relocated from commands/finance.ts)\n// ---------------------------------------------------------------------------\n\nfunction numeric(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction sumAmounts(records: ApiRecord[], candidates: string[]): number {\n return records.reduce((sum, record) => {\n for (const key of candidates) {\n if (typeof record[key] === \"number\" && Number.isFinite(record[key])) {\n return sum + Number(record[key]);\n }\n }\n return sum;\n }, 0);\n}\n\nfunction latestDate(records: ApiRecord[], candidates: string[]): string | undefined {\n const values = records\n .flatMap((record) => candidates.map((key) => record[key]))\n .filter((value): value is string => typeof value === \"string\" && value.trim().length > 0)\n .map((value) => ({ raw: value, time: new Date(value).getTime() }))\n .filter((value) => Number.isFinite(value.time))\n .sort((a, b) => b.time - a.time);\n return values[0]?.raw;\n}\n\nfunction countByStatus(records: ApiRecord[], statuses: string[]): number {\n const expected = new Set(statuses.map((status) => status.toLowerCase()));\n return records.filter((record) => expected.has(String(record.status ?? \"\").toLowerCase())).length;\n}\n\nfunction countByField(records: ApiRecord[], field: string, values: string[]): number {\n const expected = new Set(values.map((value) => value.toLowerCase()));\n return records.filter((record) => expected.has(String(record[field] ?? \"\").toLowerCase())).length;\n}\n\n// ---------------------------------------------------------------------------\n// Finance registry entries\n// ---------------------------------------------------------------------------\n\nexport const financeCommands: CommandDef[] = [\n // --- finance (summary panel) ---\n {\n name: \"finance\",\n description: \"Invoicing, payroll, payments, banking\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/finance/summary\" },\n entity: true,\n display: { title: \"Finance Summary\" },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const [\n invoices,\n accounts,\n payments,\n payrollRuns,\n distributions,\n reconciliations,\n classifications,\n ] = await Promise.all([\n ctx.client.listInvoices(eid),\n ctx.client.listBankAccounts(eid),\n ctx.client.listPayments(eid),\n ctx.client.listPayrollRuns(eid),\n ctx.client.listDistributions(eid),\n ctx.client.listReconciliations(eid),\n ctx.client.listContractorClassifications(eid),\n ]);\n\n await Promise.all([\n ctx.resolver.stabilizeRecords(\"invoice\", invoices, eid),\n ctx.resolver.stabilizeRecords(\"bank_account\", accounts, eid),\n ctx.resolver.stabilizeRecords(\"payment\", payments, eid),\n ctx.resolver.stabilizeRecords(\"payroll_run\", payrollRuns, eid),\n ctx.resolver.stabilizeRecords(\"distribution\", distributions, eid),\n ctx.resolver.stabilizeRecords(\"reconciliation\", reconciliations, eid),\n ctx.resolver.stabilizeRecords(\"classification\", classifications, eid),\n ]);\n\n const summary: ApiRecord = {\n entity_id: eid,\n invoices: {\n count: invoices.length,\n open_count: invoices.length - countByStatus(invoices, [\"paid\", \"cancelled\", \"void\"]),\n overdue_count: countByStatus(invoices, [\"overdue\"]),\n total_amount_cents: sumAmounts(invoices, [\"amount_cents\", \"total_amount_cents\"]),\n latest_due_date: latestDate(invoices, [\"due_date\", \"created_at\"]),\n },\n bank_accounts: {\n count: accounts.length,\n active_count: countByStatus(accounts, [\"active\", \"approved\", \"open\"]),\n },\n payments: {\n count: payments.length,\n pending_count: countByStatus(payments, [\"pending\", \"submitted\", \"queued\"]),\n total_amount_cents: sumAmounts(payments, [\"amount_cents\"]),\n latest_submitted_at: latestDate(payments, [\"submitted_at\", \"created_at\"]),\n },\n payroll_runs: {\n count: payrollRuns.length,\n latest_period_end: latestDate(payrollRuns, [\"pay_period_end\", \"created_at\"]),\n },\n distributions: {\n count: distributions.length,\n total_amount_cents: sumAmounts(distributions, [\"amount_cents\", \"distribution_amount_cents\"]),\n latest_declared_at: latestDate(distributions, [\"declared_at\", \"created_at\"]),\n },\n reconciliations: {\n count: reconciliations.length,\n balanced_count: reconciliations.filter((record) => record.is_balanced === true).length,\n latest_as_of_date: latestDate(reconciliations, [\"as_of_date\", \"created_at\"]),\n },\n contractor_classifications: {\n count: classifications.length,\n high_risk_count: countByField(classifications, \"risk_level\", [\"high\"]),\n medium_risk_count: countByField(classifications, \"risk_level\", [\"medium\"]),\n },\n };\n\n if (ctx.opts.json) { ctx.writer.json(summary); return; }\n printFinanceSummaryPanel(summary);\n },\n examples: [\n \"corp finance\",\n 'corp finance invoice --customer \"Client Co\" --amount-cents 500000 --due-date 2026-04-01',\n 'corp finance pay --amount-cents 250000 --recipient \"Vendor\" --method ach',\n \"corp finance payroll --period-start 2026-03-01 --period-end 2026-03-15\",\n \"corp finance open-account --institution Mercury\",\n \"corp finance statements --period 2026-Q1\",\n ],\n },\n\n // --- finance invoices ---\n {\n name: \"finance invoices\",\n description: \"List invoices\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/invoices\" },\n entity: true,\n display: {\n title: \"Invoices\",\n cols: [\"customer_name|customer>Customer\", \"$amount_cents>Amount\", \"status>Status\", \"@due_date>Due\", \"#invoice_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const invoices = await ctx.client.listInvoices(eid);\n await ctx.resolver.stabilizeRecords(\"invoice\", invoices, eid);\n if (ctx.opts.json) { ctx.writer.json(invoices); return; }\n if (invoices.length === 0) { ctx.writer.writeln(\"No invoices found.\"); return; }\n printInvoicesTable(invoices);\n },\n examples: [\"corp finance invoices\", \"corp finance invoices --json\"],\n },\n\n // --- finance invoice (create) ---\n {\n name: \"finance invoice\",\n description: \"Create an invoice\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/invoices\" },\n entity: true,\n options: [\n { flags: \"--customer <name>\", description: \"Customer name\", required: true },\n { flags: \"--amount-cents <n>\", description: \"Amount in cents (e.g. 500000 = $5,000.00)\", type: \"int\" },\n { flags: \"--amount-dollars <n>\", description: \"Amount in dollars (e.g. 5000 = $5,000.00)\", type: \"int\" },\n { flags: \"--due-date <date>\", description: \"Due date (ISO 8601)\", required: true },\n { flags: \"--description <desc>\", description: \"Description text\", default: \"Services rendered\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n if (ctx.opts.amountCents != null && ctx.opts.amountDollars != null) {\n printError(\"--amount-cents and --amount-dollars are mutually exclusive. Use one or the other.\");\n process.exit(1);\n }\n const amountCents = (ctx.opts.amountCents as number | undefined) ?? ((ctx.opts.amountDollars as number | undefined) != null ? (ctx.opts.amountDollars as number) * 100 : undefined);\n if (amountCents == null) {\n printError(\"required: --amount-cents <n> or --amount-dollars <n>\");\n process.exit(1);\n }\n const result = await ctx.client.createInvoice({\n entity_id: eid,\n customer_name: ctx.opts.customer as string,\n amount_cents: amountCents,\n due_date: ctx.opts.dueDate as string,\n description: ctx.opts.description as string,\n });\n await ctx.resolver.stabilizeRecord(\"invoice\", result, eid);\n ctx.resolver.rememberFromRecord(\"invoice\", result, eid);\n ctx.writer.writeResult(result, `Invoice created: ${result.invoice_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"invoice\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"invoice\" },\n successTemplate: \"Invoice created: {customer_name}\",\n examples: [\"corp finance invoice --customer 'name' --due-date 'date'\", \"corp finance invoice --json\"],\n },\n\n // --- finance payments ---\n {\n name: \"finance payments\",\n description: \"List payments\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/payments\" },\n entity: true,\n display: {\n title: \"Payments\",\n cols: [\"recipient>Recipient\", \"$amount_cents>Amount\", \"status>Status\", \"@submitted_at>Submitted\", \"#payment_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const payments = await ctx.client.listPayments(eid);\n await ctx.resolver.stabilizeRecords(\"payment\", payments, eid);\n if (ctx.opts.json) { ctx.writer.json(payments); return; }\n if (payments.length === 0) { ctx.writer.writeln(\"No payments found.\"); return; }\n printPaymentsTable(payments);\n },\n examples: [\"corp finance payments\", \"corp finance payments --json\"],\n },\n\n // --- finance pay ---\n {\n name: \"finance pay\",\n description: \"Submit a payment\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/payments\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <n>\", description: \"Amount in cents (e.g. 500000 = $5,000.00)\", type: \"int\" },\n { flags: \"--amount-dollars <n>\", description: \"Amount in dollars (e.g. 5000 = $5,000.00)\", type: \"int\" },\n { flags: \"--recipient <name>\", description: \"Recipient name\", required: true },\n { flags: \"--method <method>\", description: \"Payment method\", default: \"ach\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n if (ctx.opts.amountCents != null && ctx.opts.amountDollars != null) {\n printError(\"--amount-cents and --amount-dollars are mutually exclusive. Use one or the other.\");\n process.exit(1);\n }\n const amountCents = (ctx.opts.amountCents as number | undefined) ?? ((ctx.opts.amountDollars as number | undefined) != null ? (ctx.opts.amountDollars as number) * 100 : undefined);\n if (amountCents == null) {\n printError(\"required: --amount-cents <n> or --amount-dollars <n>\");\n process.exit(1);\n }\n const method = ctx.opts.method as string;\n const result = await ctx.client.submitPayment({\n entity_id: eid,\n amount_cents: amountCents,\n recipient: ctx.opts.recipient as string,\n payment_method: method,\n description: `Payment via ${method}`,\n });\n await ctx.resolver.stabilizeRecord(\"payment\", result, eid);\n ctx.resolver.rememberFromRecord(\"payment\", result, eid);\n ctx.writer.writeResult(result, `Payment submitted: ${result.payment_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"payment\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"payment\" },\n successTemplate: \"Payment submitted: {recipient_name}\",\n examples: [\"corp finance pay --recipient 'name'\", \"corp finance pay --json\"],\n },\n\n // --- finance bank-accounts ---\n {\n name: \"finance bank-accounts\",\n description: \"List bank accounts\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/bank-accounts\" },\n entity: true,\n display: {\n title: \"Bank Accounts\",\n cols: [\"bank_name|institution>Bank\", \"status>Status\", \"#bank_account_id|account_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const accounts = await ctx.client.listBankAccounts(eid);\n await ctx.resolver.stabilizeRecords(\"bank_account\", accounts, eid);\n if (ctx.opts.json) { ctx.writer.json(accounts); return; }\n if (accounts.length === 0) { ctx.writer.writeln(\"No bank accounts found.\"); return; }\n printBankAccountsTable(accounts);\n },\n examples: [\"corp finance bank-accounts\", \"corp finance bank-accounts --json\"],\n },\n\n // --- finance open-account ---\n {\n name: \"finance open-account\",\n description: \"Open a business bank account\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/bank-accounts\" },\n entity: true,\n options: [\n { flags: \"--institution <name>\", description: \"Banking institution\", default: \"Mercury\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const result = await ctx.client.openBankAccount({ entity_id: eid, bank_name: ctx.opts.institution as string });\n await ctx.resolver.stabilizeRecord(\"bank_account\", result, eid);\n ctx.resolver.rememberFromRecord(\"bank_account\", result, eid);\n ctx.writer.writeResult(result, `Bank account opened: ${result.bank_account_id ?? result.account_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"bank_account\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"bank_account\" },\n successTemplate: \"Bank account opened: {bank_name}\",\n examples: [\"corp finance open-account\", \"corp finance open-account --json\"],\n },\n\n // --- finance activate-account <account-ref> ---\n {\n name: \"finance activate-account\",\n description: \"Activate a bank account (transitions from pending_review to active)\",\n route: { method: \"POST\", path: \"/v1/bank-accounts/{pos}/activate\" },\n entity: true,\n args: [{ name: \"account-ref\", required: true, description: \"Bank account reference\" }],\n handler: async (ctx) => {\n const accountRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedId = await ctx.resolver.resolveBankAccount(eid, accountRef);\n const result = await ctx.client.activateBankAccount(resolvedId, eid);\n await ctx.resolver.stabilizeRecord(\"bank_account\", result, eid);\n ctx.resolver.rememberFromRecord(\"bank_account\", result, eid);\n ctx.writer.writeResult(result, `Bank account activated: ${resolvedId}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"bank_account\",\n showReuseHint: true,\n });\n },\n examples: [\"corp finance activate-account <account-ref>\"],\n },\n\n // --- finance payroll-runs ---\n {\n name: \"finance payroll-runs\",\n description: \"List payroll runs\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/payroll-runs\" },\n entity: true,\n display: {\n title: \"Payroll Runs\",\n cols: [\"@pay_period_start>Period Start\", \"@pay_period_end>Period End\", \"status>Status\", \"#payroll_run_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const runs = await ctx.client.listPayrollRuns(eid);\n await ctx.resolver.stabilizeRecords(\"payroll_run\", runs, eid);\n if (ctx.opts.json) { ctx.writer.json(runs); return; }\n if (runs.length === 0) { ctx.writer.writeln(\"No payroll runs found.\"); return; }\n printPayrollRunsTable(runs);\n },\n examples: [\"corp finance payroll-runs\", \"corp finance payroll-runs --json\"],\n },\n\n // --- finance payroll ---\n {\n name: \"finance payroll\",\n description: \"Run payroll\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/payroll-runs\" },\n entity: true,\n options: [\n { flags: \"--period-start <date>\", description: \"Pay period start\", required: true },\n { flags: \"--period-end <date>\", description: \"Pay period end\", required: true },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const result = await ctx.client.runPayroll({\n entity_id: eid,\n pay_period_start: ctx.opts.periodStart as string,\n pay_period_end: ctx.opts.periodEnd as string,\n });\n await ctx.resolver.stabilizeRecord(\"payroll_run\", result, eid);\n ctx.resolver.rememberFromRecord(\"payroll_run\", result, eid);\n ctx.writer.writeResult(result, `Payroll run created: ${result.payroll_run_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"payroll_run\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"payroll_run\" },\n successTemplate: \"Payroll run created\",\n examples: [\"corp finance payroll --period-start 'date' --period-end 'date'\"],\n },\n\n // --- finance distributions ---\n {\n name: \"finance distributions\",\n description: \"List distributions\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/distributions\" },\n entity: true,\n display: {\n title: \"Distributions\",\n cols: [\"$amount_cents|distribution_amount_cents>Amount\", \"status>Status\", \"@declared_at>Declared\", \"#distribution_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const distributions = await ctx.client.listDistributions(eid);\n await ctx.resolver.stabilizeRecords(\"distribution\", distributions, eid);\n if (ctx.opts.json) { ctx.writer.json(distributions); return; }\n if (distributions.length === 0) { ctx.writer.writeln(\"No distributions found.\"); return; }\n printDistributionsTable(distributions);\n },\n examples: [\"corp finance distributions\", \"corp finance distributions --json\"],\n },\n\n // --- finance reconciliations ---\n {\n name: \"finance reconciliations\",\n description: \"List reconciliations\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/reconciliations\" },\n entity: true,\n display: {\n title: \"Reconciliations\",\n cols: [\"@as_of_date>As Of\", \"is_balanced>Balanced\", \"#reconciliation_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const reconciliations = await ctx.client.listReconciliations(eid);\n await ctx.resolver.stabilizeRecords(\"reconciliation\", reconciliations, eid);\n if (ctx.opts.json) { ctx.writer.json(reconciliations); return; }\n if (reconciliations.length === 0) { ctx.writer.writeln(\"No reconciliations found.\"); return; }\n printReconciliationsTable(reconciliations);\n },\n examples: [\"corp finance reconciliations\", \"corp finance reconciliations --json\"],\n },\n\n // --- finance reconcile ---\n {\n name: \"finance reconcile\",\n description: \"Reconcile ledger (requires --start-date and --end-date)\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/reconciliations\" },\n entity: true,\n options: [\n { flags: \"--start-date <date>\", description: \"Period start (required, ISO 8601)\", required: true },\n { flags: \"--end-date <date>\", description: \"Period end (required, ISO 8601)\", required: true },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const result = await ctx.client.reconcileLedger({\n entity_id: eid,\n start_date: ctx.opts.startDate as string,\n end_date: ctx.opts.endDate as string,\n });\n await ctx.resolver.stabilizeRecord(\"reconciliation\", result, eid);\n ctx.resolver.rememberFromRecord(\"reconciliation\", result, eid);\n ctx.writer.writeResult(result, `Ledger reconciled: ${result.reconciliation_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"reconciliation\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"reconciliation\" },\n successTemplate: \"Reconciliation created\",\n examples: [\"corp finance reconcile --start-date 'date' --end-date 'date'\"],\n },\n\n // --- finance classifications ---\n {\n name: \"finance classifications\",\n description: \"List contractor classifications\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/contractor-classifications\" },\n entity: true,\n display: {\n title: \"Contractor Classifications\",\n cols: [\"contractor_name>Contractor\", \"risk_level>Risk\", \"state>State\", \"#classification_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const classifications = await ctx.client.listContractorClassifications(eid);\n await ctx.resolver.stabilizeRecords(\"classification\", classifications, eid);\n if (ctx.opts.json) { ctx.writer.json(classifications); return; }\n if (classifications.length === 0) { ctx.writer.writeln(\"No contractor classifications found.\"); return; }\n printClassificationsTable(classifications);\n },\n examples: [\"corp finance classifications\", \"corp finance classifications --json\"],\n },\n\n // --- finance classify-contractor ---\n {\n name: \"finance classify-contractor\",\n description: \"Analyze contractor classification risk\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/contractor-classifications\" },\n entity: true,\n options: [\n { flags: \"--name <name>\", description: \"Contractor name\", required: true },\n { flags: \"--state <code>\", description: \"US state code\", required: true },\n { flags: \"--hours <n>\", description: \"Hours per week\", required: true, type: \"int\" },\n { flags: \"--exclusive\", description: \"Exclusive client\", default: false },\n { flags: \"--duration <n>\", description: \"Duration in months\", required: true, type: \"int\" },\n { flags: \"--provides-tools\", description: \"Company provides tools\", default: false },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const result = await ctx.client.classifyContractor({\n entity_id: eid,\n contractor_name: ctx.opts.name as string,\n state: ctx.opts.state as string,\n hours_per_week: ctx.opts.hours as number,\n exclusive_client: !!ctx.opts.exclusive,\n duration_months: ctx.opts.duration as number,\n provides_tools: !!ctx.opts.providesTools,\n });\n await ctx.resolver.stabilizeRecord(\"classification\", result, eid);\n ctx.resolver.rememberFromRecord(\"classification\", result, eid);\n ctx.writer.writeResult(result, `Classification: ${result.risk_level ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"classification\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"classification\" },\n successTemplate: \"Classification created: {contractor_name}\",\n examples: [\"corp finance classify-contractor --name 'name' --state 'code' --hours 'n' --duration 'n'\", \"corp finance classify-contractor --json\"],\n },\n\n // --- finance statements ---\n {\n name: \"finance statements\",\n description: \"View financial statements (P&L, balance sheet)\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/financial-statements\" },\n entity: \"query\",\n display: { title: \"Financial Statements\" },\n options: [\n { flags: \"--period <period>\", description: \"Period (e.g. 2026-Q1, 2025)\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const params: Record<string, string> = {};\n if (ctx.opts.period) params.period = ctx.opts.period as string;\n const result = await ctx.client.getFinancialStatements(eid, params);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n printJson(result);\n },\n examples: [\"corp finance statements\", \"corp finance statements --json\"],\n },\n];","import chalk from \"chalk\";\nimport type { CommandDef, CommandContext } from \"./types.js\";\nimport type { ApiRecord } from \"../types.js\";\nimport {\n printGovernanceTable,\n printSeatsTable,\n printMeetingsTable,\n printResolutionsTable,\n printAgendaItemsTable,\n printReferenceSummary,\n} from \"../output.js\";\nimport { confirm } from \"@inquirer/prompts\";\nimport { writtenConsent as writtenConsentWorkflow } from \"@thecorporation/corp-tools\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst FINALIZE_ITEM_STATUS_CHOICES = [\n \"discussed\",\n \"voted\",\n \"tabled\",\n \"withdrawn\",\n] as const;\n\n// ---------------------------------------------------------------------------\n// Governance registry entries\n// ---------------------------------------------------------------------------\n\nexport const governanceCommands: CommandDef[] = [\n // --- governance (list bodies) ---\n {\n name: \"governance\",\n description: \"Governance bodies, seats, meetings, resolutions\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance-bodies\" },\n entity: true,\n display: {\n title: \"Governance Bodies\",\n cols: [\"name>Body\", \"body_type>Type\", \"seat_count|seats>Seats\", \"meeting_count|meetings>Meetings\", \"#body_id>ID\"],\n },\n options: [\n { flags: \"--body-id <ref>\", description: \"Governance body reference\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const bodies = await ctx.client.listGovernanceBodies(eid);\n await ctx.resolver.stabilizeRecords(\"body\", bodies, eid);\n if (ctx.opts.json) { ctx.writer.json(bodies); return; }\n if (bodies.length === 0) { ctx.writer.writeln(\"No governance bodies found.\"); return; }\n printGovernanceTable(bodies);\n },\n examples: [\n \"corp governance\",\n 'corp governance create-body --name \"Board of Directors\" --body-type board_of_directors',\n 'corp governance add-seat @last:body --holder \"alice\"',\n 'corp governance convene --body board --type board_meeting --title \"Q1 Review\" --agenda \"Approve budget\"',\n \"corp governance open @last:meeting --present-seat alice-seat\",\n \"corp governance vote @last:meeting <item-ref> --voter alice --vote for\",\n 'corp governance written-consent --body board --title \"Approve Option Plan\" --description \"Board approves 2026 option plan\"',\n \"corp governance mode\",\n \"corp governance mode --set board\",\n \"corp governance resign <seat-ref>\",\n \"corp governance incidents\",\n \"corp governance profile\",\n ],\n },\n\n // --- governance seats <body-ref> ---\n {\n name: \"governance seats\",\n description: \"Seats for a governance body\",\n route: { method: \"GET\", path: \"/v1/governance-bodies/{pos}/seats\" },\n entity: \"query\",\n args: [{ name: \"body-ref\", required: true, description: \"Governance body reference\" }],\n display: {\n title: \"Seats\",\n cols: [\"holder_name|holder>Holder\", \"role>Role\", \"status>Status\", \"#seat_id>ID\"],\n },\n handler: async (ctx) => {\n const bodyRef = ctx.positional[0];\n if (!bodyRef) {\n throw new Error(\"Missing required argument <body-ref>.\\n List bodies first: corp governance\\n Then: corp governance seats <body-id>\");\n }\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedBodyId = await ctx.resolver.resolveBody(eid, bodyRef);\n const seats = await ctx.client.getGovernanceSeats(resolvedBodyId, eid);\n await ctx.resolver.stabilizeRecords(\"seat\", seats, eid);\n if (ctx.opts.json) { ctx.writer.json(seats); return; }\n if (seats.length === 0) { ctx.writer.writeln(\"No seats found.\"); return; }\n printSeatsTable(seats);\n },\n examples: [\"corp governance seats <body-ref>\", \"corp governance seats <body-ref> --json\"],\n },\n\n // --- governance meetings <body-ref> ---\n {\n name: \"governance meetings\",\n description: \"Meetings for a governance body\",\n route: { method: \"GET\", path: \"/v1/governance-bodies/{pos}/meetings\" },\n entity: \"query\",\n args: [{ name: \"body-ref\", required: true, description: \"Governance body reference\" }],\n display: {\n title: \"Meetings\",\n cols: [\"title>Title\", \"@scheduled_date>Date\", \"status>Status\", \"resolution_count|resolutions>Resolutions\", \"#meeting_id>ID\"],\n },\n handler: async (ctx) => {\n const bodyRef = ctx.positional[0];\n if (!bodyRef) {\n throw new Error(\"Missing required argument <body-ref>.\\n List bodies first: corp governance\\n Then: corp governance meetings <body-id>\");\n }\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedBodyId = await ctx.resolver.resolveBody(eid, bodyRef);\n const meetings = await ctx.client.listMeetings(resolvedBodyId, eid);\n await ctx.resolver.stabilizeRecords(\"meeting\", meetings, eid);\n if (ctx.opts.json) { ctx.writer.json(meetings); return; }\n if (meetings.length === 0) { ctx.writer.writeln(\"No meetings found.\"); return; }\n printMeetingsTable(meetings);\n },\n examples: [\"corp governance meetings <body-ref>\", \"corp governance meetings <body-ref> --json\"],\n },\n\n // --- governance resolutions <meeting-ref> ---\n {\n name: \"governance resolutions\",\n description: \"Resolutions for a meeting\",\n route: { method: \"GET\", path: \"/v1/meetings/{pos}/resolutions\" },\n entity: \"query\",\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n display: {\n title: \"Resolutions\",\n cols: [\"title>Title\", \"resolution_type>Type\", \"status>Status\", \"votes_for>For\", \"votes_against>Against\", \"#resolution_id>ID\"],\n },\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n if (!meetingRef) {\n throw new Error(\"Missing required argument <meeting-ref>.\\n List meetings first: corp governance meetings <body-ref>\\n Then: corp governance resolutions <meeting-id>\");\n }\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n const resolutions = await ctx.client.getMeetingResolutions(resolvedMeetingId, eid);\n await ctx.resolver.stabilizeRecords(\"resolution\", resolutions, eid);\n if (ctx.opts.json) { ctx.writer.json(resolutions); return; }\n if (resolutions.length === 0) { ctx.writer.writeln(\"No resolutions found.\"); return; }\n printResolutionsTable(resolutions);\n },\n examples: [\"corp governance resolutions <meeting-ref>\", \"corp governance resolutions <meeting-ref> --json\"],\n },\n\n // --- governance agenda-items <meeting-ref> ---\n {\n name: \"governance agenda-items\",\n description: \"List agenda items for a meeting\",\n route: { method: \"GET\", path: \"/v1/meetings/{pos}/agenda-items\" },\n entity: \"query\",\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n display: {\n title: \"Agenda Items\",\n cols: [\"title>Title\", \"status>Status\", \"item_type>Type\", \"#agenda_item_id>ID\"],\n },\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n if (!meetingRef) {\n throw new Error(\"Missing required argument <meeting-ref>.\\n List meetings first: corp governance meetings <body-ref>\\n Then: corp governance agenda-items <meeting-id>\");\n }\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n const items = await ctx.client.listAgendaItems(resolvedMeetingId, eid);\n await ctx.resolver.stabilizeRecords(\"agenda_item\", items, eid);\n if (ctx.opts.json) { ctx.writer.json(items); return; }\n if (items.length === 0) { ctx.writer.writeln(\"No agenda items found.\"); return; }\n printAgendaItemsTable(items);\n },\n examples: [\"corp governance agenda-items <meeting-ref>\", \"corp governance agenda-items <meeting-ref> --json\"],\n },\n\n // --- governance incidents ---\n {\n name: \"governance incidents\",\n description: \"Report a governance incident\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/incidents\" },\n entity: true,\n display: { title: \"Governance Incidents\" },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const incidents = await ctx.client.listGovernanceIncidents(eid);\n if (ctx.opts.json) { ctx.writer.json(incidents); return; }\n if (incidents.length === 0) { ctx.writer.writeln(\"No governance incidents found.\"); return; }\n for (const inc of incidents) {\n const status = String(inc.status ?? \"open\");\n const colored = status === \"resolved\" ? chalk.green(status) : chalk.red(status);\n console.log(` [${colored}] ${inc.incident_type ?? \"unknown\"}: ${inc.description ?? inc.id}`);\n }\n },\n examples: [\"corp governance incidents\", \"corp governance incidents --json\"],\n },\n\n // --- governance profile ---\n {\n name: \"governance profile\",\n description: \"View governance profile and configuration\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/profile\" },\n entity: true,\n display: { title: \"Governance Profile\" },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const profile = await ctx.client.getGovernanceProfile(eid);\n if (ctx.opts.json) { ctx.writer.json(profile); return; }\n console.log(chalk.blue(\"\\u2500\".repeat(40)));\n console.log(chalk.blue.bold(\" Governance Profile\"));\n console.log(chalk.blue(\"\\u2500\".repeat(40)));\n for (const [key, value] of Object.entries(profile)) {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n console.log(` ${chalk.bold(key.replaceAll(\"_\", \" \") + \":\")} ${value}`);\n }\n }\n console.log(chalk.blue(\"\\u2500\".repeat(40)));\n },\n examples: [\"corp governance profile\", \"corp governance profile --json\"],\n },\n\n // --- governance mode ---\n {\n name: \"governance mode\",\n description: \"View or set governance mode\",\n route: { method: \"GET\", path: \"/v1/governance/mode\" },\n entity: true,\n display: { title: \"Governance Mode\" },\n options: [\n {\n flags: \"--set <mode>\",\n description: \"Set governance mode\",\n choices: [\"founder\", \"board\", \"executive\", \"normal\", \"incident_lockdown\"],\n },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const setMode = ctx.opts.set as string | undefined;\n if (setMode) {\n const result = await ctx.client.setGovernanceMode({ entity_id: eid, mode: setMode });\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Governance mode set to: ${setMode}`);\n } else {\n const result = await ctx.client.getGovernanceMode(eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n console.log(` ${chalk.bold(\"Governance Mode:\")} ${result.mode ?? \"N/A\"}`);\n if (result.reason) console.log(` ${chalk.bold(\"Reason:\")} ${result.reason}`);\n }\n },\n examples: [\"corp governance mode\", \"corp governance mode --json\"],\n },\n\n // --- governance create-body ---\n {\n name: \"governance create-body\",\n description: \"Create a governance body\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/governance-bodies\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--name <name>\", description: \"Body name (e.g. 'Board of Directors')\", required: true },\n { flags: \"--body-type <type>\", description: \"Body type\", required: true, choices: [\"board_of_directors\", \"llc_member_vote\"] },\n { flags: \"--quorum <rule>\", description: \"Quorum rule\", default: \"majority\", choices: [\"majority\", \"supermajority\", \"unanimous\"] },\n { flags: \"--voting <method>\", description: \"Voting method\", default: \"per_capita\", choices: [\"per_capita\", \"per_unit\"] },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const payload = {\n entity_id: eid,\n body_type: ctx.opts.bodyType as string,\n name: ctx.opts.name as string,\n quorum_rule: ctx.opts.quorum as string,\n voting_method: ctx.opts.voting as string,\n };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.create_body\", payload);\n return;\n }\n const result = await ctx.client.createGovernanceBody(payload);\n await ctx.resolver.stabilizeRecord(\"body\", result, eid);\n ctx.resolver.rememberFromRecord(\"body\", result, eid);\n const bodyId = result.body_id ?? \"OK\";\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Governance body created: ${bodyId}`);\n printReferenceSummary(\"body\", result, { showReuseHint: true });\n console.log(chalk.dim(\"\\n Next steps:\"));\n console.log(chalk.dim(` corp governance add-seat @last:body --holder <contact-ref>`));\n console.log(chalk.dim(` corp governance seats @last:body`));\n },\n produces: { kind: \"body\" },\n successTemplate: \"Governance body created: {name}\",\n examples: [\"corp governance create-body --name 'name' --body-type 'type'\", \"corp governance create-body --json\"],\n },\n\n // --- governance add-seat <body-ref> ---\n {\n name: \"governance add-seat\",\n description: \"Add a seat to a governance body\",\n route: { method: \"POST\", path: \"/v1/governance-bodies/{pos}/seats\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"body-ref\", required: true, description: \"Governance body reference\" }],\n options: [\n { flags: \"--holder <contact-ref>\", description: \"Contact reference for the seat holder\", required: true },\n { flags: \"--role <role>\", description: \"Seat role (chair, member, officer, observer)\", default: \"member\" },\n ],\n handler: async (ctx) => {\n const bodyRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedBodyId = await ctx.resolver.resolveBody(eid, bodyRef);\n const resolvedHolderId = await ctx.resolver.resolveContact(eid, ctx.opts.holder as string);\n const data: Record<string, unknown> = { holder_id: resolvedHolderId, role: ctx.opts.role ?? \"member\" };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.add_seat\", { entity_id: eid, body_id: resolvedBodyId, ...data });\n return;\n }\n const result = await ctx.client.createGovernanceSeat(resolvedBodyId, eid, data);\n await ctx.resolver.stabilizeRecord(\"seat\", result, eid);\n ctx.resolver.rememberFromRecord(\"seat\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Seat added: ${result.seat_id ?? \"OK\"}`);\n printReferenceSummary(\"seat\", result, { showReuseHint: true });\n },\n produces: { kind: \"seat\" },\n successTemplate: \"Seat added to {body_id}\",\n examples: [\"corp governance add-seat <body-ref> --holder 'contact-ref'\", \"corp governance add-seat --json\"],\n },\n\n // --- governance convene ---\n {\n name: \"governance convene\",\n description: \"Convene a governance meeting\",\n route: { method: \"POST\", path: \"/v1/meetings\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--body <ref>\", description: \"Governance body reference\", required: true },\n { flags: \"--type <type>\", description: \"Meeting type (board_meeting, shareholder_meeting, member_meeting, written_consent)\", required: true },\n { flags: \"--title <title>\", description: \"Meeting title\", required: true },\n { flags: \"--date <date>\", description: \"Meeting date (ISO 8601)\" },\n { flags: \"--agenda <item>\", description: \"Agenda item (repeatable)\", type: \"array\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedBodyId = await ctx.resolver.resolveBody(eid, ctx.opts.body as string);\n const payload: Record<string, unknown> = {\n entity_id: eid,\n body_id: resolvedBodyId,\n meeting_type: ctx.opts.type as string,\n title: ctx.opts.title as string,\n agenda_item_titles: (ctx.opts.agenda as string[]) ?? [],\n };\n if (ctx.opts.date) payload.scheduled_date = ctx.opts.date as string;\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.schedule_meeting\", payload);\n return;\n }\n const result = await ctx.client.scheduleMeeting(payload);\n await ctx.resolver.stabilizeRecord(\"meeting\", result, eid);\n ctx.resolver.rememberFromRecord(\"meeting\", result, eid);\n const meetingId = result.meeting_id ?? \"OK\";\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Meeting scheduled: ${meetingId}`);\n printReferenceSummary(\"meeting\", result, { showReuseHint: true });\n console.log(chalk.dim(\"\\n Next steps:\"));\n console.log(chalk.dim(` corp governance notice @last:meeting`));\n console.log(chalk.dim(` corp governance open @last:meeting --present-seat <seat-ref>`));\n console.log(chalk.dim(` corp governance agenda-items @last:meeting`));\n },\n produces: { kind: \"meeting\" },\n successTemplate: \"Meeting scheduled: {title}\",\n examples: [\"corp governance convene --body 'ref' --type 'type' --title 'title'\", \"corp governance convene --json\"],\n },\n\n // --- governance open <meeting-ref> ---\n {\n name: \"governance open\",\n description: \"Open a scheduled meeting for voting\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/open\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n options: [\n { flags: \"--present-seat <ref>\", description: \"Seat reference present at the meeting (repeatable)\", required: true, type: \"array\" },\n ],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n const presentSeats = ctx.opts.presentSeat as string[];\n let resolvedSeats: string[];\n try {\n resolvedSeats = await Promise.all(\n presentSeats.map((seatRef) => ctx.resolver.resolveSeat(eid, seatRef)),\n );\n } catch (err) {\n throw new Error(\n `Failed to resolve seat reference: ${err}\\n` +\n \" --present-seat expects seat IDs, not contact IDs.\\n\" +\n \" Find seat IDs with: corp governance seats <body-ref>\",\n );\n }\n const payload = { present_seat_ids: resolvedSeats };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.open_meeting\", { entity_id: eid, meeting_id: resolvedMeetingId, ...payload });\n return;\n }\n const result = await ctx.client.conveneMeeting(resolvedMeetingId, eid, payload);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Meeting opened: ${resolvedMeetingId}`);\n },\n examples: [\"corp governance open <meeting-ref> --present-seat 'ref'\"],\n },\n\n // --- governance vote <meeting-ref> <item-ref> ---\n {\n name: \"governance vote\",\n description: \"Cast a vote on an agenda item\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/agenda-items/{pos}/votes\" },\n entity: true,\n dryRun: true,\n args: [\n { name: \"meeting-ref\", required: true, description: \"Meeting reference\" },\n { name: \"item-ref\", required: true, description: \"Agenda item reference\" },\n ],\n options: [\n { flags: \"--voter <ref>\", description: \"Voter contact reference\", required: true },\n { flags: \"--vote <value>\", description: \"Vote (for, against, abstain, recusal)\", required: true, choices: [\"for\", \"against\", \"abstain\", \"recusal\"] },\n ],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const itemRef = ctx.positional[1];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n const resolvedItemId = await ctx.resolver.resolveAgendaItem(eid, resolvedMeetingId, itemRef);\n const resolvedVoterId = await ctx.resolver.resolveContact(eid, ctx.opts.voter as string);\n const payload = { voter_id: resolvedVoterId, vote_value: ctx.opts.vote as string };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.cast_vote\", {\n entity_id: eid, meeting_id: resolvedMeetingId, agenda_item_id: resolvedItemId, ...payload,\n });\n return;\n }\n try {\n const result = await ctx.client.castVote(eid, resolvedMeetingId, resolvedItemId, payload);\n ctx.resolver.rememberFromRecord(\"agenda_item\", { agenda_item_id: resolvedItemId, title: itemRef }, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Vote cast: ${result.vote_id ?? \"OK\"}`);\n } catch (err) {\n const message = String(err);\n if (message.includes(\"voting session is not open\")) {\n ctx.writer.error(\n `Failed to cast vote: ${err}\\n` +\n ` Open the meeting first: corp governance open ${meetingRef} --present-seat <seat-ref>`,\n );\n } else {\n throw err;\n }\n }\n },\n examples: [\"corp governance vote <meeting-ref> <item-ref> --voter for --vote for\"],\n },\n\n // --- governance notice <meeting-ref> ---\n {\n name: \"governance notice\",\n description: \"Send meeting notice\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/notice\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.send_notice\", { entity_id: eid, meeting_id: resolvedMeetingId });\n return;\n }\n const result = await ctx.client.sendNotice(resolvedMeetingId, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Notice sent for meeting ${resolvedMeetingId}`);\n },\n examples: [\"corp governance notice <meeting-ref>\"],\n },\n\n // --- governance adjourn <meeting-ref> ---\n {\n name: \"governance adjourn\",\n description: \"Adjourn a meeting\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/adjourn\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.adjourn_meeting\", { entity_id: eid, meeting_id: resolvedMeetingId });\n return;\n }\n const result = await ctx.client.adjournMeeting(resolvedMeetingId, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Meeting ${resolvedMeetingId} adjourned`);\n },\n examples: [\"corp governance adjourn <meeting-ref>\"],\n },\n\n // --- governance reopen <meeting-ref> ---\n {\n name: \"governance reopen\",\n description: \"Re-open an adjourned meeting\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/reopen\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.reopen_meeting\", { entity_id: eid, meeting_id: resolvedMeetingId });\n return;\n }\n const result = await ctx.client.reopenMeeting(resolvedMeetingId, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Meeting ${resolvedMeetingId} re-opened`);\n },\n examples: [\"corp governance reopen <meeting-ref>\"],\n },\n\n // --- governance cancel <meeting-ref> ---\n {\n name: \"governance cancel\",\n description: \"Cancel a meeting\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/cancel\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n options: [\n { flags: \"--yes, -y\", description: \"Skip confirmation prompt\" },\n ],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.cancel_meeting\", { entity_id: eid, meeting_id: resolvedMeetingId });\n return;\n }\n if (!ctx.opts.yes) {\n const ok = await confirm({\n message: `Cancel meeting ${resolvedMeetingId}?`,\n default: false,\n });\n if (!ok) {\n ctx.writer.writeln(\"Cancelled.\");\n return;\n }\n }\n const result = await ctx.client.cancelMeeting(resolvedMeetingId, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Meeting ${resolvedMeetingId} cancelled`);\n },\n examples: [\"corp governance cancel <meeting-ref>\", \"corp governance cancel --json\"],\n },\n\n // --- governance finalize-item <meeting-ref> <item-ref> ---\n {\n name: \"governance finalize-item\",\n description: \"Finalize an agenda item\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/agenda-items/{pos}/finalize\" },\n entity: true,\n dryRun: true,\n args: [\n { name: \"meeting-ref\", required: true, description: \"Meeting reference\" },\n { name: \"item-ref\", required: true, description: \"Agenda item reference\" },\n ],\n options: [\n {\n flags: \"--status <status>\",\n description: `Status (${[...FINALIZE_ITEM_STATUS_CHOICES].join(\", \")})`,\n required: true,\n choices: [...FINALIZE_ITEM_STATUS_CHOICES],\n },\n ],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const itemRef = ctx.positional[1];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n const resolvedItemId = await ctx.resolver.resolveAgendaItem(eid, resolvedMeetingId, itemRef);\n const payload = { entity_id: eid, status: ctx.opts.status as string };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.finalize_agenda_item\", { meeting_id: resolvedMeetingId, agenda_item_id: resolvedItemId, ...payload });\n return;\n }\n const result = await ctx.client.finalizeAgendaItem(resolvedMeetingId, resolvedItemId, payload);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Agenda item ${resolvedItemId} finalized as ${ctx.opts.status}`);\n },\n examples: [\"corp governance finalize-item <meeting-ref> <item-ref>\"],\n },\n\n // --- governance resolve <meeting-ref> <item-ref> ---\n {\n name: \"governance resolve\",\n description: \"Compute a resolution for an agenda item\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/agenda-items/{pos}/resolution\" },\n entity: true,\n dryRun: true,\n args: [\n { name: \"meeting-ref\", required: true, description: \"Meeting reference\" },\n { name: \"item-ref\", required: true, description: \"Agenda item reference\" },\n ],\n options: [\n { flags: \"--text <resolution_text>\", description: \"Resolution text\", required: true },\n ],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const itemRef = ctx.positional[1];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n const resolvedItemId = await ctx.resolver.resolveAgendaItem(eid, resolvedMeetingId, itemRef);\n const payload = { resolution_text: ctx.opts.text as string };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.compute_resolution\", {\n entity_id: eid, meeting_id: resolvedMeetingId, agenda_item_id: resolvedItemId, ...payload,\n });\n return;\n }\n const result = await ctx.client.computeResolution(resolvedMeetingId, resolvedItemId, eid, payload);\n await ctx.resolver.stabilizeRecord(\"resolution\", result, eid);\n ctx.resolver.rememberFromRecord(\"resolution\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Resolution computed for agenda item ${itemRef}`);\n printReferenceSummary(\"resolution\", result, { showReuseHint: true });\n },\n produces: { kind: \"resolution\" },\n successTemplate: \"Resolution computed\",\n examples: [\"corp governance resolve <meeting-ref> <item-ref> --text 'resolution_text'\"],\n },\n\n // --- governance written-consent ---\n {\n name: \"governance written-consent\",\n description: \"Create a written consent action\",\n route: { method: \"POST\", path: \"/v1/governance/written-consent\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--body <ref>\", description: \"Governance body reference\", required: true },\n { flags: \"--title <title>\", description: \"Title\", required: true },\n { flags: \"--description <desc>\", description: \"Description text\", required: true },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedBodyId = await ctx.resolver.resolveBody(eid, ctx.opts.body as string);\n const payload = {\n entity_id: eid, body_id: resolvedBodyId, title: ctx.opts.title as string, description: ctx.opts.description as string,\n };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.written_consent\", payload);\n return;\n }\n\n const result = await writtenConsentWorkflow(ctx.client, {\n entityId: eid,\n bodyId: resolvedBodyId,\n title: ctx.opts.title as string,\n description: ctx.opts.description as string,\n });\n\n if (!result.success) {\n ctx.writer.error(result.error!);\n return;\n }\n\n await ctx.resolver.stabilizeRecord(\"meeting\", result.data!, eid);\n ctx.resolver.rememberFromRecord(\"meeting\", result.data!, eid);\n const meetingId = String(result.data?.meeting_id ?? \"\");\n\n if (ctx.opts.json) { ctx.writer.json(result.data); return; }\n ctx.writer.success(`Written consent created: ${meetingId || \"OK\"}`);\n printReferenceSummary(\"meeting\", result.data!, { showReuseHint: true });\n console.log(chalk.dim(\"\\n Next steps:\"));\n console.log(chalk.dim(` corp governance agenda-items @last:meeting`));\n console.log(chalk.dim(` corp governance vote @last:meeting <item-ref> --voter <contact-ref> --vote for`));\n },\n produces: { kind: \"meeting\" },\n successTemplate: \"Written consent created: {title}\",\n examples: [\"corp governance written-consent --body 'ref' --title 'title' --description 'desc'\"],\n },\n\n // --- governance quick-approve ---\n {\n name: \"governance quick-approve\",\n description: \"One-step board approval: create written consent, auto-vote, return meeting + resolution IDs\",\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--body <ref>\", description: \"Governance body reference (auto-detected if only one exists)\" },\n { flags: \"--text <resolution_text>\", description: \"Resolution text (e.g. 'RESOLVED: authorize SAFE issuance')\", required: true },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n\n // Auto-detect body if not specified\n let resolvedBodyId: string;\n if (ctx.opts.body) {\n resolvedBodyId = await ctx.resolver.resolveBody(eid, ctx.opts.body as string);\n } else {\n const bodies = await ctx.client.listGovernanceBodies(eid);\n const active = bodies.filter((b: ApiRecord) => b.status === \"active\");\n if (active.length === 1) {\n resolvedBodyId = String(active[0].body_id);\n } else if (active.length === 0) {\n throw new Error(\"No active governance bodies found. Create one first: corp governance create-body\");\n } else {\n throw new Error(`Multiple governance bodies found (${active.length}). Specify --body <ref>.`);\n }\n }\n\n const resolutionText = ctx.opts.text as string;\n const title = `Board Approval: ${resolutionText.slice(0, 60)}`;\n\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.quick_approve\", {\n entity_id: eid, body_id: resolvedBodyId, title, resolution_text: resolutionText,\n });\n return;\n }\n\n // Step 1: Create written consent\n const consentResult = await writtenConsentWorkflow(ctx.client, {\n entityId: eid,\n bodyId: resolvedBodyId,\n title,\n description: resolutionText,\n });\n if (!consentResult.success) {\n throw new Error(`Written consent failed: ${consentResult.error}`);\n }\n const meetingId = String(consentResult.data?.meeting_id);\n ctx.resolver.remember(\"meeting\", meetingId, eid);\n\n // Step 2: Get agenda items\n const agendaItems = await ctx.client.listAgendaItems(meetingId, eid);\n if (agendaItems.length === 0) {\n throw new Error(\"Written consent created but no agenda items found.\");\n }\n const itemId = String((agendaItems[0] as ApiRecord).agenda_item_id);\n\n // Step 3: Convene (open) the meeting if not already convened\n const seats = await ctx.client.getGovernanceSeats(resolvedBodyId, eid);\n const filledSeats = seats.filter((s: ApiRecord) => s.status === \"filled\" || s.status === \"active\");\n const seatIds = filledSeats.map((s: ApiRecord) => String(s.seat_id));\n if (seatIds.length === 0) {\n throw new Error(\"No filled seats found on this governance body. Add seats first: corp governance add-seat <body-ref>\");\n }\n // Written consent creates meetings already in \"convened\" state — skip if so\n const meetingStatus = consentResult.data?.status ?? consentResult.data?.meeting_status;\n if (meetingStatus !== \"convened\") {\n await ctx.client.conveneMeeting(meetingId, eid, { present_seat_ids: seatIds });\n }\n\n // Step 4: Cast votes — each seat's holder votes \"for\"\n for (const seat of filledSeats) {\n const voterId = String(seat.holder_id);\n if (!voterId) continue;\n try {\n await ctx.client.castVote(eid, meetingId, itemId, {\n voter_id: voterId,\n vote_value: \"for\",\n });\n } catch {\n // Seat may have already voted or be ineligible — continue\n }\n }\n\n // Step 5: Compute resolution (tallies votes and determines outcome)\n const resolution = await ctx.client.computeResolution(meetingId, itemId, eid, {\n resolution_text: resolutionText,\n });\n const resolutionId = String(resolution.resolution_id);\n ctx.resolver.remember(\"resolution\", resolutionId, eid);\n\n const passed = resolution.passed === true;\n\n if (ctx.opts.json) {\n ctx.writer.json({ meeting_id: meetingId, resolution_id: resolutionId, passed, votes: filledSeats.length });\n return;\n }\n ctx.writer.success(passed ? \"Board approval completed\" : \"Board vote completed (resolution did not pass)\");\n console.log(` Meeting: ${meetingId}`);\n console.log(` Resolution: ${resolutionId}`);\n console.log(chalk.dim(\"\\n Use with:\"));\n console.log(chalk.dim(` --meeting-id ${meetingId} --resolution-id ${resolutionId}`));\n console.log(chalk.dim(` or: --meeting-id @last:meeting --resolution-id @last:resolution`));\n },\n produces: { kind: \"resolution\" },\n successTemplate: \"Board approval completed\",\n examples: [\n 'corp governance quick-approve --text \"RESOLVED: authorize SAFE issuance to Seed Fund\"',\n 'corp governance quick-approve --body @last:body --text \"RESOLVED: issue Series A equity round\"',\n ],\n },\n\n // --- governance resign <seat-ref> ---\n {\n name: \"governance resign\",\n description: \"Resign from a governance seat\",\n route: { method: \"POST\", path: \"/v1/seats/{pos}/resign\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"seat-ref\", required: true, description: \"Seat reference\" }],\n options: [\n { flags: \"--body-id <ref>\", description: \"Governance body reference\" },\n ],\n handler: async (ctx) => {\n const seatRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const seatId = await ctx.resolver.resolveSeat(eid, seatRef, ctx.opts.bodyId as string | undefined);\n const result = await ctx.client.resignSeat(seatId, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Seat ${seatId} resigned.`);\n },\n examples: [\"corp governance resign <seat-ref>\", \"corp governance resign --json\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"entities governance-audit-checkpoints\",\n description: \"List governance audit checkpoints\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/audit/checkpoints\" },\n entity: true,\n display: { title: \"Entities Governance Audit Checkpoints\", cols: [\"#checkpoint_id>ID\", \"@created_at>Created At\", \"#entity_id>ID\", \"latest_entry_hash>Latest Entry Hash\", \"#latest_entry_id>ID\", \"total_entries>Total Entries\"] },\n examples: [\"corp entities governance-audit-checkpoints\", \"corp entities governance-audit-checkpoints --json\"],\n },\n {\n name: \"entities governance-audit-entries\",\n description: \"List governance audit log entries\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/audit/entries\" },\n entity: true,\n display: { title: \"Entities Governance Audit Entries\", cols: [\"action>Action\", \"details>Details\", \"entry_hash>Entry Hash\", \"event_type>Event Type\", \"@created_at>Created At\", \"#audit_entry_id>ID\"] },\n examples: [\"corp entities governance-audit-entries\", \"corp entities governance-audit-entries --json\"],\n },\n {\n name: \"entities governance-audit-verifications\",\n description: \"List governance audit verifications\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/audit/verifications\" },\n entity: true,\n display: { title: \"Entities Governance Audit Verifications\", cols: [\"anomalies>Anomalies\", \"latest_entry_hash>Latest Entry Hash\", \"ok>Ok\", \"total_entries>Total Entries\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp entities governance-audit-verifications\", \"corp entities governance-audit-verifications --json\"],\n },\n {\n name: \"entities governance-doc-bundles\",\n description: \"List governance document bundles\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/doc-bundles\" },\n entity: true,\n display: { title: \"Entities Governance Doc Bundles\", cols: [\"document_count>Document Count\", \"entity_type>Entity Type\", \"generated_at>Generated At\", \"profile_version>Profile Version\", \"#bundle_id>ID\"] },\n examples: [\"corp entities governance-doc-bundles\", \"corp entities governance-doc-bundles --json\"],\n },\n {\n name: \"entities governance-doc-bundles-current\",\n description: \"View the current governance document bundle\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/doc-bundles/current\" },\n entity: true,\n display: { title: \"Entities Governance Doc Bundles Current\", cols: [\"#bundle_id>ID\", \"#entity_id>ID\", \"generated_at>Generated At\", \"manifest_path>Manifest Path\", \"template_version>Template Version\"] },\n examples: [\"corp entities governance-doc-bundles-current\", \"corp entities governance-doc-bundles-current --json\"],\n },\n {\n name: \"entities governance-doc-bundles-generate\",\n description: \"Generate a new governance document bundle\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/governance/doc-bundles/generate\" },\n entity: true,\n options: [\n { flags: \"--template-version <template-version>\", description: \"Template Version\" },\n ],\n examples: [\"corp entities governance-doc-bundles-generate\", \"corp entities governance-doc-bundles-generate --json\"],\n successTemplate: \"Governance Doc Bundles Generate created\",\n },\n {\n name: \"entities governance-doc-bundle\",\n description: \"List governance document bundles\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/doc-bundles/{pos}\" },\n entity: true,\n args: [{ name: \"bundle-id\", required: true, description: \"Document bundle ID\" }],\n display: { title: \"Entities Governance Doc Bundles\", cols: [\"documents>Documents\", \"entity_type>Entity Type\", \"generated_at>Generated At\", \"profile_version>Profile Version\", \"#bundle_id>ID\"] },\n examples: [\"corp entities governance-doc-bundles\", \"corp entities governance-doc-bundles --json\"],\n },\n {\n name: \"entities governance-mode-history\",\n description: \"View governance mode change history\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/mode-history\" },\n entity: true,\n display: { title: \"Entities Governance Mode History\", cols: [\"evidence_refs>Evidence Refs\", \"from_mode>From Mode\", \"incident_ids>Incident Ids\", \"reason>Reason\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp entities governance-mode-history\", \"corp entities governance-mode-history --json\"],\n },\n {\n name: \"entities governance-triggers\",\n description: \"List governance triggers for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/triggers\" },\n entity: true,\n display: { title: \"Entities Governance Triggers\", cols: [\"description>Description\", \"evidence_refs>Evidence Refs\", \"idempotency_key_hash>Idempotency Key Hash\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp entities governance-triggers\", \"corp entities governance-triggers --json\"],\n },\n {\n name: \"governance-bodies\",\n description: \"List all governance bodies\",\n route: { method: \"GET\", path: \"/v1/governance-bodies\" },\n entity: true,\n display: { title: \"Governance Bodies\", cols: [\"body_type>Body Type\", \"name>Name\", \"quorum_rule>Quorum Rule\", \"status>Status\", \"@created_at>Created At\", \"#body_id>ID\"] },\n examples: [\"corp governance-bodies\", \"corp governance-bodies --json\"],\n },\n {\n name: \"governance-bodies create\",\n description: \"List all governance bodies\",\n route: { method: \"POST\", path: \"/v1/governance-bodies\" },\n options: [\n { flags: \"--body-type <body-type>\", description: \"The type of governance body.\", required: true, choices: [\"board_of_directors\", \"llc_member_vote\"] },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--quorum-rule <quorum-rule>\", description: \"The threshold required for a vote to pass.\", required: true, choices: [\"majority\", \"supermajority\", \"unanimous\"] },\n { flags: \"--voting-method <voting-method>\", description: \"How votes are counted.\", required: true, choices: [\"per_capita\", \"per_unit\"] },\n ],\n examples: [\"corp governance-bodies --body-type board_of_directors --name majority --quorum-rule majority --voting-method per_capita\"],\n successTemplate: \"Governance Bodies created\",\n },\n {\n name: \"governance-seats scan-expired\",\n description: \"Scan for and flag expired governance seats\",\n route: { method: \"POST\", path: \"/v1/governance-seats/scan-expired\" },\n entity: true,\n examples: [\"corp governance-seats scan-expired\"],\n successTemplate: \"Scan Expired created\",\n },\n {\n name: \"governance-seats resign\",\n description: \"Resign from a governance seat\",\n route: { method: \"POST\", path: \"/v1/governance-seats/{pos}/resign\" },\n entity: true,\n args: [{ name: \"seat-id\", required: true, description: \"Governance seat ID\" }],\n examples: [\"corp governance-seats resign <seat-id>\"],\n successTemplate: \"Resign created\",\n },\n {\n name: \"governance audit-checkpoints\",\n description: \"Create a governance audit checkpoint\",\n route: { method: \"POST\", path: \"/v1/governance/audit/checkpoints\" },\n entity: true,\n examples: [\"corp governance audit-checkpoints\"],\n successTemplate: \"Audit Checkpoints created\",\n },\n {\n name: \"governance audit-events\",\n description: \"Record a governance audit event\",\n route: { method: \"POST\", path: \"/v1/governance/audit/events\" },\n entity: true,\n options: [\n { flags: \"--action <action>\", description: \"Action\", required: true },\n { flags: \"--details <details>\", description: \"Details\" },\n { flags: \"--event-type <event-type>\", description: \"Event Type\", required: true, choices: [\"mode_changed\", \"lockdown_trigger_applied\", \"manual_event\", \"checkpoint_written\", \"chain_verified\", \"chain_verification_failed\"] },\n { flags: \"--evidence-refs <evidence-refs>\", description: \"Evidence Refs\", type: \"array\" },\n { flags: \"--linked-incident-id <linked-incident-id>\", description: \"Linked Incident Id\" },\n { flags: \"--linked-intent-id <linked-intent-id>\", description: \"Linked Intent Id\" },\n { flags: \"--linked-mode-event-id <linked-mode-event-id>\", description: \"Linked Mode Event Id\" },\n { flags: \"--linked-trigger-id <linked-trigger-id>\", description: \"Linked Trigger Id\" },\n ],\n examples: [\"corp governance audit-events --action 'action' --event-type mode_changed\", \"corp governance audit-events --json\"],\n successTemplate: \"Audit Events created\",\n },\n {\n name: \"governance audit-verify\",\n description: \"Verify governance state integrity\",\n route: { method: \"POST\", path: \"/v1/governance/audit/verify\" },\n entity: true,\n examples: [\"corp governance audit-verify\"],\n successTemplate: \"Audit Verify created\",\n },\n {\n name: \"governance delegation-schedule\",\n description: \"View the current delegation schedule\",\n route: { method: \"GET\", path: \"/v1/governance/delegation-schedule\" },\n entity: true,\n display: { title: \"Governance Delegation Schedule\", cols: [\"allowed_tier1_intent_types>Allowed Tier1 Intent Types\", \"last_reauthorized_at>Last Reauthorized At\", \"next_mandatory_review_at>Next Mandatory Review At\", \"reauth_full_suspension_at_days>Reauth Full Suspension At Days\", \"@created_at>Created At\", \"#adopted_resolution_id>ID\"] },\n examples: [\"corp governance delegation-schedule\", \"corp governance delegation-schedule --json\"],\n },\n {\n name: \"governance delegation-schedule-amend\",\n description: \"Amend the delegation schedule\",\n route: { method: \"POST\", path: \"/v1/governance/delegation-schedule/amend\" },\n entity: true,\n options: [\n { flags: \"--adopted-resolution-id <adopted-resolution-id>\", description: \"Adopted Resolution Id\" },\n { flags: \"--allowed-tier1-intent-types <allowed-tier1-intent-types>\", description: \"Allowed Tier1 Intent Types\" },\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\" },\n { flags: \"--next-mandatory-review-at <next-mandatory-review-at>\", description: \"Next Mandatory Review At\" },\n { flags: \"--rationale <rationale>\", description: \"Rationale\" },\n { flags: \"--tier1-max-amount-cents <tier1-max-amount-cents>\", description: \"Tier1 Max Amount Cents\" },\n ],\n examples: [\"corp governance delegation-schedule-amend\", \"corp governance delegation-schedule-amend --json\"],\n successTemplate: \"Delegation Schedule Amend created\",\n },\n {\n name: \"governance delegation-schedule-history\",\n description: \"View delegation schedule change history\",\n route: { method: \"GET\", path: \"/v1/governance/delegation-schedule/history\" },\n entity: true,\n display: { title: \"Governance Delegation Schedule History\", cols: [\"added_tier1_intent_types>Added Tier1 Intent Types\", \"authority_expansion>Authority Expansion\", \"from_version>From Version\", \"new_tier1_max_amount_cents>New Tier1 Max Amount Cents\", \"@created_at>Created At\", \"#adopted_resolution_id>ID\"] },\n examples: [\"corp governance delegation-schedule-history\", \"corp governance delegation-schedule-history --json\"],\n },\n {\n name: \"governance delegation-schedule-reauthorize\",\n description: \"Reauthorize the delegation schedule\",\n route: { method: \"POST\", path: \"/v1/governance/delegation-schedule/reauthorize\" },\n entity: true,\n options: [\n { flags: \"--adopted-resolution-id <adopted-resolution-id>\", description: \"Adopted Resolution Id\", required: true },\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\", required: true },\n { flags: \"--rationale <rationale>\", description: \"Rationale\" },\n ],\n examples: [\"corp governance delegation-schedule-reauthorize --adopted-resolution-id 'adopted-resolution-id' --meeting-id 'meeting-id'\", \"corp governance delegation-schedule-reauthorize --json\"],\n successTemplate: \"Delegation Schedule Reauthorize created\",\n },\n {\n name: \"governance evaluate\",\n description: \"Evaluate governance compliance for an action\",\n route: { method: \"POST\", path: \"/v1/governance/evaluate\" },\n entity: true,\n options: [\n { flags: \"--intent-type <intent-type>\", description: \"Type of intent\", required: true },\n { flags: \"--metadata <metadata>\", description: \"Additional metadata (JSON)\" },\n ],\n examples: [\"corp governance evaluate --intent-type 'intent-type'\", \"corp governance evaluate --json\"],\n successTemplate: \"Evaluate created\",\n },\n {\n name: \"governance report-incident\",\n description: \"Report a governance incident\",\n route: { method: \"POST\", path: \"/v1/governance/incidents\" },\n entity: true,\n options: [\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--severity <severity>\", description: \"Severity level\", required: true, choices: [\"low\", \"medium\", \"high\", \"critical\"] },\n { flags: \"--title <title>\", description: \"Title\", required: true },\n ],\n examples: [\"corp governance incidents --description low --severity low --title 'title'\"],\n successTemplate: \"Incidents created\",\n },\n {\n name: \"governance incidents-resolve\",\n description: \"Resolve a governance incident\",\n route: { method: \"POST\", path: \"/v1/governance/incidents/{pos}/resolve\" },\n entity: true,\n args: [{ name: \"incident-id\", required: true, description: \"Incident ID\" }],\n examples: [\"corp governance incidents-resolve <incident-id>\"],\n successTemplate: \"Incidents Resolve created\",\n },\n {\n name: \"meetings written-consent\",\n description: \"Create a written consent resolution (no meeting)\",\n route: { method: \"POST\", path: \"/v1/meetings/written-consent\" },\n options: [\n { flags: \"--body-id <body-id>\", description: \"Governance body ID\", required: true },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--title <title>\", description: \"Title\", required: true },\n ],\n examples: [\"corp meetings written-consent --body-id 'body-id' --description 'description' --title 'title'\"],\n successTemplate: \"Written Consent created\",\n },\n {\n name: \"meetings agenda-items-vote\",\n description: \"Cast a vote on a meeting agenda item\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/agenda-items/{pos2}/vote\" },\n entity: true,\n args: [{ name: \"meeting-id\", required: true, description: \"Meeting ID\" }, { name: \"item-id\", required: true, description: \"Agenda item ID\" }],\n options: [\n { flags: \"--vote-value <vote-value>\", description: \"How a participant voted.\", required: true, choices: [\"for\", \"against\", \"abstain\", \"recusal\"] },\n { flags: \"--voter-id <voter-id>\", description: \"Voter Id\", required: true },\n ],\n examples: [\"corp meetings agenda-items-vote <meeting-id> <item-id> --vote-value for --voter-id 'voter-id'\"],\n successTemplate: \"Agenda Items Vote created\",\n },\n {\n name: \"meetings convene\",\n description: \"Convene a scheduled meeting (start it)\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/convene\" },\n entity: true,\n args: [{ name: \"meeting-id\", required: true, description: \"Meeting ID\" }],\n options: [\n { flags: \"--present-seat-ids <present-seat-ids>\", description: \"Present Seat Ids\", required: true, type: \"array\" },\n ],\n examples: [\"corp meetings convene <meeting-id> --present-seat-ids 'present-seat-ids'\"],\n successTemplate: \"Convene created\",\n },\n {\n name: \"meetings resolutions-attach-document\",\n description: \"Attach a document to a meeting resolution\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/resolutions/{pos2}/attach-document\" },\n args: [{ name: \"meeting-id\", required: true, description: \"Meeting ID\" }, { name: \"resolution-id\", required: true, description: \"Resolution ID\" }],\n options: [\n { flags: \"--document-id <document-id>\", description: \"Document ID\", required: true },\n ],\n examples: [\"corp meetings resolutions-attach-document <meeting-id> <resolution-id> --document-id 'document-id'\"],\n successTemplate: \"Resolutions Attach Document created\",\n },\n\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n printDocumentsTable,\n printError,\n printReferenceSummary,\n printSuccess,\n printJson,\n printWriteResult,\n} from \"../output.js\";\nimport { autoSignFormationDocument, autoSignFormationDocuments } from \"../formation-automation.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst HUMANS_APP_ORIGIN = \"https://humans.thecorporation.ai\";\n\nfunction formatSigningLink(docId: string, result: { token?: unknown; signing_url?: unknown }): string {\n if (typeof result.token === \"string\" && result.token.length > 0) {\n return `${HUMANS_APP_ORIGIN}/sign/${docId}?token=${encodeURIComponent(result.token)}`;\n }\n if (typeof result.signing_url === \"string\" && result.signing_url.length > 0) {\n if (/^https?:\\/\\//.test(result.signing_url)) {\n return result.signing_url;\n }\n const normalizedPath = result.signing_url.startsWith(\"/human/sign/\")\n ? result.signing_url.replace(\"/human/sign/\", \"/sign/\")\n : result.signing_url;\n return `${HUMANS_APP_ORIGIN}${normalizedPath.startsWith(\"/\") ? normalizedPath : `/${normalizedPath}`}`;\n }\n return `${HUMANS_APP_ORIGIN}/sign/${docId}`;\n}\n\nfunction coerceParamValue(raw: string): unknown {\n if (raw === \"true\") return true;\n if (raw === \"false\") return false;\n if (/^-?\\d+(\\.\\d+)?$/.test(raw)) return Number(raw);\n if ((raw.startsWith(\"{\") && raw.endsWith(\"}\")) || (raw.startsWith(\"[\") && raw.endsWith(\"]\"))) {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n }\n return raw;\n}\n\n// ---------------------------------------------------------------------------\n// Document registry entries\n// ---------------------------------------------------------------------------\n\nexport const documentCommands: CommandDef[] = [\n // --- documents (list) ---\n {\n name: \"documents\",\n description: \"List formation and governance documents\",\n route: { method: \"GET\", path: \"/v1/formations/{eid}/documents\" },\n entity: true,\n display: {\n title: \"Documents\",\n cols: [\"title>Title\", \"document_type>Type\", \"status>Status\", \"@created_at>Date\", \"#document_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const docs = await ctx.client.getEntityDocuments(eid);\n await ctx.resolver.stabilizeRecords(\"document\", docs, eid);\n if (ctx.opts.json) { ctx.writer.json(docs); return; }\n if (docs.length === 0) { ctx.writer.writeln(\"No documents found.\"); return; }\n printDocumentsTable(docs);\n },\n examples: [\"corp documents\", \"corp documents --json\"],\n },\n\n // --- documents signing-link <doc-ref> ---\n {\n name: \"documents signing-link\",\n description: \"Get a signing link for a document\",\n route: { method: \"GET\", path: \"/v1/sign/{pos}\" },\n entity: \"query\",\n args: [{ name: \"doc-ref\", required: true, description: \"Document reference\" }],\n display: { title: \"Signing Link\" },\n handler: async (ctx) => {\n const docRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n let resolvedDocumentId: string;\n try {\n resolvedDocumentId = await ctx.resolver.resolveDocument(eid, docRef);\n } catch {\n printError(\n `Could not resolve '${docRef}' as a document. If you just generated a contract, ` +\n \"use the document_id from the generate output, not @last (which may reference the contract_id).\\n\" +\n \" List documents with: corp documents\",\n );\n process.exit(1);\n return;\n }\n const result = await ctx.client.getSigningLink(resolvedDocumentId, eid);\n const shareUrl = formatSigningLink(resolvedDocumentId, result);\n if (process.stdout.isTTY) {\n ctx.writer.success(\"Signing link generated.\");\n const summaryRecord = await ctx.resolver.stabilizeRecord(\"document\", { document_id: resolvedDocumentId, title: docRef }, eid);\n printReferenceSummary(\"document\", summaryRecord, { label: \"Document Ref:\" });\n }\n console.log(shareUrl);\n },\n examples: [\"corp documents signing-link\", \"corp documents signing-link --json\"],\n },\n\n // --- documents sign <doc-ref> ---\n {\n name: \"documents sign\",\n description: \"Sign a formation document, or auto-sign all missing required signatures\",\n route: { method: \"POST\", path: \"/v1/documents/{pos}/sign\" },\n entity: true,\n args: [{ name: \"doc-ref\", required: true, description: \"Document reference\" }],\n options: [\n { flags: \"--signer-name <name>\", description: \"Manual signer name\" },\n { flags: \"--signer-role <role>\", description: \"Manual signer role\" },\n { flags: \"--signer-email <email>\", description: \"Manual signer email\" },\n { flags: \"--signature-text <text>\", description: \"Manual signature text (defaults to signer name)\" },\n ],\n handler: async (ctx) => {\n const docRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedDocumentId = await ctx.resolver.resolveDocument(eid, docRef);\n const signerName = ctx.opts.signerName as string | undefined;\n const signerRole = ctx.opts.signerRole as string | undefined;\n const signerEmail = ctx.opts.signerEmail as string | undefined;\n const signatureText = ctx.opts.signatureText as string | undefined;\n\n if (signerName || signerRole || signerEmail || signatureText) {\n if (!signerName || !signerRole || !signerEmail) {\n throw new Error(\"Manual signing requires --signer-name, --signer-role, and --signer-email.\");\n }\n const result = await ctx.client.signDocument(resolvedDocumentId, eid, {\n signer_name: signerName,\n signer_role: signerRole,\n signer_email: signerEmail,\n signature_text: signatureText ?? signerName,\n });\n await ctx.resolver.stabilizeRecord(\"document\", { document_id: resolvedDocumentId, title: docRef }, eid);\n ctx.writer.writeResult(result, `Document ${resolvedDocumentId} signed.`, { jsonOnly: ctx.opts.json });\n return;\n }\n\n const result = await autoSignFormationDocument(ctx.client, eid, resolvedDocumentId);\n await ctx.resolver.stabilizeRecord(\"document\", result.document, eid);\n ctx.resolver.rememberFromRecord(\"document\", result.document, eid);\n if (ctx.opts.json) {\n ctx.writer.json({\n document_id: resolvedDocumentId,\n signatures_added: result.signatures_added,\n document: result.document,\n });\n return;\n }\n ctx.writer.success(\n result.signatures_added > 0\n ? `Applied ${result.signatures_added} signature(s) to ${resolvedDocumentId}.`\n : `No signatures were needed for ${resolvedDocumentId}.`,\n );\n printReferenceSummary(\"document\", result.document, { showReuseHint: true });\n printJson(result.document);\n },\n examples: [\"corp documents sign <doc-ref>\", \"corp documents sign --json\"],\n },\n\n // --- documents sign-all ---\n {\n name: \"documents sign-all\",\n description: \"Auto-sign all outstanding formation documents for an entity\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/sign-all\" },\n entity: true,\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const result = await autoSignFormationDocuments(ctx.client, ctx.resolver, eid);\n if (ctx.opts.json) {\n ctx.writer.json(result);\n return;\n }\n ctx.writer.success(\n `Processed ${result.documents_seen} formation document(s); added ${result.signatures_added} signature(s) across ${result.documents_signed} document(s).`,\n );\n printJson(result.documents.map((document: Record<string, unknown>) => ({\n document_id: document.document_id,\n title: document.title,\n status: document.status,\n signatures: Array.isArray(document.signatures) ? document.signatures.length : document.signatures,\n })));\n },\n examples: [\"corp documents sign-all\"],\n },\n\n // --- documents generate ---\n {\n name: \"documents generate\",\n description: \"Generate a contract from a template\",\n route: { method: \"POST\", path: \"/v1/contracts/generate\" },\n entity: true,\n options: [\n { flags: \"--template <type>\", description: \"Template type (consulting_agreement, employment_offer, contractor_agreement, nda, custom)\", required: true },\n { flags: \"--counterparty <name>\", description: \"Counterparty name\", required: true },\n { flags: \"--effective-date <date>\", description: \"Effective date (ISO 8601, defaults to today)\" },\n { flags: \"--base-salary <amount>\", description: \"Employment offer base salary (for employment_offer)\" },\n { flags: \"--param <key=value>\", description: \"Additional template parameter (repeatable)\", type: \"array\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const template = ctx.opts.template as string;\n const counterparty = ctx.opts.counterparty as string;\n const baseSalary = ctx.opts.baseSalary as string | undefined;\n const paramRaw = (ctx.opts.param as string[] | undefined) ?? [];\n\n const parameters: Record<string, unknown> = {};\n if (baseSalary) parameters.base_salary = baseSalary;\n for (const raw of paramRaw) {\n const idx = raw.indexOf(\"=\");\n if (idx <= 0) throw new Error(`Invalid --param value: ${raw}. Expected key=value.`);\n const key = raw.slice(0, idx).trim();\n const value = raw.slice(idx + 1).trim();\n if (!key) throw new Error(`Invalid --param value: ${raw}. Expected key=value.`);\n parameters[key] = coerceParamValue(value);\n }\n\n // Early validation for known required template parameters\n if (template === \"employment_offer\" && !parameters.base_salary) {\n throw new Error(\n \"base_salary is required for employment_offer template.\\n\" +\n \" Use: --base-salary 150000\\n\" +\n \" Or: --param base_salary=150000\",\n );\n }\n\n try {\n const result = await ctx.client.generateContract({\n entity_id: eid,\n template_type: template,\n counterparty_name: counterparty,\n effective_date: (ctx.opts.effectiveDate as string | undefined) ?? new Date().toISOString().slice(0, 10),\n parameters,\n });\n await ctx.resolver.stabilizeRecord(\"document\", result, eid);\n ctx.resolver.rememberFromRecord(\"document\", result, eid);\n if (result.document_id) {\n ctx.resolver.remember(\"document\", String(result.document_id), eid);\n }\n ctx.writer.writeResult(result, `Contract generated: ${result.contract_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"document\",\n showReuseHint: true,\n });\n } catch (err) {\n const msg = String(err);\n if (template === \"employment_offer\" && (msg.includes(\"base_salary\") || msg.includes(\"required\"))) {\n printError(\n `Failed to generate employment_offer: ${msg}\\n` +\n \" Hint: employment_offer requires base_salary. Use:\\n\" +\n \" --base-salary 150000\\n\" +\n \" Or: --param base_salary=150000\\n\" +\n \" Optional params: position_title, start_date, work_location, classification,\\n\" +\n \" bonus_terms, equity_terms, benefits_summary, governing_law\",\n );\n } else if (template === \"safe_agreement\" && (msg.includes(\"purchase_amount\") || msg.includes(\"investment_amount\") || msg.includes(\"valuation_cap\") || msg.includes(\"investor_notice\") || msg.includes(\"required\"))) {\n printError(\n `Failed to generate safe_agreement: ${msg}\\n` +\n \" Hint: safe_agreement requires purchase_amount, valuation_cap, and investor_notice_address. Use:\\n\" +\n \" --param purchase_amount=50000000 --param valuation_cap=10000000\\n\" +\n ' --param investor_notice_address=\"123 Main St, City, ST 12345\"',\n );\n } else {\n printError(`Failed to generate contract: ${err}`);\n }\n process.exit(1);\n }\n },\n produces: { kind: \"document\" },\n successTemplate: \"Document generated: {title}\",\n examples: [\"corp documents generate --template 'type' --counterparty 'name'\", \"corp documents generate --json\"],\n },\n\n // --- documents preview-pdf ---\n {\n name: \"documents preview-pdf\",\n description: \"Validate and print the authenticated PDF preview URL for a governance document\",\n route: { method: \"GET\", path: \"/v1/documents/preview/pdf\" },\n entity: true,\n options: [\n { flags: \"--definition-id <id>\", description: \"AST document definition ID (e.g. 'bylaws')\" },\n { flags: \"--document-id <id>\", description: \"Deprecated alias for --definition-id\" },\n ],\n handler: async (ctx) => {\n const documentId = (ctx.opts.definitionId as string | undefined) ?? (ctx.opts.documentId as string | undefined);\n if (!documentId || documentId.trim().length === 0) {\n printError(\"preview-pdf requires --definition-id (or deprecated alias --document-id)\");\n process.exit(1);\n }\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n await ctx.client.validatePreviewPdf(eid, documentId);\n const url = ctx.client.getPreviewPdfUrl(eid, documentId);\n ctx.writer.success(`Preview PDF URL: ${url}`);\n console.log(\"The document definition was validated successfully. Use your API key to download the PDF.\");\n },\n examples: [\"corp documents preview-pdf\", \"corp documents preview-pdf --json\"],\n },\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n printDeadlinesTable,\n printError,\n printJson,\n printTaxFilingsTable,\n printWriteResult,\n} from \"../output.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst TAX_DOCUMENT_TYPE_DISPLAY = [\n \"1120\", \"1120s\", \"1065\", \"franchise_tax\", \"annual_report\", \"83b\",\n \"1099_nec\", \"k1\", \"941\", \"w2\",\n] as const;\n\nconst TAX_DOCUMENT_TYPE_ALIASES: Record<string, string> = {\n form_1120: \"1120\", form_1120s: \"1120s\", form_1065: \"1065\",\n form_1099_nec: \"1099_nec\", form_k1: \"k1\", form_941: \"941\", form_w2: \"w2\",\n};\n\nconst TAX_DOCUMENT_TYPE_CHOICES = [\n ...TAX_DOCUMENT_TYPE_DISPLAY,\n ...Object.keys(TAX_DOCUMENT_TYPE_ALIASES),\n];\n\nfunction normalizeRecurrence(recurrence?: string): string | undefined {\n if (!recurrence) return undefined;\n if (recurrence === \"yearly\") return \"annual\";\n return recurrence;\n}\n\n// ---------------------------------------------------------------------------\n// Tax / Compliance registry entries\n// ---------------------------------------------------------------------------\n\nexport const complianceCommands: CommandDef[] = [\n // --- tax (summary: filings + deadlines) ---\n {\n name: \"tax\",\n description: \"Tax filings and deadline tracking\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/tax-filings\" },\n entity: true,\n display: { title: \"Tax Summary\" },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const [filings, deadlines] = await Promise.all([\n ctx.client.listTaxFilings(eid),\n ctx.client.listDeadlines(eid),\n ]);\n if (ctx.opts.json) { ctx.writer.json({ filings, deadlines }); return; }\n if (filings.length === 0 && deadlines.length === 0) {\n ctx.writer.writeln(\"No tax filings or deadlines found.\");\n return;\n }\n if (filings.length > 0) printTaxFilingsTable(filings);\n if (deadlines.length > 0) printDeadlinesTable(deadlines);\n },\n examples: [\"corp tax\", \"corp tax --json\"],\n },\n\n // --- tax filings ---\n {\n name: \"tax filings\",\n description: \"Create a tax filing record\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/tax-filings\" },\n entity: true,\n display: {\n title: \"Tax Filings\",\n cols: [\"document_type>Type\", \"tax_year>Year\", \"status>Status\", \"#filing_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const filings = await ctx.client.listTaxFilings(eid);\n await ctx.resolver.stabilizeRecords(\"tax_filing\", filings, eid);\n if (ctx.opts.json) { ctx.writer.json(filings); return; }\n if (filings.length === 0) { ctx.writer.writeln(\"No tax filings found.\"); return; }\n printTaxFilingsTable(filings);\n },\n examples: [\"corp tax filings\", \"corp tax filings --json\"],\n },\n\n // --- tax file ---\n {\n name: \"tax file\",\n description: \"File a tax document\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/tax-filings\" },\n entity: true,\n options: [\n {\n flags: \"--type <type>\",\n description: `Document type (${TAX_DOCUMENT_TYPE_DISPLAY.join(\", \")})`,\n required: true,\n choices: [...TAX_DOCUMENT_TYPE_CHOICES],\n },\n { flags: \"--year <year>\", description: \"Tax year\", required: true, type: \"int\" },\n { flags: \"--filer-contact-id <ref>\", description: \"Contact reference for per-person filings (e.g. 83(b) elections)\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const rawType = ctx.opts.type as string;\n const docType = TAX_DOCUMENT_TYPE_ALIASES[rawType] ?? rawType;\n const filerContactId = (ctx.opts.filerContactId as string | undefined)\n ? await ctx.resolver.resolveContact(eid, ctx.opts.filerContactId as string)\n : undefined;\n const payload: Record<string, unknown> = {\n entity_id: eid,\n document_type: docType,\n tax_year: ctx.opts.year as number,\n };\n if (filerContactId) payload.filer_contact_id = filerContactId;\n const result = await ctx.client.fileTaxDocument(payload);\n await ctx.resolver.stabilizeRecord(\"tax_filing\", result, eid);\n ctx.resolver.rememberFromRecord(\"tax_filing\", result, eid);\n ctx.writer.writeResult(result, `Tax document filed: ${result.filing_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"tax_filing\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"tax_filing\" },\n successTemplate: \"Tax filing created\",\n examples: [\"corp tax file --year 'year'\"],\n },\n\n // --- tax deadlines ---\n {\n name: \"tax deadlines\",\n description: \"List tracked deadlines\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/deadlines\" },\n entity: true,\n display: {\n title: \"Deadlines\",\n cols: [\"deadline_type>Type\", \"@due_date>Due\", \"description>Description\", \"#deadline_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const deadlines = await ctx.client.listDeadlines(eid);\n await ctx.resolver.stabilizeRecords(\"deadline\", deadlines, eid);\n if (ctx.opts.json) { ctx.writer.json(deadlines); return; }\n if (deadlines.length === 0) { ctx.writer.writeln(\"No deadlines found.\"); return; }\n printDeadlinesTable(deadlines);\n },\n examples: [\"corp tax deadlines\", \"corp tax deadlines --json\"],\n },\n\n // --- tax deadline ---\n {\n name: \"tax deadline\",\n description: \"Track a compliance deadline\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/deadlines\" },\n entity: true,\n options: [\n { flags: \"--type <type>\", description: \"Deadline type\", required: true },\n { flags: \"--due-date <date>\", description: \"Due date (ISO 8601)\", required: true },\n { flags: \"--description <desc>\", description: \"Description text\", required: true },\n { flags: \"--recurrence <recurrence>\", description: \"Recurrence (e.g. annual; 'yearly' is normalized). Required for annual_report type.\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n let recurrence = normalizeRecurrence(ctx.opts.recurrence as string | undefined);\n if (!recurrence && (ctx.opts.type as string) === \"annual_report\") {\n recurrence = \"annual\";\n }\n const payload: Record<string, unknown> = {\n entity_id: eid,\n deadline_type: ctx.opts.type as string,\n due_date: ctx.opts.dueDate as string,\n description: ctx.opts.description as string,\n };\n if (recurrence) payload.recurrence = recurrence;\n const result = await ctx.client.trackDeadline(payload);\n await ctx.resolver.stabilizeRecord(\"deadline\", result, eid);\n ctx.resolver.rememberFromRecord(\"deadline\", result, eid);\n ctx.writer.writeResult(result, `Deadline tracked: ${result.deadline_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"deadline\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"deadline\" },\n successTemplate: \"Deadline tracked\",\n examples: [\"corp tax deadline --type 'type' --due-date 'date' --description 'desc'\", \"corp tax deadline --json\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"compliance escalations-scan\",\n description: \"Scan for compliance issues and create escalations\",\n route: { method: \"POST\", path: \"/v1/compliance/escalations/scan\" },\n examples: [\"corp compliance escalations-scan\"],\n successTemplate: \"Escalations Scan created\",\n },\n {\n name: \"compliance escalations-resolve-with-evidence\",\n description: \"Resolve a compliance escalation with evidence\",\n route: { method: \"POST\", path: \"/v1/compliance/escalations/{pos}/resolve-with-evidence\" },\n args: [{ name: \"escalation-id\", required: true, description: \"Escalation ID\" }],\n options: [\n { flags: \"--evidence-type <evidence-type>\", description: \"Evidence Type\" },\n { flags: \"--filing-reference <filing-reference>\", description: \"Filing Reference\" },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n { flags: \"--packet-id <packet-id>\", description: \"Document packet ID\" },\n { flags: \"--resolve-incident\", description: \"Resolve Incident\" },\n { flags: \"--resolve-obligation\", description: \"Resolve Obligation\" },\n ],\n examples: [\"corp compliance escalations-resolve-with-evidence <escalation-id>\", \"corp compliance escalations-resolve-with-evidence --json\"],\n successTemplate: \"Escalations Resolve With Evidence created\",\n },\n {\n name: \"contractors classify\",\n description: \"Classify a worker as employee or contractor\",\n route: { method: \"POST\", path: \"/v1/contractors/classify\" },\n entity: true,\n options: [\n { flags: \"--contractor-name <contractor-name>\", description: \"Contractor Name\", required: true },\n { flags: \"--duration-months <duration-months>\", description: \"Duration Months\" },\n { flags: \"--exclusive-client <exclusive-client>\", description: \"Exclusive Client\" },\n { flags: \"--factors <factors>\", description: \"Factors\" },\n { flags: \"--hours-per-week <hours-per-week>\", description: \"Hours Per Week\" },\n { flags: \"--provides-tools <provides-tools>\", description: \"Provides Tools\" },\n { flags: \"--state <state>\", description: \"State\" },\n ],\n examples: [\"corp contractors classify --contractor-name 'contractor-name'\", \"corp contractors classify --json\"],\n successTemplate: \"Classify created\",\n },\n {\n name: \"deadlines\",\n description: \"Create a compliance deadline\",\n route: { method: \"POST\", path: \"/v1/deadlines\" },\n options: [\n { flags: \"--deadline-type <deadline-type>\", description: \"Deadline Type\", required: true },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--due-date <due-date>\", description: \"Due date (ISO 8601, e.g. 2026-06-30)\", required: true },\n { flags: \"--recurrence <recurrence>\", description: \"Recurrence pattern for a deadline.\", choices: [\"one_time\", \"monthly\", \"quarterly\", \"annual\"] },\n { flags: \"--severity <severity>\", description: \"Risk severity of missing a deadline.\", choices: [\"low\", \"medium\", \"high\", \"critical\"] },\n ],\n examples: [\"corp deadlines --deadline-type 'deadline-type' --description 'description' --due-date one_time\", \"corp deadlines --json\"],\n successTemplate: \"Deadlines created\",\n },\n {\n name: \"entities compliance-escalations\",\n description: \"List compliance escalations for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/compliance/escalations\" },\n entity: true,\n display: { title: \"Entities Compliance Escalations\", cols: [\"action>Action\", \"authority>Authority\", \"milestone>Milestone\", \"@created_at>Created At\", \"#deadline_id>ID\"] },\n examples: [\"corp entities compliance-escalations\", \"corp entities compliance-escalations --json\"],\n },\n {\n name: \"tax create-filing\",\n description: \"Create a tax filing record\",\n route: { method: \"POST\", path: \"/v1/tax/filings\" },\n entity: true,\n options: [\n { flags: \"--document-type <document-type>\", description: \"Type of document required\", required: true },\n { flags: \"--tax-year <tax-year>\", description: \"Tax Year\", required: true, type: \"int\" },\n ],\n examples: [\"corp tax filings --document-type 'document-type' --tax-year 'tax-year'\"],\n successTemplate: \"Filings created\",\n },\n\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n printAgentsTable,\n printError,\n printJson,\n printReferenceSummary,\n printSuccess,\n printWriteResult,\n} from \"../output.js\";\nimport { confirm } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport type { ApiRecord } from \"../types.js\";\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport { relative, resolve } from \"node:path\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveTextInput(\n inlineText: string | undefined,\n filePath: string | undefined,\n label: string,\n required = false,\n): string | undefined {\n if (inlineText && filePath) {\n throw new Error(`Pass either --${label} or --${label}-file, not both.`);\n }\n if (filePath) {\n if (process.env.CORP_ALLOW_UNSAFE_FILE_INPUT === \"1\") {\n return readFileSync(filePath, \"utf8\");\n }\n const resolvedFile = realpathSync(resolve(filePath));\n const workingTreeRoot = realpathSync(process.cwd());\n const rel = relative(workingTreeRoot, resolvedFile);\n if (rel === \"\" || (!rel.startsWith(\"..\") && !rel.startsWith(\"/\"))) {\n return readFileSync(resolvedFile, \"utf8\");\n }\n throw new Error(\n `--${label}-file must stay inside the current working directory unless CORP_ALLOW_UNSAFE_FILE_INPUT=1 is set.`,\n );\n }\n if (inlineText) return inlineText;\n if (required) throw new Error(`Provide --${label} or --${label}-file.`);\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Agent registry entries\n// ---------------------------------------------------------------------------\n\nexport const agentCommands: CommandDef[] = [\n // --- agents (list) ---\n {\n name: \"agents\",\n description: \"Agent management\",\n route: { method: \"GET\", path: \"/v1/agents\" },\n display: {\n title: \"Agents\",\n cols: [\"name>Name\", \"status>Status\", \"model>Model\", \"#agent_id|id>ID\"],\n },\n handler: async (ctx) => {\n const agents = await ctx.client.listAgents();\n await ctx.resolver.stabilizeRecords(\"agent\", agents);\n if (ctx.opts.json) { ctx.writer.json(agents); return; }\n if (agents.length === 0) { ctx.writer.writeln(\"No agents found.\"); return; }\n printAgentsTable(agents);\n },\n examples: [\n \"corp agents\",\n 'corp agents create --name \"bookkeeper\" --prompt \"You manage accounts payable\"',\n 'corp agents message @last:agent --body \"Process this month\\'s invoices\"',\n 'corp agents skill @last:agent --name invoice-processing --description \"Process AP invoices\"',\n \"corp agents execution @last:agent <execution-id>\",\n \"corp agents kill @last:agent <execution-id>\",\n ],\n },\n\n // --- agents show <agent-ref> ---\n {\n name: \"agents show\",\n description: \"Show agent detail\",\n route: { method: \"GET\", path: \"/v1/agents/{pos}/resolved\" },\n args: [{ name: \"agent-ref\", required: true, description: \"Agent reference\" }],\n display: { title: \"Agent Detail\" },\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n const agent = await ctx.client.getAgent(resolvedAgentId);\n await ctx.resolver.stabilizeRecord(\"agent\", agent);\n if (ctx.opts.json) { ctx.writer.json(agent); return; }\n console.log(chalk.magenta(\"\\u2500\".repeat(40)));\n console.log(chalk.magenta.bold(\" Agent Detail\"));\n console.log(chalk.magenta(\"\\u2500\".repeat(40)));\n console.log(` ${chalk.bold(\"Name:\")} ${agent.name ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Status:\")} ${agent.status ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Model:\")} ${agent.model ?? \"N/A\"}`);\n printReferenceSummary(\"agent\", agent, { showReuseHint: true });\n if (agent.system_prompt) {\n let prompt = String(agent.system_prompt);\n if (prompt.length > 100) prompt = prompt.slice(0, 97) + \"...\";\n console.log(` ${chalk.bold(\"Prompt:\")} ${prompt}`);\n }\n if (agent.skills && Array.isArray(agent.skills) && agent.skills.length > 0) {\n console.log(` ${chalk.bold(\"Skills:\")} ${(agent.skills as Array<{ name?: string }>).map((s) => s.name ?? \"?\").join(\", \")}`);\n }\n console.log(chalk.magenta(\"\\u2500\".repeat(40)));\n },\n examples: [\"corp agents show\"],\n },\n\n // --- agents create ---\n {\n name: \"agents create\",\n description: \"Create a new agent\",\n route: { method: \"POST\", path: \"/v1/agents\" },\n options: [\n { flags: \"--name <name>\", description: \"Agent name\", required: true },\n { flags: \"--prompt <prompt>\", description: \"System prompt\", required: true },\n { flags: \"--model <model>\", description: \"LLM model name\" },\n ],\n handler: async (ctx) => {\n const data: ApiRecord = {\n name: ctx.opts.name as string,\n system_prompt: ctx.opts.prompt as string,\n };\n if (ctx.opts.model) data.model = ctx.opts.model as string;\n try {\n const result = await ctx.client.createAgent(data);\n await ctx.resolver.stabilizeRecord(\"agent\", result);\n ctx.resolver.rememberFromRecord(\"agent\", result);\n ctx.writer.writeResult(result, `Agent created: ${result.agent_id ?? result.id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"agent\",\n showReuseHint: true,\n });\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"409\") || msg.includes(\"conflict\") || msg.includes(\"already exists\")) {\n printError(\n `Agent name '${ctx.opts.name}' is already in use (deleted agents still reserve their name).\\n` +\n \" Choose a different name, e.g.: corp agents create --name '...-v2' --prompt '...'\",\n );\n } else {\n printError(`Failed to create agent: ${err}`);\n }\n process.exit(1);\n }\n },\n produces: { kind: \"agent\" },\n successTemplate: \"Agent created: {name}\",\n examples: [\"corp agents create --name 'name' --prompt 'prompt'\", \"corp agents create --json\"],\n },\n\n // --- agents pause <agent-ref> ---\n {\n name: \"agents pause\",\n description: \"Pause an active agent\",\n route: { method: \"POST\", path: \"/v1/agents/{pos}/pause\" },\n args: [{ name: \"agent-ref\", required: true, description: \"Agent reference\" }],\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n const result = await ctx.client.updateAgent(resolvedAgentId, { status: \"paused\" });\n ctx.writer.writeResult(result, `Agent ${resolvedAgentId} paused.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp agents pause <agent-ref>\"],\n },\n\n // --- agents resume <agent-ref> ---\n {\n name: \"agents resume\",\n description: \"Resume a paused agent\",\n route: { method: \"POST\", path: \"/v1/agents/{pos}/resume\" },\n args: [{ name: \"agent-ref\", required: true, description: \"Agent reference\" }],\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n try {\n const result = await ctx.client.updateAgent(resolvedAgentId, { status: \"active\" });\n ctx.writer.writeResult(result, `Agent ${resolvedAgentId} resumed.`, { jsonOnly: ctx.opts.json });\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"409\") || msg.includes(\"disabled\") || msg.includes(\"deleted\")) {\n printError(\n `Cannot resume agent ${agentRef}: the agent may be disabled or deleted.\\n` +\n \" Disabled/deleted agents cannot be resumed. Create a new agent instead:\\n\" +\n \" corp agents create --name '...' --prompt '...'\",\n );\n } else {\n printError(`Failed to resume agent: ${err}`);\n }\n process.exit(1);\n }\n },\n examples: [\"corp agents resume <agent-ref>\"],\n },\n\n // --- agents delete <agent-ref> ---\n {\n name: \"agents delete\",\n description: \"Delete an agent\",\n route: { method: \"DELETE\", path: \"/v1/agents/{pos}\" },\n args: [{ name: \"agent-ref\", required: true, description: \"Agent reference\" }],\n options: [\n { flags: \"--yes, -y\", description: \"Skip confirmation prompt\" },\n ],\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n if (!ctx.opts.yes) {\n const ok = await confirm({\n message: `Delete agent ${resolvedAgentId}? This cannot be undone.`,\n default: false,\n });\n if (!ok) { console.log(\"Cancelled.\"); return; }\n }\n const result = await ctx.client.deleteAgent(resolvedAgentId);\n ctx.writer.writeResult(result, `Agent ${resolvedAgentId} deleted.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp agents delete <agent-ref>\", \"corp agents delete --json\"],\n },\n\n // --- agents message <agent-ref> ---\n {\n name: \"agents message\",\n description: \"Send a message to an agent\",\n route: { method: \"POST\", path: \"/v1/agents/{pos}/messages\" },\n args: [{ name: \"agent-ref\", required: true, description: \"Agent reference\" }],\n options: [\n { flags: \"--body <text>\", description: \"Message text\" },\n { flags: \"--body-file <path>\", description: \"Read the message body from a file\" },\n ],\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const body = resolveTextInput(ctx.opts.body as string | undefined, ctx.opts.bodyFile as string | undefined, \"body\", true);\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n try {\n const result = await ctx.client.sendAgentMessage(resolvedAgentId, body!);\n ctx.writer.writeResult(result, `Message sent. Execution: ${result.execution_id ?? \"OK\"}`, { jsonOnly: ctx.opts.json });\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"409\")) {\n printError(\n `Cannot message agent: the agent must be active or paused (not disabled/deleted).\\n` +\n \" Check agent status: corp agents show \" + agentRef + \"\\n\" +\n \" Resume a paused agent: corp agents resume \" + agentRef,\n );\n } else {\n printError(`Failed to send message: ${err}`);\n }\n process.exit(1);\n }\n },\n examples: [\"corp agents message <agent-ref>\", \"corp agents message --json\"],\n },\n\n // --- agents skill <agent-ref> ---\n {\n name: \"agents skill\",\n description: \"Add a skill to an agent\",\n route: { method: \"POST\", path: \"/v1/agents/{pos}/skills\" },\n args: [{ name: \"agent-ref\", required: true, description: \"Agent reference\" }],\n options: [\n { flags: \"--name <name>\", description: \"Skill name\", required: true },\n { flags: \"--description <desc>\", description: \"Skill description\", required: true },\n { flags: \"--instructions <text>\", description: \"Skill instructions text\" },\n { flags: \"--instructions-file <path>\", description: \"Read skill instructions from a file\" },\n ],\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const instructions = resolveTextInput(\n ctx.opts.instructions as string | undefined,\n ctx.opts.instructionsFile as string | undefined,\n \"instructions\",\n );\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n const result = await ctx.client.addAgentSkill(resolvedAgentId, {\n name: ctx.opts.name as string,\n description: ctx.opts.description as string,\n parameters: instructions ? { instructions } : {},\n });\n ctx.writer.writeResult(result, `Skill '${ctx.opts.name}' added to agent ${resolvedAgentId}.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp agents skill <agent-ref> --name 'name' --description 'desc'\", \"corp agents skill --json\"],\n },\n\n // --- agents execution <agent-ref> <execution-id> ---\n {\n name: \"agents execution\",\n description: \"Check execution status\",\n route: { method: \"GET\", path: \"/v1/agents/{pos}/executions/{pos2}\" },\n args: [\n { name: \"agent-ref\", required: true, description: \"Agent reference\" },\n { name: \"execution-id\", required: true, description: \"Execution ID\" },\n ],\n display: { title: \"Execution Status\" },\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const executionId = ctx.positional[1];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n const result = await ctx.client.getAgentExecution(resolvedAgentId, executionId);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n console.log(chalk.magenta(\"\\u2500\".repeat(40)));\n console.log(chalk.magenta.bold(\" Execution Status\"));\n console.log(chalk.magenta(\"\\u2500\".repeat(40)));\n console.log(` ${chalk.bold(\"Execution:\")} ${executionId}`);\n console.log(` ${chalk.bold(\"Agent:\")} ${resolvedAgentId}`);\n console.log(` ${chalk.bold(\"Status:\")} ${result.status ?? \"N/A\"}`);\n if (result.started_at) console.log(` ${chalk.bold(\"Started:\")} ${result.started_at}`);\n if (result.completed_at) console.log(` ${chalk.bold(\"Completed:\")} ${result.completed_at}`);\n console.log(chalk.magenta(\"\\u2500\".repeat(40)));\n },\n examples: [\"corp agents execution\"],\n },\n\n // --- agents execution-result <agent-ref> <execution-id> ---\n {\n name: \"agents execution-result\",\n description: \"Get execution result\",\n route: { method: \"GET\", path: \"/v1/agents/{pos}/executions/{pos2}/result\" },\n args: [\n { name: \"agent-ref\", required: true, description: \"Agent reference\" },\n { name: \"execution-id\", required: true, description: \"Execution ID\" },\n ],\n display: { title: \"Execution Result\" },\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const executionId = ctx.positional[1];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n const result = await ctx.client.getAgentExecutionResult(resolvedAgentId, executionId);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Result for execution ${executionId}:`);\n printJson(result);\n },\n examples: [\"corp agents execution-result\"],\n },\n\n // --- agents kill <agent-ref> <execution-id> ---\n {\n name: \"agents kill\",\n description: \"Kill a running execution\",\n route: { method: \"POST\", path: \"/v1/agents/{pos}/executions/{pos2}/kill\" },\n args: [\n { name: \"agent-ref\", required: true, description: \"Agent reference\" },\n { name: \"execution-id\", required: true, description: \"Execution ID\" },\n ],\n options: [\n { flags: \"--yes\", description: \"Skip confirmation\" },\n ],\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const executionId = ctx.positional[1];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n if (!ctx.opts.yes) {\n const ok = await confirm({ message: `Kill execution ${executionId}?`, default: false });\n if (!ok) { console.log(\"Cancelled.\"); return; }\n }\n const result = await ctx.client.killAgentExecution(resolvedAgentId, executionId);\n ctx.writer.writeResult(result, `Execution ${executionId} killed.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp agents kill <agent-ref> <execution-id>\", \"corp agents kill --json\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"agents executions-logs\",\n description: \"View execution logs for an agent run\",\n route: { method: \"GET\", path: \"/v1/agents/{pos}/executions/{pos2}/logs\" },\n args: [{ name: \"agent-id\", required: true, description: \"Agent ID\" }, { name: \"execution-id\", required: true, description: \"Agent execution ID\" }],\n display: { title: \"Execution Logs\", cols: [\"@timestamp>Time\", \"level>Level\", \"message>Message\"] },\n examples: [\"corp agents executions-logs\"],\n },\n\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"agents messages\",\n description: \"View a specific agent message\",\n route: { method: \"GET\", path: \"/v1/agents/{pos}/messages/{pos2}\" },\n args: [{ name: \"agent-id\", required: true, description: \"Agent ID\" }, { name: \"message-id\", required: true, description: \"Message Id\" }],\n display: { title: \"Agent Message\" },\n examples: [\"corp agents messages\"],\n },\n\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n printReferenceSummary,\n printWorkItemsTable,\n printError,\n printJson,\n printWriteResult,\n} from \"../output.js\";\nimport { confirm } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction actorLabel(record: Record<string, unknown>, key: \"claimed_by\" | \"completed_by\" | \"created_by\"): string | undefined {\n const actor = record[`${key}_actor`];\n if (actor && typeof actor === \"object\" && !Array.isArray(actor)) {\n const label = (actor as Record<string, unknown>).label;\n const actorType = (actor as Record<string, unknown>).actor_type;\n if (typeof label === \"string\" && label.trim()) {\n return typeof actorType === \"string\" && actorType.trim()\n ? `${label} (${actorType})`\n : label;\n }\n }\n const legacy = record[key];\n return typeof legacy === \"string\" && legacy.trim() ? legacy : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Work-item registry entries\n// ---------------------------------------------------------------------------\n\nexport const workItemCommands: CommandDef[] = [\n // --- work-items (list) ---\n {\n name: \"work-items\",\n description: \"Long-term work item coordination\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/work-items\" },\n entity: true,\n optQP: [\"status\", \"category\"],\n display: {\n title: \"Work Items\",\n cols: [\"title>Title\", \"category>Category\", \"effective_status|status>Status\", \"@deadline>Deadline\", \"#work_item_id|id>ID\"],\n },\n options: [\n { flags: \"--status <status>\", description: \"Filter by status (open, claimed, completed, cancelled)\" },\n { flags: \"--category <category>\", description: \"Filter by category\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const params: Record<string, string> = {};\n if (ctx.opts.status) params.status = ctx.opts.status as string;\n if (ctx.opts.category) params.category = ctx.opts.category as string;\n const items = await ctx.client.listWorkItems(eid, Object.keys(params).length > 0 ? params : undefined);\n await ctx.resolver.stabilizeRecords(\"work_item\", items, eid);\n if (ctx.opts.json) { ctx.writer.json(items); return; }\n if (items.length === 0) { ctx.writer.writeln(\"No work items found.\"); return; }\n printWorkItemsTable(items);\n },\n examples: [\n \"corp work-items\",\n 'corp work-items create --title \"File Q1 taxes\" --category compliance --deadline 2026-04-15',\n \"corp work-items claim @last:work_item --by bookkeeper-agent\",\n 'corp work-items complete @last:work_item --by bookkeeper-agent --result \"Filed 1120 for Q1\"',\n ],\n },\n\n // --- work-items show <item-ref> ---\n {\n name: \"work-items show\",\n description: \"Show work item detail\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/work-items/{pos}\" },\n entity: true,\n args: [{ name: \"item-ref\", required: true, description: \"Work item reference\" }],\n display: { title: \"Work Item Detail\" },\n handler: async (ctx) => {\n const itemRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedWorkItemId = await ctx.resolver.resolveWorkItem(eid, itemRef);\n const w = await ctx.client.getWorkItem(eid, resolvedWorkItemId);\n await ctx.resolver.stabilizeRecord(\"work_item\", w, eid);\n if (ctx.opts.json) { ctx.writer.json(w); return; }\n console.log(chalk.cyan(\"\\u2500\".repeat(40)));\n console.log(chalk.cyan.bold(\" Work Item Detail\"));\n console.log(chalk.cyan(\"\\u2500\".repeat(40)));\n console.log(` ${chalk.bold(\"Title:\")} ${w.title ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Category:\")} ${w.category ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Status:\")} ${w.effective_status ?? w.status ?? \"N/A\"}`);\n printReferenceSummary(\"work_item\", w, { showReuseHint: true });\n if (w.description) console.log(` ${chalk.bold(\"Description:\")} ${w.description}`);\n if (w.deadline) console.log(` ${chalk.bold(\"Deadline:\")} ${w.deadline}`);\n if (w.asap) console.log(` ${chalk.bold(\"Priority:\")} ${chalk.red.bold(\"ASAP\")}`);\n const claimedBy = actorLabel(w, \"claimed_by\");\n const completedBy = actorLabel(w, \"completed_by\");\n const createdBy = actorLabel(w, \"created_by\");\n if (claimedBy) console.log(` ${chalk.bold(\"Claimed by:\")} ${claimedBy}`);\n if (w.claimed_at) console.log(` ${chalk.bold(\"Claimed at:\")} ${w.claimed_at}`);\n if (w.claim_ttl_seconds) console.log(` ${chalk.bold(\"Claim TTL:\")} ${w.claim_ttl_seconds}s`);\n if (completedBy) console.log(` ${chalk.bold(\"Completed by:\")} ${completedBy}`);\n if (w.completed_at) console.log(` ${chalk.bold(\"Completed at:\")} ${w.completed_at}`);\n if (w.result) console.log(` ${chalk.bold(\"Result:\")} ${w.result}`);\n if (createdBy) console.log(` ${chalk.bold(\"Created by:\")} ${createdBy}`);\n console.log(` ${chalk.bold(\"Created at:\")} ${w.created_at ?? \"N/A\"}`);\n console.log(chalk.cyan(\"\\u2500\".repeat(40)));\n },\n examples: [\"corp work-items show\", \"corp work-items show --json\"],\n },\n\n // --- work-items create ---\n {\n name: \"work-items create\",\n description: \"Create a new work item\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/work-items\" },\n entity: true,\n options: [\n { flags: \"--title <title>\", description: \"Work item title\", required: true },\n { flags: \"--category <category>\", description: \"Work item category\", required: true },\n { flags: \"--description <desc>\", description: \"Description text\" },\n { flags: \"--deadline <date>\", description: \"Deadline (YYYY-MM-DD)\" },\n { flags: \"--asap\", description: \"Mark as ASAP priority\" },\n { flags: \"--created-by <name>\", description: \"Creator identifier\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const category = ctx.opts.category as string | undefined;\n if (!category) {\n printError(\"required option '--category <category>' not specified\");\n process.exit(1);\n }\n const data: Record<string, unknown> = { title: ctx.opts.title as string, category };\n if (ctx.opts.description) data.description = ctx.opts.description as string;\n if (ctx.opts.deadline) data.deadline = ctx.opts.deadline as string;\n if (ctx.opts.asap) data.asap = true;\n if (ctx.opts.createdBy) data.created_by_actor = await ctx.resolver.resolveWorkItemActor(eid, ctx.opts.createdBy as string);\n const result = await ctx.client.createWorkItem(eid, data);\n await ctx.resolver.stabilizeRecord(\"work_item\", result, eid);\n ctx.resolver.rememberFromRecord(\"work_item\", result, eid);\n ctx.writer.writeResult(\n result,\n `Work item created: ${result.work_item_id ?? result.id ?? \"OK\"}`,\n { jsonOnly: ctx.opts.json, referenceKind: \"work_item\", showReuseHint: true },\n );\n },\n produces: { kind: \"work_item\" },\n successTemplate: \"Work item created: {title}\",\n examples: [\"corp work-items create --title 'title'\", \"corp work-items create --json\"],\n },\n\n // --- work-items claim <item-ref> ---\n {\n name: \"work-items claim\",\n description: \"Claim a work item\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/work-items/{pos}/claim\" },\n entity: true,\n args: [{ name: \"item-ref\", required: true, description: \"Work item reference\" }],\n options: [\n { flags: \"--by <name>\", description: \"Agent or user claiming the item (required)\" },\n { flags: \"--claimer <name>\", description: \"Alias for --by\" },\n { flags: \"--ttl <seconds>\", description: \"Auto-release TTL in seconds\", type: \"int\" },\n ],\n handler: async (ctx) => {\n const itemRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedWorkItemId = await ctx.resolver.resolveWorkItem(eid, itemRef);\n const claimedBy = (ctx.opts.by as string | undefined) ?? (ctx.opts.claimer as string | undefined);\n if (!claimedBy) {\n printError(\"required option '--by <name>' not specified\");\n process.exit(1);\n }\n const data: Record<string, unknown> = {\n claimed_by_actor: await ctx.resolver.resolveWorkItemActor(eid, claimedBy),\n };\n if (ctx.opts.ttl != null) data.ttl_seconds = ctx.opts.ttl as number;\n const result = await ctx.client.claimWorkItem(eid, resolvedWorkItemId, data);\n ctx.writer.writeResult(result, `Work item ${resolvedWorkItemId} claimed by ${claimedBy}.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp work-items claim <item-ref>\", \"corp work-items claim --json\"],\n },\n\n // --- work-items complete <item-ref> ---\n {\n name: \"work-items complete\",\n description: \"Mark a work item as completed\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/work-items/{pos}/complete\" },\n entity: true,\n args: [{ name: \"item-ref\", required: true, description: \"Work item reference\" }],\n options: [\n { flags: \"--by <name>\", description: \"Agent or user completing the item (required)\" },\n { flags: \"--completed-by <name>\", description: \"Alias for --by\" },\n { flags: \"--result <text>\", description: \"Completion result or notes\" },\n { flags: \"--notes <text>\", description: \"Alias for --result\" },\n ],\n handler: async (ctx) => {\n const itemRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedWorkItemId = await ctx.resolver.resolveWorkItem(eid, itemRef);\n const completedBy = (ctx.opts.by as string | undefined) ?? (ctx.opts.completedBy as string | undefined);\n if (!completedBy) {\n printError(\"required option '--by <name>' not specified\");\n process.exit(1);\n }\n const data: Record<string, unknown> = {\n completed_by_actor: await ctx.resolver.resolveWorkItemActor(eid, completedBy),\n };\n const resultText = (ctx.opts.result as string | undefined) ?? (ctx.opts.notes as string | undefined);\n if (resultText) data.result = resultText;\n const result = await ctx.client.completeWorkItem(eid, resolvedWorkItemId, data);\n ctx.writer.writeResult(result, `Work item ${resolvedWorkItemId} completed.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp work-items complete <item-ref>\", \"corp work-items complete --json\"],\n },\n\n // --- work-items release <item-ref> ---\n {\n name: \"work-items release\",\n description: \"Release a claimed work item\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/work-items/{pos}/release\" },\n entity: true,\n args: [{ name: \"item-ref\", required: true, description: \"Work item reference\" }],\n handler: async (ctx) => {\n const itemRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedWorkItemId = await ctx.resolver.resolveWorkItem(eid, itemRef);\n const result = await ctx.client.releaseWorkItem(eid, resolvedWorkItemId);\n ctx.writer.writeResult(result, `Work item ${resolvedWorkItemId} claim released.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp work-items release <item-ref>\"],\n },\n\n // --- work-items cancel <item-ref> ---\n {\n name: \"work-items cancel\",\n description: \"Cancel a work item\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/work-items/{pos}/cancel\" },\n entity: true,\n args: [{ name: \"item-ref\", required: true, description: \"Work item reference\" }],\n options: [\n { flags: \"--yes, -y\", description: \"Skip confirmation prompt\" },\n ],\n handler: async (ctx) => {\n const itemRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedWorkItemId = await ctx.resolver.resolveWorkItem(eid, itemRef);\n if (!ctx.opts.yes) {\n const ok = await confirm({\n message: `Cancel work item ${resolvedWorkItemId}?`,\n default: false,\n });\n if (!ok) { console.log(\"Cancelled.\"); return; }\n }\n const result = await ctx.client.cancelWorkItem(eid, resolvedWorkItemId);\n ctx.writer.writeResult(result, `Work item ${resolvedWorkItemId} cancelled.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp work-items cancel <item-ref>\", \"corp work-items cancel --json\"],\n },\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n printServiceCatalogTable,\n printServiceRequestsTable,\n printDryRun,\n printError,\n printJson,\n printReferenceSummary,\n printSuccess,\n printWriteResult,\n} from \"../output.js\";\nimport chalk from \"chalk\";\n\n// ---------------------------------------------------------------------------\n// Service registry entries\n// ---------------------------------------------------------------------------\n\nexport const serviceCommands: CommandDef[] = [\n // --- services (alias to catalog) ---\n {\n name: \"services\",\n description: \"Service catalog and fulfillment\",\n route: { method: \"GET\", path: \"/v1/services/catalog\" },\n entity: true,\n display: {\n title: \"Service Catalog\",\n cols: [\"name>Name\", \"slug>Slug\", \"$price_cents>Price\", \"#service_id|id>ID\"],\n },\n handler: async (ctx) => {\n const items = await ctx.client.listServiceCatalog();\n if (ctx.opts.json) { ctx.writer.json(items); return; }\n printServiceCatalogTable(items);\n },\n examples: [\"corp services\", \"corp services --json\"],\n },\n\n // --- services catalog ---\n {\n name: \"services catalog\",\n description: \"List the service catalog\",\n route: { method: \"GET\", path: \"/v1/services/catalog\" },\n display: {\n title: \"Service Catalog\",\n cols: [\"name>Name\", \"slug>Slug\", \"$price_cents>Price\", \"#service_id|id>ID\"],\n },\n handler: async (ctx) => {\n const items = await ctx.client.listServiceCatalog();\n if (ctx.opts.json) { ctx.writer.json(items); return; }\n printServiceCatalogTable(items);\n },\n examples: [\"corp services catalog\"],\n },\n\n // --- services list ---\n {\n name: \"services list\",\n description: \"List service requests for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/service-requests\" },\n entity: true,\n display: {\n title: \"Service Requests\",\n cols: [\"service_slug>Service\", \"status>Status\", \"@created_at>Created\", \"#request_id|id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const requests = await ctx.client.listServiceRequests(eid);\n const stable = await ctx.resolver.stabilizeRecords(\"service_request\", requests, eid);\n if (ctx.opts.json) { ctx.writer.json(stable); return; }\n printServiceRequestsTable(stable);\n },\n examples: [\"corp services list\", \"corp services list --json\"],\n },\n\n // --- services show <ref> ---\n {\n name: \"services show\",\n description: \"Show service request detail\",\n route: { method: \"GET\", path: \"/v1/service-requests/{pos}\" },\n entity: true,\n args: [{ name: \"ref\", required: true, description: \"Service request reference\" }],\n display: { title: \"Service Request Detail\" },\n handler: async (ctx) => {\n const ref_ = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const requestId = await ctx.resolver.resolveServiceRequest(eid, ref_);\n const result = await ctx.client.getServiceRequest(requestId, eid);\n await ctx.resolver.stabilizeRecord(\"service_request\", result, eid);\n ctx.resolver.rememberFromRecord(\"service_request\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n printReferenceSummary(\"service_request\", result);\n printJson(result);\n },\n examples: [\"corp services show\", \"corp services show --json\"],\n },\n\n // --- services buy <slug> ---\n {\n name: \"services buy\",\n description: \"Purchase a service from the catalog\",\n route: { method: \"POST\", path: \"/v1/service-requests\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"slug\", required: true, description: \"Service catalog slug\" }],\n handler: async (ctx) => {\n const slug = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const payload = { entity_id: eid, service_slug: slug };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"services.create_request\", payload);\n return;\n }\n const result = await ctx.client.createServiceRequest(payload);\n await ctx.resolver.stabilizeRecord(\"service_request\", result, eid);\n ctx.resolver.rememberFromRecord(\"service_request\", result, eid);\n\n // Auto-begin checkout to get the URL.\n const requestId = String(result.request_id ?? result.id ?? \"\");\n if (requestId) {\n const checkout = await ctx.client.beginServiceCheckout(requestId, { entity_id: eid });\n if (ctx.opts.json) { ctx.writer.json(checkout); return; }\n ctx.writer.success(`Service request created: ${requestId}`);\n printReferenceSummary(\"service_request\", result, { showReuseHint: true });\n if (checkout.checkout_url) {\n console.log(`\\n ${chalk.bold(\"Checkout URL:\")} ${checkout.checkout_url}`);\n }\n console.log(chalk.dim(\"\\n Next steps:\"));\n console.log(chalk.dim(\" Complete payment at the checkout URL above\"));\n console.log(chalk.dim(\" corp services list --entity-id <id>\"));\n } else {\n ctx.writer.writeResult(result, \"Service request created\", {\n referenceKind: \"service_request\",\n showReuseHint: true,\n });\n }\n },\n produces: { kind: \"service_request\" },\n successTemplate: \"Service request created\",\n examples: [\"corp services buy <slug>\"],\n },\n\n // --- services fulfill <ref> ---\n {\n name: \"services fulfill\",\n description: \"Mark a service request as fulfilled (operator)\",\n route: { method: \"POST\", path: \"/v1/service-requests/{pos}/fulfill\" },\n entity: true,\n args: [{ name: \"ref\", required: true, description: \"Service request reference\" }],\n options: [\n { flags: \"--note <note>\", description: \"Fulfillment note\" },\n ],\n handler: async (ctx) => {\n const ref_ = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const requestId = await ctx.resolver.resolveServiceRequest(eid, ref_);\n const result = await ctx.client.fulfillServiceRequest(requestId, {\n entity_id: eid,\n note: ctx.opts.note as string | undefined,\n });\n await ctx.resolver.stabilizeRecord(\"service_request\", result, eid);\n ctx.resolver.rememberFromRecord(\"service_request\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Service request fulfilled: ${requestId}`);\n printReferenceSummary(\"service_request\", result, { showReuseHint: true });\n printJson(result);\n },\n examples: [\"corp services fulfill <ref>\", \"corp services fulfill --json\"],\n },\n\n // --- services cancel <ref> ---\n {\n name: \"services cancel\",\n description: \"Cancel a service request\",\n route: { method: \"POST\", path: \"/v1/service-requests/{pos}/cancel\" },\n entity: true,\n args: [{ name: \"ref\", required: true, description: \"Service request reference\" }],\n handler: async (ctx) => {\n const ref_ = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const requestId = await ctx.resolver.resolveServiceRequest(eid, ref_);\n const result = await ctx.client.cancelServiceRequest(requestId, {\n entity_id: eid,\n });\n await ctx.resolver.stabilizeRecord(\"service_request\", result, eid);\n ctx.resolver.rememberFromRecord(\"service_request\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Service request cancelled: ${requestId}`);\n printReferenceSummary(\"service_request\", result, { showReuseHint: true });\n printJson(result);\n },\n examples: [\"corp services cancel <ref>\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"services create-request\",\n description: \"Submit a new service request\",\n route: { method: \"POST\", path: \"/v1/services/requests\" },\n options: [\n { flags: \"--obligation-id <obligation-id>\", description: \"Obligation ID\" },\n { flags: \"--service-slug <service-slug>\", description: \"Service Slug\", required: true },\n ],\n examples: [\"corp services requests --service-slug 'service-slug'\", \"corp services requests --json\"],\n successTemplate: \"Requests created\",\n },\n {\n name: \"services requests\",\n description: \"Submit a new service request\",\n route: { method: \"GET\", path: \"/v1/services/requests/{pos}\" },\n entity: true,\n args: [{ name: \"request-id\", required: true, description: \"Document request ID\" }],\n display: { title: \"Services Requests\", cols: [\"amount_cents>Amount Cents\", \"checkout_url>Checkout Url\", \"failed_at>Failed At\", \"fulfilled_at>Fulfilled At\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp services requests\", \"corp services requests --json\"],\n },\n {\n name: \"services requests-cancel\",\n description: \"Cancel a service request\",\n route: { method: \"POST\", path: \"/v1/services/requests/{pos}/cancel\" },\n args: [{ name: \"request-id\", required: true, description: \"Document request ID\" }],\n examples: [\"corp services requests-cancel <request-id>\"],\n successTemplate: \"Requests Cancel created\",\n },\n {\n name: \"services requests-checkout\",\n description: \"Start checkout for a service request\",\n route: { method: \"POST\", path: \"/v1/services/requests/{pos}/checkout\" },\n args: [{ name: \"request-id\", required: true, description: \"Document request ID\" }],\n examples: [\"corp services requests-checkout <request-id>\"],\n successTemplate: \"Requests Checkout created\",\n },\n {\n name: \"services requests-fulfill\",\n description: \"Fulfill a service request\",\n route: { method: \"POST\", path: \"/v1/services/requests/{pos}/fulfill\" },\n args: [{ name: \"request-id\", required: true, description: \"Document request ID\" }],\n options: [\n { flags: \"--note <note>\", description: \"Note\" },\n ],\n examples: [\"corp services requests-fulfill <request-id>\", \"corp services requests-fulfill --json\"],\n successTemplate: \"Requests Fulfill created\",\n },\n\n];","import { input, confirm, select } from \"@inquirer/prompts\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { existsSync, mkdirSync, readdirSync } from \"node:fs\";\nimport { loadConfig, saveConfig, validateApiUrl } from \"../config.js\";\nimport { provisionWorkspace } from \"../api-client.js\";\nimport {\n generateSecret,\n generateFernetKey,\n processRequest,\n} from \"@thecorporation/corp-tools\";\nimport { printSuccess, printError } from \"../output.js\";\n\nconst CLOUD_API_URL = \"https://api.thecorporation.ai\";\nconst DEFAULT_DATA_DIR = join(homedir(), \".corp\", \"data\");\n\n// ── Magic link auth (unchanged) ─────────────────────────────────────\n\nasync function requestMagicLink(\n apiUrl: string,\n email: string,\n tosAccepted: boolean\n): Promise<void> {\n const resp = await fetch(`${apiUrl}/v1/auth/magic-link`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email, tos_accepted: tosAccepted }),\n });\n if (!resp.ok) {\n const data = await resp.json().catch(() => ({}));\n const detail =\n (data as Record<string, unknown>)?.error ??\n (data as Record<string, unknown>)?.message ??\n resp.statusText;\n throw new Error(\n typeof detail === \"string\" ? detail : JSON.stringify(detail)\n );\n }\n}\n\nasync function verifyMagicLinkCode(\n apiUrl: string,\n code: string\n): Promise<{ api_key: string; workspace_id: string }> {\n const resp = await fetch(`${apiUrl}/v1/auth/magic-link/verify`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code, client: \"cli\" }),\n });\n const data = (await resp.json().catch(() => ({}))) as Record<string, unknown>;\n if (!resp.ok) {\n const detail = data?.error ?? data?.message ?? resp.statusText;\n throw new Error(\n typeof detail === \"string\" ? detail : JSON.stringify(detail)\n );\n }\n if (!data.api_key || !data.workspace_id) {\n throw new Error(\"Unexpected response — missing api_key or workspace_id\");\n }\n return {\n api_key: data.api_key as string,\n workspace_id: data.workspace_id as string,\n };\n}\n\nfunction isCloudApi(url: string): boolean {\n return url.replace(/\\/+$/, \"\").includes(\"thecorporation.ai\");\n}\n\nasync function magicLinkAuth(\n apiUrl: string,\n email: string\n): Promise<{ api_key: string; workspace_id: string }> {\n console.log(\"\\nSending magic link to \" + email + \"...\");\n await requestMagicLink(apiUrl, email, true);\n console.log(\"Check your email for a sign-in link from TheCorporation.\");\n console.log(\n \"Copy the code from the URL (the ?code=... part) and paste it below.\\n\"\n );\n\n const code = await input({ message: \"Paste your magic link code\" });\n const trimmed = code.trim().replace(/^.*[?&]code=/, \"\");\n if (!trimmed) {\n throw new Error(\"No code provided\");\n }\n\n console.log(\"Verifying...\");\n return verifyMagicLinkCode(apiUrl, trimmed);\n}\n\n// ── Local provisioning ──────────────────────────────────────────────\n\nfunction setupDataDir(dirPath: string): { isNew: boolean } {\n if (!existsSync(dirPath)) {\n mkdirSync(dirPath, { recursive: true });\n return { isNew: true };\n }\n try {\n const entries = readdirSync(dirPath);\n if (entries.length > 0) {\n console.log(\"Found existing data, reusing.\");\n return { isNew: false };\n }\n } catch {\n // empty or unreadable\n }\n return { isNew: true };\n}\n\nasync function localProvision(\n dataDir: string,\n name: string\n): Promise<{ api_key: string; workspace_id: string }> {\n const resp = processRequest(\n \"process://\",\n \"POST\",\n \"/v1/workspaces/provision\",\n { \"Content-Type\": \"application/json\" },\n JSON.stringify({ name }),\n { dataDir },\n );\n\n if (!resp.ok) {\n const detail = await resp.text();\n throw new Error(`Provision failed: HTTP ${resp.status} — ${detail}`);\n }\n\n const body = (await resp.json()) as Record<string, unknown>;\n if (!body.api_key || !body.workspace_id) {\n throw new Error(\"Provision response missing api_key or workspace_id\");\n }\n return {\n api_key: body.api_key as string,\n workspace_id: body.workspace_id as string,\n };\n}\n\n// ── Main setup ──────────────────────────────────────────────────────\n\nexport async function setupCommand(): Promise<void> {\n const cfg = loadConfig();\n console.log(\"Welcome to corp — corporate governance from the terminal.\\n\");\n\n // User info\n console.log(\"--- User Info ---\");\n const user = cfg.user ?? { name: \"\", email: \"\" };\n user.name = await input({\n message: \"Your name\",\n default: user.name || undefined,\n });\n user.email = await input({\n message: \"Your email\",\n default: user.email || undefined,\n });\n cfg.user = user;\n\n // Hosting mode\n console.log(\"\\n--- Hosting Mode ---\");\n const hostingMode = await select({\n message: \"How would you like to run corp?\",\n choices: [\n { value: \"local\", name: \"Local (your machine)\" },\n { value: \"cloud\", name: \"TheCorporation cloud\" },\n { value: \"self-hosted\", name: \"Self-hosted server (custom URL)\" },\n ],\n default: cfg.hosting_mode || \"local\",\n });\n cfg.hosting_mode = hostingMode;\n\n if (hostingMode === \"local\") {\n // Data directory\n const dataDir = await input({\n message: \"Data directory\",\n default: cfg.data_dir || DEFAULT_DATA_DIR,\n });\n cfg.data_dir = dataDir;\n cfg.api_url = \"process://\";\n\n const { isNew } = setupDataDir(dataDir);\n\n // Generate server secrets\n const serverSecrets = {\n jwt_secret: generateSecret(),\n secrets_master_key: generateFernetKey(),\n internal_worker_token: generateSecret(),\n };\n\n // Inject into process.env so processRequest can use them immediately\n process.env.JWT_SECRET = serverSecrets.jwt_secret;\n process.env.SECRETS_MASTER_KEY = serverSecrets.secrets_master_key;\n process.env.INTERNAL_WORKER_TOKEN = serverSecrets.internal_worker_token;\n\n // Store secrets via _server_secrets (picked up by serializeAuth)\n (cfg as Record<string, unknown>)._server_secrets = serverSecrets;\n\n if (isNew || !cfg.workspace_id) {\n console.log(\"\\nProvisioning workspace...\");\n try {\n const result = await localProvision(dataDir, `${user.name}'s workspace`);\n cfg.api_key = result.api_key;\n cfg.workspace_id = result.workspace_id;\n printSuccess(`Local workspace ready: ${result.workspace_id}`);\n } catch (err) {\n printError(`Workspace provisioning failed: ${err}`);\n console.log(\"You can retry with 'corp setup'.\");\n }\n } else {\n console.log(\"\\nExisting workspace found.\");\n }\n } else if (hostingMode === \"cloud\") {\n cfg.api_url = CLOUD_API_URL;\n cfg.data_dir = \"\";\n\n const needsAuth = !cfg.api_key || !cfg.workspace_id;\n if (needsAuth) {\n try {\n const result = await magicLinkAuth(cfg.api_url, user.email);\n cfg.api_key = result.api_key;\n cfg.workspace_id = result.workspace_id;\n printSuccess(`Authenticated. Workspace: ${result.workspace_id}`);\n } catch (err) {\n printError(`Authentication failed: ${err}`);\n console.log(\n \"You can manually set credentials with: corp config set api_key <key>\"\n );\n }\n } else {\n console.log(\"\\nExisting credentials found. Run 'corp status' to verify.\");\n }\n } else {\n // Self-hosted\n const url = await input({\n message: \"Server URL\",\n default:\n cfg.api_url !== CLOUD_API_URL && !cfg.api_url.startsWith(\"process://\")\n ? cfg.api_url\n : undefined,\n });\n try {\n cfg.api_url = validateApiUrl(url);\n } catch (err) {\n printError(`Invalid URL: ${err}`);\n process.exit(1);\n }\n cfg.data_dir = \"\";\n\n const needsAuth = !cfg.api_key || !cfg.workspace_id;\n if (needsAuth) {\n console.log(\"\\nProvisioning workspace...\");\n try {\n const result = await provisionWorkspace(\n cfg.api_url,\n `${user.name}'s workspace`\n );\n cfg.api_key = result.api_key as string;\n cfg.workspace_id = result.workspace_id as string;\n console.log(`Workspace provisioned: ${result.workspace_id}`);\n } catch (err) {\n printError(`Auto-provision failed: ${err}`);\n console.log(\n \"You can manually set credentials with: corp config set api_key <key>\"\n );\n }\n }\n }\n\n saveConfig(cfg);\n console.log(\"\\nSettings saved to ~/.corp/config.json\");\n console.log(\"Credentials saved to ~/.corp/auth.json\");\n console.log(\"Run 'corp status' to verify your connection.\");\n}\n","import { configForDisplay, getValue, loadConfig, requireConfig, setValue, updateConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printJson } from \"../output.js\";\nimport { ReferenceResolver } from \"../references.js\";\n\nfunction looksLikeCanonicalId(value: string): boolean {\n const trimmed = value.trim();\n return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(trimmed)\n || /^ent_[a-z0-9-]+$/i.test(trimmed);\n}\n\nexport async function configSetCommand(\n key: string,\n value: string,\n options: { force?: boolean } = {},\n): Promise<void> {\n let resolvedValue = value;\n try {\n if (key === \"active_entity_id\" && !looksLikeCanonicalId(value)) {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n resolvedValue = await resolver.resolveEntity(value);\n }\n updateConfig((cfg) => {\n setValue(cfg as unknown as Record<string, unknown>, key, resolvedValue, {\n forceSensitive: options.force,\n });\n });\n } catch (err) {\n printError(`Failed to update config: ${err}`);\n process.exit(1);\n }\n\n if (key === \"api_key\" || key === \"llm.api_key\") {\n console.log(`${key} updated.`);\n return;\n }\n if (key === \"active_entity_id\") {\n console.log(`${key} updated to ${resolvedValue}.`);\n return;\n }\n console.log(`${key} updated.`);\n}\n\nexport function configGetCommand(key: string): void {\n const cfg = loadConfig();\n const val = getValue(cfg as unknown as Record<string, unknown>, key);\n if (val === undefined) {\n printError(`Key not found: ${key}`);\n process.exit(1);\n }\n if (typeof val === \"object\" && val !== null) {\n printJson(val);\n } else {\n console.log(String(val));\n }\n}\n\nexport function configListCommand(): void {\n const cfg = loadConfig();\n printJson(configForDisplay(cfg));\n}\n","import { resolve } from \"node:path\";\nimport type { ChildProcess } from \"node:child_process\";\nimport { ensureEnvFile, loadEnvFile } from \"@thecorporation/corp-tools\";\n\ninterface ServeOptions {\n port: string;\n dataDir: string;\n}\n\nexport async function serveCommand(opts: ServeOptions): Promise<void> {\n let server: { getBinaryPath: () => string | null; isAvailable: () => boolean; startServer: (options: Record<string, unknown>) => ChildProcess };\n try {\n // @ts-expect-error — optional dependency, handled by catch block\n server = await import(\"@thecorporation/server\");\n } catch {\n console.error(\n \"Error: @thecorporation/server is not installed.\\n\\n\" +\n \"Install it with:\\n\" +\n \" npm install @thecorporation/server\\n\\n\" +\n \"Or run the Rust binary directly:\\n\" +\n \" cd services/api-rs && cargo run\"\n );\n process.exit(1);\n }\n\n if (!server.isAvailable()) {\n console.error(\n \"Error: No server binary available for this platform.\\n\\n\" +\n \"Pre-built binaries are available for:\\n\" +\n \" - linux-x64, linux-arm64\\n\" +\n \" - darwin-x64, darwin-arm64\\n\" +\n \" - win32-x64\\n\\n\" +\n \"You can build from source:\\n\" +\n \" cd services/api-rs && cargo build --release\"\n );\n process.exit(1);\n }\n\n const port = parseInt(opts.port, 10);\n if (isNaN(port) || port > 65535) {\n console.error(`Error: Invalid port \"${opts.port}\"`);\n process.exit(1);\n }\n\n // Load .env file, generating one if it doesn't exist\n const envPath = resolve(process.cwd(), \".env\");\n ensureEnvFile(envPath);\n loadEnvFile(envPath);\n\n const localUrl = `http://localhost:${port}`;\n console.log(`Starting server on port ${port}...`);\n console.log(`Data directory: ${opts.dataDir}`);\n console.log(`CLI API URL remains unchanged.`);\n console.log(` Use CORP_API_URL=${localUrl} for commands against this local server.\\n`);\n\n const child = server.startServer({\n port,\n dataDir: opts.dataDir,\n });\n\n const shutdown = () => {\n console.log(\"\\nShutting down server...\");\n child.kill(\"SIGTERM\");\n };\n\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n child.on(\"exit\", (code) => {\n process.exit(code ?? 0);\n });\n}\n","import { requireConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printJson, printReferenceSummary, printSuccess } from \"../output.js\";\nimport { withSpinner } from \"../spinner.js\";\nimport { ReferenceResolver } from \"../references.js\";\nimport { activateFormationEntity } from \"../formation-automation.js\";\nimport type { ApiRecord } from \"../types.js\";\n\ntype DemoOptions = {\n name: string;\n scenario?: string;\n minimal?: boolean;\n json?: boolean;\n};\n\nfunction scenarioConfig(name: string, scenario: string): ApiRecord {\n switch (scenario) {\n case \"llc\":\n return {\n entity_type: \"llc\",\n legal_name: name,\n jurisdiction: \"US-WY\",\n members: [\n {\n name: \"Alice Chen\",\n email: \"alice@example.com\",\n role: \"member\",\n investor_type: \"natural_person\",\n ownership_pct: 60,\n address: {\n street: \"251 Little Falls Dr\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19808\",\n },\n },\n {\n name: \"Bob Martinez\",\n email: \"bob@example.com\",\n role: \"member\",\n investor_type: \"natural_person\",\n ownership_pct: 40,\n address: {\n street: \"251 Little Falls Dr\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19808\",\n },\n },\n ],\n fiscal_year_end: \"12-31\",\n company_address: {\n street: \"251 Little Falls Dr\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19808\",\n },\n };\n case \"restaurant\":\n return {\n entity_type: \"llc\",\n legal_name: name,\n jurisdiction: \"US-DE\",\n members: [\n {\n name: \"Rosa Alvarez\",\n email: \"rosa@example.com\",\n role: \"manager\",\n investor_type: \"natural_person\",\n ownership_pct: 55,\n address: {\n street: \"18 Market St\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19801\",\n },\n },\n {\n name: \"Noah Patel\",\n email: \"noah@example.com\",\n role: \"member\",\n investor_type: \"natural_person\",\n ownership_pct: 45,\n address: {\n street: \"18 Market St\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19801\",\n },\n },\n ],\n fiscal_year_end: \"12-31\",\n company_address: {\n street: \"18 Market St\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19801\",\n },\n };\n case \"startup\":\n default:\n return {\n entity_type: \"c_corp\",\n legal_name: name,\n jurisdiction: \"US-DE\",\n authorized_shares: 10_000_000,\n par_value: \"0.0001\",\n transfer_restrictions: true,\n right_of_first_refusal: true,\n members: [\n {\n name: \"Alice Chen\",\n email: \"alice@example.com\",\n role: \"chair\",\n investor_type: \"natural_person\",\n shares_purchased: 6_000_000,\n officer_title: \"ceo\",\n is_incorporator: true,\n address: {\n street: \"251 Little Falls Dr\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19808\",\n },\n },\n {\n name: \"Bob Martinez\",\n email: \"bob@example.com\",\n role: \"director\",\n investor_type: \"natural_person\",\n shares_purchased: 4_000_000,\n officer_title: \"cto\",\n address: {\n street: \"251 Little Falls Dr\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19808\",\n },\n },\n ],\n fiscal_year_end: \"12-31\",\n company_address: {\n street: \"251 Little Falls Dr\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19808\",\n },\n };\n }\n}\n\nfunction meetingTypeForBody(body: ApiRecord): string {\n return String(body.body_type) === \"llc_member_vote\" ? \"member_meeting\" : \"board_meeting\";\n}\n\nexport async function demoCommand(opts: DemoOptions): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n const scenario = opts.scenario ?? \"startup\";\n\n try {\n if (opts.minimal) {\n const result = await withSpinner(\"Loading\", () => client.seedDemo({\n name: opts.name,\n scenario,\n }));\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(\"Minimal demo seeded.\");\n printJson(result);\n return;\n }\n\n const formationPayload = scenarioConfig(opts.name, scenario);\n const created = await withSpinner(\"Creating demo entity\", () =>\n client.createFormationWithCapTable(formationPayload),\n );\n const entityId = String(created.entity_id ?? created.formation_id ?? \"\");\n if (!entityId) {\n throw new Error(\"demo formation did not return an entity_id\");\n }\n\n await resolver.stabilizeRecord(\"entity\", created as ApiRecord);\n resolver.rememberFromRecord(\"entity\", created as ApiRecord);\n\n const activation = await withSpinner(\"Activating formation\", () =>\n activateFormationEntity(client, resolver, entityId),\n );\n\n const agent = await withSpinner(\"Creating demo agent\", () =>\n client.createAgent({\n name: `${opts.name} Operator`,\n entity_id: entityId,\n system_prompt: `Operate ${opts.name} and keep the workspace data clean.`,\n scopes: [],\n }),\n );\n await resolver.stabilizeRecord(\"agent\", agent);\n resolver.rememberFromRecord(\"agent\", agent);\n\n const bodies = await client.listGovernanceBodies(entityId);\n await resolver.stabilizeRecords(\"body\", bodies as ApiRecord[], entityId);\n\n let meeting: ApiRecord | undefined;\n if (bodies.length > 0) {\n meeting = await client.scheduleMeeting({\n entity_id: entityId,\n body_id: (bodies[0] as ApiRecord).body_id,\n meeting_type: meetingTypeForBody(bodies[0] as ApiRecord),\n title: \"Demo kickoff meeting\",\n agenda_item_titles: [\n \"Approve demo operating budget\",\n \"Review founder vesting and cap table\",\n ],\n });\n await resolver.stabilizeRecord(\"meeting\", meeting, entityId);\n resolver.rememberFromRecord(\"meeting\", meeting, entityId);\n }\n\n const workItem = await client.createWorkItem(entityId, {\n title: \"Review demo workspace\",\n description: \"Check documents, governance, cap table, and treasury setup.\",\n category: \"ops\",\n created_by_actor: {\n actor_type: \"agent\",\n actor_id: String(agent.agent_id),\n },\n });\n await resolver.stabilizeRecord(\"work_item\", workItem, entityId);\n resolver.rememberFromRecord(\"work_item\", workItem, entityId);\n\n const claimedWorkItem = await client.claimWorkItem(entityId, String(workItem.work_item_id), {\n claimed_by_actor: {\n actor_type: \"agent\",\n actor_id: String(agent.agent_id),\n },\n });\n\n const bankAccount = await client.openBankAccount({\n entity_id: entityId,\n bank_name: \"Mercury\",\n });\n await resolver.stabilizeRecord(\"bank_account\", bankAccount, entityId);\n resolver.rememberFromRecord(\"bank_account\", bankAccount, entityId);\n\n const invoice = await client.createInvoice({\n entity_id: entityId,\n customer_name: \"Acme Customer\",\n amount_cents: 250000,\n due_date: \"2026-04-01\",\n description: \"Demo advisory services\",\n });\n await resolver.stabilizeRecord(\"invoice\", invoice, entityId);\n resolver.rememberFromRecord(\"invoice\", invoice, entityId);\n\n const contract = await client.generateContract({\n entity_id: entityId,\n template_type: \"nda\",\n counterparty_name: \"Example Counterparty\",\n effective_date: \"2026-03-12\",\n parameters: {},\n });\n await resolver.stabilizeRecord(\"document\", contract, entityId);\n resolver.rememberFromRecord(\"document\", contract, entityId);\n\n const result: ApiRecord = {\n scenario,\n entity: created,\n activation,\n agent,\n meeting,\n work_item: claimedWorkItem,\n bank_account: bankAccount,\n invoice,\n contract,\n };\n\n if (opts.json) {\n printJson(result);\n return;\n }\n\n printSuccess(`Demo environment created for ${opts.name}.`);\n printReferenceSummary(\"entity\", created as ApiRecord, { showReuseHint: true });\n printReferenceSummary(\"agent\", agent, { showReuseHint: true });\n if (meeting) {\n printReferenceSummary(\"meeting\", meeting, { showReuseHint: true });\n }\n printReferenceSummary(\"work_item\", claimedWorkItem, { showReuseHint: true });\n printReferenceSummary(\"invoice\", invoice, { showReuseHint: true });\n printReferenceSummary(\"bank_account\", bankAccount, { showReuseHint: true });\n printJson(result);\n } catch (err) {\n printError(`Failed to seed demo: ${err}`);\n process.exit(1);\n }\n}\n","import type { ToolCall, LLMResponse } from \"./types.js\";\nimport type OpenAI from \"openai\";\nimport type { ChatCompletionCreateParamsNonStreaming } from \"openai/resources/chat/completions.js\";\n\nconst PROVIDER_BASE_URLS: Record<string, string> = {\n openrouter: \"https://openrouter.ai/api/v1\",\n};\n\nexport async function chat(\n messages: Record<string, unknown>[],\n tools?: Record<string, unknown>[],\n provider = \"openrouter\",\n apiKey = \"\",\n model = \"\",\n baseUrl?: string,\n): Promise<LLMResponse> {\n const effectiveUrl = baseUrl ?? PROVIDER_BASE_URLS[provider] ?? PROVIDER_BASE_URLS.openrouter;\n const { default: OpenAIClient } = await import(\"openai\");\n const client = new OpenAIClient({ apiKey, baseURL: effectiveUrl });\n\n const params: ChatCompletionCreateParamsNonStreaming = {\n model: model || \"gpt-4o\",\n messages: messages as unknown as OpenAI.ChatCompletionMessageParam[],\n max_tokens: 4096,\n };\n if (tools?.length) {\n params.tools = tools as unknown as OpenAI.ChatCompletionTool[];\n params.tool_choice = \"auto\";\n }\n\n const response = await client.chat.completions.create(params);\n const choice = response.choices[0];\n const message = choice.message;\n\n const toolCallsOut: ToolCall[] = [];\n if (message.tool_calls) {\n for (const tc of message.tool_calls) {\n let args: Record<string, unknown>;\n try {\n args = JSON.parse(tc.function.arguments);\n } catch {\n args = { _raw: tc.function.arguments };\n }\n toolCallsOut.push({ id: tc.id, name: tc.function.name, arguments: args });\n }\n }\n\n return {\n content: message.content,\n tool_calls: toolCallsOut,\n usage: {\n prompt_tokens: response.usage?.prompt_tokens ?? 0,\n completion_tokens: response.usage?.completion_tokens ?? 0,\n total_tokens: response.usage?.total_tokens ?? 0,\n },\n finish_reason: choice.finish_reason ?? null,\n };\n}\n","import {\n TOOL_DEFINITIONS as _TOOL_DEFINITIONS,\n isWriteTool as _isWriteTool,\n executeTool as _executeTool,\n} from \"@thecorporation/corp-tools\";\nimport type { CorpAPIClient } from \"@thecorporation/corp-tools\";\nimport { setActiveEntityId, updateConfig } from \"./config.js\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nexport const TOOL_DEFINITIONS = _TOOL_DEFINITIONS;\nexport const isWriteTool: (name: string, args?: Record<string, unknown>) => boolean = _isWriteTool;\n\nexport async function executeTool(\n name: string,\n args: Record<string, unknown>,\n client: CorpAPIClient,\n): Promise<string> {\n return _executeTool(name, args, client, {\n dataDir: join(homedir(), \".corp\"),\n onEntityFormed: (entityId) => {\n try {\n updateConfig((cfg) => {\n setActiveEntityId(cfg, entityId);\n });\n } catch { /* ignore */ }\n },\n });\n}\n","import { createInterface } from \"node:readline\";\nimport chalk from \"chalk\";\nimport { requireConfig, configForDisplay, getValue, setValue, saveConfig } from \"./config.js\";\nimport { CorpAPIClient } from \"./api-client.js\";\nimport { chat as llmChat } from \"./llm.js\";\nimport { TOOL_DEFINITIONS, executeTool, isWriteTool } from \"./tools.js\";\nimport { printError, printStatusPanel, printObligationsTable, printJson } from \"./output.js\";\nimport type { CorpConfig, LLMResponse, ToolCall } from \"./types.js\";\n\nconst SYSTEM_PROMPT = `You are **corp**, an AI assistant for corporate governance.\nYou help users manage their companies — entities, cap tables, compliance, governance, finances, and more.\nYou have tools to read and write corporate data. Use them to fulfill user requests.\nFor write operations, confirm with the user before proceeding.\nMonetary values are in cents (e.g. 100000 = $1,000.00).\nDocuments must be signed by the human — you cannot sign on their behalf.\nAfter completing actions, suggest logical next steps.`;\n\nexport async function chatCommand(): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\", \"llm.api_key\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n\n const messages: Record<string, unknown>[] = [{ role: \"system\", content: SYSTEM_PROMPT }];\n let totalTokens = 0;\n\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const prompt = () => new Promise<string>((resolve) => rl.question(chalk.green.bold(\"> \"), resolve));\n\n console.log(chalk.blue.bold(\"corp chat\") + \" — type /help for commands, /quit to exit\\n\");\n\n const slashHandlers: Record<string, (args: string) => void> = {\n \"/status\": async () => {\n try { printStatusPanel(await client.getStatus()); } catch (e) { printError(`Status error: ${e}`); }\n },\n \"/obligations\": async () => {\n try {\n const data = await client.getObligations();\n const obls = (data.obligations ?? []) as Record<string, unknown>[];\n if (obls.length) printObligationsTable(obls);\n else console.log(chalk.dim(\"No obligations found.\"));\n } catch (e) { printError(`Obligations error: ${e}`); }\n },\n \"/digest\": async () => {\n try {\n const digests = await client.listDigests();\n if (digests.length) printJson(digests);\n else console.log(chalk.dim(\"No digest history.\"));\n } catch (e) { printError(`Digest error: ${e}`); }\n },\n \"/config\": () => printJson(configForDisplay(cfg)),\n \"/model\": (args: string) => {\n const model = args.trim();\n if (!model) { console.log(`Current model: ${getValue(cfg as unknown as Record<string, unknown>, \"llm.model\")}`); return; }\n setValue(cfg as unknown as Record<string, unknown>, \"llm.model\", model);\n saveConfig(cfg);\n console.log(`Model switched to: ${model}`);\n },\n \"/cost\": () => console.log(`Session tokens used: ${totalTokens.toLocaleString()}`),\n \"/clear\": () => {\n messages.length = 0;\n messages.push({ role: \"system\", content: SYSTEM_PROMPT });\n totalTokens = 0;\n console.log(chalk.dim(\"Conversation cleared.\"));\n },\n \"/help\": () => {\n console.log(`\n${chalk.bold(\"Chat Slash Commands\")}\n /status Show workspace status\n /obligations List obligations\n /digest Show digest history\n /config Show current config (masked keys)\n /model <name> Switch LLM model\n /cost Show token usage\n /clear Clear conversation\n /help Show this help\n /quit Exit chat`);\n },\n };\n\n try {\n while (true) {\n let userInput: string;\n try {\n userInput = (await prompt()).trim();\n } catch {\n console.log(\"\\n\" + chalk.dim(\"Goodbye.\"));\n break;\n }\n\n if (!userInput) continue;\n\n if (userInput.startsWith(\"/\")) {\n const [cmd, ...rest] = userInput.split(/\\s+/);\n const args = rest.join(\" \");\n if (cmd === \"/quit\" || cmd === \"/exit\") {\n console.log(chalk.dim(\"Goodbye.\"));\n break;\n }\n const handler = slashHandlers[cmd.toLowerCase()];\n if (handler) { await handler(args); continue; }\n printError(`Unknown command: ${cmd}. Type /help for available commands.`);\n continue;\n }\n\n messages.push({ role: \"user\", content: userInput });\n\n const llmCfg = cfg.llm;\n while (true) {\n let response: LLMResponse;\n try {\n response = await llmChat(\n messages, TOOL_DEFINITIONS, llmCfg.provider, llmCfg.api_key, llmCfg.model, llmCfg.base_url,\n );\n } catch (err) {\n printError(`LLM error: ${err}`);\n break;\n }\n\n totalTokens += response.usage.total_tokens;\n\n const assistantMsg: Record<string, unknown> = { role: \"assistant\", content: response.content };\n if (response.tool_calls.length > 0) {\n assistantMsg.tool_calls = response.tool_calls.map((tc) => ({\n id: tc.id, type: \"function\",\n function: { name: tc.name, arguments: JSON.stringify(tc.arguments) },\n }));\n if (!response.content) assistantMsg.content = null;\n }\n messages.push(assistantMsg);\n\n if (response.tool_calls.length === 0) {\n if (response.content) console.log(\"\\n\" + response.content + \"\\n\");\n break;\n }\n\n for (const tc of response.tool_calls) {\n console.log(chalk.dim(` ${isWriteTool(tc.name, tc.arguments) ? \"\\u2699\" : \"\\u2139\"} ${tc.name}(${JSON.stringify(tc.arguments).slice(0, 80)})`));\n const result = await executeTool(tc.name, tc.arguments, client);\n const short = result.length > 200 ? result.slice(0, 197) + \"...\" : result;\n console.log(chalk.dim(` => ${short}`));\n messages.push({ role: \"tool\", tool_call_id: tc.id, content: result });\n }\n }\n }\n } finally {\n rl.close();\n }\n}\n","import { confirm } from \"@inquirer/prompts\";\nimport { requireConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printJson, printSuccess, printWriteResult } from \"../output.js\";\n\nexport async function apiKeysListCommand(opts: { json?: boolean }): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n try {\n const keys = await client.listApiKeys();\n if (opts.json) { printJson(keys); return; }\n if (keys.length === 0) { console.log(\"No API keys found.\"); return; }\n for (const k of keys) {\n const name = k.name ?? k.label ?? \"unnamed\";\n const id = k.key_id ?? k.id;\n const scopes = Array.isArray(k.scopes) ? (k.scopes as string[]).join(\", \") : \"all\";\n console.log(` ${name} [${id}] scopes: ${scopes}`);\n }\n } catch (err) { printError(`Failed to list API keys: ${err}`); process.exit(1); }\n}\n\nexport async function apiKeysCreateCommand(opts: {\n name: string; scopes?: string; json?: boolean;\n}): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n try {\n const data: Record<string, unknown> = { name: opts.name };\n if (opts.scopes) data.scopes = opts.scopes.split(\",\").map((s) => s.trim());\n const result = await client.createApiKey(data);\n printWriteResult(result, `API key created: ${result.key_id ?? \"OK\"}`, opts.json);\n if (!opts.json && result.api_key) {\n printSuccess(`Key: ${result.api_key}`);\n console.log(\" Save this key — it will not be shown again.\");\n }\n } catch (err) { printError(`Failed to create API key: ${err}`); process.exit(1); }\n}\n\nexport async function apiKeysRevokeCommand(keyId: string, opts: {\n yes?: boolean; json?: boolean;\n}): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n try {\n if (!opts.yes) {\n const ok = await confirm({ message: `Revoke API key ${keyId}? This cannot be undone.`, default: false });\n if (!ok) { console.log(\"Cancelled.\"); return; }\n }\n await client.revokeApiKey(keyId);\n if (opts.json) { printJson({ revoked: true, key_id: keyId }); return; }\n printSuccess(`API key ${keyId} revoked.`);\n } catch (err) { printError(`Failed to revoke API key: ${err}`); process.exit(1); }\n}\n\nexport async function apiKeysRotateCommand(keyId: string, opts: {\n json?: boolean;\n}): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n try {\n const result = await client.rotateApiKey(keyId);\n printWriteResult(result, `API key ${keyId} rotated.`, opts.json);\n if (!opts.json && result.api_key) {\n printSuccess(`New key: ${result.api_key}`);\n console.log(\" Save this key — it will not be shown again.\");\n }\n } catch (err) { printError(`Failed to rotate API key: ${err}`); process.exit(1); }\n}\n","import { requireConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printSuccess } from \"../output.js\";\n\nexport async function linkCommand(opts: { externalId: string; provider: string }): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n try {\n const data = await client.createLink(opts.externalId, opts.provider);\n printSuccess(`Workspace linked to ${opts.provider} (external ID: ${opts.externalId})`);\n if (data.workspace_id) console.log(` Workspace: ${data.workspace_id}`);\n } catch (err) {\n printError(`${err}`);\n process.exit(1);\n }\n}\n","import { loadConfig, saveConfig } from \"../config.js\";\nimport { printError } from \"../output.js\";\n\nexport async function claimCommand(code: string): Promise<void> {\n const cfg = loadConfig();\n const apiUrl = (cfg.api_url || \"https://api.thecorporation.ai\").replace(/\\/+$/, \"\");\n if (apiUrl.startsWith(\"process://\")) {\n printError(\n \"Claim codes require a remote API server.\\n\" +\n \" Run: npx corp config set api_url https://api.thecorporation.ai --force\\n\" +\n \" Or use: npx corp setup\",\n );\n process.exit(1);\n }\n try {\n const resp = await fetch(`${apiUrl}/v1/workspaces/claim`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code }),\n });\n if (!resp.ok) {\n let detail = \"\";\n try { const body = await resp.json() as Record<string, string>; detail = body.detail ?? \"\"; } catch { /* ignore */ }\n printError(detail || `${resp.status} ${resp.statusText}`);\n process.exit(1);\n }\n const data = await resp.json() as Record<string, string>;\n cfg.api_key = data.api_key;\n cfg.workspace_id = data.workspace_id;\n saveConfig(cfg);\n console.log(`Workspace joined: ${data.workspace_id}`);\n console.log(\"Credentials saved to ~/.corp/auth.json\");\n console.log(\"Settings remain in ~/.corp/config.json\");\n } catch (err) {\n printError(`${err}`);\n process.exit(1);\n }\n}\n","import { requireConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printJson } from \"../output.js\";\nimport chalk from \"chalk\";\n\ninterface FeedbackOptions {\n category?: string;\n email?: string;\n json?: boolean;\n}\n\nconst MAX_FEEDBACK_LENGTH = 10_000;\n\nexport async function feedbackCommand(message: string, opts: FeedbackOptions): Promise<void> {\n if (!message || message.trim().length === 0) {\n printError(\"Feedback message cannot be empty\");\n process.exit(1);\n }\n if (message.length > MAX_FEEDBACK_LENGTH) {\n printError(`Feedback message must be at most ${MAX_FEEDBACK_LENGTH} characters (got ${message.length})`);\n process.exit(1);\n }\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n try {\n const result = await client.submitFeedback(message, opts.category, opts.email);\n if (opts.json) {\n printJson(result);\n return;\n }\n console.log(`\\n${chalk.green(\"✓\")} Feedback submitted (${chalk.dim(result.feedback_id)})`);\n } catch (err: any) {\n const detail = String(err);\n if (detail.includes(\"404\") || detail.includes(\"Not found\") || detail.includes(\"not found\")) {\n printError(\n `Failed to submit feedback: ${detail}\\n` +\n \" This server does not expose /v1/feedback. Local api-rs dev servers currently do not support feedback submission.\",\n );\n } else {\n printError(`Failed to submit feedback: ${detail}`);\n }\n process.exit(1);\n }\n}\n","import { requireConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printJson } from \"../output.js\";\nimport { ReferenceResolver, shortId, type ResourceKind } from \"../references.js\";\n\nconst KINDS = new Set<ResourceKind>([\n \"entity\",\n \"contact\",\n \"share_transfer\",\n \"invoice\",\n \"bank_account\",\n \"payment\",\n \"payroll_run\",\n \"distribution\",\n \"reconciliation\",\n \"tax_filing\",\n \"deadline\",\n \"classification\",\n \"body\",\n \"meeting\",\n \"seat\",\n \"agenda_item\",\n \"resolution\",\n \"document\",\n \"work_item\",\n \"agent\",\n \"valuation\",\n \"safe_note\",\n \"instrument\",\n \"share_class\",\n \"round\",\n]);\n\nconst ENTITY_SCOPED_KINDS = new Set<ResourceKind>([\n \"contact\",\n \"share_transfer\",\n \"invoice\",\n \"bank_account\",\n \"payment\",\n \"payroll_run\",\n \"distribution\",\n \"reconciliation\",\n \"tax_filing\",\n \"deadline\",\n \"classification\",\n \"body\",\n \"meeting\",\n \"seat\",\n \"agenda_item\",\n \"resolution\",\n \"document\",\n \"work_item\",\n \"valuation\",\n \"safe_note\",\n \"instrument\",\n \"share_class\",\n \"round\",\n]);\n\nexport async function resolveCommand(\n kind: string,\n ref: string,\n opts: { entityId?: string; bodyId?: string; meetingId?: string },\n): Promise<void> {\n const normalizedKind = kind.trim().toLowerCase() as ResourceKind;\n if (!KINDS.has(normalizedKind)) {\n printError(`Unsupported resolve kind: ${kind}`);\n process.exit(1);\n }\n\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n const entityId = ENTITY_SCOPED_KINDS.has(normalizedKind) || opts.entityId || opts.bodyId || opts.meetingId\n ? await resolver.resolveEntity(opts.entityId)\n : undefined;\n const bodyId = entityId && opts.bodyId ? await resolver.resolveBody(entityId, opts.bodyId) : undefined;\n const meetingId = entityId && opts.meetingId\n ? await resolver.resolveMeeting(entityId, opts.meetingId, bodyId)\n : undefined;\n\n let resolvedId: string;\n switch (normalizedKind) {\n case \"entity\":\n resolvedId = await resolver.resolveEntity(ref);\n break;\n case \"contact\":\n resolvedId = await resolver.resolveContact(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"share_transfer\":\n resolvedId = await resolver.resolveShareTransfer(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"invoice\":\n resolvedId = await resolver.resolveInvoice(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"bank_account\":\n resolvedId = await resolver.resolveBankAccount(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"payment\":\n resolvedId = await resolver.resolvePayment(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"payroll_run\":\n resolvedId = await resolver.resolvePayrollRun(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"distribution\":\n resolvedId = await resolver.resolveDistribution(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"reconciliation\":\n resolvedId = await resolver.resolveReconciliation(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"tax_filing\":\n resolvedId = await resolver.resolveTaxFiling(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"deadline\":\n resolvedId = await resolver.resolveDeadline(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"classification\":\n resolvedId = await resolver.resolveClassification(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"body\":\n resolvedId = await resolver.resolveBody(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"meeting\":\n resolvedId = await resolver.resolveMeeting(requiredEntity(entityId, normalizedKind), ref, bodyId);\n break;\n case \"seat\":\n resolvedId = await resolver.resolveSeat(requiredEntity(entityId, normalizedKind), ref, bodyId);\n break;\n case \"agenda_item\":\n resolvedId = await resolver.resolveAgendaItem(\n requiredEntity(entityId, normalizedKind),\n requiredMeeting(meetingId, normalizedKind),\n ref,\n );\n break;\n case \"resolution\":\n resolvedId = await resolver.resolveResolution(requiredEntity(entityId, normalizedKind), ref, meetingId);\n break;\n case \"document\":\n resolvedId = await resolver.resolveDocument(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"work_item\":\n resolvedId = await resolver.resolveWorkItem(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"agent\":\n resolvedId = await resolver.resolveAgent(ref);\n break;\n case \"valuation\":\n resolvedId = await resolver.resolveValuation(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"safe_note\":\n resolvedId = await resolver.resolveSafeNote(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"instrument\":\n resolvedId = await resolver.resolveInstrument(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"share_class\":\n resolvedId = await resolver.resolveShareClass(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"round\":\n resolvedId = await resolver.resolveRound(requiredEntity(entityId, normalizedKind), ref);\n break;\n default:\n throw new Error(`Unhandled resolve kind: ${normalizedKind}`);\n }\n\n printJson({\n kind: normalizedKind,\n input: ref,\n resolved_id: resolvedId,\n short_id: shortId(resolvedId),\n ...(entityId ? { entity_id: entityId } : {}),\n ...(bodyId ? { body_id: bodyId } : {}),\n ...(meetingId ? { meeting_id: meetingId } : {}),\n });\n } catch (err) {\n printError(`Failed to resolve reference: ${err}`);\n process.exit(1);\n }\n}\n\nfunction requiredEntity(entityId: string | undefined, kind: ResourceKind): string {\n if (!entityId) {\n throw new Error(`--entity-id is required to resolve ${kind}.`);\n }\n return entityId;\n}\n\nfunction requiredMeeting(meetingId: string | undefined, kind: ResourceKind): string {\n if (!meetingId) {\n throw new Error(`--meeting-id is required to resolve ${kind}.`);\n }\n return meetingId;\n}\n","import chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport { requireConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printJson } from \"../output.js\";\nimport { ReferenceResolver, type ResourceKind } from \"../references.js\";\n\nconst KINDS = new Set<ResourceKind>([\n \"entity\",\n \"contact\",\n \"share_transfer\",\n \"invoice\",\n \"bank_account\",\n \"payment\",\n \"payroll_run\",\n \"distribution\",\n \"reconciliation\",\n \"tax_filing\",\n \"deadline\",\n \"classification\",\n \"body\",\n \"meeting\",\n \"seat\",\n \"agenda_item\",\n \"resolution\",\n \"document\",\n \"work_item\",\n \"agent\",\n \"valuation\",\n \"safe_note\",\n \"instrument\",\n \"share_class\",\n \"round\",\n]);\n\nconst ENTITY_SCOPED_KINDS = new Set<ResourceKind>([\n \"contact\",\n \"share_transfer\",\n \"invoice\",\n \"bank_account\",\n \"payment\",\n \"payroll_run\",\n \"distribution\",\n \"reconciliation\",\n \"tax_filing\",\n \"deadline\",\n \"classification\",\n \"body\",\n \"meeting\",\n \"seat\",\n \"agenda_item\",\n \"resolution\",\n \"document\",\n \"work_item\",\n \"valuation\",\n \"safe_note\",\n \"instrument\",\n \"share_class\",\n \"round\",\n]);\n\nexport async function findCommand(\n kind: string,\n query: string,\n opts: { entityId?: string; bodyId?: string; meetingId?: string; json?: boolean },\n): Promise<void> {\n const normalizedKind = kind.trim().toLowerCase() as ResourceKind;\n if (!KINDS.has(normalizedKind)) {\n printError(`Unsupported find kind: ${kind}`);\n process.exit(1);\n }\n\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n const entityId = ENTITY_SCOPED_KINDS.has(normalizedKind) || opts.entityId || opts.bodyId || opts.meetingId\n ? await resolver.resolveEntity(opts.entityId)\n : undefined;\n const bodyId = entityId && opts.bodyId ? await resolver.resolveBody(entityId, opts.bodyId) : undefined;\n const meetingId = entityId && opts.meetingId\n ? await resolver.resolveMeeting(entityId, opts.meetingId, bodyId)\n : undefined;\n\n const matches = await resolver.find(normalizedKind, query, { entityId, bodyId, meetingId });\n if (opts.json) {\n printJson({\n kind: normalizedKind,\n query,\n ...(entityId ? { entity_id: entityId } : {}),\n ...(bodyId ? { body_id: bodyId } : {}),\n ...(meetingId ? { meeting_id: meetingId } : {}),\n matches: matches.map((match) => ({\n kind: match.kind,\n id: match.id,\n short_id: match.short_id,\n alias: match.alias,\n label: match.label,\n })),\n });\n return;\n }\n\n if (matches.length === 0) {\n console.log(`No ${normalizedKind.replaceAll(\"_\", \" \")} matches for \"${query}\".`);\n return;\n }\n\n const table = new Table({\n head: [\n chalk.dim(\"Short\"),\n chalk.dim(\"Alias\"),\n chalk.dim(\"Label\"),\n chalk.dim(\"ID\"),\n ],\n });\n for (const match of matches) {\n table.push([\n match.short_id,\n match.alias ?? \"\",\n match.label,\n match.id,\n ]);\n }\n console.log(table.toString());\n } catch (err) {\n printError(`Failed to find references: ${err}`);\n process.exit(1);\n }\n}\n","import type { CommandDef } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Admin / utility commands\n// ---------------------------------------------------------------------------\n\nexport const adminCommands: CommandDef[] = [\n // ── setup (local, interactive) ──────────────────────────────────────\n {\n name: \"setup\",\n description: \"Interactive setup wizard\",\n local: true,\n handler: async () => {\n const { setupCommand } = await import(\"../commands/setup.js\");\n await setupCommand();\n },\n examples: [\"corp setup\"],\n },\n\n // ── config (local) ──────────────────────────────────────────────────\n {\n name: \"config\",\n description: \"Manage configuration\",\n local: true,\n examples: [\"corp config\"],\n },\n {\n name: \"config set\",\n description: \"Set a config value (dot-path)\",\n local: true,\n args: [\n { name: \"key\", required: true, description: \"Config key (dot-path)\" },\n { name: \"value\", required: true, description: \"Value to set\" },\n ],\n options: [\n { flags: \"--force\", description: \"Allow updating a security-sensitive config key\" },\n ],\n handler: async (ctx) => {\n const { configSetCommand } = await import(\"../commands/config.js\");\n await configSetCommand(\n ctx.positional[0],\n ctx.positional[1],\n { force: ctx.opts.force as boolean | undefined },\n );\n },\n examples: [\"corp config set\"],\n },\n {\n name: \"config get\",\n description: \"Get a config value (dot-path)\",\n local: true,\n args: [\n { name: \"key\", required: true, description: \"Config key (dot-path)\" },\n ],\n handler: async (ctx) => {\n const { configGetCommand } = await import(\"../commands/config.js\");\n configGetCommand(ctx.positional[0]);\n },\n examples: [\"corp config get\"],\n },\n {\n name: \"config list\",\n description: \"List all config (API keys masked)\",\n local: true,\n handler: async () => {\n const { configListCommand } = await import(\"../commands/config.js\");\n configListCommand();\n },\n examples: [\"corp config list\"],\n },\n\n // ── schema (local, special) ─────────────────────────────────────────\n {\n name: \"schema\",\n description: \"Dump the CLI command catalog as JSON\",\n local: true,\n options: [\n { flags: \"--compact\", description: \"Emit compact JSON\" },\n { flags: \"--web-routes\", description: \"Emit web-routes manifest instead of command schema\" },\n ],\n handler: async (ctx) => {\n const { registry, generateWebRoutes, generateSchema } = await import(\"../registry/index.js\");\n if (ctx.opts.webRoutes) {\n const manifest = generateWebRoutes(registry);\n console.log(JSON.stringify(manifest));\n return;\n }\n const { createRequire } = await import(\"node:module\");\n const require = createRequire(import.meta.url);\n let pkg: { version: string };\n try { pkg = require(\"../../package.json\"); } catch { pkg = require(\"../package.json\"); }\n const schema = generateSchema(registry, \"corp\", pkg.version);\n if (ctx.opts.compact) {\n console.log(JSON.stringify(schema));\n } else {\n ctx.writer.json(schema);\n }\n },\n examples: [\"corp schema\"],\n },\n\n // ── serve (local, complex) ──────────────────────────────────────────\n {\n name: \"serve\",\n description: \"Start the API server locally\",\n local: true,\n options: [\n { flags: \"--port <port>\", description: \"Port to listen on\", default: \"8000\" },\n { flags: \"--data-dir <path>\", description: \"Data directory\", default: \"./data/repos\" },\n ],\n handler: async (ctx) => {\n const { serveCommand } = await import(\"../commands/serve.js\");\n await serveCommand({\n port: (ctx.opts.port as string) ?? \"8000\",\n dataDir: (ctx.opts.dataDir as string) ?? \"./data/repos\",\n });\n },\n examples: [\"corp serve\"],\n },\n\n // ── demo (complex, uses API) ────────────────────────────────────────\n {\n name: \"demo\",\n description: \"Create a usable demo workspace environment\",\n local: true,\n options: [\n { flags: \"--name <name>\", description: \"Corporation name\", required: true },\n { flags: \"--scenario <scenario>\", description: \"Scenario to create (startup, llc, restaurant)\", default: \"startup\" },\n { flags: \"--minimal\", description: \"Use the minimal server-side demo seed instead of the full CLI workflow\" },\n { flags: \"--json\", description: \"Output as JSON\" },\n ],\n handler: async (ctx) => {\n const { demoCommand } = await import(\"../commands/demo.js\");\n await demoCommand({\n name: ctx.opts.name as string,\n scenario: ctx.opts.scenario as string | undefined,\n minimal: ctx.opts.minimal as boolean | undefined,\n json: ctx.opts.json as boolean | undefined,\n });\n },\n examples: [\"corp demo\"],\n },\n\n // ── chat (local, interactive) ───────────────────────────────────────\n {\n name: \"chat\",\n description: \"Interactive LLM chat session\",\n local: true,\n handler: async () => {\n const { chatCommand } = await import(\"../chat.js\");\n await chatCommand();\n },\n examples: [\"corp chat\"],\n },\n\n // ── api-keys (API, parent + subcommands) ────────────────────────────\n {\n name: \"api-keys\",\n description: \"API key management\",\n route: { method: \"GET\", path: \"/v1/api-keys\" },\n display: {\n title: \"API Keys\",\n cols: [\"name>Name\", \"key_prefix|prefix>Prefix\", \"@created_at>Created\", \"#api_key_id>ID\"],\n },\n handler: async (ctx) => {\n const { apiKeysListCommand } = await import(\"../commands/api-keys.js\");\n await apiKeysListCommand({ json: ctx.opts.json as boolean | undefined });\n },\n examples: [\"corp api-keys\"],\n },\n {\n name: \"api-keys create\",\n description: \"Create a new API key\",\n route: { method: \"POST\", path: \"/v1/api-keys\" },\n options: [\n { flags: \"--name <name>\", description: \"Key name/label\", required: true },\n { flags: \"--scopes <scopes>\", description: \"Comma-separated scopes\" },\n { flags: \"--json\", description: \"Output as JSON\" },\n ],\n handler: async (ctx) => {\n const { apiKeysCreateCommand } = await import(\"../commands/api-keys.js\");\n await apiKeysCreateCommand({\n name: ctx.opts.name as string,\n scopes: ctx.opts.scopes as string | undefined,\n json: ctx.opts.json as boolean | undefined,\n });\n },\n produces: { kind: \"api_key\" },\n successTemplate: \"API key created\",\n examples: [\"corp api-keys create --name 'name'\", \"corp api-keys create --json\"],\n },\n {\n name: \"api-keys revoke\",\n description: \"Revoke an API key\",\n route: { method: \"DELETE\", path: \"/v1/api-keys/{pos}\" },\n args: [\n { name: \"key-id\", required: true, description: \"API key ID to revoke\" },\n ],\n options: [\n { flags: \"--yes\", description: \"Skip confirmation\" },\n { flags: \"--json\", description: \"Output as JSON\" },\n ],\n handler: async (ctx) => {\n const { apiKeysRevokeCommand } = await import(\"../commands/api-keys.js\");\n await apiKeysRevokeCommand(ctx.positional[0], {\n yes: ctx.opts.yes as boolean | undefined,\n json: ctx.opts.json as boolean | undefined,\n });\n },\n examples: [\"corp api-keys revoke <key-id>\", \"corp api-keys revoke --json\"],\n },\n {\n name: \"api-keys rotate\",\n description: \"Rotate an API key (returns new key)\",\n route: { method: \"POST\", path: \"/v1/api-keys/{pos}/rotate\" },\n args: [\n { name: \"key-id\", required: true, description: \"API key ID to rotate\" },\n ],\n options: [\n { flags: \"--json\", description: \"Output as JSON\" },\n ],\n handler: async (ctx) => {\n const { apiKeysRotateCommand } = await import(\"../commands/api-keys.js\");\n await apiKeysRotateCommand(ctx.positional[0], {\n json: ctx.opts.json as boolean | undefined,\n });\n },\n produces: { kind: \"api_key\" },\n successTemplate: \"API key rotated\",\n examples: [\"corp api-keys rotate <key-id>\", \"corp api-keys rotate --json\"],\n },\n\n // ── link (API, write) ───────────────────────────────────────────────\n {\n name: \"link\",\n description: \"Link workspace to an external provider\",\n route: { method: \"POST\", path: \"/v1/workspaces/link\" },\n options: [\n { flags: \"--external-id <id>\", description: \"External ID to link\", required: true },\n { flags: \"--provider <provider>\", description: \"Provider name (e.g. stripe, github)\", required: true },\n ],\n handler: async (ctx) => {\n const { linkCommand } = await import(\"../commands/link.js\");\n await linkCommand({\n externalId: ctx.opts.externalId as string,\n provider: ctx.opts.provider as string,\n });\n },\n examples: [\"corp link --external-id 'id' --provider 'provider'\"],\n },\n\n // ── claim (API, write) ──────────────────────────────────────────────\n {\n name: \"claim\",\n description: \"Redeem a claim code to join a workspace\",\n route: { method: \"POST\", path: \"/v1/entities/claim\" },\n args: [\n { name: \"code\", required: true, description: \"Claim code to redeem\" },\n ],\n handler: async (ctx) => {\n const { claimCommand } = await import(\"../commands/claim.js\");\n await claimCommand(ctx.positional[0]);\n },\n produces: { kind: \"entity\", trackEntity: true },\n examples: [\"corp claim <code>\"],\n },\n\n // ── feedback (API, write) ───────────────────────────────────────────\n {\n name: \"feedback\",\n description: \"Submit feedback to TheCorporation\",\n route: { method: \"POST\", path: \"/v1/feedback\" },\n args: [\n { name: \"message\", required: true, description: \"Feedback message\" },\n ],\n options: [\n { flags: \"--category <category>\", description: \"Category (e.g. bug, feature, general)\", default: \"general\" },\n { flags: \"--email <email>\", description: \"Your email address (to receive a copy)\" },\n ],\n handler: async (ctx) => {\n const { feedbackCommand } = await import(\"../commands/feedback.js\");\n await feedbackCommand(ctx.positional[0], {\n category: ctx.opts.category as string | undefined,\n email: ctx.opts.email as string | undefined,\n json: ctx.opts.json as boolean | undefined,\n });\n },\n examples: [\"corp feedback <message>\", \"corp feedback --json\"],\n },\n\n // ── resolve (API, read) ─────────────────────────────────────────────\n {\n name: \"resolve\",\n description: \"Resolve a human-friendly reference to a canonical ID\",\n args: [\n { name: \"kind\", required: true, description: \"Resource kind to resolve\" },\n { name: \"ref\", required: true, description: \"Human-friendly reference\" },\n ],\n options: [\n { flags: \"--entity-id <ref>\", description: \"Entity reference for entity-scoped resources\" },\n { flags: \"--body-id <ref>\", description: \"Governance body reference for body-scoped resources\" },\n { flags: \"--meeting-id <ref>\", description: \"Meeting reference for meeting-scoped resources\" },\n ],\n handler: async (ctx) => {\n const { resolveCommand } = await import(\"../commands/resolve.js\");\n await resolveCommand(ctx.positional[0], ctx.positional[1], {\n entityId: ctx.opts.entityId as string | undefined,\n bodyId: ctx.opts.bodyId as string | undefined,\n meetingId: ctx.opts.meetingId as string | undefined,\n });\n },\n examples: [\"corp resolve\"],\n },\n\n // ── find (API, read) ────────────────────────────────────────────────\n {\n name: \"find\",\n description: \"List matching references for a resource kind\",\n args: [\n { name: \"kind\", required: true, description: \"Resource kind to search\" },\n { name: \"query\", required: true, description: \"Fuzzy search query\" },\n ],\n options: [\n { flags: \"--entity-id <ref>\", description: \"Entity reference for entity-scoped resources\" },\n { flags: \"--body-id <ref>\", description: \"Governance body reference for body-scoped resources\" },\n { flags: \"--meeting-id <ref>\", description: \"Meeting reference for meeting-scoped resources\" },\n { flags: \"--json\", description: \"Output as JSON\" },\n ],\n handler: async (ctx) => {\n const { findCommand } = await import(\"../commands/find.js\");\n await findCommand(ctx.positional[0], ctx.positional[1], {\n entityId: ctx.opts.entityId as string | undefined,\n bodyId: ctx.opts.bodyId as string | undefined,\n meetingId: ctx.opts.meetingId as string | undefined,\n json: ctx.opts.json as boolean | undefined,\n });\n },\n examples: [\"corp find\"],\n },\n\n // ── approvals (informational) ───────────────────────────────────────\n {\n name: \"approvals\",\n description: \"Approvals are managed through governance meetings and execution intents\",\n local: true,\n handler: async () => {\n process.stderr.write(\n \"Approvals are managed through governance meetings and execution intents.\\n\" +\n \"Use these commands to manage approvals:\\n\\n\" +\n \" Board approval via meeting vote:\\n\" +\n ' corp governance convene --body <body> --type board_meeting --title \"Approve X\"\\n' +\n \" corp governance vote <meeting> <item> --voter <contact> --vote for\\n\\n\" +\n \" Written consent (no meeting needed):\\n\" +\n ' corp governance written-consent --body <body> --title \"Approve X\" --description \"...\"\\n\\n' +\n \" View pending items:\\n\" +\n \" corp governance meetings <body> # see scheduled meetings\\n\" +\n \" corp governance agenda-items <meeting> # see items awaiting votes\\n\" +\n \" corp cap-table valuations # see pending valuations\\n\",\n );\n process.exit(1);\n },\n examples: [\"corp approvals\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"admin audit-events\",\n description: \"View audit log of workspace events\",\n route: { method: \"GET\", path: \"/v1/admin/audit-events\" },\n display: { title: \"Admin Audit Events\", cols: [\"details>Details\", \"#event_id>ID\", \"event_type>Event Type\", \"timestamp>Timestamp\"] },\n examples: [\"corp admin audit-events\"],\n },\n {\n name: \"admin system-health\",\n description: \"Check API server health and uptime\",\n route: { method: \"GET\", path: \"/v1/admin/system-health\" },\n display: { title: \"Admin System Health\", cols: [\"git_storage>Git Storage\", \"status>Status\", \"uptime_seconds>Uptime Seconds\", \"version>Version\", \"workspace_count>Workspace Count\"] },\n examples: [\"corp admin system-health\"],\n },\n {\n name: \"admin workspaces\",\n description: \"List all workspaces (admin)\",\n route: { method: \"GET\", path: \"/v1/admin/workspaces\" },\n display: { title: \"Admin Workspaces\", cols: [\"entity_count>Entity Count\", \"name>Name\", \"#workspace_id>ID\"] },\n examples: [\"corp admin workspaces\"],\n },\n {\n name: \"billing plans\",\n description: \"View available billing plans\",\n route: { method: \"GET\", path: \"/v1/billing/plans\" },\n display: { title: \"Billing Plans\", cols: [\"plans>Plans\"] },\n examples: [\"corp billing plans\"],\n },\n {\n name: \"billing status\",\n description: \"Check current billing and subscription status\",\n route: { method: \"GET\", path: \"/v1/billing/status\" },\n display: { title: \"Billing Status\", cols: [\"current_period_end>Current Period End\", \"plan>Plan\", \"status>Status\", \"#workspace_id>ID\"] },\n examples: [\"corp billing status\"],\n },\n {\n name: \"server-config\",\n description: \"View server configuration (environment, version, features)\",\n route: { method: \"GET\", path: \"/v1/config\" },\n display: { title: \"Server Config\", cols: [\"environment>Environment\", \"version>Version\", \"features>Features\"] },\n examples: [\"corp server-config\", \"corp server-config --json\"],\n },\n {\n name: \"demo seed\",\n description: \"Seed a demo workspace with sample data\",\n route: { method: \"POST\", path: \"/v1/demo/seed\" },\n options: [\n { flags: \"--name <name>\", description: \"Display name\" },\n { flags: \"--scenario <scenario>\", description: \"Demo scenario to use\" },\n ],\n examples: [\"corp demo seed\", \"corp demo seed --json\"],\n successTemplate: \"Seed created\",\n },\n {\n name: \"digests trigger\",\n description: \"Trigger digest generation now\",\n route: { method: \"POST\", path: \"/v1/digests/trigger\" },\n examples: [\"corp digests trigger\"],\n successTemplate: \"Trigger created\",\n },\n {\n name: \"digests\",\n description: \"View a specific digest by key\",\n route: { method: \"GET\", path: \"/v1/digests/{pos}\" },\n args: [{ name: \"digest-key\", required: true, description: \"Digest key\" }],\n display: { title: \"Digest\" },\n examples: [\"corp digests\"],\n },\n {\n name: \"service-token\",\n description: \"Get a service authentication token\",\n route: { method: \"GET\", path: \"/v1/service-token\" },\n display: { title: \"Service Token\", cols: [\"#api_key_id>ID\", \"expires_in>Expires In\", \"token>Token\", \"token_type>Token Type\"] },\n examples: [\"corp service-token\"],\n },\n {\n name: \"workspace entities\",\n description: \"List entities in current workspace\",\n route: { method: \"GET\", path: \"/v1/workspace/entities\" },\n display: { title: \"Workspace Entities\", cols: [\"#entity_id>ID\"] },\n examples: [\"corp workspace entities\"],\n },\n {\n name: \"workspace status\",\n description: \"Show current workspace status\",\n route: { method: \"GET\", path: \"/v1/workspace/status\" },\n display: { title: \"Workspace Status\", cols: [\"entity_count>Entity Count\", \"name>Name\", \"status>Status\", \"#workspace_id>ID\"] },\n examples: [\"corp workspace status\"],\n },\n {\n name: \"workspaces claim\",\n description: \"Claim a workspace using a claim token\",\n route: { method: \"POST\", path: \"/v1/workspaces/claim\" },\n options: [\n { flags: \"--claim-token <claim-token>\", description: \"Workspace claim token\", required: true },\n ],\n examples: [\"corp workspaces claim --claim-token 'claim-token'\"],\n successTemplate: \"Claim created\",\n },\n {\n name: \"workspaces contacts\",\n description: \"List contacts across the workspace\",\n route: { method: \"GET\", path: \"/v1/workspaces/{workspace_id}/contacts\" },\n display: { title: \"Workspaces Contacts\", cols: [\"#contact_id>ID\", \"#entity_id>ID\"] },\n examples: [\"corp workspaces contacts\"],\n },\n {\n name: \"workspaces entities\",\n description: \"List all entities in a workspace\",\n route: { method: \"GET\", path: \"/v1/workspaces/{workspace_id}/entities\" },\n display: { title: \"Workspaces Entities\", cols: [\"#entity_id>ID\"] },\n examples: [\"corp workspaces entities\"],\n },\n\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"auth token-exchange\",\n description: \"Exchange an API key for a short-lived JWT\",\n route: { method: \"POST\", path: \"/v1/auth/token-exchange\" },\n options: [\n { flags: \"--api-key <api-key>\", description: \"API key (starts with sk_)\", required: true },\n { flags: \"--ttl-seconds <ttl-seconds>\", description: \"Token TTL in seconds (60-86400)\", type: \"int\" },\n ],\n examples: [\"corp auth token-exchange --api-key 'api-key'\", \"corp auth token-exchange --json\"],\n successTemplate: \"Token Exchange created\",\n },\n {\n name: \"ssh-keys\",\n description: \"List registered SSH public keys\",\n route: { method: \"GET\", path: \"/v1/ssh-keys\" },\n display: { title: \"SSH Keys\", cols: [\"name>Name\", \"algorithm>Algorithm\", \"fingerprint>Fingerprint\", \"@created_at>Created\", \"#key_id>ID\"] },\n examples: [\"corp ssh-keys\"],\n },\n {\n name: \"ssh-keys add\",\n description: \"Register a new SSH public key\",\n route: { method: \"POST\", path: \"/v1/ssh-keys\" },\n options: [\n { flags: \"--name <name>\", description: \"Key name/label\", required: true },\n { flags: \"--public-key <key>\", description: \"SSH public key in OpenSSH format\", required: true },\n { flags: \"--scopes <scopes>\", description: \"Comma-separated scopes (e.g. git_read,git_write)\", type: \"array\" },\n { flags: \"--entity-ids <ids>\", description: \"Restrict key to specific entity IDs\" },\n { flags: \"--contact-id <id>\", description: \"Associate with a contact\" },\n ],\n examples: [\"corp ssh-keys add --name laptop --public-key 'ssh-ed25519 AAAA...'\", \"corp ssh-keys add --name ci --public-key 'ssh-ed25519 AAAA...' --scopes git_read,git_write\"],\n successTemplate: \"SSH key {name} added ({fingerprint})\",\n },\n {\n name: \"ssh-keys revoke\",\n description: \"Revoke an SSH public key\",\n route: { method: \"DELETE\", path: \"/v1/ssh-keys/{pos}\" },\n args: [{ name: \"key-id\", required: true, description: \"SSH key ID to revoke\" }],\n examples: [\"corp ssh-keys revoke <key-id>\"],\n successTemplate: \"SSH key revoked\",\n },\n {\n name: \"workspaces provision\",\n description: \"Provision a new workspace\",\n route: { method: \"POST\", path: \"/v1/workspaces/provision\" },\n options: [\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--owner-email <owner-email>\", description: \"Workspace owner email address\" },\n ],\n examples: [\"corp workspaces provision --name 'name'\", \"corp workspaces provision --json\"],\n successTemplate: \"Provision created\",\n },\n\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"references sync\",\n description: \"Sync reference aliases for a resource kind\",\n route: { method: \"POST\", path: \"/v1/references/sync\" },\n options: [\n { flags: \"--items <items>\", description: \"Items to sync (JSON array)\", required: true, type: \"array\" },\n { flags: \"--kind <kind>\", description: \"Resource kind\", required: true, choices: [\"entity\", \"contact\", \"share_transfer\", \"invoice\", \"bank_account\", \"payment\", \"payroll_run\", \"distribution\", \"reconciliation\", \"tax_filing\", \"deadline\", \"classification\", \"body\", \"meeting\", \"seat\", \"agenda_item\", \"resolution\", \"document\", \"work_item\", \"agent\", \"valuation\", \"safe_note\", \"instrument\", \"share_class\", \"round\"] },\n ],\n examples: [\"corp references sync --items 'items' --kind 'kind'\"],\n successTemplate: \"Sync created\",\n },\n\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"secrets interpolate\",\n description: \"Interpolate secrets into a template string\",\n route: { method: \"POST\", path: \"/v1/secrets/interpolate\" },\n options: [\n { flags: \"--execution-id <execution-id>\", description: \"Agent execution ID\", required: true },\n { flags: \"--template <template>\", description: \"Template string with {{secret}} placeholders\", required: true },\n ],\n examples: [\"corp secrets interpolate --execution-id 'execution-id' --template 'template'\"],\n successTemplate: \"Interpolate created\",\n },\n {\n name: \"secrets resolve\",\n description: \"Resolve a secrets token to its values\",\n route: { method: \"POST\", path: \"/v1/secrets/resolve\" },\n options: [\n { flags: \"--token <token>\", description: \"Secrets access token\", required: true },\n ],\n examples: [\"corp secrets resolve --token 'token'\"],\n successTemplate: \"Resolve created\",\n },\n\n {\n name: \"documents validate-preview\",\n description: \"Validate a document preview without generating PDF\",\n route: { method: \"GET\", path: \"/v1/documents/preview/pdf/validate\" },\n entity: true,\n display: { title: \"Document Preview Validation\" },\n examples: [\"corp documents validate-preview\", \"corp documents validate-preview --json\"],\n },\n];\n","import type { CommandDef } from \"./types.js\";\n\nexport const executionCommands: CommandDef[] = [\n {\n name: \"document-requests fulfill\",\n description: \"Fulfill a document request with uploaded content\",\n route: { method: \"PATCH\", path: \"/v1/document-requests/{pos}/fulfill\" },\n entity: true,\n args: [{ name: \"request-id\", required: true, description: \"Document request ID\" }],\n examples: [\"corp document-requests fulfill <request-id>\"],\n successTemplate: \"Fulfill updated\",\n },\n {\n name: \"document-requests not-applicable\",\n description: \"Mark a document request as not applicable\",\n route: { method: \"PATCH\", path: \"/v1/document-requests/{pos}/not-applicable\" },\n entity: true,\n args: [{ name: \"request-id\", required: true, description: \"Document request ID\" }],\n examples: [\"corp document-requests not-applicable <request-id>\"],\n successTemplate: \"Not Applicable updated\",\n },\n {\n name: \"entities approval-artifacts\",\n description: \"List approval artifacts for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/approval-artifacts\" },\n entity: true,\n display: { title: \"Entities Approval Artifacts\", cols: [\"approved_at>Approved At\", \"approver_identity>Approver Identity\", \"channel>Channel\", \"expires_at>Expires At\", \"@created_at>Created At\", \"#approval_artifact_id>ID\"] },\n examples: [\"corp entities approval-artifacts\", \"corp entities approval-artifacts --json\"],\n },\n {\n name: \"entities intents\",\n description: \"List execution intents for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/intents\" },\n entity: true,\n display: { title: \"Entities Intents\", cols: [\"authority_tier>Authority Tier\", \"authorized_at>Authorized At\", \"bound_document_request_ids>Bound Document Request Ids\", \"cancelled_at>Cancelled At\", \"@created_at>Created At\", \"#bound_approval_artifact_id>ID\"] },\n examples: [\"corp entities intents\", \"corp entities intents --json\"],\n },\n {\n name: \"entities obligations\",\n description: \"List obligations for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/obligations\" },\n entity: true,\n display: { title: \"Entities Obligations\", cols: [\"assignee_type>Assignee Type\", \"description>Description\", \"expired_at>Expired At\", \"fulfilled_at>Fulfilled At\", \"@created_at>Created At\", \"#assignee_id>ID\"] },\n examples: [\"corp entities obligations\", \"corp entities obligations --json\"],\n },\n {\n name: \"entities obligations-human\",\n description: \"List human-actionable obligations for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/obligations/human\" },\n entity: true,\n display: { title: \"Entities Obligations Human\", cols: [\"assignee_type>Assignee Type\", \"description>Description\", \"expired_at>Expired At\", \"fulfilled_at>Fulfilled At\", \"@created_at>Created At\", \"#assignee_id>ID\"] },\n examples: [\"corp entities obligations-human\", \"corp entities obligations-human --json\"],\n },\n {\n name: \"entities obligations-summary\",\n description: \"View obligation summary (pending/fulfilled/expired)\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/obligations/summary\" },\n entity: true,\n display: { title: \"Entities Obligations Summary\", cols: [\"expired>Expired\", \"fulfilled>Fulfilled\", \"pending>Pending\", \"total>Total\", \"waived>Waived\"] },\n examples: [\"corp entities obligations-summary\", \"corp entities obligations-summary --json\"],\n },\n {\n name: \"entities packets\",\n description: \"List document packets for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/packets\" },\n entity: true,\n display: { title: \"Entities Packets\", cols: [\"finalized_at>Finalized At\", \"items>Items\", \"manifest_hash>Manifest Hash\", \"required_signers>Required Signers\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp entities packets\", \"corp entities packets --json\"],\n },\n {\n name: \"execution approval-artifacts\",\n description: \"Create an approval artifact (e.g. board vote record)\",\n route: { method: \"POST\", path: \"/v1/execution/approval-artifacts\" },\n entity: true,\n options: [\n { flags: \"--approved-at <approved-at>\", description: \"Timestamp of approval (ISO 8601)\" },\n { flags: \"--approver-identity <approver-identity>\", description: \"Identity of the approver\", required: true },\n { flags: \"--channel <channel>\", description: \"Approval channel (board_vote, written_consent, etc.)\", required: true },\n { flags: \"--expires-at <expires-at>\", description: \"Expiration timestamp (ISO 8601)\" },\n { flags: \"--explicit\", description: \"Whether approval is explicit (vs implied)\" },\n { flags: \"--intent-type <intent-type>\", description: \"Type of intent\", required: true },\n { flags: \"--max-amount-cents <max-amount-cents>\", description: \"Maximum authorized amount in cents\" },\n { flags: \"--scope <scope>\", description: \"Authorization scope\", required: true },\n ],\n examples: [\"corp execution approval-artifacts --approver-identity 'approver-identity' --channel 'channel' --intent-type 'intent-type' --scope 'scope'\", \"corp execution approval-artifacts --json\"],\n successTemplate: \"Approval Artifacts created\",\n },\n {\n name: \"execution intents\",\n description: \"Create an execution intent (action requiring authorization)\",\n route: { method: \"POST\", path: \"/v1/execution/intents\" },\n entity: true,\n options: [\n { flags: \"--authority-tier <authority-tier>\", description: \"Authority tier required (tier_1, tier_2, tier_3)\", choices: [\"tier_1\", \"tier_2\", \"tier_3\"] },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--intent-type <intent-type>\", description: \"Type of intent\", required: true },\n { flags: \"--metadata <metadata>\", description: \"Additional metadata (JSON)\" },\n ],\n examples: [\"corp execution intents --description 'description' --intent-type 'intent-type'\", \"corp execution intents --json\"],\n successTemplate: \"Intents created\",\n },\n {\n name: \"execution obligations\",\n description: \"Create an obligation (task assigned to a party)\",\n route: { method: \"POST\", path: \"/v1/execution/obligations\" },\n entity: true,\n options: [\n { flags: \"--assignee-id <assignee-id>\", description: \"ID of the party to assign to\" },\n { flags: \"--assignee-type <assignee-type>\", description: \"Who is responsible for fulfilling an obligation.\", required: true, choices: [\"internal\", \"third_party\", \"human\"] },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--due-date <due-date>\", description: \"Due date (ISO 8601, e.g. 2026-06-30)\" },\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\" },\n { flags: \"--obligation-type <obligation-type>\", description: \"Type of obligation\", required: true },\n ],\n examples: [\"corp execution obligations --assignee-type internal --description 'description' --obligation-type 'obligation-type'\", \"corp execution obligations --json\"],\n successTemplate: \"Obligations created\",\n },\n {\n name: \"execution packets\",\n description: \"View a document packet\",\n route: { method: \"GET\", path: \"/v1/execution/packets/{pos}\" },\n entity: true,\n args: [{ name: \"packet-id\", required: true, description: \"Document packet ID\" }],\n display: { title: \"Execution Packets\", cols: [\"finalized_at>Finalized At\", \"items>Items\", \"manifest_hash>Manifest Hash\", \"required_signers>Required Signers\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp execution packets\", \"corp execution packets --json\"],\n },\n {\n name: \"intents authorize\",\n description: \"Authorize an execution intent\",\n route: { method: \"POST\", path: \"/v1/intents/{pos}/authorize\" },\n entity: true,\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n examples: [\"corp intents authorize <intent-id>\"],\n successTemplate: \"Authorize created\",\n },\n {\n name: \"intents bind-approval-artifact\",\n description: \"Bind an approval artifact to an intent\",\n route: { method: \"POST\", path: \"/v1/intents/{pos}/bind-approval-artifact\" },\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n options: [\n { flags: \"--approval-artifact-id <approval-artifact-id>\", description: \"Approval artifact ID to bind\", required: true },\n ],\n examples: [\"corp intents bind-approval-artifact <intent-id> --approval-artifact-id 'approval-artifact-id'\"],\n successTemplate: \"Bind Approval Artifact created\",\n },\n {\n name: \"intents bind-document-request\",\n description: \"Bind a document request to an intent\",\n route: { method: \"POST\", path: \"/v1/intents/{pos}/bind-document-request\" },\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n options: [\n { flags: \"--request-id <request-id>\", description: \"Document request ID\", required: true },\n ],\n examples: [\"corp intents bind-document-request <intent-id> --request-id 'request-id'\"],\n successTemplate: \"Bind Document Request created\",\n },\n {\n name: \"intents cancel\",\n description: \"Cancel an execution intent\",\n route: { method: \"POST\", path: \"/v1/intents/{pos}/cancel\" },\n entity: true,\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n examples: [\"corp intents cancel <intent-id>\"],\n successTemplate: \"Cancel created\",\n },\n {\n name: \"intents evaluate\",\n description: \"Evaluate whether an intent meets its requirements\",\n route: { method: \"POST\", path: \"/v1/intents/{pos}/evaluate\" },\n entity: true,\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n examples: [\"corp intents evaluate <intent-id>\"],\n successTemplate: \"Evaluate created\",\n },\n {\n name: \"intents execute\",\n description: \"Execute an authorized intent\",\n route: { method: \"POST\", path: \"/v1/intents/{pos}/execute\" },\n entity: true,\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n examples: [\"corp intents execute <intent-id>\"],\n successTemplate: \"Execute created\",\n },\n {\n name: \"intents receipts\",\n description: \"View execution receipts for an intent\",\n route: { method: \"GET\", path: \"/v1/intents/{pos}/receipts\" },\n entity: true,\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n display: { title: \"Intents Receipts\", cols: [\"executed_at>Executed At\", \"idempotency_key>Idempotency Key\", \"request_hash>Request Hash\", \"response_hash>Response Hash\", \"@created_at>Created At\", \"#intent_id>ID\"] },\n examples: [\"corp intents receipts\", \"corp intents receipts --json\"],\n },\n {\n name: \"obligations assign\",\n description: \"Assign an obligation to a party\",\n route: { method: \"POST\", path: \"/v1/obligations/{pos}/assign\" },\n entity: true,\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n options: [\n { flags: \"--assignee-id <assignee-id>\", description: \"ID of the party to assign to\", required: true },\n ],\n examples: [\"corp obligations assign <obligation-id> --assignee-id 'assignee-id'\"],\n successTemplate: \"Assign created\",\n },\n {\n name: \"obligations document-requests\",\n description: \"List or create document requests for an obligation\",\n route: { method: \"GET\", path: \"/v1/obligations/{pos}/document-requests\" },\n entity: true,\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n display: { title: \"Obligations Document Requests\", cols: [\"description>Description\", \"document_type>Document Type\", \"fulfilled_at>Fulfilled At\", \"not_applicable_at>Not Applicable At\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp obligations document-requests\", \"corp obligations document-requests --json\"],\n },\n {\n name: \"obligations create-document-request\",\n description: \"List or create document requests for an obligation\",\n route: { method: \"POST\", path: \"/v1/obligations/{pos}/document-requests\" },\n entity: true,\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n options: [\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--document-type <document-type>\", description: \"Type of document required\", required: true },\n ],\n examples: [\"corp obligations document-requests <obligation-id> --description 'description' --document-type 'document-type'\"],\n successTemplate: \"Document Requests created\",\n },\n {\n name: \"obligations expire\",\n description: \"Mark an obligation as expired\",\n route: { method: \"POST\", path: \"/v1/obligations/{pos}/expire\" },\n entity: true,\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n examples: [\"corp obligations expire <obligation-id>\"],\n successTemplate: \"Expire created\",\n },\n {\n name: \"obligations fulfill\",\n description: \"Mark an obligation as fulfilled\",\n route: { method: \"POST\", path: \"/v1/obligations/{pos}/fulfill\" },\n entity: true,\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n examples: [\"corp obligations fulfill <obligation-id>\"],\n successTemplate: \"Fulfill created\",\n },\n {\n name: \"obligations waive\",\n description: \"Waive an obligation\",\n route: { method: \"POST\", path: \"/v1/obligations/{pos}/waive\" },\n entity: true,\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n examples: [\"corp obligations waive <obligation-id>\"],\n successTemplate: \"Waive created\",\n },\n {\n name: \"receipts\",\n description: \"View an execution receipt\",\n route: { method: \"GET\", path: \"/v1/receipts/{pos}\" },\n entity: true,\n args: [{ name: \"receipt-id\", required: true, description: \"Execution receipt ID\" }],\n display: { title: \"Receipts\", cols: [\"executed_at>Executed At\", \"idempotency_key>Idempotency Key\", \"request_hash>Request Hash\", \"response_hash>Response Hash\", \"@created_at>Created At\", \"#intent_id>ID\"] },\n examples: [\"corp receipts\", \"corp receipts --json\"],\n },\n\n // ── Human obligations ───────────────────────────────────────────────\n {\n name: \"human-obligations\",\n description: \"List obligations requiring human action (signing, upload)\",\n route: { method: \"GET\", path: \"/v1/human-obligations\" },\n display: {\n title: \"Human Obligations\",\n cols: [\"obligation_type>Type\", \"status>Status\", \"@due_at>Due\", \"#obligation_id>ID\"],\n },\n examples: [\"corp human-obligations\"],\n },\n {\n name: \"human-obligations fulfill\",\n description: \"Fulfill a human obligation\",\n route: { method: \"POST\", path: \"/v1/human-obligations/{pos}/fulfill\" },\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n successTemplate: \"Obligation fulfilled\",\n examples: [\"corp human-obligations fulfill <obligation-id>\"],\n },\n {\n name: \"human-obligations signer-token\",\n description: \"Get a signing token for a human obligation\",\n route: { method: \"POST\", path: \"/v1/human-obligations/{pos}/signer-token\" },\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n successTemplate: \"Signer token issued\",\n examples: [\"corp human-obligations signer-token <obligation-id>\"],\n },\n];","import type { CommandDef } from \"./types.js\";\n\nexport const secretProxyCommands: CommandDef[] = [\n {\n name: \"secret-proxies\",\n description: \"List secret proxies for the workspace\",\n route: { method: \"GET\", path: \"/v1/workspaces/{wid}/secret-proxies\" },\n display: {\n title: \"Secret Proxies\",\n cols: [\"name>Name\", \"url>URL\", \"description>Description\", \"secret_count>Secrets\", \"@created_at>Created\"],\n },\n examples: [\"corp secret-proxies\"],\n },\n {\n name: \"secret-proxies create\",\n description: \"Create a secret proxy\",\n route: { method: \"POST\", path: \"/v1/workspaces/{wid}/secret-proxies\" },\n options: [\n { flags: \"--name <name>\", description: \"Proxy name\", required: true },\n { flags: \"--url <url>\", description: \"Proxy URL (or 'self' for local encrypted secrets)\", required: true },\n { flags: \"--description <desc>\", description: \"Description text\" },\n ],\n successTemplate: \"Secret proxy {name} created\",\n examples: [\"corp secret-proxies create --name 'name' --url 'url'\", \"corp secret-proxies create --json\"],\n },\n {\n name: \"secret-proxies show\",\n description: \"Show a secret proxy\",\n route: { method: \"GET\", path: \"/v1/workspaces/{wid}/secret-proxies/{pos}\" },\n args: [{ name: \"proxy-name\", required: true, description: \"Proxy name\" }],\n display: {\n title: \"Secret Proxy\",\n cols: [\"name>Name\", \"url>URL\", \"description>Description\", \"secret_count>Secrets\", \"@created_at>Created\"],\n },\n examples: [\"corp secret-proxies show\"],\n },\n {\n name: \"secret-proxies secrets\",\n description: \"List secret names in a proxy\",\n route: { method: \"GET\", path: \"/v1/workspaces/{wid}/secret-proxies/{pos}/secrets\" },\n args: [{ name: \"proxy-name\", required: true, description: \"Proxy name\" }],\n display: {\n title: \"Secrets\",\n cols: [\"names>Secret Names\", \"proxy_name>Proxy\"],\n },\n examples: [\"corp secret-proxies secrets\"],\n },\n {\n name: \"secret-proxies set-secrets\",\n description: \"Set secrets in a proxy (key-value pairs, server encrypts)\",\n route: { method: \"PUT\", path: \"/v1/workspaces/{wid}/secret-proxies/{pos}/secrets\" },\n args: [{ name: \"proxy-name\", required: true, description: \"Proxy name\" }],\n options: [\n { flags: \"--secrets <json>\", description: \"JSON object of key-value secret pairs\", required: true },\n ],\n successTemplate: \"Secrets updated for {proxy_name}\",\n examples: [\"corp secret-proxies set-secrets <proxy-name> --secrets 'json'\"],\n },\n];","import type { CommandDef } from \"./types.js\";\n\nexport const treasuryCommands: CommandDef[] = [\n {\n name: \"bank-accounts close\",\n description: \"Close a bank account\",\n route: { method: \"POST\", path: \"/v1/bank-accounts/{pos}/close\" },\n entity: true,\n args: [{ name: \"bank-account-id\", required: true, description: \"Bank account ID\" }],\n examples: [\"corp bank-accounts close <bank-account-id>\"],\n successTemplate: \"Close created\",\n },\n {\n name: \"distributions\",\n description: \"Record a distribution (dividend, member draw)\",\n route: { method: \"POST\", path: \"/v1/distributions\" },\n options: [\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--distribution-type <distribution-type>\", description: \"Type of distribution.\", choices: [\"dividend\", \"return\", \"liquidation\"] },\n { flags: \"--total-amount-cents <total-amount-cents>\", description: \"Total Amount Cents\", required: true, type: \"int\" },\n ],\n examples: [\"corp distributions --description dividend --total-amount-cents 'total-amount-cents'\", \"corp distributions --json\"],\n successTemplate: \"Distributions created\",\n },\n {\n name: \"entities accounts\",\n description: \"List ledger accounts for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/accounts\" },\n entity: true,\n display: { title: \"Entities Accounts\", cols: [\"account_code>Account Code\", \"account_name>Account Name\", \"account_type>Account Type\", \"currency>Currency\", \"@created_at>Created At\", \"#account_id>ID\"] },\n examples: [\"corp entities accounts\", \"corp entities accounts --json\"],\n },\n {\n name: \"entities journal-entries\",\n description: \"List journal entries for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/journal-entries\" },\n entity: true,\n display: { title: \"Entities Journal Entries\", cols: [\"description>Description\", \"effective_date>Effective Date\", \"status>Status\", \"total_credits_cents>Total Credits Cents\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp entities journal-entries\", \"corp entities journal-entries --json\"],\n },\n {\n name: \"entities spending-limits\",\n description: \"List spending limits for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/spending-limits\" },\n entity: true,\n display: { title: \"Entities Spending Limits\", cols: [\"amount_cents>Amount Cents\", \"category>Category\", \"@created_at>Created At\", \"#entity_id>ID\", \"period>Period\", \"#spending_limit_id>ID\"] },\n examples: [\"corp entities spending-limits\", \"corp entities spending-limits --json\"],\n },\n {\n name: \"entities stripe-account\",\n description: \"View Stripe account for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/stripe-account\" },\n entity: true,\n display: { title: \"Entities Stripe Account\", cols: [\"@created_at>Created At\", \"#entity_id>ID\", \"status>Status\", \"#stripe_account_id>ID\"] },\n examples: [\"corp entities stripe-account\", \"corp entities stripe-account --json\"],\n },\n {\n name: \"invoices from-agent-request\",\n description: \"Create an invoice from an agent request\",\n route: { method: \"POST\", path: \"/v1/invoices/from-agent-request\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--customer-name <customer-name>\", description: \"Customer name for the invoice\", required: true },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--due-date <due-date>\", description: \"Due date (ISO 8601, e.g. 2026-06-30)\", required: true },\n ],\n examples: [\"corp invoices from-agent-request --amount-cents 'amount-cents' --customer-name 'customer-name' --description 'description' --due-date 'due-date'\"],\n successTemplate: \"From Agent Request created\",\n },\n {\n name: \"invoices\",\n description: \"Create a new invoice\",\n route: { method: \"GET\", path: \"/v1/invoices/{pos}\" },\n entity: true,\n args: [{ name: \"invoice-id\", required: true, description: \"Invoice ID\" }],\n display: { title: \"Invoices\", cols: [\"amount_cents>Amount Cents\", \"customer_name>Customer Name\", \"description>Description\", \"status>Status\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp invoices\", \"corp invoices --json\"],\n },\n {\n name: \"invoices mark-paid\",\n description: \"Mark an invoice as paid\",\n route: { method: \"POST\", path: \"/v1/invoices/{pos}/mark-paid\" },\n entity: true,\n args: [{ name: \"invoice-id\", required: true, description: \"Invoice ID\" }],\n examples: [\"corp invoices mark-paid <invoice-id>\"],\n successTemplate: \"Mark Paid created\",\n },\n {\n name: \"invoices pay-instructions\",\n description: \"Get payment instructions for an invoice\",\n route: { method: \"GET\", path: \"/v1/invoices/{pos}/pay-instructions\" },\n entity: true,\n args: [{ name: \"invoice-id\", required: true, description: \"Invoice ID\" }],\n display: { title: \"Invoices Pay Instructions\", cols: [\"amount_cents>Amount Cents\", \"currency>Currency\", \"instructions>Instructions\", \"#invoice_id>ID\", \"payment_method>Payment Method\"] },\n examples: [\"corp invoices pay-instructions\", \"corp invoices pay-instructions --json\"],\n },\n {\n name: \"invoices send\",\n description: \"Send an invoice to the recipient\",\n route: { method: \"POST\", path: \"/v1/invoices/{pos}/send\" },\n entity: true,\n args: [{ name: \"invoice-id\", required: true, description: \"Invoice ID\" }],\n examples: [\"corp invoices send <invoice-id>\"],\n successTemplate: \"Send created\",\n },\n {\n name: \"invoices status\",\n description: \"Check invoice payment status\",\n route: { method: \"GET\", path: \"/v1/invoices/{pos}/status\" },\n entity: true,\n args: [{ name: \"invoice-id\", required: true, description: \"Invoice ID\" }],\n display: { title: \"Invoices Status\", cols: [\"amount_cents>Amount Cents\", \"customer_name>Customer Name\", \"description>Description\", \"status>Status\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp invoices status\", \"corp invoices status --json\"],\n },\n {\n name: \"journal-entries post\",\n description: \"Post a journal entry (make it permanent)\",\n route: { method: \"POST\", path: \"/v1/journal-entries/{pos}/post\" },\n entity: true,\n args: [{ name: \"entry-id\", required: true, description: \"Journal entry ID\" }],\n examples: [\"corp journal-entries post <entry-id>\"],\n successTemplate: \"Post created\",\n },\n {\n name: \"journal-entries void\",\n description: \"Void a journal entry\",\n route: { method: \"POST\", path: \"/v1/journal-entries/{pos}/void\" },\n entity: true,\n args: [{ name: \"entry-id\", required: true, description: \"Journal entry ID\" }],\n examples: [\"corp journal-entries void <entry-id>\"],\n successTemplate: \"Void created\",\n },\n {\n name: \"ledger reconcile\",\n description: \"Reconcile the ledger\",\n route: { method: \"POST\", path: \"/v1/ledger/reconcile\" },\n entity: true,\n options: [\n { flags: \"--as-of-date <as-of-date>\", description: \"As Of Date\" },\n { flags: \"--end-date <end-date>\", description: \"End Date\" },\n { flags: \"--start-date <start-date>\", description: \"Start Date\" },\n ],\n examples: [\"corp ledger reconcile\", \"corp ledger reconcile --json\"],\n successTemplate: \"Reconcile created\",\n },\n {\n name: \"payments\",\n description: \"Record a new payment\",\n route: { method: \"POST\", path: \"/v1/payments\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--payment-method <payment-method>\", description: \"How a payment is made or received.\", choices: [\"bank_transfer\", \"card\", \"check\", \"wire\", \"ach\"] },\n { flags: \"--recipient <recipient>\", description: \"Recipient\", required: true },\n ],\n examples: [\"corp payments --amount-cents 'amount-cents' --description bank_transfer --recipient 'recipient'\", \"corp payments --json\"],\n successTemplate: \"Payments created\",\n },\n {\n name: \"payments execute\",\n description: \"Execute a pending payment\",\n route: { method: \"POST\", path: \"/v1/payments/execute\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--payment-method <payment-method>\", description: \"How a payment is made or received.\", choices: [\"bank_transfer\", \"card\", \"check\", \"wire\", \"ach\"] },\n { flags: \"--recipient <recipient>\", description: \"Recipient\", required: true },\n ],\n examples: [\"corp payments execute --amount-cents 'amount-cents' --description bank_transfer --recipient 'recipient'\", \"corp payments execute --json\"],\n successTemplate: \"Execute created\",\n },\n {\n name: \"payroll runs\",\n description: \"Create a payroll run\",\n route: { method: \"POST\", path: \"/v1/payroll/runs\" },\n entity: true,\n options: [\n { flags: \"--pay-period-end <pay-period-end>\", description: \"Pay Period End\", required: true },\n { flags: \"--pay-period-start <pay-period-start>\", description: \"Pay Period Start\", required: true },\n ],\n examples: [\"corp payroll runs --pay-period-end 'pay-period-end' --pay-period-start 'pay-period-start'\"],\n successTemplate: \"Runs created\",\n },\n {\n name: \"spending-limits\",\n description: \"Set a spending limit\",\n route: { method: \"POST\", path: \"/v1/spending-limits\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--category <category>\", description: \"Category\", required: true },\n { flags: \"--period <period>\", description: \"Period\", required: true },\n ],\n examples: [\"corp spending-limits --amount-cents 'amount-cents' --category 'category' --period 'period'\"],\n successTemplate: \"Spending Limits created\",\n },\n {\n name: \"treasury accounts\",\n description: \"Create a new ledger account\",\n route: { method: \"POST\", path: \"/v1/treasury/accounts\" },\n entity: true,\n options: [\n { flags: \"--account-code <account-code>\", description: \"Standard GL account codes with integer discriminants matching the code number.\", required: true, choices: [\"Cash\", \"AccountsReceivable\", \"AccountsPayable\", \"AccruedExpenses\", \"FounderCapital\", \"Revenue\", \"OperatingExpenses\", \"Cogs\"] },\n ],\n examples: [\"corp treasury accounts --account-code Cash\"],\n successTemplate: \"Accounts created\",\n },\n {\n name: \"treasury bank-accounts\",\n description: \"Register a new bank account\",\n route: { method: \"POST\", path: \"/v1/treasury/bank-accounts\" },\n entity: true,\n options: [\n { flags: \"--account-type <account-type>\", description: \"Account type (checking, savings)\", choices: [\"checking\", \"savings\"] },\n { flags: \"--bank-name <bank-name>\", description: \"Bank name\", required: true },\n ],\n examples: [\"corp treasury bank-accounts --bank-name 'bank-name'\", \"corp treasury bank-accounts --json\"],\n successTemplate: \"Bank Accounts created\",\n },\n {\n name: \"treasury chart-of-accounts\",\n description: \"View chart of accounts for an entity\",\n route: { method: \"GET\", path: \"/v1/treasury/chart-of-accounts/{eid}\" },\n entity: true,\n display: { title: \"Treasury Chart Of Accounts\", cols: [\"accounts>Accounts\", \"#entity_id>ID\"] },\n examples: [\"corp treasury chart-of-accounts\", \"corp treasury chart-of-accounts --json\"],\n },\n {\n name: \"treasury invoices\",\n description: \"Create a new invoice\",\n route: { method: \"POST\", path: \"/v1/treasury/invoices\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--customer-name <customer-name>\", description: \"Customer name for the invoice\", required: true },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--due-date <due-date>\", description: \"Due date (ISO 8601, e.g. 2026-06-30)\", required: true },\n ],\n examples: [\"corp treasury invoices --amount-cents 'amount-cents' --customer-name 'customer-name' --description 'description' --due-date 'due-date'\"],\n successTemplate: \"Invoices created\",\n },\n {\n name: \"treasury journal-entries\",\n description: \"Create a journal entry\",\n route: { method: \"POST\", path: \"/v1/treasury/journal-entries\" },\n entity: true,\n options: [\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--effective-date <effective-date>\", description: \"Effective Date\", required: true },\n { flags: \"--lines <lines>\", description: \"Lines\", required: true, type: \"array\" },\n ],\n examples: [\"corp treasury journal-entries --description 'description' --effective-date 'effective-date' --lines 'lines'\"],\n successTemplate: \"Journal Entries created\",\n },\n {\n name: \"treasury payment-intents\",\n description: \"Create a payment intent\",\n route: { method: \"POST\", path: \"/v1/treasury/payment-intents\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--currency <currency>\", description: \"Currency code (e.g. USD)\" },\n { flags: \"--description <description>\", description: \"Description text\" },\n ],\n examples: [\"corp treasury payment-intents --amount-cents 'amount-cents'\", \"corp treasury payment-intents --json\"],\n successTemplate: \"Payment Intents created\",\n },\n {\n name: \"treasury payouts\",\n description: \"Create a payout\",\n route: { method: \"POST\", path: \"/v1/treasury/payouts\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--description <description>\", description: \"Description text\" },\n { flags: \"--destination <destination>\", description: \"Destination\", required: true },\n ],\n examples: [\"corp treasury payouts --amount-cents 'amount-cents' --destination 'destination'\", \"corp treasury payouts --json\"],\n successTemplate: \"Payouts created\",\n },\n {\n name: \"treasury seed-chart-of-accounts\",\n description: \"Initialize chart of accounts for an entity\",\n route: { method: \"POST\", path: \"/v1/treasury/seed-chart-of-accounts\" },\n entity: true,\n options: [\n { flags: \"--template <template>\", description: \"Template string with {{secret}} placeholders\" },\n ],\n examples: [\"corp treasury seed-chart-of-accounts\", \"corp treasury seed-chart-of-accounts --json\"],\n successTemplate: \"Seed Chart Of Accounts created\",\n },\n {\n name: \"treasury stripe-accounts\",\n description: \"Register a Stripe account\",\n route: { method: \"POST\", path: \"/v1/treasury/stripe-accounts\" },\n entity: true,\n examples: [\"corp treasury stripe-accounts\"],\n successTemplate: \"Stripe Accounts created\",\n },\n\n];","import type { CommandDef } from \"./types.js\";\n\nexport const branchCommands: CommandDef[] = [\n {\n name: \"branches\",\n description: \"List branches for an entity repo\",\n route: { method: \"GET\", path: \"/v1/branches\" },\n entity: \"query\",\n display: {\n title: \"Branches\",\n cols: [\"name>Branch\", \"head_oid>HEAD\"],\n },\n examples: [\"corp branches\", \"corp branches --json\"],\n },\n {\n name: \"branches create\",\n description: \"Create a new branch from an existing one\",\n route: { method: \"POST\", path: \"/v1/branches\" },\n entity: \"query\",\n options: [\n { flags: \"--name <name>\", description: \"Branch name\", required: true },\n { flags: \"--from <branch>\", description: \"Base branch (default: main)\", default: \"main\" },\n ],\n successTemplate: \"Branch {branch} created at {base_commit}\",\n examples: [\"corp branches create --name 'name'\", \"corp branches create --json\"],\n },\n {\n name: \"branches merge\",\n description: \"Merge a branch into another (default: main)\",\n route: { method: \"POST\", path: \"/v1/branches/{pos}/merge\" },\n entity: \"query\",\n args: [{ name: \"branch\", required: true, description: \"Branch to merge\" }],\n options: [\n { flags: \"--into <branch>\", description: \"Target branch (default: main)\", default: \"main\" },\n { flags: \"--squash\", description: \"Squash merge (default: true)\" },\n ],\n successTemplate: \"Merge {strategy}: {commit}\",\n examples: [\"corp branches merge <branch>\", \"corp branches merge --json\"],\n },\n {\n name: \"branches delete\",\n description: \"Delete a branch\",\n route: { method: \"DELETE\", path: \"/v1/branches/{pos}\" },\n entity: \"query\",\n args: [{ name: \"branch\", required: true, description: \"Branch to delete\" }],\n successTemplate: \"Branch deleted\",\n examples: [\"corp branches delete <branch>\"],\n },\n {\n name: \"branches prune\",\n description: \"Prune a merged branch\",\n route: { method: \"POST\", path: \"/v1/branches/{pos}/prune\" },\n entity: \"query\",\n args: [{ name: \"branch\", required: true, description: \"Branch to prune\" }],\n successTemplate: \"Branch pruned\",\n examples: [\"corp branches prune <branch>\"],\n },\n];","import type { CommandDef, WebRouteEntry } from \"./types.js\";\n\n// Domain registries — uncomment as they're created\nimport { workspaceCommands } from \"./workspace.js\";\nimport { entityCommands } from \"./entities.js\";\nimport { formationCommands } from \"./formation.js\";\nimport { capTableCommands } from \"./cap-table.js\";\nimport { financeCommands } from \"./finance.js\";\nimport { governanceCommands } from \"./governance.js\";\nimport { documentCommands } from \"./documents.js\";\nimport { complianceCommands } from \"./compliance.js\";\nimport { agentCommands } from \"./agents.js\";\nimport { workItemCommands } from \"./work-items.js\";\nimport { serviceCommands } from \"./services.js\";\nimport { adminCommands } from \"./admin.js\";\nimport { executionCommands } from \"./execution.js\";\nimport { secretProxyCommands } from \"./secret-proxies.js\";\nimport { treasuryCommands } from \"./treasury.js\";\nimport { branchCommands } from \"./branches.js\";\n\nexport const registry: CommandDef[] = [\n ...workspaceCommands,\n ...entityCommands,\n ...formationCommands,\n ...capTableCommands,\n ...financeCommands,\n ...governanceCommands,\n ...documentCommands,\n ...complianceCommands,\n ...agentCommands,\n ...workItemCommands,\n ...serviceCommands,\n ...adminCommands,\n ...executionCommands,\n ...secretProxyCommands,\n ...treasuryCommands,\n ...branchCommands,\n];\n\n/** Attach produces/successTemplate to a web-route entry if present on the CommandDef */\nfunction attachProducesFields(entry: WebRouteEntry, cmd: CommandDef): WebRouteEntry {\n if (cmd.produces) entry.produces = cmd.produces;\n if (cmd.successTemplate) entry.successTemplate = cmd.successTemplate;\n return entry;\n}\n\n/** Generate web-routes.json manifest from registry */\nexport function generateWebRoutes(commands: CommandDef[]): { commands: Record<string, WebRouteEntry> } {\n const entries: Record<string, WebRouteEntry> = {};\n for (const cmd of commands) {\n if (cmd.hidden) continue;\n if (cmd.local) {\n entries[cmd.name] = { local: true };\n continue;\n }\n const entry: WebRouteEntry = {};\n // Route info — always emit path when available so the web generic executor can use it\n if (cmd.route) {\n entry.method = cmd.route.method;\n entry.path = cmd.route.path;\n if (cmd.route.method !== \"GET\") entry.write = true;\n }\n // Entity scoping\n if (cmd.entity !== undefined) entry.entity = cmd.entity;\n // Display metadata\n if (cmd.display) {\n entry.title = cmd.display.title;\n if (cmd.display.cols) entry.cols = cmd.display.cols;\n if (cmd.display.listKey) entry.listKey = cmd.display.listKey;\n }\n if (cmd.optQP) entry.optQP = cmd.optQP;\n // Custom handler flag — tells web CLI a CUSTOM handler should override generic\n if (cmd.handler) entry.custom = true;\n // Skip commands with no route and no handler (nothing the web CLI can do)\n if (!cmd.route && !cmd.handler) continue;\n entries[cmd.name] = attachProducesFields(entry, cmd);\n }\n return { commands: entries };\n}\n\n/** Generate cli-schema.json from registry (for tab completion) */\nexport function generateSchema(commands: CommandDef[], programName: string, version: string): unknown {\n // Build hierarchical structure from flat command list\n // Group by parent: \"governance seats\" -> parent \"governance\", child \"seats\"\n\n interface SchemaCmd {\n path: string;\n name: string;\n description: string;\n aliases: string[];\n arguments: { name: string; required: boolean; variadic: boolean }[];\n options: {\n flags: string;\n name: string;\n description: string;\n required: boolean;\n mandatory: boolean;\n variadic: boolean;\n choices?: string[];\n }[];\n examples?: string[];\n subcommands: SchemaCmd[];\n }\n\n const parentMap = new Map<string, SchemaCmd>();\n const topLevel: SchemaCmd[] = [];\n\n for (const cmd of commands) {\n if (cmd.hidden) continue;\n const parts = cmd.name.split(\" \");\n const entry: SchemaCmd = {\n path: `${programName} ${cmd.name}`,\n name: parts[parts.length - 1],\n description: cmd.description,\n aliases: cmd.aliases || [],\n arguments: (cmd.args || []).map((a) => ({\n name: a.name,\n required: a.required ?? false,\n variadic: a.variadic ?? false,\n })),\n options: [\n // Always include --json\n {\n flags: \"--json\",\n name: \"json\",\n description: \"Output as JSON\",\n required: false,\n mandatory: false,\n variadic: false,\n },\n // Entity option if applicable\n ...(cmd.entity\n ? [\n {\n flags: \"--entity-id <ref>\",\n name: \"entityId\",\n description: \"Entity reference\",\n required: false,\n mandatory: false,\n variadic: false,\n },\n ]\n : []),\n // Dry run if applicable\n ...(cmd.dryRun\n ? [\n {\n flags: \"--dry-run\",\n name: \"dryRun\",\n description: \"Preview without executing\",\n required: false,\n mandatory: false,\n variadic: false,\n },\n ]\n : []),\n // Command-specific options\n ...(cmd.options || []).map((o) => ({\n flags: o.flags,\n name: o.flags.replace(/^--/, \"\").split(/[\\s,<]/)[0],\n description: o.description,\n required: o.required ?? false,\n mandatory: o.required ?? false,\n variadic: false,\n ...(o.choices && { choices: o.choices }),\n })),\n ],\n ...(cmd.examples?.length ? { examples: cmd.examples } : {}),\n subcommands: [],\n };\n\n if (parts.length === 1) {\n topLevel.push(entry);\n parentMap.set(parts[0], entry);\n } else {\n const parentName = parts[0];\n let parent = parentMap.get(parentName);\n if (!parent) {\n // Auto-create parent stub\n parent = {\n path: `${programName} ${parentName}`,\n name: parentName,\n description: \"\",\n aliases: [],\n arguments: [],\n options: [],\n subcommands: [],\n };\n topLevel.push(parent);\n parentMap.set(parentName, parent);\n }\n parent.subcommands.push(entry);\n }\n }\n\n return {\n name: programName,\n version,\n description: \"corp — Corporate governance from the terminal\",\n generated_at: new Date().toISOString(),\n commands: topLevel,\n };\n}\n","import { createRequire } from \"node:module\";\nimport { buildCLI } from \"./cli.js\";\nimport { registry } from \"./registry/index.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../package.json\");\n\nconst program = buildCLI(registry, pkg.version);\nprogram.parseAsync(process.argv).catch((err) => {\n console.error(err);\n process.exit(1);\n});\n","import { Command, Option } from \"commander\";\nimport type { CommandDef, CommandContext } from \"./registry/types.js\";\nimport { executeGenericRead, executeGenericWrite } from \"./generic-executor.js\";\nimport { createWriter } from \"./writer.js\";\nimport { requireConfig, resolveEntityId } from \"./config.js\";\nimport { CorpAPIClient } from \"./api-client.js\";\nimport { ReferenceResolver } from \"./references.js\";\n\n/**\n * Build a Commander program from a flat array of CommandDef objects.\n *\n * Top-level commands (name has no space) are added directly to the program.\n * Sub-commands (e.g. \"governance seats\") are grouped under a parent command\n * whose name is the first word.\n */\nexport function buildCLI(commands: CommandDef[], version: string): Command {\n const program = new Command();\n program\n .name(\"corp\")\n .description(\"corp — Corporate governance from the terminal\")\n .version(version)\n .enablePositionalOptions();\n program.option(\"-q, --quiet\", \"Only output the resource ID (for scripting)\");\n program.action(() => {\n program.outputHelp();\n });\n program.addHelpText(\n \"after\",\n '\\nTip: Run \"corp next\" to see your recommended next actions.\\n',\n );\n\n // ── Group commands: top-level vs subcommands ──────────────────────────────\n\n const topLevel: CommandDef[] = [];\n const children = new Map<string, CommandDef[]>();\n\n for (const def of commands) {\n const parts = def.name.split(\" \");\n if (parts.length === 1) {\n topLevel.push(def);\n } else {\n const parent = parts[0];\n if (!children.has(parent)) children.set(parent, []);\n children.get(parent)!.push(def);\n }\n }\n\n // ── Create top-level commands ─────────────────────────────────────────────\n\n const parentCmds = new Map<string, Command>();\n for (const def of topLevel) {\n const cmd = wireCommand(program, def);\n parentCmds.set(def.name, cmd);\n }\n\n // ── Create subcommands ────────────────────────────────────────────────────\n\n for (const [parentName, childDefs] of children) {\n let parentCmd = parentCmds.get(parentName);\n if (!parentCmd) {\n // Parent not explicitly defined — create a stub so children have a home.\n const parentDescriptions: Record<string, string> = {\n workspaces: \"Workspace management\",\n workspace: \"Workspace settings\",\n equity: \"Equity system (low-level grants, holders, instruments)\",\n execution: \"Execution intents, obligations, and approval artifacts\",\n meetings: \"Meeting management (convene, adjourn, notice)\",\n compliance: \"Compliance escalations and monitoring\",\n contractors: \"Contractor classification\",\n admin: \"Admin tools (audit, billing, SSH keys, secrets)\",\n auth: \"Authentication and API key management\",\n references: \"Reference tracking and sync\",\n secrets: \"Secret management and proxy configuration\",\n \"document-requests\": \"Document request fulfillment\",\n intents: \"Execution intent management\",\n \"bank-accounts\": \"Bank account management\",\n \"journal-entries\": \"Ledger journal entries\",\n ledger: \"Ledger operations and reconciliation\",\n payroll: \"Payroll runs\",\n payments: \"Payment submission and tracking\",\n invoices: \"Invoice management\",\n treasury: \"Treasury, invoices, payments, and payouts\",\n \"governance-seats\": \"Governance seat management\",\n \"governance-bodies\": \"Governance body management\",\n \"human-obligations\": \"Human obligation fulfillment\",\n \"ssh-keys\": \"SSH key management\",\n \"secret-proxies\": \"Secret proxy configuration\",\n formations: \"Formation workflows (low-level API)\",\n valuations: \"Valuation management\",\n branches: \"Git branch management\",\n digests: \"Digest generation and viewing\",\n obligations: \"Obligation tracking and fulfillment\",\n \"spending-limits\": \"Spending limit management\",\n receipts: \"Execution receipts\",\n \"share-transfers\": \"Share transfer workflows\",\n \"safe-notes\": \"SAFE note management\",\n distributions: \"Distribution management\",\n deadlines: \"Compliance deadline management\",\n };\n parentCmd = program.command(parentName).description(parentDescriptions[parentName] ?? \"\");\n parentCmds.set(parentName, parentCmd);\n }\n for (const def of childDefs) {\n const childName = def.name.split(\" \").slice(1).join(\" \");\n wireCommand(parentCmd, { ...def, name: childName });\n }\n }\n\n return program;\n}\n\n// ── Internal: attach a single CommandDef to a parent Command ────────────────\n\nfunction wireCommand(parent: Command, def: CommandDef): Command {\n // Build command string with positional args\n let cmdStr = def.name;\n for (const arg of def.args || []) {\n if (arg.variadic) {\n cmdStr += arg.required ? ` <${arg.name}...>` : ` [${arg.name}...]`;\n } else {\n cmdStr += arg.required ? ` <${arg.name}>` : ` [${arg.name}]`;\n }\n }\n\n const cmd = def.hidden\n ? parent.command(cmdStr, { hidden: true }).description(def.description)\n : parent.command(cmdStr).description(def.description);\n\n // Aliases\n for (const alias of def.aliases || []) {\n cmd.alias(alias);\n }\n\n // Standard options — every command gets --json (unless already defined in options)\n const definedFlags = new Set((def.options || []).map((o) => o.flags));\n if (!definedFlags.has(\"--json\")) {\n cmd.option(\"--json\", \"Output as JSON\");\n }\n\n // Entity-scoped commands get --entity-id\n if (def.entity && !definedFlags.has(\"--entity-id <ref>\")) {\n cmd.option(\n \"--entity-id <ref>\",\n \"Entity reference (overrides active entity and parent command)\",\n );\n }\n\n // Dry-run support\n if (def.dryRun && !definedFlags.has(\"--dry-run\")) {\n cmd.option(\"--dry-run\", \"Preview the request without executing\");\n }\n\n // Command-specific options\n for (const opt of def.options || []) {\n let coerce: ((val: string, prev?: unknown) => unknown) | undefined;\n if (opt.type === \"int\") coerce = (v) => parseInt(v, 10);\n else if (opt.type === \"float\") coerce = (v) => parseFloat(v);\n else if (opt.type === \"array\")\n coerce = (v: string, prev: unknown) => [\n ...((prev as string[]) || []),\n v,\n ];\n\n // Hidden options: accepted by parser but not shown in --help\n if (opt.hidden) {\n const o = new Option(opt.flags, opt.description);\n o.hideHelp();\n if (coerce) o.argParser(coerce as (value: string, previous: unknown) => unknown);\n cmd.addOption(o);\n continue;\n }\n\n // When choices are specified, use Commander's Option class with .choices()\n // so Commander validates the value at parse time.\n if (opt.choices && opt.choices.length > 0) {\n const o = new Option(opt.flags, opt.description);\n o.choices(opt.choices);\n if (opt.required) o.makeOptionMandatory(true);\n if (opt.default !== undefined) o.default(opt.default);\n if (coerce) o.argParser(coerce as (value: string, previous: unknown) => unknown);\n cmd.addOption(o);\n } else {\n const defaultVal = opt.default as string | boolean | string[] | undefined;\n if (opt.required) {\n if (coerce) cmd.requiredOption(opt.flags, opt.description, coerce, opt.default);\n else cmd.requiredOption(opt.flags, opt.description, defaultVal);\n } else {\n if (coerce) cmd.option(opt.flags, opt.description, coerce, opt.default);\n else cmd.option(opt.flags, opt.description, defaultVal);\n }\n }\n }\n\n // Help text — examples\n if (def.examples?.length) {\n cmd.addHelpText(\n \"after\",\n \"\\nExamples:\\n\" + def.examples.map((e) => ` $ ${e}`).join(\"\\n\") + \"\\n\",\n );\n }\n\n // Pass-through options (e.g. for commands that forward unknown flags)\n if (def.passThroughOptions) {\n cmd.enablePositionalOptions().passThroughOptions();\n }\n\n // ── Action handler ──────────────────────────────────────────────────────\n\n cmd.action(async (...actionArgs: unknown[]) => {\n // Commander passes: (positionalArg1, ..., positionalArgN, opts, command)\n const cmdInstance = actionArgs[actionArgs.length - 1] as Command;\n const opts = actionArgs[actionArgs.length - 2] as Record<string, unknown>;\n const positional = actionArgs.slice(0, -2).map(String);\n\n // Merge parent opts (child values take precedence over parent)\n const parentOpts = cmdInstance.parent?.opts() ?? {};\n const mergedOpts: Record<string, unknown> = { ...parentOpts, ...opts };\n // Inherit specific options from parent when child doesn't set them\n for (const key of [\"json\", \"entityId\", \"dryRun\", \"quiet\"]) {\n if (mergedOpts[key] === undefined && parentOpts[key] !== undefined) {\n mergedOpts[key] = parentOpts[key];\n }\n }\n\n const quiet = !!mergedOpts.quiet;\n const dryRun = !!mergedOpts.dryRun;\n const writer = createWriter();\n\n // ── Local commands: no API client needed ───────────────────────────\n\n if (def.local) {\n if (def.handler) {\n try {\n await def.handler({\n client: null as unknown as CommandContext[\"client\"],\n positional,\n opts: mergedOpts,\n resolver: null as unknown as CommandContext[\"resolver\"],\n writer,\n quiet,\n dryRun,\n });\n } catch (err: unknown) {\n writer.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n }\n return;\n }\n\n // ── API commands: set up client + resolver ─────────────────────────\n\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n // Resolve entity ID for entity-scoped commands.\n // For generic reads (display without handler), let the generic executor\n // handle missing entity gracefully rather than hard-exiting here.\n let entityId: string | undefined;\n if (def.entity) {\n const explicitEid = mergedOpts.entityId as string | undefined;\n if (def.handler) {\n // Custom handler — use resolveEntityId which exits on missing\n entityId = resolveEntityId(cfg, explicitEid);\n } else {\n // Generic read — soft resolve; executor handles missing entity\n entityId = explicitEid || (cfg.active_entity_id || undefined);\n if (!entityId && cfg.workspace_id && cfg.active_entity_ids?.[cfg.workspace_id]) {\n entityId = cfg.active_entity_ids[cfg.workspace_id];\n }\n }\n }\n\n const ctx: CommandContext = {\n client,\n positional,\n opts: mergedOpts,\n entityId,\n resolver,\n writer,\n quiet,\n dryRun,\n };\n\n try {\n if (def.handler) {\n await def.handler(ctx);\n } else if (def.display) {\n await executeGenericRead(def, ctx);\n } else if (def.route && def.route.method !== \"GET\") {\n await executeGenericWrite(def, ctx);\n } else {\n writer.error(`Command \"${def.name}\" has no handler or display config`);\n process.exit(1);\n }\n\n // After generic write commands with produces metadata, print a @last hint.\n // Skip for commands with custom handlers — they manage their own output.\n if (def.produces?.kind && !def.handler && !quiet && !mergedOpts.json) {\n const kind = def.produces.kind as string;\n const lastId = resolver.getLastId(kind as Parameters<typeof resolver.getLastId>[0]);\n if (lastId) {\n const shortRef = lastId.length > 12 ? lastId.slice(0, 8) + \"…\" : lastId;\n console.log(` Ref: @last:${kind} → ${shortRef}`);\n }\n }\n } catch (err: unknown) {\n writer.error(`Failed: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n });\n\n return cmd;\n}\n","import type { CommandDef, CommandContext } from \"./registry/types.js\";\nimport { withSpinner } from \"./spinner.js\";\n\n// ── Formatting helpers (local versions matching output.ts private helpers) ──\n\nfunction s(val: unknown, maxLen?: number): string {\n const str = val == null ? \"\" : String(val);\n if (maxLen && str.length > maxLen) return str.slice(0, maxLen);\n return str;\n}\n\nfunction money(val: unknown): string {\n if (typeof val === \"number\") {\n const dollars = val / 100;\n return `$${dollars.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;\n }\n return s(val);\n}\n\nfunction fmtDate(val: unknown): string {\n const str = s(val);\n if (!str) return \"\";\n const parsed = new Date(str);\n return Number.isNaN(parsed.getTime()) ? str : parsed.toISOString().slice(0, 10);\n}\n\nfunction shortId(val: string): string {\n return val.length > 8 ? val.slice(0, 8) + \"\\u2026\" : val;\n}\n\n// ── Column spec parsing ──\n\ninterface ColSpec {\n keys: string[];\n label: string;\n fmt: \"money\" | \"date\" | \"id\" | null;\n}\n\nfunction parseCol(spec: string): ColSpec {\n let fmt: ColSpec[\"fmt\"] = null;\n let rest = spec;\n if (rest[0] === \"$\") {\n fmt = \"money\";\n rest = rest.slice(1);\n } else if (rest[0] === \"@\") {\n fmt = \"date\";\n rest = rest.slice(1);\n } else if (rest[0] === \"#\") {\n fmt = \"id\";\n rest = rest.slice(1);\n }\n const [fieldPart, label] = rest.split(\">\");\n return { keys: fieldPart.split(\"|\"), label: label || fieldPart, fmt };\n}\n\nfunction getField(obj: Record<string, unknown>, keys: string[]): unknown {\n for (const k of keys) {\n if (obj[k] != null) return obj[k];\n }\n return null;\n}\n\nfunction fmtField(val: unknown, fmt: ColSpec[\"fmt\"]): string {\n if (val == null) return \"\";\n if (fmt === \"money\") return money(val);\n if (fmt === \"date\") return fmtDate(val);\n if (fmt === \"id\") return shortId(String(val));\n return String(val);\n}\n\n// ── Auto-detect columns from first item ──\n\nfunction autoCols(items: unknown[]): ColSpec[] {\n if (!items.length) return [];\n const sample = items[0];\n if (typeof sample !== \"object\" || sample === null) return [];\n\n const keys = Object.keys(sample as Record<string, unknown>);\n const priority = [\n \"name\", \"legal_name\", \"title\", \"slug\", \"symbol\", \"type\", \"kind\",\n \"entity_type\", \"body_type\", \"status\", \"effective_status\", \"category\", \"email\",\n \"description\", \"amount_cents\", \"total_cents\", \"due_date\", \"due_at\", \"created_at\", \"date\",\n ];\n\n const picked: ColSpec[] = [];\n for (const p of priority) {\n if (keys.includes(p) && picked.length < 5) {\n let fmt: ColSpec[\"fmt\"] = null;\n if (p.endsWith(\"_cents\")) fmt = \"money\";\n else if (p.includes(\"date\") || p.endsWith(\"_at\")) fmt = \"date\";\n const label = p\n .replace(/_cents$/, \"\")\n .replace(/_/g, \" \")\n .replace(/\\b\\w/g, (ch) => ch.toUpperCase());\n picked.push({ keys: [p], label, fmt });\n }\n }\n\n // Add an ID column if available\n const idKeys = keys.filter((k) => k.endsWith(\"_id\") && k !== \"workspace_id\" && k !== \"entity_id\");\n if (idKeys.length && picked.length < 6) {\n picked.push({ keys: [idKeys[0]], label: \"ID\", fmt: \"id\" });\n }\n\n return picked;\n}\n\n// ── Panel display for single objects ──\n\nfunction displayPanel(data: Record<string, unknown>, title: string, ctx: CommandContext): void {\n const entries = Object.entries(data).filter(\n ([k, v]) => v != null && typeof v !== \"object\" && k !== \"workspace_id\",\n );\n const lines = entries.slice(0, 15).map(([k, v]) => {\n const label = k\n .replace(/_/g, \" \")\n .replace(/\\b\\w/g, (ch) => ch.toUpperCase());\n let formatted: string;\n if (k.endsWith(\"_cents\") && typeof v === \"number\") formatted = money(v);\n else if ((k.includes(\"date\") || k.endsWith(\"_at\")) && v) formatted = fmtDate(v);\n else if (k.endsWith(\"_id\")) formatted = shortId(String(v));\n else formatted = String(v);\n return `${label}: ${formatted}`;\n });\n ctx.writer.panel(title, \"blue\", lines);\n}\n\n// ── Main executor ──\n\nexport async function executeGenericRead(def: CommandDef, ctx: CommandContext): Promise<void> {\n if (!def.route?.path) {\n ctx.writer.error(\"No route defined for this command\");\n return;\n }\n\n let path = def.route.path;\n const qp: Record<string, string> = {};\n let posIdx = 0;\n\n // Resolve {eid}\n if (def.entity) {\n let eid: string | undefined;\n const explicitEid = ctx.opts[\"entity-id\"] as string | undefined;\n\n if (explicitEid) {\n eid = await ctx.resolver.resolveEntity(explicitEid);\n } else if (def.entity === true && !path.includes(\"{pos}\") && ctx.positional[posIdx]) {\n eid = await ctx.resolver.resolveEntity(ctx.positional[posIdx++]);\n } else {\n eid = ctx.entityId; // active entity from config\n }\n\n if (eid) {\n path = path.replace(\"{eid}\", encodeURIComponent(eid));\n if (def.entity === \"query\") qp.entity_id = eid;\n } else if (path.includes(\"{eid}\")) {\n ctx.writer.error(\"Entity ID required. Use --entity-id or set active entity with 'corp use <name>'.\");\n return;\n }\n }\n\n // Resolve {pos}\n if (path.includes(\"{pos}\")) {\n if (!ctx.positional[posIdx]) {\n ctx.writer.error(\"Missing required argument (ID or reference).\");\n return;\n }\n path = path.replace(\"{pos}\", encodeURIComponent(ctx.positional[posIdx++]));\n }\n\n // Resolve workspace ID placeholders\n path = path.replace(\"{wid}\", encodeURIComponent(ctx.client.workspaceId));\n path = path.replace(\"{workspace_id}\", encodeURIComponent(ctx.client.workspaceId));\n\n // Forward optQP options as query params\n if (def.optQP) {\n for (const optName of def.optQP) {\n const val = ctx.opts[optName];\n if (val) qp[optName] = String(val);\n }\n }\n\n // Fetch\n const data = await withSpinner(\n \"Loading\",\n () => ctx.client.fetchJSON(path, Object.keys(qp).length ? qp : undefined),\n ctx.opts.json as boolean,\n );\n\n // JSON output\n if (ctx.opts.json) {\n ctx.writer.json(data);\n return;\n }\n\n // Unwrap listKey\n let items = data;\n if (def.display?.listKey && data && !Array.isArray(data)) {\n items = (data as Record<string, unknown>)[def.display.listKey] || [];\n }\n\n // Display\n const title = def.display?.title || def.name;\n\n if (Array.isArray(items)) {\n const cols = def.display?.cols ? def.display.cols.map(parseCol) : autoCols(items);\n if (!cols.length && items.length) {\n ctx.writer.json(items); // fallback when no columns can be determined\n return;\n }\n const headers = cols.map((c) => c.label);\n const rows = items.map((item) =>\n cols.map((col) => fmtField(getField(item as Record<string, unknown>, col.keys), col.fmt)),\n );\n ctx.writer.table(title, headers, rows);\n } else if (data && typeof data === \"object\") {\n // Single object -> panel\n displayPanel(data as Record<string, unknown>, title, ctx);\n } else {\n ctx.writer.json(data);\n }\n}\n\n/**\n * Generic write executor for POST/PATCH/DELETE commands that lack a custom handler.\n * Resolves path placeholders, collects option values as the body, and calls submitJSON.\n */\nexport async function executeGenericWrite(def: CommandDef, ctx: CommandContext): Promise<void> {\n if (!def.route?.path || !def.route?.method) {\n ctx.writer.error(\"No route defined for this command\");\n return;\n }\n\n let path = def.route.path;\n let posIdx = 0;\n\n // Resolve {eid}\n if (def.entity) {\n let eid: string | undefined;\n const explicitEid = ctx.opts[\"entity-id\"] as string | undefined;\n if (explicitEid) {\n eid = await ctx.resolver.resolveEntity(explicitEid);\n } else if (def.entity === true && !path.includes(\"{pos}\") && ctx.positional[posIdx]) {\n eid = await ctx.resolver.resolveEntity(ctx.positional[posIdx++]);\n } else {\n eid = ctx.entityId;\n }\n if (eid) {\n path = path.replace(\"{eid}\", encodeURIComponent(eid));\n } else if (path.includes(\"{eid}\")) {\n ctx.writer.error(\"Entity ID required. Use --entity-id or set active entity with 'corp use <name>'.\");\n return;\n }\n }\n\n // Resolve {pos} and {pos2}\n if (path.includes(\"{pos}\")) {\n if (!ctx.positional[posIdx]) {\n ctx.writer.error(\"Missing required argument (ID or reference).\");\n return;\n }\n path = path.replace(\"{pos}\", encodeURIComponent(ctx.positional[posIdx++]));\n }\n if (path.includes(\"{pos2}\")) {\n if (!ctx.positional[posIdx]) {\n ctx.writer.error(\"Missing required second argument (ID or reference).\");\n return;\n }\n path = path.replace(\"{pos2}\", encodeURIComponent(ctx.positional[posIdx++]));\n }\n\n // Resolve workspace placeholders\n path = path.replace(\"{wid}\", encodeURIComponent(ctx.client.workspaceId));\n path = path.replace(\"{workspace_id}\", encodeURIComponent(ctx.client.workspaceId));\n\n // Build body from defined options\n const body: Record<string, unknown> = {};\n if (def.entity && ctx.entityId) {\n body.entity_id = ctx.entityId;\n }\n for (const opt of def.options ?? []) {\n // Extract camelCase key from flags like \"--foo-bar <val>\"\n const match = opt.flags.match(/^--([a-z0-9-]+)/);\n if (!match) continue;\n const camelKey = match[1].replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());\n const val = ctx.opts[camelKey];\n if (val != null && camelKey !== \"entityId\" && camelKey !== \"json\") {\n body[match[1].replace(/-/g, \"_\")] = val;\n }\n }\n\n if (ctx.dryRun) {\n ctx.writer.dryRun(def.name.replace(/ /g, \".\"), body);\n return;\n }\n\n const data = await withSpinner(\n \"Submitting\",\n () => ctx.client.submitJSON(def.route!.method, path, Object.keys(body).length ? body : undefined),\n ctx.opts.json as boolean,\n );\n\n if (ctx.opts.json) {\n ctx.writer.json(data);\n return;\n }\n\n // Try to extract an ID from the response for a friendly message\n const result = data as Record<string, unknown> | null;\n const idKey = result ? Object.keys(result).find((k) => k.endsWith(\"_id\")) : undefined;\n const idVal = idKey && result ? result[idKey] : undefined;\n ctx.writer.success(`${def.description ?? def.name}: ${idVal ?? \"OK\"}`);\n}\n","import chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport { printError, printSuccess, printWarning, printJson, printWriteResult, printDryRun } from \"./output.js\";\nimport type { OutputWriter } from \"./registry/types.js\";\n\nexport function createWriter(): OutputWriter {\n return {\n writeln(text = \"\") {\n console.log(text);\n },\n json(data) {\n printJson(data);\n },\n table(title, columns, rows) {\n if (rows.length === 0) {\n console.log(`No ${title.toLowerCase()} found.`);\n return;\n }\n console.log(`\\n${chalk.bold(title)}`);\n const table = new Table({ head: columns.map((c) => chalk.dim(c)) });\n for (const row of rows) table.push(row.map((cell) => String(cell ?? \"\")));\n console.log(table.toString());\n },\n panel(title, color, lines) {\n const colorFn = (chalk as unknown as Record<string, typeof chalk.blue>)[color] || chalk.blue;\n const w = 50;\n console.log(colorFn(\"─\".repeat(w)));\n console.log(colorFn.bold(` ${title}`));\n console.log(colorFn(\"─\".repeat(w)));\n for (const l of lines) console.log(` ${l}`);\n console.log(colorFn(\"─\".repeat(w)));\n },\n error(msg) {\n printError(msg);\n },\n success(msg) {\n printSuccess(msg);\n },\n warning(msg) {\n printWarning(msg);\n },\n writeResult(result, message, options) {\n printWriteResult(result, message, options ?? {});\n },\n quietId(id) {\n console.log(id);\n },\n dryRun(operation, payload) {\n printDryRun(operation, payload);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AA4FO,SAAS,YAAY,OAAuB;AACjD,QAAM,OAAmB,CAAC;AAC1B,WAAS,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;AACzC,UAAM,WAAW,UAAU,CAAC;AAC5B,UAAM,IAAI,SAAS;AACnB,UAAM,UAAU,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,QAAQ,CAAC,CAAC;AAClD,UAAM,QAAQ,SAAS,CAAC,GAAG,UAAU;AACr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AAM,YAAY,IAAI,IAAI,oCAAoC;AACrE,gBAAQ,KAAK,CAAC;AAAA,MAChB;AAIA,UAAI,IAAI,UAAU,QAAQ,CAAC,IAAI,WAAW,CAAC,SAAS,CAAC,WAAW,MAAM;AACpE,cAAM,OAAO,IAAI,SAAS;AAC1B,cAAM,SAAS,SAAS,UAAU,IAAgD;AAClF,YAAI,QAAQ;AACV,gBAAM,WAAW,OAAO,SAAS,KAAK,OAAO,MAAM,GAAG,CAAC,IAAI,WAAM;AACjE,kBAAQ,IAAI,gBAAgB,IAAI,WAAM,QAAQ,EAAE;AAAA,QAClD;AAAA,MACF;AAAA,IACF,SAAS,KAAc;AACrB,aAAO,MAAM,WAAW,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE;AAC1E,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF,CAAC;AAED,SAAO;AACT;;;ADxTA;AAEA,IAAMC,WAAU,cAAc,YAAY,GAAG;AAC7C,IAAM,MAAMA,SAAQ,iBAAiB;AAErC,IAAM,UAAU,SAAS,UAAU,IAAI,OAAO;AAC9C,QAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,QAAQ;AAC9C,UAAQ,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["shortId","describeReferenceRecord","getReferenceAlias","shortId","s","money","holders","chalk","chalk","confirm","chalk","Table","readFileSync","input","chalk","Table","formCommand","parseCsvAddress","shouldResolveEntityRefForDryRun","resolveEntityRefForFormCommand","SUPPORTED_ENTITY_TYPES","chalk","s","shortId","chalk","confirm","s","result","confirm","chalk","readFileSync","realpathSync","relative","resolve","s","confirm","chalk","actorLabel","chalk","input","select","homedir","join","existsSync","mkdirSync","init_config","resolve","result","join","homedir","chalk","resolve","confirm","s","chalk","shortId","chalk","Table","KINDS","ENTITY_SCOPED_KINDS","setupCommand","configSetCommand","configGetCommand","configListCommand","registry","generateWebRoutes","generateSchema","createRequire","require","pkg","serveCommand","demoCommand","chatCommand","apiKeysListCommand","apiKeysCreateCommand","apiKeysRevokeCommand","apiKeysRotateCommand","linkCommand","claimCommand","feedbackCommand","resolveCommand","findCommand","chalk","Table","program","require"]}
1
+ {"version":3,"sources":["../src/animation.ts","../src/spinner.ts","../src/config.ts","../src/references.ts","../src/output.ts","../src/api-client.ts","../src/registry/workspace.ts","../src/registry/entities.ts","../src/formation-automation.ts","../src/commands/form.ts","../src/registry/formation.ts","../src/registry/cap-table.ts","../src/registry/finance.ts","../src/registry/governance.ts","../src/registry/documents.ts","../src/registry/compliance.ts","../src/registry/agents.ts","../src/registry/work-items.ts","../src/registry/services.ts","../src/commands/setup.ts","../src/commands/config.ts","../src/commands/serve.ts","../src/commands/demo.ts","../src/llm.ts","../src/tools.ts","../src/chat.ts","../src/commands/api-keys.ts","../src/commands/link.ts","../src/commands/claim.ts","../src/commands/feedback.ts","../src/commands/resolve.ts","../src/commands/find.ts","../src/registry/admin.ts","../src/registry/execution.ts","../src/registry/secret-proxies.ts","../src/registry/treasury.ts","../src/registry/branches.ts","../src/registry/index.ts","../src/index.ts","../src/cli.ts","../src/generic-executor.ts","../src/writer.ts"],"sourcesContent":["/**\n * Rising cityscape boot animation — ported from packages/cli/corp/tui/widgets/mascot.py\n */\n\n// prettier-ignore\nconst BUILDINGS: string[][] = [\n [\n \" ┌┐ \",\n \" ││ \",\n \" ││ \",\n \" ┌┤├┐ \",\n \" │││││\",\n \" │││││\",\n ],\n [\n \" ╔══╗ \",\n \" ║▪▪║ \",\n \" ║▪▪║ \",\n \" ║▪▪║ \",\n \" ║▪▪║ \",\n \" ║▪▪║ \",\n \" ║▪▪║ \",\n \" ║▪▪║ \",\n ],\n [\n \" /\\\\ \",\n \" / \\\\ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n ],\n [\n \" ┌──┐ \",\n \" │≋≋│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n \" │▪▪│ \",\n ],\n [\n \" ╻ \",\n \" ┃ \",\n \" ┌┤┐ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n ],\n [\n \" ┌┐ \",\n \" ├┤ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n ],\n [\n \" ╔═══╗\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n \" ║▪ ▪║\",\n ],\n [\n \" ┬─┬ \",\n \" │~│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n \" │▪│ \",\n ],\n];\n\nconst MAX_HEIGHT = Math.max(...BUILDINGS.map((b) => b.length));\nconst TOTAL_FRAMES = MAX_HEIGHT + 4; // 15 frames, ~1.5s at 100ms\n\nconst GOLD = \"\\x1b[38;2;212;160;23m\";\nconst RESET = \"\\x1b[0m\";\n\nexport function renderFrame(frame: number): string {\n const cols: string[][] = [];\n for (let i = 0; i < BUILDINGS.length; i++) {\n const building = BUILDINGS[i];\n const h = building.length;\n const visible = Math.max(0, Math.min(h, frame - i));\n const width = building[0]?.length ?? 6;\n const blank = \" \".repeat(width);\n const col: string[] = Array(MAX_HEIGHT - visible).fill(blank);\n col.push(...building.slice(h - visible));\n cols.push(col);\n }\n\n const lines: string[] = [];\n for (let row = 0; row < MAX_HEIGHT; row++) {\n lines.push(cols.map((col) => col[row]).join(\"\"));\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Run an async function while displaying the rising cityscape animation.\n * No-ops when stdout is not a TTY (piped, CI, etc.).\n */\nexport async function withAnimation<T>(fn: () => Promise<T>): Promise<T> {\n if (!process.stdout.isTTY) {\n return fn();\n }\n\n let frame = 0;\n let animDone = false;\n const spinChars = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\n let spinIdx = 0;\n let lastLineCount = 0;\n\n const clearPrev = () => {\n if (lastLineCount > 0) {\n process.stdout.write(`\\x1b[${lastLineCount}A\\x1b[0J`);\n }\n };\n\n const drawFrame = () => {\n clearPrev();\n if (!animDone) {\n const art = renderFrame(frame);\n const output = `${GOLD}${art}${RESET}\\n`;\n process.stdout.write(output);\n lastLineCount = MAX_HEIGHT + 1;\n frame++;\n if (frame >= TOTAL_FRAMES) {\n animDone = true;\n }\n } else {\n // Dot spinner fallback after animation finishes\n const line = `${GOLD}${spinChars[spinIdx % spinChars.length]} Loading...${RESET}\\n`;\n process.stdout.write(line);\n lastLineCount = 1;\n spinIdx++;\n }\n };\n\n drawFrame();\n const timer = setInterval(drawFrame, 100);\n\n try {\n const result = await fn();\n return result;\n } finally {\n clearInterval(timer);\n clearPrev();\n }\n}\n","import { withAnimation } from \"./animation.js\";\n\n/**\n * Run an async function with a loading animation.\n * Silently skipped when `json` is truthy (pure JSON output) or non-TTY.\n */\nexport async function withSpinner<T>(\n _label: string,\n fn: () => Promise<T>,\n json?: boolean,\n): Promise<T> {\n if (json) {\n return fn();\n }\n return withAnimation(fn);\n}\n","import {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { CorpConfig } from \"./types.js\";\n\nconst CONFIG_DIR = process.env.CORP_CONFIG_DIR || join(homedir(), \".corp\");\nconst CONFIG_FILE = join(CONFIG_DIR, \"config.json\");\nconst AUTH_FILE = join(CONFIG_DIR, \"auth.json\");\nconst CONFIG_LOCK_DIR = join(CONFIG_DIR, \"config.lock\");\nconst CONFIG_LOCK_TIMEOUT_MS = 5000;\nconst CONFIG_LOCK_RETRY_MS = 25;\nconst CONFIG_STALE_LOCK_MS = 60_000;\nconst MAX_LAST_REFERENCES = 4096;\nconst TRUSTED_API_HOST_SUFFIXES = [\"thecorporation.ai\"];\n\nconst CONFIG_WAIT_BUFFER = new SharedArrayBuffer(4);\nconst CONFIG_WAIT_SIGNAL = new Int32Array(CONFIG_WAIT_BUFFER);\n\nconst ALLOWED_CONFIG_KEYS = new Set([\n \"api_url\",\n \"api_key\",\n \"workspace_id\",\n \"hosting_mode\",\n \"llm.provider\",\n \"llm.api_key\",\n \"llm.model\",\n \"llm.base_url\",\n \"user.name\",\n \"user.email\",\n \"active_entity_id\",\n \"data_dir\",\n]);\n\nconst SENSITIVE_CONFIG_KEYS = new Set([\"api_url\", \"api_key\", \"workspace_id\"]);\n\ntype CorpAuthConfig = {\n api_url?: string;\n api_key?: string;\n workspace_id?: string;\n llm?: {\n api_key?: string;\n };\n server_secrets?: {\n jwt_secret: string;\n secrets_master_key: string;\n internal_worker_token: string;\n };\n};\n\nconst DEFAULTS: CorpConfig = {\n api_url: process.env.CORP_API_URL || \"https://api.thecorporation.ai\",\n api_key: process.env.CORP_API_KEY || \"\",\n workspace_id: process.env.CORP_WORKSPACE_ID || \"\",\n hosting_mode: \"\",\n llm: {\n provider: \"anthropic\",\n api_key: process.env.CORP_LLM_API_KEY || \"\",\n model: \"claude-sonnet-4-6\",\n base_url: process.env.CORP_LLM_BASE_URL || undefined,\n },\n user: { name: \"\", email: \"\" },\n active_entity_id: \"\",\n data_dir: \"\",\n};\n\nfunction sleepSync(ms: number): void {\n Atomics.wait(CONFIG_WAIT_SIGNAL, 0, 0, ms);\n}\n\nfunction withConfigLock<T>(fn: () => T): T {\n mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });\n const startedAt = Date.now();\n while (true) {\n try {\n mkdirSync(CONFIG_LOCK_DIR, { mode: 0o700 });\n break;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw err;\n }\n try {\n const ageMs = Date.now() - statSync(CONFIG_LOCK_DIR).mtimeMs;\n if (ageMs >= CONFIG_STALE_LOCK_MS) {\n rmSync(CONFIG_LOCK_DIR, { recursive: true, force: true });\n continue;\n }\n } catch {\n // Ignore lock-stat failures and continue waiting.\n }\n if (Date.now() - startedAt >= CONFIG_LOCK_TIMEOUT_MS) {\n throw new Error(\"timed out waiting for the corp config lock\");\n }\n sleepSync(CONFIG_LOCK_RETRY_MS);\n }\n }\n\n try {\n return fn();\n } finally {\n rmSync(CONFIG_LOCK_DIR, { recursive: true, force: true });\n }\n}\n\nfunction ensureSecurePermissions(): void {\n mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });\n try {\n chmodSync(CONFIG_DIR, 0o700);\n } catch {\n // Ignore chmod failures on filesystems without POSIX permission support.\n }\n if (existsSync(CONFIG_FILE)) {\n try {\n chmodSync(CONFIG_FILE, 0o600);\n } catch {\n // Ignore chmod failures on filesystems without POSIX permission support.\n }\n }\n if (existsSync(AUTH_FILE)) {\n try {\n chmodSync(AUTH_FILE, 0o600);\n } catch {\n // Ignore chmod failures on filesystems without POSIX permission support.\n }\n }\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isLoopbackHost(hostname: string): boolean {\n return hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"::1\";\n}\n\nfunction isTrustedCorpHost(hostname: string): boolean {\n return TRUSTED_API_HOST_SUFFIXES.some(\n (suffix) => hostname === suffix || hostname.endsWith(`.${suffix}`),\n );\n}\n\nfunction allowUnsafeApiUrl(): boolean {\n return process.env.CORP_UNSAFE_API_URL === \"1\";\n}\n\nexport function validateApiUrl(value: string): string {\n const trimmed = value.trim();\n\n // Process transport: process:// or process:///path/to/binary\n if (trimmed.startsWith(\"process://\")) {\n return trimmed;\n }\n\n let parsed: URL;\n try {\n parsed = new URL(trimmed);\n } catch {\n throw new Error(\"api_url must be a valid absolute URL\");\n }\n\n if (parsed.username || parsed.password) {\n throw new Error(\"api_url must not include embedded credentials\");\n }\n\n const protocol = parsed.protocol.toLowerCase();\n const hostname = parsed.hostname.toLowerCase();\n if (protocol !== \"https:\" && !(protocol === \"http:\" && isLoopbackHost(hostname))) {\n throw new Error(\"api_url must use https, or http only for localhost/loopback development\");\n }\n if (protocol === \"https:\" && !isLoopbackHost(hostname) && !isTrustedCorpHost(hostname) && !allowUnsafeApiUrl()) {\n throw new Error(\n \"api_url must point to a trusted TheCorporation host or localhost; set CORP_UNSAFE_API_URL=1 to allow a custom self-hosted URL\",\n );\n }\n\n parsed.hash = \"\";\n return parsed.toString().replace(/\\/+$/, \"\");\n}\n\nexport function validateLlmBaseUrl(value: string): string {\n let parsed: URL;\n try {\n parsed = new URL(value.trim());\n } catch {\n throw new Error(\"llm.base_url must be a valid absolute URL\");\n }\n\n if (parsed.username || parsed.password) {\n throw new Error(\"llm.base_url must not include embedded credentials\");\n }\n\n const protocol = parsed.protocol.toLowerCase();\n const hostname = parsed.hostname.toLowerCase();\n if (protocol !== \"https:\" && !(protocol === \"http:\" && isLoopbackHost(hostname))) {\n throw new Error(\"llm.base_url must use https, or http only for localhost/loopback development\");\n }\n\n parsed.hash = \"\";\n return parsed.toString().replace(/\\/+$/, \"\");\n}\n\nfunction normalizeString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction normalizeActiveEntityMap(value: unknown): Record<string, string> | undefined {\n if (!isObject(value)) {\n return undefined;\n }\n const entries = Object.entries(value).filter(\n (entry): entry is [string, string] =>\n typeof entry[0] === \"string\" && typeof entry[1] === \"string\" && entry[1].length > 0,\n );\n if (entries.length === 0) {\n return undefined;\n }\n return Object.fromEntries(entries) as Record<string, string>;\n}\n\nfunction trimReferenceEntries(\n entries: Array<[string, string]>,\n): Array<[string, string]> {\n if (entries.length <= MAX_LAST_REFERENCES) {\n return entries;\n }\n return entries.slice(entries.length - MAX_LAST_REFERENCES);\n}\n\nfunction normalizeReferenceMap(value: unknown): Record<string, string> | undefined {\n if (!isObject(value)) {\n return undefined;\n }\n const entries = Object.entries(value).filter(\n (entry): entry is [string, string] => typeof entry[0] === \"string\" && typeof entry[1] === \"string\" && (entry[1] as string).trim().length > 0,\n );\n if (entries.length === 0) {\n return undefined;\n }\n return Object.fromEntries(\n trimReferenceEntries(entries.map(([key, val]) => [key, val.trim()])),\n );\n}\n\nfunction mergeConfigAndAuth(\n configRaw: unknown,\n authRaw: unknown,\n): Record<string, unknown> {\n const merged: Record<string, unknown> = isObject(configRaw) ? { ...configRaw } : {};\n if (!isObject(authRaw)) {\n return merged;\n }\n for (const key of [\"api_url\", \"api_key\", \"workspace_id\"]) {\n const value = authRaw[key];\n if (typeof value === \"string\") {\n merged[key] = value;\n }\n }\n if (isObject(authRaw.llm)) {\n const llm = isObject(merged.llm) ? { ...merged.llm } : {};\n if (typeof authRaw.llm.api_key === \"string\") {\n llm.api_key = authRaw.llm.api_key;\n }\n merged.llm = llm;\n }\n return merged;\n}\n\nfunction readJsonFile(path: string): unknown {\n if (!existsSync(path)) {\n return {};\n }\n return JSON.parse(readFileSync(path, \"utf-8\")) as unknown;\n}\n\nfunction hasLegacySensitiveConfig(raw: unknown): boolean {\n if (!isObject(raw)) {\n return false;\n }\n if (typeof raw.api_url === \"string\" || typeof raw.api_key === \"string\" || typeof raw.workspace_id === \"string\") {\n return true;\n }\n return isObject(raw.llm) && typeof raw.llm.api_key === \"string\";\n}\n\nfunction normalizeConfig(raw: unknown): CorpConfig {\n const cfg = structuredClone(DEFAULTS) as CorpConfig;\n if (!isObject(raw)) {\n return cfg;\n }\n\n const savedApiUrl = normalizeString(raw.api_url);\n if (savedApiUrl) {\n try {\n cfg.api_url = validateApiUrl(savedApiUrl);\n } catch {\n cfg.api_url = DEFAULTS.api_url;\n }\n }\n cfg.api_key = normalizeString(raw.api_key) ?? cfg.api_key;\n cfg.workspace_id = normalizeString(raw.workspace_id) ?? cfg.workspace_id;\n cfg.hosting_mode = normalizeString(raw.hosting_mode) ?? cfg.hosting_mode;\n cfg.active_entity_id = normalizeString(raw.active_entity_id) ?? cfg.active_entity_id;\n cfg.data_dir = normalizeString(raw.data_dir) ?? cfg.data_dir;\n\n if (isObject(raw.llm)) {\n cfg.llm.provider = normalizeString(raw.llm.provider) ?? cfg.llm.provider;\n cfg.llm.api_key = normalizeString(raw.llm.api_key) ?? cfg.llm.api_key;\n cfg.llm.model = normalizeString(raw.llm.model) ?? cfg.llm.model;\n const baseUrl = normalizeString(raw.llm.base_url);\n if (baseUrl && baseUrl.trim()) {\n try {\n cfg.llm.base_url = validateLlmBaseUrl(baseUrl);\n } catch {\n cfg.llm.base_url = undefined;\n }\n }\n }\n\n if (isObject(raw.user)) {\n cfg.user.name = normalizeString(raw.user.name) ?? cfg.user.name;\n cfg.user.email = normalizeString(raw.user.email) ?? cfg.user.email;\n }\n\n const activeEntityIds = normalizeActiveEntityMap(raw.active_entity_ids);\n if (activeEntityIds) {\n cfg.active_entity_ids = activeEntityIds;\n }\n const lastReferences = normalizeReferenceMap(raw.last_references);\n if (lastReferences) {\n cfg.last_references = lastReferences;\n }\n if (cfg.workspace_id && cfg.active_entity_id) {\n cfg.active_entity_ids = {\n ...(cfg.active_entity_ids ?? {}),\n [cfg.workspace_id]: cfg.active_entity_id,\n };\n }\n\n return cfg;\n}\n\nfunction serializeConfig(cfg: CorpConfig): string {\n const normalized = normalizeConfig(cfg);\n const serialized: Record<string, unknown> = {\n hosting_mode: normalized.hosting_mode,\n llm: {\n provider: normalized.llm.provider,\n model: normalized.llm.model,\n ...(normalized.llm.base_url ? { base_url: normalized.llm.base_url } : {}),\n },\n user: {\n name: normalized.user.name,\n email: normalized.user.email,\n },\n active_entity_id: normalized.active_entity_id,\n ...(normalized.data_dir ? { data_dir: normalized.data_dir } : {}),\n };\n if (normalized.active_entity_ids && Object.keys(normalized.active_entity_ids).length > 0) {\n serialized.active_entity_ids = normalized.active_entity_ids;\n }\n if (normalized.last_references && Object.keys(normalized.last_references).length > 0) {\n serialized.last_references = normalized.last_references;\n }\n return JSON.stringify(serialized, null, 2) + \"\\n\";\n}\n\nfunction serializeAuth(cfg: CorpConfig): string {\n const normalized = normalizeConfig(cfg);\n const serialized: CorpAuthConfig = {\n api_url: normalized.api_url,\n api_key: normalized.api_key,\n workspace_id: normalized.workspace_id,\n };\n if (normalized.llm.api_key) {\n serialized.llm = { api_key: normalized.llm.api_key };\n }\n // Preserve server_secrets from existing auth file\n const existingAuth = readJsonFile(AUTH_FILE);\n if (isObject(existingAuth) && isObject(existingAuth.server_secrets)) {\n const ss = existingAuth.server_secrets;\n if (typeof ss.jwt_secret === \"string\" && typeof ss.secrets_master_key === \"string\" && typeof ss.internal_worker_token === \"string\") {\n serialized.server_secrets = {\n jwt_secret: ss.jwt_secret,\n secrets_master_key: ss.secrets_master_key,\n internal_worker_token: ss.internal_worker_token,\n };\n }\n }\n // Allow overriding via cfg._server_secrets (used by setup to write new secrets)\n if ((cfg as Record<string, unknown>)._server_secrets) {\n serialized.server_secrets = (cfg as Record<string, unknown>)._server_secrets as CorpAuthConfig[\"server_secrets\"];\n }\n return JSON.stringify(serialized, null, 2) + \"\\n\";\n}\n\nfunction requireSupportedConfigKey(dotPath: string): void {\n if (!ALLOWED_CONFIG_KEYS.has(dotPath)) {\n throw new Error(`unsupported config key: ${dotPath}`);\n }\n}\n\nfunction validateSensitiveConfigUpdate(dotPath: string, forceSensitive = false): void {\n if (SENSITIVE_CONFIG_KEYS.has(dotPath) && !forceSensitive) {\n throw new Error(\n `refusing to update security-sensitive key '${dotPath}' without --force; ` +\n \"this key controls authentication or API routing, so explicit confirmation is required\",\n );\n }\n}\n\nfunction setKnownConfigValue(cfg: CorpConfig, dotPath: string, value: string): void {\n switch (dotPath) {\n case \"api_url\":\n cfg.api_url = validateApiUrl(value);\n return;\n case \"api_key\":\n cfg.api_key = value.trim();\n return;\n case \"workspace_id\":\n cfg.workspace_id = value.trim();\n return;\n case \"hosting_mode\":\n cfg.hosting_mode = value.trim();\n return;\n case \"data_dir\":\n cfg.data_dir = value.trim();\n return;\n case \"llm.provider\":\n cfg.llm.provider = value.trim();\n return;\n case \"llm.api_key\":\n cfg.llm.api_key = value.trim();\n return;\n case \"llm.model\":\n cfg.llm.model = value.trim();\n return;\n case \"llm.base_url\":\n cfg.llm.base_url = value.trim() ? validateLlmBaseUrl(value) : undefined;\n return;\n case \"user.name\":\n cfg.user.name = value.trim();\n return;\n case \"user.email\":\n cfg.user.email = value.trim();\n return;\n case \"active_entity_id\":\n setActiveEntityId(cfg, value.trim());\n return;\n default:\n throw new Error(`unsupported config key: ${dotPath}`);\n }\n}\n\nfunction readConfigUnlocked(): CorpConfig {\n ensureSecurePermissions();\n const configRaw = readJsonFile(CONFIG_FILE);\n const authRaw = readJsonFile(AUTH_FILE);\n return normalizeConfig(mergeConfigAndAuth(configRaw, authRaw));\n}\n\nfunction writeConfigUnlocked(cfg: CorpConfig): void {\n ensureSecurePermissions();\n const configTempFile = `${CONFIG_FILE}.${process.pid}.tmp`;\n const authTempFile = `${AUTH_FILE}.${process.pid}.tmp`;\n writeFileSync(configTempFile, serializeConfig(cfg), { mode: 0o600 });\n writeFileSync(authTempFile, serializeAuth(cfg), { mode: 0o600 });\n renameSync(configTempFile, CONFIG_FILE);\n renameSync(authTempFile, AUTH_FILE);\n ensureSecurePermissions();\n}\n\nfunction migrateLegacySensitiveConfigIfNeeded(): void {\n withConfigLock(() => {\n ensureSecurePermissions();\n const configRaw = readJsonFile(CONFIG_FILE);\n if (!hasLegacySensitiveConfig(configRaw)) {\n return;\n }\n const authRaw = readJsonFile(AUTH_FILE);\n const migrated = normalizeConfig(mergeConfigAndAuth(configRaw, authRaw));\n writeConfigUnlocked(migrated);\n });\n}\n\nexport function loadConfig(): CorpConfig {\n migrateLegacySensitiveConfigIfNeeded();\n return readConfigUnlocked();\n}\n\nexport interface ServerSecrets {\n jwt_secret: string;\n secrets_master_key: string;\n internal_worker_token: string;\n}\n\nexport function loadServerSecrets(): ServerSecrets | null {\n const authRaw = readJsonFile(AUTH_FILE);\n if (!isObject(authRaw) || !isObject(authRaw.server_secrets)) {\n return null;\n }\n const ss = authRaw.server_secrets;\n if (typeof ss.jwt_secret !== \"string\" || typeof ss.secrets_master_key !== \"string\" || typeof ss.internal_worker_token !== \"string\") {\n return null;\n }\n return {\n jwt_secret: ss.jwt_secret,\n secrets_master_key: ss.secrets_master_key,\n internal_worker_token: ss.internal_worker_token,\n };\n}\n\nexport function saveConfig(cfg: CorpConfig): void {\n withConfigLock(() => {\n writeConfigUnlocked(cfg);\n });\n}\n\nexport function updateConfig(mutator: (cfg: CorpConfig) => void): CorpConfig {\n return withConfigLock(() => {\n const cfg = readConfigUnlocked();\n mutator(cfg);\n writeConfigUnlocked(cfg);\n return cfg;\n });\n}\n\nexport function getValue(cfg: Record<string, unknown>, dotPath: string): unknown {\n const keys = dotPath.split(\".\");\n let current: unknown = cfg;\n for (const key of keys) {\n if (typeof current === \"object\" && current !== null && key in current) {\n current = (current as Record<string, unknown>)[key];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\nexport function setValue(\n cfg: Record<string, unknown>,\n dotPath: string,\n value: string,\n options: { forceSensitive?: boolean } = {},\n): void {\n requireSupportedConfigKey(dotPath);\n validateSensitiveConfigUpdate(dotPath, options.forceSensitive);\n setKnownConfigValue(cfg as CorpConfig, dotPath, value);\n}\n\nexport function requireConfig(...fields: string[]): CorpConfig {\n const cfg = loadConfig();\n const missing = fields.filter((f) => !getValue(cfg as unknown as Record<string, unknown>, f));\n if (missing.length > 0) {\n console.error(`Missing config: ${missing.join(\", \")}`);\n console.error(\"Run 'corp setup' to configure.\");\n process.exit(1);\n }\n return cfg;\n}\n\nexport function maskKey(value: string): string {\n if (!value || value.length < 8) return \"***\";\n return \"***\" + value.slice(-4);\n}\n\nexport function configForDisplay(cfg: CorpConfig): Record<string, unknown> {\n const display = { ...cfg } as Record<string, unknown>;\n if (display.api_key) display.api_key = maskKey(display.api_key as string);\n delete display.last_references;\n if (typeof display.llm === \"object\" && display.llm !== null) {\n const llm = { ...(display.llm as Record<string, unknown>) };\n if (llm.api_key) llm.api_key = maskKey(llm.api_key as string);\n display.llm = llm;\n }\n return display;\n}\n\nexport function getActiveEntityId(cfg: CorpConfig): string {\n if (cfg.workspace_id && cfg.active_entity_ids?.[cfg.workspace_id]) {\n return cfg.active_entity_ids[cfg.workspace_id];\n }\n return cfg.active_entity_id;\n}\n\nexport function setActiveEntityId(cfg: CorpConfig, entityId: string): void {\n cfg.active_entity_id = entityId;\n if (!cfg.workspace_id) {\n return;\n }\n cfg.active_entity_ids = {\n ...(cfg.active_entity_ids ?? {}),\n [cfg.workspace_id]: entityId,\n };\n}\n\nfunction referenceScopeKey(workspaceId: string, entityId?: string): string {\n if (workspaceId && entityId) {\n return `workspace:${workspaceId}:entity:${entityId}`;\n }\n if (workspaceId) {\n return `workspace:${workspaceId}`;\n }\n return \"global\";\n}\n\nexport function getLastReference(\n cfg: CorpConfig,\n kind: string,\n entityId?: string,\n): string | undefined {\n const normalizedKind = kind.trim().toLowerCase();\n const entityScopedKey = `${referenceScopeKey(cfg.workspace_id, entityId)}:${normalizedKind}`;\n if (entityId) {\n return cfg.last_references?.[entityScopedKey];\n }\n const workspaceScopedKey = `${referenceScopeKey(cfg.workspace_id)}:${normalizedKind}`;\n return cfg.last_references?.[workspaceScopedKey];\n}\n\nexport function setLastReference(\n cfg: CorpConfig,\n kind: string,\n referenceId: string,\n entityId?: string,\n): void {\n const normalizedKind = kind.trim().toLowerCase();\n const scopedKey = `${referenceScopeKey(cfg.workspace_id, entityId)}:${normalizedKind}`;\n const nextEntries = Object.entries({\n ...(cfg.last_references ?? {}),\n [scopedKey]: referenceId.trim(),\n });\n cfg.last_references = Object.fromEntries(trimReferenceEntries(nextEntries));\n}\n\nexport function resolveEntityId(cfg: CorpConfig, explicitId?: string): string {\n const eid = explicitId || getActiveEntityId(cfg);\n if (!eid) {\n console.error(\n \"No entity specified. Use --entity-id or set active_entity_id via 'corp config set active_entity_id <id>'.\"\n );\n process.exit(1);\n }\n return eid;\n}\n","import {\n getActiveEntityId,\n getLastReference,\n setLastReference,\n updateConfig,\n} from \"./config.js\";\nimport { CorpAPIClient } from \"./api-client.js\";\nimport type { ApiRecord, CorpConfig } from \"./types.js\";\n\n// Re-export types and pure functions from the shared core so existing\n// consumers in cli-ts can keep importing from \"./references.js\".\nexport type { ResourceKind, MatchRecord, ReferenceMatch } from \"@thecorporation/corp-tools\";\nexport {\n shortId,\n slugify,\n describeReferenceRecord,\n getReferenceId,\n getReferenceLabel,\n getReferenceAlias,\n RESOURCE_KINDS,\n} from \"@thecorporation/corp-tools\";\n\nimport {\n type ResourceKind,\n type MatchRecord,\n type ReferenceStorage,\n ReferenceTracker,\n shortId,\n normalize,\n validateReferenceInput,\n describeReferenceRecord,\n getReferenceAlias,\n isOpaqueUuid,\n isShortIdCandidate,\n parseLastReference,\n kindLabel,\n isEntityScopedKind,\n extractId,\n matchRank,\n} from \"@thecorporation/corp-tools\";\n\n// ---------------------------------------------------------------------------\n// Node-specific storage adapter\n// ---------------------------------------------------------------------------\n\nclass NodeReferenceStorage implements ReferenceStorage {\n constructor(private cfg: CorpConfig) {}\n\n getLastReference(kind: ResourceKind, entityId?: string): string | undefined {\n return getLastReference(this.cfg, kind, entityId);\n }\n\n setLastReference(kind: ResourceKind, id: string, entityId?: string): void {\n setLastReference(this.cfg, kind, id, entityId);\n }\n\n getActiveEntityId(): string | undefined {\n return getActiveEntityId(this.cfg);\n }\n}\n\n// ---------------------------------------------------------------------------\n// ReferenceResolver — Node/CLI-specific resolver with API calls and caching\n// ---------------------------------------------------------------------------\n\ntype Scope = { entityId?: string; bodyId?: string; meetingId?: string };\n\nexport class ReferenceResolver {\n private readonly client: CorpAPIClient;\n private readonly cfg: CorpConfig;\n private readonly tracker: ReferenceTracker;\n private entityCache?: ApiRecord[];\n private readonly contactsCache = new Map<string, ApiRecord[]>();\n private readonly shareTransfersCache = new Map<string, ApiRecord[]>();\n private readonly invoicesCache = new Map<string, ApiRecord[]>();\n private readonly bankAccountsCache = new Map<string, ApiRecord[]>();\n private readonly paymentsCache = new Map<string, ApiRecord[]>();\n private readonly payrollRunsCache = new Map<string, ApiRecord[]>();\n private readonly distributionsCache = new Map<string, ApiRecord[]>();\n private readonly reconciliationsCache = new Map<string, ApiRecord[]>();\n private readonly taxFilingsCache = new Map<string, ApiRecord[]>();\n private readonly deadlinesCache = new Map<string, ApiRecord[]>();\n private readonly classificationsCache = new Map<string, ApiRecord[]>();\n private readonly bodiesCache = new Map<string, ApiRecord[]>();\n private readonly meetingsCache = new Map<string, ApiRecord[]>();\n private readonly seatsCache = new Map<string, ApiRecord[]>();\n private readonly agendaCache = new Map<string, ApiRecord[]>();\n private readonly resolutionsCache = new Map<string, ApiRecord[]>();\n private readonly documentsCache = new Map<string, ApiRecord[]>();\n private readonly workItemsCache = new Map<string, ApiRecord[]>();\n private readonly valuationsCache = new Map<string, ApiRecord[]>();\n private readonly safeNotesCache = new Map<string, ApiRecord[]>();\n private readonly roundsCache = new Map<string, ApiRecord[]>();\n private readonly serviceRequestsCache = new Map<string, ApiRecord[]>();\n private readonly capTableCache = new Map<string, ApiRecord>();\n private agentsCache?: ApiRecord[];\n\n constructor(client: CorpAPIClient, cfg: CorpConfig) {\n this.client = client;\n this.cfg = cfg;\n this.tracker = new ReferenceTracker(new NodeReferenceStorage(cfg));\n }\n\n async resolveEntity(ref?: string): Promise<string> {\n if (ref !== undefined && ref !== null && !ref.trim()) {\n // An explicit but empty/whitespace-only ref is likely a bug in a script\n throw new Error(\n \"Entity reference is empty or whitespace. If you want the active entity, omit --entity-id entirely.\",\n );\n }\n if (!ref || !ref.trim()) {\n const activeEntityId = getActiveEntityId(this.cfg);\n if (!activeEntityId) {\n throw new Error(\n \"No entity specified. Use --entity-id or set active_entity_id via 'corp config set active_entity_id <ref>'.\",\n );\n }\n this.remember(\"entity\", activeEntityId);\n return activeEntityId;\n }\n return this.resolve(\"entity\", ref);\n }\n\n async resolveContact(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"contact\", ref, { entityId });\n }\n\n async resolveWorkItemActor(\n entityId: string,\n ref: string,\n ): Promise<{ actor_type: \"contact\" | \"agent\"; actor_id: string }> {\n const trimmed = validateReferenceInput(ref, \"actor reference\");\n const [contactResult, agentResult] = await Promise.allSettled([\n this.resolveContact(entityId, trimmed),\n this.resolveAgent(trimmed),\n ]);\n\n const contactId =\n contactResult.status === \"fulfilled\" ? contactResult.value : undefined;\n const agentId =\n agentResult.status === \"fulfilled\" ? agentResult.value : undefined;\n\n if (contactId && agentId && contactId !== agentId) {\n throw new Error(\n `Actor reference '${trimmed}' is ambiguous between a contact and an agent. Use a unique ref or explicit @last:contact / @last:agent.`,\n );\n }\n if (contactId) {\n return { actor_type: \"contact\", actor_id: contactId };\n }\n if (agentId) {\n return { actor_type: \"agent\", actor_id: agentId };\n }\n\n throw new Error(\n `No matching contact or agent found for '${trimmed}'. Try 'corp find contact <query>' or 'corp find agent <query>'.`,\n );\n }\n\n async resolveShareTransfer(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"share_transfer\", ref, { entityId });\n }\n\n async resolveInvoice(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"invoice\", ref, { entityId });\n }\n\n async resolveBankAccount(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"bank_account\", ref, { entityId });\n }\n\n async resolvePayment(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"payment\", ref, { entityId });\n }\n\n async resolvePayrollRun(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"payroll_run\", ref, { entityId });\n }\n\n async resolveDistribution(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"distribution\", ref, { entityId });\n }\n\n async resolveReconciliation(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"reconciliation\", ref, { entityId });\n }\n\n async resolveTaxFiling(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"tax_filing\", ref, { entityId });\n }\n\n async resolveDeadline(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"deadline\", ref, { entityId });\n }\n\n async resolveClassification(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"classification\", ref, { entityId });\n }\n\n async resolveBody(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"body\", ref, { entityId });\n }\n\n async resolveMeeting(entityId: string, ref: string, bodyId?: string): Promise<string> {\n return this.resolve(\"meeting\", ref, { entityId, bodyId });\n }\n\n async resolveSeat(entityId: string, ref: string, bodyId?: string): Promise<string> {\n return this.resolve(\"seat\", ref, { entityId, bodyId });\n }\n\n async resolveAgendaItem(entityId: string, meetingId: string, ref: string): Promise<string> {\n return this.resolve(\"agenda_item\", ref, { entityId, meetingId });\n }\n\n async resolveResolution(\n entityId: string,\n ref: string,\n meetingId?: string,\n ): Promise<string> {\n return this.resolve(\"resolution\", ref, { entityId, meetingId });\n }\n\n async resolveDocument(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"document\", ref, { entityId });\n }\n\n async resolveWorkItem(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"work_item\", ref, { entityId });\n }\n\n async resolveAgent(ref: string): Promise<string> {\n return this.resolve(\"agent\", ref);\n }\n\n async resolveValuation(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"valuation\", ref, { entityId });\n }\n\n async resolveSafeNote(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"safe_note\", ref, { entityId });\n }\n\n async resolveInstrument(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"instrument\", ref, { entityId });\n }\n\n async resolveShareClass(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"share_class\", ref, { entityId });\n }\n\n async resolveRound(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"round\", ref, { entityId });\n }\n\n async resolveServiceRequest(entityId: string, ref: string): Promise<string> {\n return this.resolve(\"service_request\", ref, { entityId });\n }\n\n async find(\n kind: ResourceKind,\n query: string,\n scope: Scope = {},\n ): Promise<{ kind: ResourceKind; id: string; short_id: string; label: string; alias?: string; raw: ApiRecord }[]> {\n const records = await this.listRecords(kind, scope);\n return this.tracker.findMatches(kind, query, records);\n }\n\n getLastId(kind: ResourceKind, entityId?: string): string | undefined {\n return getLastReference(this.cfg, kind, entityId);\n }\n\n remember(kind: ResourceKind, referenceId: string, entityId?: string): void {\n setLastReference(this.cfg, kind, referenceId, entityId);\n updateConfig((cfg) => {\n setLastReference(cfg, kind, referenceId, entityId);\n });\n }\n\n rememberFromRecord(kind: ResourceKind, record: ApiRecord, entityId?: string): void {\n const described = describeReferenceRecord(kind, record);\n if (described) {\n this.remember(kind, described.id, entityId);\n }\n }\n\n async stabilizeRecord(kind: ResourceKind, record: ApiRecord, entityId?: string): Promise<ApiRecord> {\n const described = describeReferenceRecord(kind, record);\n if (!described) return record;\n if (typeof record.handle === \"string\" && record.handle.trim().length > 0) {\n return record;\n }\n const response = await this.client.syncReferences(\n kind,\n [{ resource_id: described.id, label: described.label }],\n isEntityScopedKind(kind) ? entityId : undefined,\n );\n const handle = response.references[0]?.handle;\n if (typeof handle === \"string\" && handle.trim().length > 0) {\n record.handle = handle.trim();\n }\n return record;\n }\n\n async stabilizeRecords(kind: ResourceKind, records: ApiRecord[], entityId?: string): Promise<ApiRecord[]> {\n return this.attachStableHandles(kind, records, entityId);\n }\n\n referenceAlias(kind: ResourceKind, record: ApiRecord): string | undefined {\n return getReferenceAlias(kind, record);\n }\n\n private async resolve(kind: ResourceKind, ref: string, scope: Scope = {}): Promise<string> {\n const last = parseLastReference(ref);\n if (last.isLast) {\n const lastKind = last.kind ?? kind;\n if (lastKind !== kind) {\n throw new Error(`@last:${lastKind} cannot be used where a ${kindLabel(kind)} reference is required.`);\n }\n const remembered = getLastReference(this.cfg, lastKind, scope.entityId);\n if (!remembered) {\n throw new Error(`No ${kindLabel(lastKind)} is recorded for @last.`);\n }\n this.remember(kind, remembered, scope.entityId);\n return remembered;\n }\n\n const trimmed = validateReferenceInput(ref, `${kindLabel(kind)} reference`);\n if (isOpaqueUuid(trimmed)) {\n this.remember(kind, trimmed, scope.entityId);\n return trimmed;\n }\n\n const records = await this.listRecords(kind, scope);\n const match = this.matchRecords(kind, trimmed, records);\n this.remember(kind, match.id, scope.entityId);\n return match.id;\n }\n\n private matchRecords(kind: ResourceKind, ref: string, records: ApiRecord[]): MatchRecord {\n const described = records\n .map((record) => describeReferenceRecord(kind, record))\n .filter((record): record is MatchRecord => record !== null);\n const normalizedRef = normalize(ref);\n\n const exactIdMatches = described.filter((record) => normalize(record.id) === normalizedRef);\n if (exactIdMatches.length === 1) {\n return exactIdMatches[0];\n }\n\n const exactTokenMatches = described.filter((record) => record.tokens.has(normalizedRef));\n if (exactTokenMatches.length === 1) {\n return exactTokenMatches[0];\n }\n if (exactTokenMatches.length > 1) {\n throw new Error(this.ambiguousMessage(kind, ref, exactTokenMatches));\n }\n\n if (isShortIdCandidate(ref)) {\n const prefixMatches = described.filter((record) => normalize(record.id).startsWith(normalizedRef));\n if (prefixMatches.length === 1) {\n return prefixMatches[0];\n }\n if (prefixMatches.length > 1) {\n throw new Error(this.ambiguousMessage(kind, ref, prefixMatches));\n }\n }\n\n throw new Error(\n `No ${kindLabel(kind)} found for reference \"${ref}\". Try: corp find ${kind} ${JSON.stringify(ref)}`,\n );\n }\n\n private ambiguousMessage(kind: ResourceKind, ref: string, matches: MatchRecord[]): string {\n const previews = matches\n .slice(0, 5)\n .map((match) => `${match.label} [${shortId(match.id)}]`)\n .join(\", \");\n return `Ambiguous ${kindLabel(kind)} reference \"${ref}\". Matches: ${previews}. Try: corp find ${kind} ${JSON.stringify(ref)}`;\n }\n\n private async listRecords(kind: ResourceKind, scope: Scope): Promise<ApiRecord[]> {\n const records = await (async () => {\n switch (kind) {\n case \"entity\":\n return this.listEntities();\n case \"contact\":\n return this.listContacts(scope.entityId);\n case \"share_transfer\":\n return this.listShareTransfers(scope.entityId);\n case \"invoice\":\n return this.listInvoices(scope.entityId);\n case \"bank_account\":\n return this.listBankAccounts(scope.entityId);\n case \"payment\":\n return this.listPayments(scope.entityId);\n case \"payroll_run\":\n return this.listPayrollRuns(scope.entityId);\n case \"distribution\":\n return this.listDistributions(scope.entityId);\n case \"reconciliation\":\n return this.listReconciliations(scope.entityId);\n case \"tax_filing\":\n return this.listTaxFilings(scope.entityId);\n case \"deadline\":\n return this.listDeadlines(scope.entityId);\n case \"classification\":\n return this.listClassifications(scope.entityId);\n case \"body\":\n return this.listBodies(scope.entityId);\n case \"meeting\":\n return this.listMeetings(scope.entityId, scope.bodyId);\n case \"seat\":\n return this.listSeats(scope.entityId, scope.bodyId);\n case \"agenda_item\":\n return this.listAgendaItems(scope.entityId, scope.meetingId);\n case \"resolution\":\n return this.listResolutions(scope.entityId, scope.meetingId);\n case \"document\":\n return this.listDocuments(scope.entityId);\n case \"work_item\":\n return this.listWorkItems(scope.entityId);\n case \"agent\":\n return this.listAgents();\n case \"valuation\":\n return this.listValuations(scope.entityId);\n case \"safe_note\":\n return this.listSafeNotes(scope.entityId);\n case \"instrument\":\n return this.listInstruments(scope.entityId);\n case \"share_class\":\n return this.listShareClasses(scope.entityId);\n case \"round\":\n return this.listRounds(scope.entityId);\n case \"service_request\":\n return this.listServiceRequestRecords(scope.entityId);\n }\n })();\n return this.attachStableHandles(kind, records, scope.entityId);\n }\n\n private async attachStableHandles(\n kind: ResourceKind,\n records: ApiRecord[],\n entityId?: string,\n ): Promise<ApiRecord[]> {\n const missing = records\n .map((record) => ({ record, described: describeReferenceRecord(kind, record) }))\n .filter(\n (entry): entry is { record: ApiRecord; described: MatchRecord } =>\n entry.described !== null\n && !(typeof entry.record.handle === \"string\" && entry.record.handle.trim().length > 0),\n );\n if (missing.length === 0) {\n return records;\n }\n\n // Chunk into batches of 400 to stay under the API's 500-item limit\n const SYNC_BATCH_SIZE = 400;\n const handleById = new Map<string, string>();\n const scopeEntityId = isEntityScopedKind(kind) ? entityId : undefined;\n\n for (let i = 0; i < missing.length; i += SYNC_BATCH_SIZE) {\n const batch = missing.slice(i, i + SYNC_BATCH_SIZE);\n const response = await this.client.syncReferences(\n kind,\n batch.map(({ described }) => ({\n resource_id: described.id,\n label: described.label,\n })),\n scopeEntityId,\n );\n for (const reference of response.references) {\n if (typeof reference.resource_id === \"string\" && typeof reference.handle === \"string\") {\n handleById.set(reference.resource_id, reference.handle);\n }\n }\n }\n\n for (const { record, described } of missing) {\n const handle = handleById.get(described.id);\n if (handle) {\n record.handle = handle;\n }\n }\n return records;\n }\n\n private async listEntities(): Promise<ApiRecord[]> {\n if (!this.entityCache) {\n this.entityCache = await this.client.listEntities();\n }\n return this.entityCache;\n }\n\n private async listContacts(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve contacts.\");\n const cached = this.contactsCache.get(entityId);\n if (cached) return cached;\n const contacts = await this.client.listContacts(entityId);\n this.contactsCache.set(entityId, contacts);\n return contacts;\n }\n\n private async listShareTransfers(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve share transfers.\");\n const cached = this.shareTransfersCache.get(entityId);\n if (cached) return cached;\n const transfers = await this.client.listShareTransfers(entityId);\n this.shareTransfersCache.set(entityId, transfers);\n return transfers;\n }\n\n private async listInvoices(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve invoices.\");\n const cached = this.invoicesCache.get(entityId);\n if (cached) return cached;\n const invoices = await this.client.listInvoices(entityId);\n this.invoicesCache.set(entityId, invoices);\n return invoices;\n }\n\n private async listBankAccounts(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve bank accounts.\");\n const cached = this.bankAccountsCache.get(entityId);\n if (cached) return cached;\n const bankAccounts = await this.client.listBankAccounts(entityId);\n this.bankAccountsCache.set(entityId, bankAccounts);\n return bankAccounts;\n }\n\n private async listPayments(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve payments.\");\n const cached = this.paymentsCache.get(entityId);\n if (cached) return cached;\n const payments = await this.client.listPayments(entityId);\n this.paymentsCache.set(entityId, payments);\n return payments;\n }\n\n private async listPayrollRuns(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve payroll runs.\");\n const cached = this.payrollRunsCache.get(entityId);\n if (cached) return cached;\n const payrollRuns = await this.client.listPayrollRuns(entityId);\n this.payrollRunsCache.set(entityId, payrollRuns);\n return payrollRuns;\n }\n\n private async listDistributions(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve distributions.\");\n const cached = this.distributionsCache.get(entityId);\n if (cached) return cached;\n const distributions = await this.client.listDistributions(entityId);\n this.distributionsCache.set(entityId, distributions);\n return distributions;\n }\n\n private async listReconciliations(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve reconciliations.\");\n const cached = this.reconciliationsCache.get(entityId);\n if (cached) return cached;\n const reconciliations = await this.client.listReconciliations(entityId);\n this.reconciliationsCache.set(entityId, reconciliations);\n return reconciliations;\n }\n\n private async listTaxFilings(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve tax filings.\");\n const cached = this.taxFilingsCache.get(entityId);\n if (cached) return cached;\n const filings = await this.client.listTaxFilings(entityId);\n this.taxFilingsCache.set(entityId, filings);\n return filings;\n }\n\n private async listDeadlines(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve deadlines.\");\n const cached = this.deadlinesCache.get(entityId);\n if (cached) return cached;\n const deadlines = await this.client.listDeadlines(entityId);\n this.deadlinesCache.set(entityId, deadlines);\n return deadlines;\n }\n\n private async listClassifications(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve contractor classifications.\");\n const cached = this.classificationsCache.get(entityId);\n if (cached) return cached;\n const classifications = await this.client.listContractorClassifications(entityId);\n this.classificationsCache.set(entityId, classifications);\n return classifications;\n }\n\n private async listBodies(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve governance bodies.\");\n const cached = this.bodiesCache.get(entityId);\n if (cached) return cached;\n const bodies = await this.client.listGovernanceBodies(entityId);\n this.bodiesCache.set(entityId, bodies as ApiRecord[]);\n return bodies as ApiRecord[];\n }\n\n private async listMeetings(entityId?: string, bodyId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve meetings.\");\n const cacheKey = `${entityId}:${bodyId ?? \"*\"}`;\n const cached = this.meetingsCache.get(cacheKey);\n if (cached) return cached;\n\n const meetings: ApiRecord[] = [];\n if (bodyId) {\n meetings.push(...((await this.client.listMeetings(bodyId, entityId)) as ApiRecord[]));\n } else {\n const bodies = await this.listBodies(entityId);\n for (const body of bodies) {\n const resolvedBodyId = extractId(body, [\"body_id\", \"id\"]);\n if (!resolvedBodyId) continue;\n meetings.push(...((await this.client.listMeetings(resolvedBodyId, entityId)) as ApiRecord[]));\n }\n }\n this.meetingsCache.set(cacheKey, meetings);\n return meetings;\n }\n\n private async listSeats(entityId?: string, bodyId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve seats.\");\n const cacheKey = `${entityId}:${bodyId ?? \"*\"}`;\n const cached = this.seatsCache.get(cacheKey);\n if (cached) return cached;\n\n const seats: ApiRecord[] = [];\n if (bodyId) {\n seats.push(...((await this.client.getGovernanceSeats(bodyId, entityId)) as ApiRecord[]));\n } else {\n const bodies = await this.listBodies(entityId);\n for (const body of bodies) {\n const resolvedBodyId = extractId(body, [\"body_id\", \"id\"]);\n if (!resolvedBodyId) continue;\n seats.push(...((await this.client.getGovernanceSeats(resolvedBodyId, entityId)) as ApiRecord[]));\n }\n }\n this.seatsCache.set(cacheKey, seats);\n return seats;\n }\n\n private async listAgendaItems(entityId?: string, meetingId?: string): Promise<ApiRecord[]> {\n if (!entityId || !meetingId) {\n throw new Error(\"Entity and meeting context are required to resolve agenda items.\");\n }\n const cached = this.agendaCache.get(`${entityId}:${meetingId}`);\n if (cached) return cached;\n const items = (await this.client.listAgendaItems(meetingId, entityId)) as ApiRecord[];\n this.agendaCache.set(`${entityId}:${meetingId}`, items);\n return items;\n }\n\n private async listResolutions(entityId?: string, meetingId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve resolutions.\");\n const cacheKey = `${entityId}:${meetingId ?? \"*\"}`;\n const cached = this.resolutionsCache.get(cacheKey);\n if (cached) return cached;\n\n const resolutions: ApiRecord[] = [];\n if (meetingId) {\n resolutions.push(...((await this.client.getMeetingResolutions(meetingId, entityId)) as ApiRecord[]));\n } else {\n const meetings = await this.listMeetings(entityId);\n for (const meeting of meetings) {\n const resolvedMeetingId = extractId(meeting, [\"meeting_id\", \"id\"]);\n if (!resolvedMeetingId) continue;\n resolutions.push(...((await this.client.getMeetingResolutions(resolvedMeetingId, entityId)) as ApiRecord[]));\n }\n }\n this.resolutionsCache.set(cacheKey, resolutions);\n return resolutions;\n }\n\n private async listDocuments(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve documents.\");\n const cached = this.documentsCache.get(entityId);\n if (cached) return cached;\n const docs = (await this.client.getEntityDocuments(entityId)) as ApiRecord[];\n this.documentsCache.set(entityId, docs);\n return docs;\n }\n\n private async listWorkItems(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve work items.\");\n const cached = this.workItemsCache.get(entityId);\n if (cached) return cached;\n const items = (await this.client.listWorkItems(entityId)) as ApiRecord[];\n this.workItemsCache.set(entityId, items);\n return items;\n }\n\n private async listAgents(): Promise<ApiRecord[]> {\n if (!this.agentsCache) {\n this.agentsCache = (await this.client.listAgents()) as ApiRecord[];\n }\n return this.agentsCache;\n }\n\n private async listValuations(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve valuations.\");\n const cached = this.valuationsCache.get(entityId);\n if (cached) return cached;\n const valuations = (await this.client.getValuations(entityId)) as ApiRecord[];\n this.valuationsCache.set(entityId, valuations);\n return valuations;\n }\n\n private async listSafeNotes(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve SAFE notes.\");\n const cached = this.safeNotesCache.get(entityId);\n if (cached) return cached;\n const safeNotes = (await this.client.getSafeNotes(entityId)) as ApiRecord[];\n this.safeNotesCache.set(entityId, safeNotes);\n return safeNotes;\n }\n\n private async listRounds(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve rounds.\");\n const cached = this.roundsCache.get(entityId);\n if (cached) return cached;\n const rounds = (await this.client.listEquityRounds(entityId)) as ApiRecord[];\n this.roundsCache.set(entityId, rounds);\n return rounds;\n }\n\n private async getCapTable(entityId?: string): Promise<ApiRecord> {\n if (!entityId) throw new Error(\"An entity context is required to resolve cap table resources.\");\n const cached = this.capTableCache.get(entityId);\n if (cached) return cached;\n const capTable = (await this.client.getCapTable(entityId)) as ApiRecord;\n this.capTableCache.set(entityId, capTable);\n return capTable;\n }\n\n private async listInstruments(entityId?: string): Promise<ApiRecord[]> {\n const capTable = await this.getCapTable(entityId);\n return Array.isArray(capTable.instruments) ? (capTable.instruments as ApiRecord[]) : [];\n }\n\n private async listShareClasses(entityId?: string): Promise<ApiRecord[]> {\n const capTable = await this.getCapTable(entityId);\n return Array.isArray(capTable.share_classes) ? (capTable.share_classes as ApiRecord[]) : [];\n }\n\n private async listServiceRequestRecords(entityId?: string): Promise<ApiRecord[]> {\n if (!entityId) throw new Error(\"An entity context is required to resolve service requests.\");\n const cached = this.serviceRequestsCache.get(entityId);\n if (cached) return cached;\n const requests = (await this.client.listServiceRequests(entityId)) as ApiRecord[];\n this.serviceRequestsCache.set(entityId, requests);\n return requests;\n }\n}\n","import chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport type { ApiRecord } from \"./types.js\";\nimport type { NextStepItem, NextStepsSummary } from \"@thecorporation/corp-tools\";\nimport {\n getReferenceAlias,\n getReferenceId,\n shortId,\n type ResourceKind,\n} from \"./references.js\";\n\nconst URGENCY_COLORS: Record<string, (s: string) => string> = {\n overdue: chalk.red.bold,\n due_today: chalk.yellow.bold,\n d1: chalk.yellow,\n d7: chalk.cyan,\n d14: chalk.blue,\n d30: chalk.dim,\n upcoming: chalk.dim,\n};\n\nconst NEXT_STEP_COLORS: Record<string, (s: string) => string> = {\n critical: chalk.red.bold,\n high: chalk.yellow,\n medium: chalk.cyan,\n low: chalk.dim,\n};\n\nexport function printError(msg: string): void {\n console.error(chalk.red(\"Error:\"), msg);\n}\n\nexport function printSuccess(msg: string): void {\n console.log(chalk.green(msg));\n}\n\nexport function printWarning(msg: string): void {\n console.log(chalk.yellow(msg));\n}\n\nexport function printJson(data: unknown): void {\n console.log(JSON.stringify(data, null, 2));\n}\n\nexport function printDryRun(operation: string, payload: unknown): void {\n printJson({\n dry_run: true,\n operation,\n payload,\n });\n}\n\nexport function printQuietId(record: unknown, ...idFields: string[]): void {\n if (typeof record !== \"object\" || record === null) return;\n const rec = record as Record<string, unknown>;\n for (const field of idFields) {\n if (typeof rec[field] === \"string\" && rec[field]) {\n console.log(rec[field]);\n return;\n }\n }\n}\n\ntype WriteResultOptions =\n | boolean\n | {\n jsonOnly?: boolean;\n quiet?: boolean;\n referenceKind?: ResourceKind;\n referenceLabel?: string;\n showReuseHint?: boolean;\n idFields?: string[];\n };\n\nfunction normalizeWriteResultOptions(options?: WriteResultOptions): {\n jsonOnly?: boolean;\n quiet?: boolean;\n referenceKind?: ResourceKind;\n referenceLabel?: string;\n showReuseHint?: boolean;\n idFields?: string[];\n} {\n if (typeof options === \"boolean\") {\n return { jsonOnly: options };\n }\n return options ?? {};\n}\n\nfunction formatReferenceCell(kind: ResourceKind, record: ApiRecord): string {\n const id = getReferenceId(kind, record);\n if (!id) return \"\";\n const alias = getReferenceAlias(kind, record);\n return alias ? `${alias} [${shortId(id)}]` : shortId(id);\n}\n\nexport function printReferenceSummary(\n kind: ResourceKind,\n record: ApiRecord,\n opts: { label?: string; showReuseHint?: boolean } = {},\n): void {\n const id = getReferenceId(kind, record);\n if (!id) return;\n const alias = getReferenceAlias(kind, record);\n const token = alias ? `${alias} [${shortId(id)}]` : shortId(id);\n console.log(` ${chalk.bold(opts.label ?? \"Ref:\")} ${token}`);\n console.log(` ${chalk.bold(\"ID:\")} ${id}`);\n if (opts.showReuseHint) {\n console.log(` ${chalk.bold(\"Reuse:\")} @last:${kind}`);\n }\n}\n\nexport function printWriteResult(\n result: unknown,\n successMessage: string,\n options?: WriteResultOptions,\n): void {\n const normalized = normalizeWriteResultOptions(options);\n if (normalized.jsonOnly) {\n printJson(result);\n return;\n }\n if (normalized.quiet) {\n const defaultIdFields = [\n \"entity_id\", \"agent_id\", \"meeting_id\", \"body_id\", \"seat_id\",\n \"work_item_id\", \"document_id\", \"invoice_id\", \"payment_id\",\n \"safe_note_id\", \"valuation_id\", \"round_id\", \"instrument_id\",\n \"transfer_workflow_id\", \"distribution_id\", \"deadline_id\",\n \"filing_id\", \"bank_account_id\", \"classification_id\",\n \"resolution_id\", \"agenda_item_id\", \"contact_id\",\n \"request_id\", \"service_request_id\", \"key_id\",\n \"formation_id\", \"execution_id\", \"incident_id\",\n \"id\",\n ];\n printQuietId(result, ...(normalized.idFields ?? defaultIdFields));\n return;\n }\n printSuccess(successMessage);\n if (\n normalized.referenceKind\n && typeof result === \"object\"\n && result !== null\n && !Array.isArray(result)\n ) {\n printReferenceSummary(normalized.referenceKind, result as ApiRecord, {\n label: normalized.referenceLabel,\n showReuseHint: normalized.showReuseHint,\n });\n }\n}\n\n// --- Status Panel ---\n\nexport function printStatusPanel(data: ApiRecord): void {\n console.log(chalk.blue(\"─\".repeat(50)));\n console.log(chalk.blue.bold(\" Corp Status\"));\n console.log(chalk.blue(\"─\".repeat(50)));\n console.log(` ${chalk.bold(\"Workspace:\")} ${data.workspace_id ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Entities:\")} ${data.entity_count ?? 0}`);\n\n const urgency = (data.urgency_counts ?? {}) as Record<string, number>;\n if (Object.keys(urgency).length > 0) {\n console.log(`\\n ${chalk.bold(\"Obligations:\")}`);\n for (const [tier, count] of Object.entries(urgency)) {\n const colorFn = URGENCY_COLORS[tier] ?? ((s: string) => s);\n console.log(` ${colorFn(`${tier}:`)} ${count}`);\n }\n }\n\n if (data.next_deadline) {\n console.log(`\\n ${chalk.bold(\"Next deadline:\")} ${data.next_deadline}`);\n }\n console.log(chalk.blue(\"─\".repeat(50)));\n}\n\nexport function printFinanceSummaryPanel(data: ApiRecord): void {\n const invoices = (data.invoices ?? {}) as ApiRecord;\n const bankAccounts = (data.bank_accounts ?? {}) as ApiRecord;\n const payments = (data.payments ?? {}) as ApiRecord;\n const payrollRuns = (data.payroll_runs ?? {}) as ApiRecord;\n const distributions = (data.distributions ?? {}) as ApiRecord;\n const reconciliations = (data.reconciliations ?? {}) as ApiRecord;\n const classifications = (data.contractor_classifications ?? {}) as ApiRecord;\n\n console.log(chalk.green(\"─\".repeat(54)));\n console.log(chalk.green.bold(\" Finance Summary\"));\n console.log(chalk.green(\"─\".repeat(54)));\n console.log(` ${chalk.bold(\"Entity:\")} ${s(data.entity_id) || \"N/A\"}`);\n console.log(` ${chalk.bold(\"Invoices:\")} ${s(invoices.count)} total, ${s(invoices.open_count)} open, ${money(invoices.total_amount_cents)}`);\n if (invoices.latest_due_date) {\n console.log(` ${chalk.bold(\"Invoice Horizon:\")} next due ${date(invoices.latest_due_date)}`);\n }\n console.log(` ${chalk.bold(\"Bank Accounts:\")} ${s(bankAccounts.active_count)}/${s(bankAccounts.count)} active`);\n console.log(` ${chalk.bold(\"Payments:\")} ${s(payments.count)} total, ${s(payments.pending_count)} pending, ${money(payments.total_amount_cents)}`);\n console.log(` ${chalk.bold(\"Payroll Runs:\")} ${s(payrollRuns.count)} total${payrollRuns.latest_period_end ? `, latest ${date(payrollRuns.latest_period_end)}` : \"\"}`);\n console.log(` ${chalk.bold(\"Distributions:\")} ${s(distributions.count)} total, ${money(distributions.total_amount_cents)}`);\n console.log(` ${chalk.bold(\"Reconciliations:\")} ${s(reconciliations.balanced_count)}/${s(reconciliations.count)} balanced`);\n console.log(` ${chalk.bold(\"Contractors:\")} ${s(classifications.count)} classifications, ${s(classifications.high_risk_count)} high risk`);\n console.log(chalk.green(\"─\".repeat(54)));\n}\n\nconst CATEGORY_LABELS: Record<string, string> = {\n setup: \"Setup\",\n formation: \"Formation\",\n documents: \"Documents\",\n governance: \"Governance\",\n cap_table: \"Cap Table\",\n compliance: \"Compliance\",\n finance: \"Finance\",\n agents: \"Agents\",\n};\n\nexport function printNextSteps(data: {\n top: NextStepItem | null;\n backlog: NextStepItem[];\n summary: NextStepsSummary;\n}): void {\n if (!data.top) {\n console.log(chalk.green.bold(\"\\n All caught up! No pending actions.\\n\"));\n return;\n }\n\n // Top recommendation\n console.log();\n console.log(chalk.bold(\" Next up:\"));\n const topColor = NEXT_STEP_COLORS[data.top.urgency] ?? ((x: string) => x);\n console.log(` ${topColor(data.top.title)}`);\n if (data.top.description) {\n console.log(` ${chalk.dim(data.top.description)}`);\n }\n console.log(` ${chalk.green(\"→\")} ${chalk.green(data.top.command)}`);\n\n // Backlog grouped by category\n if (data.backlog.length > 0) {\n console.log();\n console.log(chalk.bold(\" More to do:\"));\n\n const groups = new Map<string, NextStepItem[]>();\n for (const item of data.backlog) {\n const cat = item.category || \"other\";\n if (!groups.has(cat)) groups.set(cat, []);\n groups.get(cat)!.push(item);\n }\n\n for (const [cat, items] of groups) {\n const label = CATEGORY_LABELS[cat] ?? cat;\n console.log(`\\n ${chalk.bold(`${label} (${items.length})`)}`);\n for (const item of items) {\n const color = NEXT_STEP_COLORS[item.urgency] ?? ((x: string) => x);\n console.log(` ${color(\"•\")} ${item.title}`);\n if (item.description) {\n console.log(` ${chalk.dim(item.description)}`);\n }\n console.log(` ${chalk.green(\"→\")} ${chalk.green(item.command)}`);\n }\n }\n }\n\n // Summary footer\n const { critical = 0, high = 0, medium = 0, low = 0 } = data.summary;\n const total = critical + high + medium + low;\n const parts: string[] = [];\n if (critical > 0) parts.push(chalk.red.bold(`${critical} critical`));\n if (high > 0) parts.push(chalk.yellow(`${high} high`));\n if (medium > 0) parts.push(chalk.cyan(`${medium} medium`));\n if (low > 0) parts.push(chalk.dim(`${low} low`));\n console.log(`\\n ${total} item${total === 1 ? \"\" : \"s\"} total (${parts.join(\", \")})\\n`);\n}\n\n// --- Generic table helper ---\n\nfunction makeTable(title: string, columns: string[]): Table.Table {\n console.log(`\\n${chalk.bold(title)}`);\n return new Table({ head: columns.map((c) => chalk.dim(c)) });\n}\n\nfunction s(val: unknown, maxLen?: number): string {\n const str = val == null ? \"\" : String(val);\n if (maxLen && str.length > maxLen) return str.slice(0, maxLen);\n return str;\n}\n\nfunction money(val: unknown, cents = true): string {\n if (typeof val === \"number\") {\n const dollars = cents ? val / 100 : val;\n return `$${dollars.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;\n }\n return String(val ?? \"\");\n}\n\nfunction date(val: unknown): string {\n const str = s(val);\n if (!str) return \"\";\n const parsed = new Date(str);\n return Number.isNaN(parsed.getTime()) ? str : parsed.toISOString().slice(0, 10);\n}\n\nfunction actorLabel(record: ApiRecord, field: \"claimed_by\" | \"completed_by\" | \"created_by\"): string {\n const actor = record[`${field}_actor`];\n if (actor && typeof actor === \"object\" && !Array.isArray(actor)) {\n const label = s((actor as ApiRecord).label);\n const actorType = s((actor as ApiRecord).actor_type);\n if (label) {\n return actorType ? `${label} (${actorType})` : label;\n }\n }\n return s(record[field]);\n}\n\n// --- Domain tables ---\n\nexport function printEntitiesTable(entities: ApiRecord[]): void {\n const table = makeTable(\"Entities\", [\"Ref\", \"Name\", \"Type\", \"Jurisdiction\", \"Status\"]);\n for (const e of entities) {\n table.push([\n formatReferenceCell(\"entity\", e),\n s(e.legal_name ?? e.name),\n s(e.entity_type),\n s(e.jurisdiction),\n s(e.formation_status ?? e.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printObligationsTable(obligations: ApiRecord[]): void {\n const table = makeTable(\"Obligations\", [\"ID\", \"Type\", \"Urgency\", \"Due\", \"Status\"]);\n for (const o of obligations) {\n const urg = s(o.urgency) || \"upcoming\";\n const colorFn = URGENCY_COLORS[urg] ?? ((x: string) => x);\n table.push([s(o.obligation_id, 12), s(o.obligation_type), colorFn(urg), s(o.due_at), s(o.status)]);\n }\n console.log(table.toString());\n}\n\nexport function printContactsTable(contacts: ApiRecord[]): void {\n const table = makeTable(\"Contacts\", [\"Ref\", \"Name\", \"Email\", \"Category\", \"Entity\"]);\n for (const c of contacts) {\n table.push([\n formatReferenceCell(\"contact\", c),\n s(c.name),\n s(c.email),\n s(c.category),\n s(c.entity_name ?? c.entity_id),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printCapTable(data: ApiRecord): void {\n const accessLevel = s(data.access_level) || \"admin\";\n const instruments = (data.instruments ?? []) as ApiRecord[];\n if (instruments.length > 0) {\n const table = makeTable(\"Cap Table — Instruments\", [\"Ref\", \"Symbol\", \"Kind\", \"Authorized\", \"Issued\", \"Diluted\"]);\n for (const instrument of instruments) {\n table.push([\n formatReferenceCell(\"instrument\", instrument),\n s(instrument.symbol),\n s(instrument.kind),\n s(instrument.authorized_units ?? \"unlimited\"),\n s(instrument.issued_units),\n s(instrument.diluted_units),\n ]);\n }\n console.log(table.toString());\n }\n\n const holders = (data.holders ?? []) as ApiRecord[];\n if (holders.length > 0 && accessLevel !== \"summary\") {\n const table = makeTable(\n \"Ownership Breakdown\",\n [\"Holder\", \"Outstanding\", \"As Converted\", \"Fully Diluted\", \"Fully Diluted %\"],\n );\n for (const holder of holders) {\n const dilutedBps = typeof holder.fully_diluted_bps === \"number\"\n ? `${(holder.fully_diluted_bps / 100).toFixed(2)}%`\n : \"\";\n table.push([\n s(holder.name),\n s(holder.outstanding_units),\n s(holder.as_converted_units),\n s(holder.fully_diluted_units),\n dilutedBps,\n ]);\n }\n console.log(table.toString());\n }\n\n const shareClasses = (data.share_classes ?? []) as ApiRecord[];\n if (shareClasses.length > 0) {\n const cols = [\"Ref\", \"Class\", \"Authorized\", \"Outstanding\"];\n if (accessLevel !== \"summary\") cols.push(\"Holders\");\n const table = makeTable(\"Cap Table — Share Classes\", cols);\n for (const sc of shareClasses) {\n const row = [\n formatReferenceCell(\"share_class\", sc),\n s(sc.class_code ?? sc.name),\n s(sc.authorized),\n s(sc.outstanding),\n ];\n if (accessLevel !== \"summary\") {\n const holders = (sc.holders ?? []) as ApiRecord[];\n row.push(holders.map((h) => `${h.name ?? \"?\"}(${h.percentage ?? \"?\"}%)`).join(\", \"));\n }\n table.push(row);\n }\n console.log(table.toString());\n }\n\n const ownership = (data.ownership ?? []) as ApiRecord[];\n if (ownership.length > 0 && accessLevel !== \"summary\") {\n const table = makeTable(\"Ownership Breakdown\", [\"Holder\", \"Shares\", \"Percentage\", \"Class\"]);\n for (const o of ownership) {\n table.push([s(o.holder_name ?? o.name), s(o.shares), `${o.percentage ?? \"\"}%`, s(o.share_class)]);\n }\n console.log(table.toString());\n }\n\n const pools = (data.option_pools ?? []) as ApiRecord[];\n if (pools.length > 0) {\n const table = makeTable(\"Option Pools\", [\"Name\", \"Authorized\", \"Granted\", \"Available\"]);\n for (const p of pools) {\n table.push([s(p.name), s(p.authorized), s(p.granted), s(p.available)]);\n }\n console.log(table.toString());\n }\n\n if (data.fully_diluted_shares != null) {\n const fd = data.fully_diluted_shares;\n console.log(`\\n${chalk.bold(\"Fully Diluted Shares:\")} ${typeof fd === \"number\" ? fd.toLocaleString() : fd}`);\n }\n if (data.total_units != null) {\n console.log(`\\n${chalk.bold(\"Cap Table Basis:\")} ${s(data.basis) || \"outstanding\"}`);\n console.log(`${chalk.bold(\"Total Units:\")} ${typeof data.total_units === \"number\" ? data.total_units.toLocaleString() : data.total_units}`);\n }\n}\n\nexport function printSafesTable(safes: ApiRecord[]): void {\n const table = makeTable(\"SAFE Notes\", [\"Ref\", \"Investor\", \"Amount\", \"Cap\", \"Discount\", \"Date\"]);\n for (const s_ of safes) {\n table.push([\n formatReferenceCell(\"safe_note\", s_),\n s(s_.investor_name ?? s_.investor),\n money(s_.principal_amount_cents ?? s_.investment_amount ?? s_.amount),\n money(s_.valuation_cap_cents ?? s_.valuation_cap ?? s_.cap),\n s(s_.discount_rate ?? s_.discount),\n s(s_.issued_at ?? s_.date ?? s_.created_at),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printTransfersTable(transfers: ApiRecord[]): void {\n const table = makeTable(\"Share Transfers\", [\"Ref\", \"From\", \"To\", \"Shares\", \"Type\", \"Status\"]);\n for (const t of transfers) {\n table.push([\n formatReferenceCell(\"share_transfer\", t),\n s(t.from_holder ?? t.from),\n s(t.to_holder ?? t.to),\n s(t.shares ?? t.share_count),\n s(t.transfer_type),\n s(t.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printInstrumentsTable(instruments: ApiRecord[]): void {\n const table = makeTable(\"Instruments\", [\"Ref\", \"Symbol\", \"Kind\", \"Authorized\", \"Issued\", \"Status\"]);\n for (const instrument of instruments) {\n table.push([\n formatReferenceCell(\"instrument\", instrument),\n s(instrument.symbol),\n s(instrument.kind),\n s(instrument.authorized_units ?? \"unlimited\"),\n s(instrument.issued_units),\n s(instrument.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printShareClassesTable(shareClasses: ApiRecord[]): void {\n const table = makeTable(\"Share Classes\", [\"Ref\", \"Class\", \"Authorized\", \"Outstanding\"]);\n for (const shareClass of shareClasses) {\n table.push([\n formatReferenceCell(\"share_class\", shareClass),\n s(shareClass.class_code ?? shareClass.name ?? shareClass.share_class),\n s(shareClass.authorized),\n s(shareClass.outstanding),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printRoundsTable(rounds: ApiRecord[]): void {\n const table = makeTable(\"Equity Rounds\", [\"Ref\", \"Name\", \"Status\", \"Issuer\", \"Created\"]);\n for (const round of rounds) {\n table.push([\n formatReferenceCell(\"round\", round),\n s(round.name),\n s(round.status),\n s(round.issuer_legal_entity_id),\n date(round.created_at),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printInvoicesTable(invoices: ApiRecord[]): void {\n const table = makeTable(\"Invoices\", [\"Ref\", \"Customer\", \"Amount\", \"Due\", \"Status\"]);\n for (const invoice of invoices) {\n table.push([\n formatReferenceCell(\"invoice\", invoice),\n s(invoice.customer_name),\n money(invoice.amount_cents),\n date(invoice.due_date),\n s(invoice.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printBankAccountsTable(accounts: ApiRecord[]): void {\n const table = makeTable(\"Bank Accounts\", [\"Ref\", \"Bank\", \"Type\", \"Status\", \"Created\"]);\n for (const account of accounts) {\n table.push([\n formatReferenceCell(\"bank_account\", account),\n s(account.bank_name),\n s(account.account_type),\n s(account.status),\n date(account.created_at),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printPaymentsTable(payments: ApiRecord[]): void {\n const table = makeTable(\"Payments\", [\"Ref\", \"Recipient\", \"Amount\", \"Method\", \"Status\"]);\n for (const payment of payments) {\n table.push([\n formatReferenceCell(\"payment\", payment),\n s(payment.recipient),\n money(payment.amount_cents),\n s(payment.payment_method),\n s(payment.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printPayrollRunsTable(runs: ApiRecord[]): void {\n const table = makeTable(\"Payroll Runs\", [\"Ref\", \"Start\", \"End\", \"Status\", \"Created\"]);\n for (const run of runs) {\n table.push([\n formatReferenceCell(\"payroll_run\", run),\n date(run.pay_period_start),\n date(run.pay_period_end),\n s(run.status),\n date(run.created_at),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printDistributionsTable(distributions: ApiRecord[]): void {\n const table = makeTable(\"Distributions\", [\"Ref\", \"Type\", \"Amount\", \"Status\", \"Description\"]);\n for (const distribution of distributions) {\n table.push([\n formatReferenceCell(\"distribution\", distribution),\n s(distribution.distribution_type),\n money(distribution.total_amount_cents),\n s(distribution.status),\n s(distribution.description),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printReconciliationsTable(reconciliations: ApiRecord[]): void {\n const table = makeTable(\"Reconciliations\", [\"Ref\", \"As Of\", \"Debits\", \"Credits\", \"Status\"]);\n for (const reconciliation of reconciliations) {\n table.push([\n formatReferenceCell(\"reconciliation\", reconciliation),\n date(reconciliation.as_of_date),\n money(reconciliation.total_debits_cents),\n money(reconciliation.total_credits_cents),\n s(reconciliation.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printValuationsTable(valuations: ApiRecord[]): void {\n const table = makeTable(\"Valuations\", [\"Ref\", \"Date\", \"Type\", \"Valuation\", \"PPS\"]);\n for (const v of valuations) {\n table.push([\n formatReferenceCell(\"valuation\", v),\n date(v.effective_date ?? v.valuation_date ?? v.date),\n s(v.valuation_type ?? v.type),\n money(v.enterprise_value_cents ?? v.enterprise_value ?? v.valuation),\n money(v.fmv_per_share_cents ?? v.price_per_share ?? v.pps ?? v.fmv_per_share),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printTaxFilingsTable(filings: ApiRecord[]): void {\n const table = makeTable(\"Tax Filings\", [\"Ref\", \"Type\", \"Year\", \"Status\", \"Document\"]);\n for (const filing of filings) {\n table.push([\n formatReferenceCell(\"tax_filing\", filing),\n s(filing.document_type),\n s(filing.tax_year),\n s(filing.status),\n s(filing.document_id, 12),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printDeadlinesTable(deadlines: ApiRecord[]): void {\n const table = makeTable(\"Deadlines\", [\"Ref\", \"Type\", \"Due\", \"Status\", \"Description\"]);\n for (const deadline of deadlines) {\n table.push([\n formatReferenceCell(\"deadline\", deadline),\n s(deadline.deadline_type),\n date(deadline.due_date),\n s(deadline.status),\n s(deadline.description),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printClassificationsTable(classifications: ApiRecord[]): void {\n const table = makeTable(\"Contractor Classifications\", [\"Ref\", \"Contractor\", \"State\", \"Risk\", \"Result\"]);\n for (const classification of classifications) {\n table.push([\n formatReferenceCell(\"classification\", classification),\n s(classification.contractor_name),\n s(classification.state),\n s(classification.risk_level),\n s(classification.classification),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printGovernanceTable(bodies: ApiRecord[]): void {\n const table = makeTable(\"Governance Bodies\", [\"Ref\", \"Body\", \"Type\", \"Seats\", \"Meetings\"]);\n for (const b of bodies) {\n table.push([\n formatReferenceCell(\"body\", b),\n s(b.name),\n s(b.body_type ?? b.type),\n s(b.seat_count ?? b.seats),\n s(b.meeting_count ?? b.meetings),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printSeatsTable(seats: ApiRecord[]): void {\n const table = makeTable(\"Seats\", [\"Ref\", \"Holder\", \"Role\", \"Status\"]);\n for (const st of seats) {\n table.push([\n formatReferenceCell(\"seat\", st),\n s(st.holder_name ?? st.holder ?? st.holder_id),\n s(st.role),\n s(st.status),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printMeetingsTable(meetings: ApiRecord[]): void {\n const table = makeTable(\"Meetings\", [\"Ref\", \"Title\", \"Date\", \"Status\", \"Resolutions\"]);\n for (const m of meetings) {\n table.push([\n formatReferenceCell(\"meeting\", m),\n s(m.title ?? m.name),\n s(m.scheduled_date ?? m.meeting_date ?? m.date),\n s(m.status),\n s(m.resolution_count ?? m.resolutions),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printResolutionsTable(resolutions: ApiRecord[]): void {\n const table = makeTable(\"Resolutions\", [\"Ref\", \"Title\", \"Type\", \"Status\", \"For\", \"Against\"]);\n for (const r of resolutions) {\n table.push([\n formatReferenceCell(\"resolution\", r),\n s(r.title),\n s(r.resolution_type ?? r.type),\n s(r.status),\n s(r.votes_for),\n s(r.votes_against),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printAgendaItemsTable(items: ApiRecord[]): void {\n const table = makeTable(\"Agenda Items\", [\"Ref\", \"Title\", \"Status\", \"Type\"]);\n for (const item of items) {\n table.push([\n formatReferenceCell(\"agenda_item\", item),\n s(item.title),\n s(item.status),\n s(item.item_type ?? item.type),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printDocumentsTable(docs: ApiRecord[]): void {\n const table = makeTable(\"Documents\", [\"Ref\", \"Title\", \"Type\", \"Date\", \"Status\", \"Signatures\"]);\n for (const d of docs) {\n const sigs = d.signatures;\n const sigStr = Array.isArray(sigs) ? `${sigs.length} signed` : s(sigs);\n table.push([\n formatReferenceCell(\"document\", d),\n s(d.title ?? d.name),\n s(d.document_type ?? d.type),\n s(d.date ?? d.created_at),\n s(d.status),\n sigStr,\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printWorkItemsTable(items: ApiRecord[]): void {\n const table = makeTable(\"Work Items\", [\"Ref\", \"Title\", \"Category\", \"Status\", \"Deadline\", \"Claimed By\"]);\n for (const w of items) {\n const status = s(w.effective_status ?? w.status);\n const colored =\n status === \"completed\" ? chalk.green(status) :\n status === \"claimed\" ? chalk.yellow(status) :\n status === \"cancelled\" ? chalk.dim(status) :\n status;\n table.push([\n formatReferenceCell(\"work_item\", w),\n s(w.title),\n s(w.category),\n colored,\n w.asap ? chalk.red.bold(\"ASAP\") : s(w.deadline ?? \"\"),\n actorLabel(w, \"claimed_by\"),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printAgentsTable(agents: ApiRecord[]): void {\n const table = makeTable(\"Agents\", [\"Ref\", \"Name\", \"Status\", \"Model\"]);\n for (const a of agents) {\n const status = s(a.status);\n const colored =\n status === \"active\" ? chalk.green(status) : status === \"paused\" ? chalk.yellow(status) : status;\n table.push([formatReferenceCell(\"agent\", a), s(a.name), colored, s(a.model)]);\n }\n console.log(table.toString());\n}\n\nexport function printApprovalsTable(approvals: ApiRecord[]): void {\n const table = makeTable(\"Pending Approvals\", [\"ID\", \"Type\", \"Requested By\", \"Description\", \"Created\"]);\n for (const a of approvals) {\n let desc = s(a.description ?? a.summary);\n if (desc.length > 60) desc = desc.slice(0, 57) + \"...\";\n table.push([\n s(a.approval_id ?? a.id, 12),\n s(a.approval_type ?? a.type),\n s(a.requested_by ?? a.requester),\n desc,\n s(a.created_at),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printServiceCatalogTable(items: ApiRecord[]): void {\n const table = makeTable(\"Service Catalog\", [\"Slug\", \"Name\", \"Price\", \"Type\"]);\n for (const item of items) {\n table.push([\n s(item.slug),\n s(item.name),\n money(item.amount_cents),\n s(item.price_type),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printServiceRequestsTable(requests: ApiRecord[]): void {\n const table = makeTable(\"Service Requests\", [\"Ref\", \"Service\", \"Amount\", \"Status\", \"Created\"]);\n for (const r of requests) {\n const status = s(r.status);\n const colored =\n status === \"fulfilled\" ? chalk.green(status) :\n status === \"paid\" ? chalk.cyan(status) :\n status === \"checkout\" ? chalk.yellow(status) :\n status === \"failed\" ? chalk.dim(status) :\n status;\n table.push([\n formatReferenceCell(\"service_request\", r),\n s(r.service_slug),\n money(r.amount_cents),\n colored,\n date(r.created_at),\n ]);\n }\n console.log(table.toString());\n}\n\nexport function printBillingPanel(status: ApiRecord, plans: ApiRecord[]): void {\n const plan = s(status.plan ?? status.tier) || \"free\";\n const subStatus = s(status.status) || \"active\";\n const periodEnd = s(status.current_period_end);\n const explanation = s(status.status_explanation);\n\n console.log(chalk.green(\"─\".repeat(50)));\n console.log(chalk.green.bold(\" Billing Status\"));\n console.log(chalk.green(\"─\".repeat(50)));\n console.log(` ${chalk.bold(\"Plan:\")} ${plan}`);\n console.log(` ${chalk.bold(\"Status:\")} ${subStatus}`);\n if (periodEnd) console.log(` ${chalk.bold(\"Current Period End:\")} ${periodEnd}`);\n if (explanation) console.log(` ${chalk.bold(\"Explanation:\")} ${explanation}`);\n console.log(chalk.dim(\" Manage: corp billing portal\"));\n console.log(chalk.dim(\" Upgrade: corp billing upgrade --plan <plan>\"));\n console.log(chalk.green(\"─\".repeat(50)));\n\n if (plans.length > 0) {\n const table = makeTable(\"Available Plans\", [\"Plan\", \"Price\", \"Features\"]);\n for (const p of plans) {\n const amount = (p.price_cents ?? p.amount ?? 0) as number;\n const interval = s(p.interval);\n let priceStr = \"Free\";\n if (amount > 0) {\n priceStr = interval ? `$${Math.round(amount / 100)}/${interval}` : `$${Math.round(amount / 100)}`;\n }\n const name = s(p.name ?? p.plan_id ?? p.tier);\n const features = Array.isArray(p.features) ? (p.features as string[]).join(\", \") : s(p.description);\n table.push([name, priceStr, features]);\n }\n console.log(table.toString());\n }\n}\n","export { CorpAPIClient, SessionExpiredError, provisionWorkspace } from \"@thecorporation/corp-tools\";\n","import chalk from \"chalk\";\nimport type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n loadConfig,\n requireConfig,\n resolveEntityId,\n getActiveEntityId,\n saveConfig,\n setActiveEntityId,\n} from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { ReferenceResolver, getReferenceAlias } from \"../references.js\";\nimport {\n printError,\n printJson,\n printStatusPanel,\n printNextSteps,\n printBillingPanel,\n printReferenceSummary,\n printSuccess,\n printWarning,\n} from \"../output.js\";\nimport { withSpinner } from \"../spinner.js\";\nimport type { NextStepsResponse, NextStepItem } from \"@thecorporation/corp-tools\";\nimport type { ApiRecord } from \"../types.js\";\n\n// ---------------------------------------------------------------------------\n// Local helpers (relocated from individual command files)\n// ---------------------------------------------------------------------------\n\n/** Pre-flight local checks for `next` (runs before any API call). */\nfunction localChecks(): NextStepItem[] {\n const items: NextStepItem[] = [];\n let cfg;\n try {\n cfg = loadConfig();\n } catch {\n items.push({\n category: \"setup\",\n title: \"Run initial setup\",\n description: \"No configuration found\",\n command: \"npx corp setup\",\n urgency: \"critical\",\n });\n return items;\n }\n\n if (!cfg.api_key) {\n items.push({\n category: \"setup\",\n title: \"Run setup to configure API key\",\n description: \"No API key configured\",\n command: \"npx corp setup\",\n urgency: \"critical\",\n });\n return items;\n }\n\n if (!cfg.workspace_id) {\n items.push({\n category: \"setup\",\n title: \"Claim a workspace\",\n description: \"No workspace configured\",\n command: \"npx corp claim <code>\",\n urgency: \"critical\",\n });\n return items;\n }\n\n if (!getActiveEntityId(cfg)) {\n items.push({\n category: \"setup\",\n title: \"Set an active entity\",\n description: \"No active entity — set one to get entity-specific recommendations\",\n command: \"npx corp use <entity-name>\",\n urgency: \"high\",\n });\n }\n\n return items;\n}\n\n/** Enrich billing status with explanation when pending_checkout. */\nfunction enrichBillingStatus(status: ApiRecord): ApiRecord {\n if (typeof status.status_explanation === \"string\" && status.status_explanation.trim()) {\n return status;\n }\n\n const plan = String(status.plan ?? status.tier ?? \"\").trim();\n const subStatus = String(status.status ?? \"\").trim();\n if (subStatus !== \"pending_checkout\") {\n return status;\n }\n\n const statusExplanation = plan\n ? `Checkout for the ${plan} plan has started, but billing will not become active until Stripe checkout is completed.`\n : \"Checkout has started, but billing will not become active until Stripe checkout is completed.\";\n\n return { ...status, status_explanation: statusExplanation };\n}\n\n// ---------------------------------------------------------------------------\n// Registry entries\n// ---------------------------------------------------------------------------\n\nexport const workspaceCommands: CommandDef[] = [\n // --- status ---\n {\n name: \"status\",\n description: \"Workspace summary\",\n route: { method: \"GET\", path: \"/v1/workspaces/{wid}/status\" },\n display: { title: \"Corp Status\" },\n handler: async (ctx) => {\n try {\n const data = await withSpinner(\"Loading\", () => ctx.client.getStatus());\n if (ctx.opts.json) {\n ctx.writer.json(data);\n } else {\n printStatusPanel(data);\n }\n } catch (err) {\n ctx.writer.error(`Failed to fetch status: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp status\"],\n },\n\n // --- context / whoami ---\n {\n name: \"context\",\n description: \"Show the active workspace, user, and entity context\",\n aliases: [\"whoami\"],\n display: { title: \"Corp Context\" },\n handler: async (ctx) => {\n const rawCfg = loadConfig();\n const resolver = new ReferenceResolver(ctx.client, rawCfg);\n\n try {\n const [status, entities] = await Promise.all([\n ctx.client.getStatus(),\n ctx.client.listEntities(),\n ]);\n await resolver.stabilizeRecords(\"entity\", entities);\n\n const activeEntityId = getActiveEntityId(rawCfg);\n const activeEntity = activeEntityId\n ? entities.find((entity) => entity.entity_id === activeEntityId) ?? null\n : null;\n\n const [contactsResult, documentsResult, workItemsResult] = activeEntity\n ? await Promise.allSettled([\n ctx.client.listContacts(String(activeEntity.entity_id)),\n ctx.client.getEntityDocuments(String(activeEntity.entity_id)),\n ctx.client.listWorkItems(String(activeEntity.entity_id)),\n ])\n : [null, null, null];\n\n const payload = {\n user: {\n name: rawCfg.user?.name ?? \"\",\n email: rawCfg.user?.email ?? \"\",\n },\n workspace: {\n workspace_id: rawCfg.workspace_id,\n api_url: rawCfg.api_url,\n status,\n },\n active_entity: activeEntity\n ? {\n entity: activeEntity,\n summary: {\n contact_count:\n contactsResult && contactsResult.status === \"fulfilled\"\n ? contactsResult.value.length\n : null,\n document_count:\n documentsResult && documentsResult.status === \"fulfilled\"\n ? documentsResult.value.length\n : null,\n work_item_count:\n workItemsResult && workItemsResult.status === \"fulfilled\"\n ? workItemsResult.value.length\n : null,\n },\n }\n : null,\n entity_count: entities.length,\n };\n\n if (ctx.opts.json) {\n ctx.writer.json(payload);\n return;\n }\n\n console.log(chalk.blue(\"\\u2500\".repeat(50)));\n console.log(chalk.blue.bold(\" Corp Context\"));\n console.log(chalk.blue(\"\\u2500\".repeat(50)));\n console.log(` ${chalk.bold(\"User:\")} ${payload.user.name || \"N/A\"} <${payload.user.email || \"N/A\"}>`);\n console.log(` ${chalk.bold(\"Workspace:\")} ${rawCfg.workspace_id}`);\n console.log(` ${chalk.bold(\"API URL:\")} ${rawCfg.api_url}`);\n console.log(` ${chalk.bold(\"Entities:\")} ${entities.length}`);\n if (payload.active_entity) {\n console.log(` ${chalk.bold(\"Active Entity:\")} ${payload.active_entity.entity.legal_name ?? payload.active_entity.entity.entity_id}`);\n printReferenceSummary(\"entity\", payload.active_entity.entity, { label: \"Active Entity Ref:\" });\n console.log(` ${chalk.bold(\"Contacts:\")} ${payload.active_entity.summary.contact_count ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Documents:\")} ${payload.active_entity.summary.document_count ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Work Items:\")} ${payload.active_entity.summary.work_item_count ?? \"N/A\"}`);\n } else {\n console.log(` ${chalk.bold(\"Active Entity:\")} none`);\n }\n if ((status as Record<string, unknown>).next_deadline) {\n console.log(` ${chalk.bold(\"Next Deadline:\")} ${(status as Record<string, unknown>).next_deadline}`);\n }\n console.log(chalk.blue(\"\\u2500\".repeat(50)));\n } catch (err) {\n ctx.writer.error(`Failed to fetch context: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp context\", \"corp context --json\"],\n },\n\n // --- use <entity-ref> ---\n {\n name: \"use\",\n description: \"Set the active entity by name, short ID, or reference\",\n args: [{ name: \"entity-ref\", required: true, description: \"Entity name, short ID, or reference\" }],\n handler: async (ctx) => {\n const entityRef = ctx.positional[0];\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n try {\n const entityId = await resolver.resolveEntity(entityRef);\n setActiveEntityId(cfg, entityId);\n saveConfig(cfg);\n const alias = getReferenceAlias(\"entity\", { entity_id: entityId }) ?? entityId;\n ctx.writer.success(`Active entity set to ${alias} (${entityId})`);\n } catch (err) {\n ctx.writer.error(`Failed to resolve entity: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp use\", \"corp use --json\"],\n },\n\n // --- next ---\n {\n name: \"next\",\n description: \"See what to do next — your recommended actions\",\n options: [\n { flags: \"--entity-id <ref>\", description: \"Entity to check (default: active entity)\" },\n { flags: \"--workspace\", description: \"Show recommendations across all entities\" },\n ],\n examples: [\n \"$ corp next # Next steps for active entity\",\n \"$ corp next --workspace # Next steps across all entities\",\n \"$ corp next --entity-id ent_abc123 # Next steps for specific entity\",\n \"$ corp next --json # JSON output for scripting\",\n ],\n handler: async (ctx) => {\n const opts = ctx.opts as { entityId?: string; workspace?: boolean; json?: boolean };\n\n if (opts.entityId && opts.workspace) {\n ctx.writer.error(\"--entity-id and --workspace are mutually exclusive\");\n process.exit(1);\n }\n\n const localItems = localChecks();\n const hasCriticalLocal = localItems.some((i) => i.urgency === \"critical\");\n\n if (hasCriticalLocal) {\n const top = localItems[0];\n const backlog = localItems.slice(1);\n const summary = { critical: 0, high: 0, medium: 0, low: 0 };\n for (const item of [top, ...backlog]) {\n const key = item.urgency as keyof typeof summary;\n if (key in summary) summary[key]++;\n }\n const response = { top, backlog, summary };\n if (opts.json) {\n ctx.writer.json(response);\n } else {\n printNextSteps(response);\n }\n return;\n }\n\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n\n try {\n let data: NextStepsResponse;\n if (opts.workspace) {\n data = await withSpinner(\"Loading\", () => client.getWorkspaceNextSteps(), opts.json);\n } else {\n const entityId = resolveEntityId(cfg, opts.entityId);\n data = await withSpinner(\"Loading\", () => client.getEntityNextSteps(entityId), opts.json);\n }\n\n // Merge non-critical local items into backlog\n if (localItems.length > 0) {\n data.backlog.push(...localItems);\n const all = [data.top, ...data.backlog].filter(Boolean) as NextStepItem[];\n data.summary = { critical: 0, high: 0, medium: 0, low: 0 };\n for (const item of all) {\n const key = item.urgency as keyof typeof data.summary;\n if (key in data.summary) data.summary[key]++;\n }\n }\n\n if (opts.json) {\n ctx.writer.json(data);\n } else {\n printNextSteps(data);\n }\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"Not found\") || msg.includes(\"404\")) {\n // Entity store may not exist yet (e.g. formation not finalized)\n if (localItems.length > 0) {\n const top = localItems[0];\n const backlog = localItems.slice(1);\n const summary = { critical: 0, high: 0, medium: 0, low: 0 };\n for (const item of [top, ...backlog]) {\n const key = item.urgency as keyof typeof summary;\n if (key in summary) summary[key]++;\n }\n const response = { top, backlog, summary };\n if (opts.json) { ctx.writer.json(response); } else { printNextSteps(response); }\n } else {\n console.log(\"No entities found yet. Get started:\\n\");\n console.log(' corp form --type c_corp --name \"My Company\" --member \"Name,email,director,100,street|city|state|zip,ceo,true\"');\n console.log(\"\\n Or use the staged flow:\");\n console.log(' corp form create --type llc --name \"My LLC\"');\n console.log(' corp form add-founder @last --name \"Alice\" --email \"a@co.com\" --role member --ownership-pct 100');\n console.log(\" corp form finalize @last\");\n }\n } else {\n ctx.writer.error(`Failed to fetch next steps: ${err}`);\n process.exit(1);\n }\n }\n },\n },\n\n // --- obligations (pure read) ---\n {\n name: \"obligations\",\n description: \"List obligations with urgency tiers\",\n route: { method: \"GET\", path: \"/v1/obligations/summary\" },\n display: {\n title: \"Obligations\",\n listKey: \"obligations\",\n cols: [\n \"obligation_type>Type\",\n \"urgency>Urgency\",\n \"@due_at>Due\",\n \"status>Status\",\n \"#obligation_id>ID\",\n ],\n },\n optQP: [\"tier\"],\n options: [{ flags: \"--tier <tier>\", description: \"Filter by urgency tier\" }],\n examples: [\"corp obligations\"],\n },\n\n // --- digest ---\n {\n name: \"digest\",\n description: \"View or trigger daily digests\",\n route: { method: \"GET\", path: \"/v1/digests\" },\n display: { title: \"Digests\" },\n options: [\n { flags: \"--trigger\", description: \"Trigger digest now\" },\n { flags: \"--key <key>\", description: \"Get specific digest by key\" },\n { flags: \"--entity-id <ref>\", description: \"Entity reference (ID, short ID, @last, or unique name)\" },\n ],\n handler: async (ctx) => {\n const opts = ctx.opts as { trigger?: boolean; key?: string; entityId?: string; json?: boolean };\n try {\n if (opts.trigger) {\n const result = await ctx.client.triggerDigest();\n const message = (() => {\n const value = (result as Record<string, unknown>).message;\n return typeof value === \"string\" && value.trim() ? value : null;\n })();\n if (!opts.json) {\n ctx.writer.success(result.digest_count > 0 ? \"Digest triggered.\" : \"Digest trigger accepted.\");\n }\n if (message && !opts.json) {\n ctx.writer.warning(message);\n }\n ctx.writer.json(result);\n } else if (opts.key) {\n const result = await ctx.client.getDigest(opts.key);\n ctx.writer.json(result);\n } else {\n const digests = await ctx.client.listDigests();\n if (digests.length === 0) {\n if (opts.json) {\n ctx.writer.json([]);\n } else {\n ctx.writer.writeln(\"No digest history found.\");\n }\n } else {\n ctx.writer.json(digests);\n }\n }\n } catch (err) {\n ctx.writer.error(`Failed: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp digest\"],\n },\n\n // --- billing ---\n {\n name: \"billing\",\n description: \"Billing status, plans, and subscription management\",\n display: { title: \"Billing\" },\n handler: async (ctx) => {\n try {\n const [status, plans] = await Promise.all([\n ctx.client.getBillingStatus(),\n ctx.client.getBillingPlans(),\n ]);\n const enrichedStatus = enrichBillingStatus(status);\n if (ctx.opts.json) {\n ctx.writer.json({ status: enrichedStatus, plans });\n } else {\n printBillingPanel(enrichedStatus, plans);\n }\n } catch (err) {\n ctx.writer.error(`Failed to fetch billing info: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp billing\"],\n },\n\n // --- billing portal ---\n {\n name: \"billing portal\",\n description: \"Open Stripe Customer Portal\",\n route: { method: \"POST\", path: \"/v1/billing/portal\" },\n handler: async (ctx) => {\n try {\n const result = await ctx.client.createBillingPortal();\n const url = result.portal_url as string;\n if (!url) {\n ctx.writer.error(\"No portal URL returned. Ensure you have an active subscription.\");\n process.exit(1);\n }\n ctx.writer.success(\"Stripe Customer Portal URL:\");\n ctx.writer.writeln(url);\n } catch (err) {\n ctx.writer.error(`Failed to create portal session: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp billing portal\"],\n },\n\n // --- billing upgrade ---\n {\n name: \"billing upgrade\",\n description: \"Open Stripe Checkout to upgrade your plan\",\n route: { method: \"POST\", path: \"/v1/billing/checkout\" },\n options: [\n {\n flags: \"--plan <plan>\",\n description: \"Plan ID to upgrade to (free, pro, enterprise)\",\n default: \"pro\",\n choices: [\"free\", \"pro\", \"enterprise\"],\n },\n ],\n handler: async (ctx) => {\n const opts = ctx.opts as { plan: string };\n try {\n const result = await ctx.client.createBillingCheckout(opts.plan);\n const url = result.checkout_url as string;\n if (!url) {\n ctx.writer.error(\"No checkout URL returned.\");\n process.exit(1);\n }\n ctx.writer.success(`Stripe Checkout URL for ${opts.plan}:`);\n ctx.writer.writeln(url);\n } catch (err) {\n ctx.writer.error(`Failed to create checkout session: ${err}`);\n process.exit(1);\n }\n },\n examples: [\"corp billing upgrade\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"entities next-steps\",\n description: \"View recommended next actions for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/next-steps\" },\n entity: true,\n display: { title: \"Entities Next Steps\", cols: [\"backlog>Backlog\", \"summary>Summary\", \"top>Top\"] },\n examples: [\"corp entities next-steps\", \"corp entities next-steps --json\"],\n },\n {\n name: \"workspaces next-steps\",\n description: \"View recommended next actions across the workspace\",\n route: { method: \"GET\", path: \"/v1/workspaces/{workspace_id}/next-steps\" },\n display: { title: \"Workspaces Next Steps\", cols: [\"backlog>Backlog\", \"summary>Summary\", \"top>Top\"] },\n examples: [\"corp workspaces next-steps\"],\n },\n\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport { printEntitiesTable, printContactsTable, printError, printJson, printReferenceSummary, printSuccess, printWriteResult } from \"../output.js\";\nimport { withSpinner } from \"../spinner.js\";\nimport { confirm } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport type { ApiRecord } from \"../types.js\";\n\n// ── Entity handlers ────────────────────────────────────────────\n\nasync function entitiesHandler(ctx: CommandContext): Promise<void> {\n const jsonOutput = !!ctx.opts.json;\n try {\n const entities = await withSpinner(\"Loading\", () => ctx.client.listEntities(), jsonOutput);\n await ctx.resolver.stabilizeRecords(\"entity\", entities);\n if (jsonOutput) {\n printJson(entities);\n } else if (entities.length === 0) {\n console.log(\"No entities found.\");\n } else {\n printEntitiesTable(entities);\n }\n } catch (err) {\n printError(`Failed to fetch entities: ${err}`);\n process.exit(1);\n }\n}\n\nasync function entitiesShowHandler(ctx: CommandContext): Promise<void> {\n const entityRef = ctx.positional[0];\n const jsonOutput = !!ctx.opts.json;\n const quiet = !!ctx.opts.quiet;\n try {\n const resolvedEntityId = await ctx.resolver.resolveEntity(entityRef);\n const entities = await ctx.client.listEntities();\n const entity = entities.find((e: ApiRecord) => e.entity_id === resolvedEntityId);\n if (!entity) {\n printError(`Entity not found: ${entityRef}`);\n process.exit(1);\n }\n await ctx.resolver.stabilizeRecord(\"entity\", entity);\n if (quiet) {\n console.log(String(entity.entity_id ?? resolvedEntityId));\n return;\n }\n if (jsonOutput) {\n printJson(entity);\n } else {\n console.log(chalk.blue(\"\\u2500\".repeat(40)));\n console.log(chalk.blue.bold(\" Entity Detail\"));\n console.log(chalk.blue(\"\\u2500\".repeat(40)));\n console.log(` ${chalk.bold(\"Name:\")} ${entity.legal_name ?? entity.name ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Type:\")} ${entity.entity_type ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Jurisdiction:\")} ${entity.jurisdiction ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Status:\")} ${entity.formation_status ?? entity.status ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"State:\")} ${entity.formation_state ?? \"N/A\"}`);\n printReferenceSummary(\"entity\", entity, { showReuseHint: true });\n if (entity.formation_date) console.log(` ${chalk.bold(\"Formation Date:\")} ${entity.formation_date}`);\n if (entity.ein) console.log(` ${chalk.bold(\"EIN:\")} ${entity.ein}`);\n console.log(chalk.blue(\"\\u2500\".repeat(40)));\n }\n } catch (err) {\n printError(`Failed to fetch entities: ${err}`);\n process.exit(1);\n }\n}\n\nasync function entitiesConvertHandler(ctx: CommandContext): Promise<void> {\n const entityRef = ctx.positional[0];\n try {\n const resolvedEntityId = await ctx.resolver.resolveEntity(entityRef);\n const data: Record<string, string> = { target_type: ctx.opts.to as string };\n if (ctx.opts.jurisdiction) data.new_jurisdiction = ctx.opts.jurisdiction as string;\n const result = await ctx.client.convertEntity(resolvedEntityId, data);\n printSuccess(`Entity conversion initiated: ${result.conversion_id ?? \"OK\"}`);\n printJson(result);\n } catch (err) {\n printError(`Failed to convert entity: ${err}`);\n process.exit(1);\n }\n}\n\nasync function entitiesDissolveHandler(ctx: CommandContext): Promise<void> {\n const entityRef = ctx.positional[0];\n try {\n const resolvedEntityId = await ctx.resolver.resolveEntity(entityRef);\n if (!ctx.opts.yes) {\n const ok = await confirm({\n message: `Dissolve entity ${entityRef}? This cannot be undone.`,\n default: false,\n });\n if (!ok) {\n console.log(\"Cancelled.\");\n return;\n }\n }\n const data: Record<string, string> = { reason: ctx.opts.reason as string };\n if (ctx.opts.effectiveDate) data.effective_date = ctx.opts.effectiveDate as string;\n const result = await ctx.client.dissolveEntity(resolvedEntityId, data);\n printSuccess(`Dissolution initiated: ${result.dissolution_id ?? \"OK\"}`);\n printJson(result);\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"InvalidTransition\") || msg.includes(\"422\")) {\n printError(`Cannot dissolve entity: only entities with 'active' status can be dissolved. Check the entity's current status with: corp entities show ${entityRef}`);\n } else {\n printError(`Failed to dissolve entity: ${err}`);\n }\n process.exit(1);\n }\n}\n\n// ── Contact handlers ───────────────────────────────────────────\n\nasync function contactsHandler(ctx: CommandContext): Promise<void> {\n const jsonOutput = !!ctx.opts.json;\n try {\n const eid = await ctx.resolver.resolveEntity(ctx.entityId);\n const contacts = await ctx.client.listContacts(eid);\n await ctx.resolver.stabilizeRecords(\"contact\", contacts, eid);\n if (jsonOutput) printJson(contacts);\n else if (contacts.length === 0) console.log(\"No contacts found.\");\n else printContactsTable(contacts);\n } catch (err) {\n printError(`Failed to fetch contacts: ${err}`);\n process.exit(1);\n }\n}\n\nasync function contactsShowHandler(ctx: CommandContext): Promise<void> {\n const contactRef = ctx.positional[0];\n const jsonOutput = !!ctx.opts.json;\n try {\n const eid = await ctx.resolver.resolveEntity(ctx.entityId);\n const resolvedContactId = await ctx.resolver.resolveContact(eid, contactRef);\n const profile = await ctx.client.getContactProfile(resolvedContactId, eid);\n const contact = await ctx.resolver.stabilizeRecord(\"contact\", (profile.contact ?? profile) as ApiRecord, eid);\n if (jsonOutput) {\n printJson(profile);\n } else {\n console.log(chalk.cyan(\"\\u2500\".repeat(40)));\n console.log(chalk.cyan.bold(\" Contact Profile\"));\n console.log(chalk.cyan(\"\\u2500\".repeat(40)));\n console.log(` ${chalk.bold(\"Name:\")} ${contact.name ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Email:\")} ${contact.email ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Category:\")} ${contact.category ?? \"N/A\"}`);\n printReferenceSummary(\"contact\", contact, { showReuseHint: true });\n if (contact.phone) console.log(` ${chalk.bold(\"Phone:\")} ${contact.phone}`);\n if (contact.notes) console.log(` ${chalk.bold(\"Notes:\")} ${contact.notes}`);\n const holdings = profile.equity_holdings as ApiRecord[] | undefined;\n if (holdings?.length) {\n console.log(`\\n ${chalk.bold(\"Equity Holdings:\")}`);\n for (const h of holdings) console.log(` ${h.share_class ?? \"?\"}: ${h.shares ?? \"?\"} shares`);\n }\n const obls = profile.obligations as unknown[];\n if (obls?.length) console.log(`\\n ${chalk.bold(\"Obligations:\")} ${obls.length}`);\n console.log(chalk.cyan(\"\\u2500\".repeat(40)));\n }\n } catch (err) {\n printError(`Failed to fetch contact: ${err}`);\n process.exit(1);\n }\n}\n\nasync function contactsAddHandler(ctx: CommandContext): Promise<void> {\n const jsonOutput = !!ctx.opts.json;\n try {\n const eid = await ctx.resolver.resolveEntity(ctx.entityId);\n const data: ApiRecord = {\n entity_id: eid,\n contact_type: (ctx.opts.type as string) ?? \"individual\",\n name: ctx.opts.name as string,\n email: ctx.opts.email as string,\n category: (ctx.opts.category as string) ?? \"employee\",\n };\n if (ctx.opts.phone) data.phone = ctx.opts.phone;\n if (ctx.opts.notes) data.notes = ctx.opts.notes;\n if (ctx.opts.mailingAddress ?? ctx.opts.address) data.mailing_address = ctx.opts.mailingAddress ?? ctx.opts.address;\n if (ctx.opts.capTableAccess) data.cap_table_access = ctx.opts.capTableAccess;\n const result = await ctx.client.createContact(data);\n await ctx.resolver.stabilizeRecord(\"contact\", result, eid);\n ctx.resolver.rememberFromRecord(\"contact\", result, eid);\n printWriteResult(\n result,\n `Contact created: ${result.contact_id ?? result.id ?? \"OK\"}`,\n { jsonOnly: jsonOutput, referenceKind: \"contact\", showReuseHint: true },\n );\n } catch (err) {\n printError(`Failed to create contact: ${err}`);\n process.exit(1);\n }\n}\n\nasync function contactsEditHandler(ctx: CommandContext): Promise<void> {\n const contactRef = ctx.positional[0];\n const jsonOutput = !!ctx.opts.json;\n try {\n const eid = await ctx.resolver.resolveEntity(ctx.entityId);\n const resolvedContactId = await ctx.resolver.resolveContact(eid, contactRef);\n const data: ApiRecord = { entity_id: eid };\n let hasUpdates = false;\n if (ctx.opts.name != null) { data.name = ctx.opts.name; hasUpdates = true; }\n if (ctx.opts.email != null) { data.email = ctx.opts.email; hasUpdates = true; }\n if (ctx.opts.category != null) { data.category = ctx.opts.category; hasUpdates = true; }\n if (ctx.opts.phone != null) { data.phone = ctx.opts.phone; hasUpdates = true; }\n if (ctx.opts.notes != null) { data.notes = ctx.opts.notes; hasUpdates = true; }\n if (ctx.opts.capTableAccess != null) { data.cap_table_access = ctx.opts.capTableAccess; hasUpdates = true; }\n if (ctx.opts.mailingAddress != null || ctx.opts.address != null) {\n data.mailing_address = ctx.opts.mailingAddress ?? ctx.opts.address;\n hasUpdates = true;\n }\n if (!hasUpdates) {\n console.log(\"No fields to update.\");\n return;\n }\n const result = await ctx.client.updateContact(resolvedContactId, data);\n ctx.resolver.remember(\"contact\", resolvedContactId, eid);\n printWriteResult(result, \"Contact updated.\", jsonOutput);\n } catch (err) {\n printError(`Failed to update contact: ${err}`);\n process.exit(1);\n }\n}\n\n// ── Command definitions ────────────────────────────────────────\n\nexport const entityCommands: CommandDef[] = [\n // ── entities ──\n {\n name: \"entities\",\n description: \"List all entities\",\n handler: entitiesHandler,\n examples: [\"corp entities\"],\n },\n {\n name: \"entities show\",\n description: \"Show entity detail\",\n args: [{ name: \"entity-ref\", required: true }],\n handler: entitiesShowHandler,\n examples: [\"corp entities show\"],\n },\n {\n name: \"entities convert\",\n description: \"Convert entity to a different type\",\n route: { method: \"POST\", path: \"/v1/entities/{pos}/convert\" },\n args: [{ name: \"entity-ref\", required: true }],\n options: [\n { flags: \"--to <type>\", description: \"Target entity type (llc, c_corp)\", required: true },\n { flags: \"--jurisdiction <jurisdiction>\", description: \"New jurisdiction\" },\n ],\n handler: entitiesConvertHandler,\n examples: [\"corp entities convert <entity-ref> --to 'type'\", \"corp entities convert --json\"],\n },\n {\n name: \"entities dissolve\",\n description: \"Dissolve an entity\",\n route: { method: \"POST\", path: \"/v1/entities/{pos}/dissolve\" },\n args: [{ name: \"entity-ref\", required: true }],\n options: [\n { flags: \"--reason <reason>\", description: \"Dissolution reason\", required: true },\n { flags: \"--effective-date <date>\", description: \"Effective date (ISO 8601)\" },\n { flags: \"--yes, -y\", description: \"Skip confirmation prompt\" },\n ],\n handler: entitiesDissolveHandler,\n examples: [\"corp entities dissolve <entity-ref> --reason 'reason'\", \"corp entities dissolve --json\"],\n },\n\n // ── contacts ──\n {\n name: \"contacts\",\n description: \"Contact management\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/contacts\" },\n entity: true,\n display: {\n title: \"Contacts\",\n cols: [\"name>Name\", \"email>Email\", \"category>Category\", \"#contact_id>ID\"],\n },\n handler: contactsHandler,\n examples: [\"corp contacts\", \"corp contacts --json\"],\n },\n {\n name: \"contacts show\",\n description: \"Show contact detail/profile\",\n route: { method: \"GET\", path: \"/v1/contacts/{pos}/profile\" },\n entity: \"query\",\n display: { title: \"Contact Profile\" },\n args: [{ name: \"contact-ref\", required: true }],\n handler: contactsShowHandler,\n examples: [\"corp contacts show\", \"corp contacts show --json\"],\n },\n {\n name: \"contacts add\",\n description: \"Add a new contact\",\n route: { method: \"POST\", path: \"/v1/contacts\" },\n entity: true,\n options: [\n { flags: \"--name <name>\", description: \"Contact name\", required: true },\n { flags: \"--email <email>\", description: \"Contact email\", required: true },\n { flags: \"--type <type>\", description: \"Contact type (individual, organization)\", default: \"individual\" },\n { flags: \"--category <category>\", description: \"Category (employee, contractor, board_member, investor, law_firm, valuation_firm, accounting_firm, officer, founder, member, other)\" },\n { flags: \"--cap-table-access <level>\", description: \"Cap table access (none, summary, detailed)\" },\n { flags: \"--address <address>\", description: \"Mailing address\" },\n { flags: \"--mailing-address <address>\", description: \"Alias for --address\" },\n { flags: \"--phone <phone>\", description: \"Phone number\" },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n ],\n handler: contactsAddHandler,\n produces: { kind: \"contact\" },\n successTemplate: \"Contact created: {name}\",\n examples: [\"corp contacts add --name 'name' --email 'email'\", \"corp contacts add --json\"],\n },\n {\n name: \"contacts edit\",\n description: \"Edit an existing contact\",\n route: { method: \"PATCH\", path: \"/v1/contacts/{pos}\" },\n entity: true,\n args: [{ name: \"contact-ref\", required: true }],\n options: [\n { flags: \"--name <name>\", description: \"Contact name\" },\n { flags: \"--email <email>\", description: \"Contact email\" },\n { flags: \"--category <category>\", description: \"Contact category\" },\n { flags: \"--cap-table-access <level>\", description: \"Cap table access (none, summary, detailed)\" },\n { flags: \"--address <address>\", description: \"Mailing address\" },\n { flags: \"--mailing-address <address>\", description: \"Alias for --address\" },\n { flags: \"--phone <phone>\", description: \"Phone number\" },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n ],\n handler: contactsEditHandler,\n examples: [\"corp contacts edit <contact-ref>\", \"corp contacts edit --json\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"contacts notification-prefs\",\n description: \"View notification preferences for a contact\",\n route: { method: \"GET\", path: \"/v1/contacts/{pos}/notification-prefs\" },\n args: [{ name: \"contact-id\", required: true, description: \"Contact ID\" }],\n display: { title: \"Contacts Notification Prefs\", cols: [\"#contact_id>ID\", \"email_enabled>Email Enabled\", \"sms_enabled>Sms Enabled\", \"@updated_at>Updated At\", \"webhook_enabled>Webhook Enabled\"] },\n examples: [\"corp contacts notification-prefs\"],\n },\n {\n name: \"contacts update-notification-prefs\",\n description: \"View notification preferences for a contact\",\n route: { method: \"PATCH\", path: \"/v1/contacts/{pos}/notification-prefs\" },\n args: [{ name: \"contact-id\", required: true, description: \"Contact ID\" }],\n options: [\n { flags: \"--email-enabled <email-enabled>\", description: \"Email Enabled\" },\n { flags: \"--sms-enabled <sms-enabled>\", description: \"Sms Enabled\" },\n { flags: \"--webhook-enabled <webhook-enabled>\", description: \"Webhook Enabled\" },\n ],\n examples: [\"corp contacts notification-prefs <contact-id>\", \"corp contacts notification-prefs --json\"],\n successTemplate: \"Notification Prefs updated\",\n },\n\n];","import { CorpAPIClient } from \"./api-client.js\";\nimport { ReferenceResolver } from \"./references.js\";\nimport type { ApiRecord } from \"./types.js\";\n\nconst DEFAULT_SIGNATURE_CONSENT = \"I agree to sign this document electronically.\";\nconst DEFAULT_ATTESTATION_CONSENT = \"I attest the filing information is accurate and authorized.\";\n\ntype SignatureRequirement = {\n role: string;\n signer_name: string;\n signer_email?: string;\n};\n\nexport type AutoSignSummary = {\n documents_seen: number;\n documents_signed: number;\n signatures_added: number;\n documents: ApiRecord[];\n};\n\nexport type ActivationSummary = {\n entity_id: string;\n initial_status: string;\n final_status: string;\n signatures_added: number;\n documents_signed: number;\n steps: string[];\n formation: ApiRecord;\n};\n\nfunction normalizeRole(value: unknown): string {\n return String(value ?? \"\").trim().toLowerCase();\n}\n\nfunction fallbackSignerEmail(requirement: SignatureRequirement): string {\n const slug = String(requirement.signer_name ?? \"signer\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \".\")\n .replace(/^\\.+|\\.+$/g, \"\");\n return `${slug || \"signer\"}@example.com`;\n}\n\nfunction getSignatureRequirements(document: ApiRecord): SignatureRequirement[] {\n const content = document.content;\n if (!content || typeof content !== \"object\" || Array.isArray(content)) {\n return [];\n }\n const requirements = (content as ApiRecord).signature_requirements;\n if (!Array.isArray(requirements)) {\n return [];\n }\n return requirements\n .filter((item): item is ApiRecord => typeof item === \"object\" && item !== null && !Array.isArray(item))\n .map((item) => ({\n role: String(item.role ?? \"\").trim(),\n signer_name: String(item.signer_name ?? \"\").trim(),\n signer_email:\n typeof item.signer_email === \"string\" && item.signer_email.trim()\n ? item.signer_email.trim()\n : undefined,\n }))\n .filter((item) => item.role.length > 0 && item.signer_name.length > 0);\n}\n\nfunction getSignedRoles(document: ApiRecord): Set<string> {\n const signatures = Array.isArray(document.signatures) ? document.signatures : [];\n return new Set(\n signatures\n .filter((item): item is ApiRecord => typeof item === \"object\" && item !== null && !Array.isArray(item))\n .map((item) => normalizeRole(item.signer_role))\n .filter(Boolean),\n );\n}\n\nfunction deterministicEin(entityId: string): string {\n const digits = entityId.replace(/\\D/g, \"\");\n const nineDigits = `${digits}123456789`.slice(0, 9).padEnd(9, \"0\");\n return `${nineDigits.slice(0, 2)}-${nineDigits.slice(2)}`;\n}\n\nfunction filingIdentifier(prefix: string, entityId: string): string {\n const token = entityId.replace(/[^a-zA-Z0-9]/g, \"\").slice(0, 12).toLowerCase() || \"formation\";\n return `${prefix}-${token}`;\n}\n\nexport async function autoSignFormationDocument(\n client: CorpAPIClient,\n entityId: string,\n documentId: string,\n): Promise<{ document: ApiRecord; signatures_added: number }> {\n const document = await client.getDocument(documentId, entityId) as ApiRecord;\n const requiredSignatures = getSignatureRequirements(document);\n if (requiredSignatures.length === 0) {\n return { document, signatures_added: 0 };\n }\n\n const signedRoles = getSignedRoles(document);\n let signaturesAdded = 0;\n for (const requirement of requiredSignatures) {\n if (signedRoles.has(normalizeRole(requirement.role))) {\n continue;\n }\n await client.signDocument(documentId, entityId, {\n signer_name: requirement.signer_name,\n signer_role: requirement.role,\n signer_email: requirement.signer_email ?? fallbackSignerEmail(requirement),\n signature_text: requirement.signer_name,\n consent_text: DEFAULT_SIGNATURE_CONSENT,\n });\n signedRoles.add(normalizeRole(requirement.role));\n signaturesAdded += 1;\n }\n\n const refreshed = await client.getDocument(documentId, entityId) as ApiRecord;\n return { document: refreshed, signatures_added: signaturesAdded };\n}\n\nexport async function autoSignFormationDocuments(\n client: CorpAPIClient,\n resolver: ReferenceResolver,\n entityId: string,\n): Promise<AutoSignSummary> {\n const summaries = await client.getEntityDocuments(entityId) as ApiRecord[];\n await resolver.stabilizeRecords(\"document\", summaries, entityId);\n\n let signaturesAdded = 0;\n let documentsSigned = 0;\n const documents: ApiRecord[] = [];\n\n for (const summary of summaries) {\n const documentId = String(summary.document_id ?? \"\");\n if (!documentId) {\n continue;\n }\n const { document, signatures_added } = await autoSignFormationDocument(\n client,\n entityId,\n documentId,\n );\n signaturesAdded += signatures_added;\n if (signatures_added > 0) {\n documentsSigned += 1;\n }\n documents.push(document);\n }\n\n return {\n documents_seen: summaries.length,\n documents_signed: documentsSigned,\n signatures_added: signaturesAdded,\n documents,\n };\n}\n\nexport async function activateFormationEntity(\n client: CorpAPIClient,\n resolver: ReferenceResolver,\n entityId: string,\n options: {\n evidenceUri?: string;\n evidenceType?: string;\n filingId?: string;\n receiptReference?: string;\n ein?: string;\n } = {},\n): Promise<ActivationSummary> {\n let formation = await client.getFormation(entityId) as ApiRecord;\n const initialStatus = String(formation.formation_status ?? \"\");\n const steps: string[] = [];\n let signaturesAdded = 0;\n let documentsSigned = 0;\n\n for (let i = 0; i < 10; i += 1) {\n const status = String(formation.formation_status ?? \"\");\n if (status === \"active\") {\n if (initialStatus === \"active\") {\n steps.push(\"entity is already active — no action needed\");\n }\n return {\n entity_id: entityId,\n initial_status: initialStatus,\n final_status: status,\n signatures_added: signaturesAdded,\n documents_signed: documentsSigned,\n steps,\n formation,\n };\n }\n\n if (status === \"pending\") {\n throw new Error(\n \"Formation is still pending — finalize before activation.\\n\" +\n \" Run: corp form finalize \" + entityId,\n );\n }\n\n if (status === \"documents_generated\") {\n const signed = await autoSignFormationDocuments(client, resolver, entityId);\n signaturesAdded += signed.signatures_added;\n documentsSigned += signed.documents_signed;\n await client.markFormationDocumentsSigned(entityId);\n steps.push(`signed ${signed.signatures_added} signatures across ${signed.documents_signed} documents`);\n formation = await client.getFormation(entityId) as ApiRecord;\n continue;\n }\n\n if (status === \"documents_signed\") {\n const gates = await client.getFormationGates(entityId);\n if (gates.requires_natural_person_attestation && !gates.attestation_recorded) {\n await client.recordFilingAttestation(entityId, {\n signer_name: gates.designated_attestor_name,\n signer_role: gates.designated_attestor_role,\n signer_email: gates.designated_attestor_email ?? fallbackSignerEmail({\n role: String(gates.designated_attestor_role ?? \"attestor\"),\n signer_name: String(gates.designated_attestor_name ?? \"attestor\"),\n }),\n consent_text: DEFAULT_ATTESTATION_CONSENT,\n notes: \"Recorded automatically by corp form activate\",\n });\n steps.push(\"recorded filing attestation\");\n }\n const gatesAfterAttestation = await client.getFormationGates(entityId);\n if (\n gatesAfterAttestation.requires_registered_agent_consent_evidence\n && Number(gatesAfterAttestation.registered_agent_consent_evidence_count ?? 0) === 0\n ) {\n await client.addRegisteredAgentConsentEvidence(entityId, {\n evidence_uri: options.evidenceUri ?? `generated://registered-agent-consent/${entityId}`,\n evidence_type: options.evidenceType ?? \"generated\",\n notes: \"Recorded automatically by corp form activate\",\n });\n steps.push(\"recorded registered-agent consent evidence\");\n }\n const finalGates = await client.getFormationGates(entityId);\n if (Array.isArray(finalGates.filing_submission_blockers) && finalGates.filing_submission_blockers.length > 0) {\n throw new Error(\n `Formation filing is still blocked: ${finalGates.filing_submission_blockers.join(\"; \")}`,\n );\n }\n await client.submitFiling(entityId);\n steps.push(\"submitted filing\");\n formation = await client.getFormation(entityId) as ApiRecord;\n continue;\n }\n\n if (status === \"filing_submitted\") {\n await client.confirmFiling(entityId, {\n external_filing_id: options.filingId ?? filingIdentifier(\"sim\", entityId),\n receipt_reference: options.receiptReference ?? filingIdentifier(\"receipt\", entityId),\n });\n steps.push(\"confirmed filing\");\n formation = await client.getFormation(entityId) as ApiRecord;\n continue;\n }\n\n if (status === \"filed\") {\n await client.applyEin(entityId);\n steps.push(\"submitted EIN application\");\n formation = await client.getFormation(entityId) as ApiRecord;\n continue;\n }\n\n if (status === \"ein_applied\") {\n await client.confirmEin(entityId, { ein: options.ein ?? deterministicEin(entityId) });\n steps.push(\"confirmed EIN\");\n formation = await client.getFormation(entityId) as ApiRecord;\n continue;\n }\n\n throw new Error(`Unsupported formation status for activation: ${status || \"unknown\"}`);\n }\n\n throw new Error(\"Formation activation did not converge within 10 steps.\");\n}\n","import { input, select, confirm, number } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport { relative, resolve } from \"node:path\";\nimport { requireConfig, setActiveEntityId, saveConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printDryRun, printError, printJson, printReferenceSummary, printSuccess } from \"../output.js\";\nimport { ReferenceResolver } from \"../references.js\";\nimport type { ApiRecord } from \"../types.js\";\nimport { EntityType, OfficerTitle } from \"@thecorporation/corp-tools\";\nimport { activateFormationEntity } from \"../formation-automation.js\";\n\n// ── Types ──────────────────────────────────────────────────────\n\ninterface FounderInfo {\n name: string;\n email: string;\n role: string;\n address?: { street: string; street2?: string; city: string; state: string; zip: string };\n officer_title?: string;\n is_incorporator?: boolean;\n shares_purchased?: number;\n ownership_pct?: number;\n vesting?: { total_months: number; cliff_months: number; acceleration?: string };\n ip_description?: string;\n}\n\ninterface FormOptions {\n type?: string;\n name?: string;\n jurisdiction?: string;\n member?: string[];\n memberJson?: string[];\n membersFile?: string;\n fiscalYearEnd?: string;\n sCorp?: boolean;\n transferRestrictions?: boolean;\n rofr?: boolean;\n address?: string;\n principalName?: string;\n json?: boolean;\n dryRun?: boolean;\n quiet?: boolean;\n}\n\n// ── Helpers ────────────────────────────────────────────────────\n\nfunction isCorp(entityType: string): boolean {\n return entityType === \"c_corp\" || entityType === \"s_corp\" || entityType === \"corporation\";\n}\n\nfunction sectionHeader(title: string): void {\n console.log();\n console.log(chalk.blue(\"─\".repeat(50)));\n console.log(chalk.blue.bold(` ${title}`));\n console.log(chalk.blue(\"─\".repeat(50)));\n}\n\nfunction officerTitleLabel(title: string): string {\n switch (title) {\n case \"ceo\":\n return \"CEO\";\n case \"cfo\":\n return \"CFO\";\n case \"cto\":\n return \"CTO\";\n case \"coo\":\n return \"COO\";\n case \"vp\":\n return \"VP\";\n default:\n return title.charAt(0).toUpperCase() + title.slice(1);\n }\n}\n\nfunction parseBoolean(value: unknown): boolean | undefined {\n if (typeof value === \"boolean\") return value;\n if (typeof value !== \"string\") return undefined;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n return undefined;\n}\n\nfunction parseAddressValue(raw: unknown): FounderInfo[\"address\"] {\n if (!raw) return undefined;\n if (typeof raw === \"string\") {\n const parts = raw.split(\"|\").map((part) => part.trim());\n if (parts.length === 4) {\n return { street: parts[0], city: parts[1], state: parts[2], zip: parts[3] };\n }\n throw new Error(`Invalid founder address: ${raw}. Expected street|city|state|zip.`);\n }\n if (typeof raw === \"object\" && raw !== null) {\n const value = raw as Record<string, unknown>;\n if (\n typeof value.street === \"string\" &&\n typeof value.city === \"string\" &&\n typeof value.state === \"string\" &&\n typeof value.zip === \"string\"\n ) {\n return {\n street: value.street,\n street2: typeof value.street2 === \"string\" ? value.street2 : undefined,\n city: value.city,\n state: value.state,\n zip: value.zip,\n };\n }\n }\n throw new Error(\"Founder address must be an object or street|city|state|zip string.\");\n}\n\nfunction normalizeFounderInfo(input: Record<string, unknown>): FounderInfo {\n const name = typeof input.name === \"string\" ? input.name.trim() : \"\";\n const email = typeof input.email === \"string\" ? input.email.trim() : \"\";\n const role = typeof input.role === \"string\" ? input.role.trim() : \"\";\n if (!name || !email || !role) {\n throw new Error(\"Founder JSON requires non-empty name, email, and role.\");\n }\n\n const founder: FounderInfo = { name, email, role };\n const ownershipPct = input.ownership_pct ?? input.membership_pct ?? input.pct;\n if (ownershipPct != null) founder.ownership_pct = Number(ownershipPct);\n const sharesPurchased = input.shares_purchased ?? input.shares;\n if (sharesPurchased != null) founder.shares_purchased = Number(sharesPurchased);\n if (typeof input.officer_title === \"string\") founder.officer_title = input.officer_title;\n const incorporator = parseBoolean(input.is_incorporator ?? input.incorporator);\n if (incorporator !== undefined) founder.is_incorporator = incorporator;\n if (input.address != null) founder.address = parseAddressValue(input.address);\n if (typeof input.ip_description === \"string\") founder.ip_description = input.ip_description;\n if (input.vesting && typeof input.vesting === \"object\") {\n const vesting = input.vesting as Record<string, unknown>;\n if (vesting.total_months != null && vesting.cliff_months != null) {\n founder.vesting = {\n total_months: Number(vesting.total_months),\n cliff_months: Number(vesting.cliff_months),\n acceleration:\n typeof vesting.acceleration === \"string\" ? vesting.acceleration : undefined,\n };\n }\n }\n return founder;\n}\n\nfunction parseLegacyMemberSpec(raw: string): FounderInfo {\n const parts = raw.split(\",\").map((p) => p.trim());\n if (parts.length < 3) {\n throw new Error(\n `Invalid member format: ${raw}. Expected: name,email,role[,pct[,street|city|state|zip[,officer_title[,is_incorporator]]]]`,\n );\n }\n const founder: FounderInfo = { name: parts[0], email: parts[1], role: parts[2] };\n if (parts.length >= 4) founder.ownership_pct = parseFloat(parts[3]);\n if (parts.length >= 5 && parts[4]) founder.address = parseAddressValue(parts[4]);\n if (parts.length >= 6 && parts[5]) founder.officer_title = parts[5];\n if (parts.length >= 7) {\n const incorporator = parseBoolean(parts[6]);\n if (incorporator !== undefined) founder.is_incorporator = incorporator;\n }\n return founder;\n}\n\nfunction parseKeyValueMemberSpec(raw: string): FounderInfo {\n const parsed: Record<string, unknown> = {};\n for (const segment of raw.split(\",\")) {\n const [key, ...rest] = segment.split(\"=\");\n if (!key || rest.length === 0) {\n throw new Error(`Invalid member format: ${raw}. Expected key=value pairs.`);\n }\n parsed[key.trim()] = rest.join(\"=\").trim();\n }\n return normalizeFounderInfo(parsed);\n}\n\nfunction readSafeJsonFile(filePath: string, label: string): string {\n if (process.env.CORP_ALLOW_UNSAFE_FILE_INPUT === \"1\") {\n return readFileSync(filePath, \"utf8\");\n }\n const resolvedFile = realpathSync(resolve(filePath));\n const workingTreeRoot = realpathSync(process.cwd());\n const rel = relative(workingTreeRoot, resolvedFile);\n if (rel === \"\" || (!rel.startsWith(\"..\") && !rel.startsWith(\"/\"))) {\n return readFileSync(resolvedFile, \"utf8\");\n }\n throw new Error(\n `--${label} must stay inside the current working directory unless CORP_ALLOW_UNSAFE_FILE_INPUT=1 is set.`,\n );\n}\n\nfunction validateFounders(founders: FounderInfo[]): void {\n // Check for duplicate emails\n const seenEmails = new Set<string>();\n for (const f of founders) {\n const email = f.email.toLowerCase().trim();\n if (seenEmails.has(email)) {\n throw new Error(`Duplicate founder email: ${email}. Each founder must have a unique email address.`);\n }\n seenEmails.add(email);\n }\n\n // Check total ownership doesn't exceed 100%\n let totalOwnership = 0;\n for (const f of founders) {\n if (f.ownership_pct != null) {\n if (f.ownership_pct <= 0 || f.ownership_pct > 100) {\n throw new Error(`Invalid ownership_pct ${f.ownership_pct} for ${f.name}. Must be between 0 and 100.`);\n }\n totalOwnership += f.ownership_pct;\n }\n }\n if (totalOwnership > 100.000001) {\n throw new Error(`Total ownership_pct is ${totalOwnership.toFixed(2)}%, which exceeds 100%. Reduce ownership percentages.`);\n }\n}\n\nfunction parseScriptedFounders(opts: FormOptions): FounderInfo[] {\n const founders: FounderInfo[] = [];\n for (const raw of opts.member ?? []) {\n founders.push(raw.includes(\"=\") ? parseKeyValueMemberSpec(raw) : parseLegacyMemberSpec(raw));\n }\n for (const raw of opts.memberJson ?? []) {\n founders.push(normalizeFounderInfo(JSON.parse(raw) as Record<string, unknown>));\n }\n if (opts.membersFile) {\n const parsed = JSON.parse(readSafeJsonFile(opts.membersFile, \"members-file\")) as unknown;\n let entries: unknown[];\n if (Array.isArray(parsed)) {\n entries = parsed;\n } else if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n \"members\" in parsed &&\n Array.isArray((parsed as { members?: unknown }).members)\n ) {\n entries = (parsed as { members: unknown[] }).members;\n } else {\n throw new Error(\"members file must be a JSON array or {\\\"members\\\": [...]}\");\n }\n for (const entry of entries) {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n throw new Error(\"each founder entry must be a JSON object\");\n }\n founders.push(normalizeFounderInfo(entry as Record<string, unknown>));\n }\n }\n validateFounders(founders);\n return founders;\n}\n\nasync function promptAddress(): Promise<{ street: string; city: string; state: string; zip: string }> {\n const street = await input({ message: \" Street address\" });\n const city = await input({ message: \" City\" });\n const state = await input({ message: \" State (2-letter)\", default: \"DE\" });\n const zip = await input({ message: \" ZIP code\" });\n return { street, city, state, zip };\n}\n\n// ── Phase 1: Entity Details ────────────────────────────────────\n\nasync function phaseEntityDetails(opts: FormOptions, serverCfg: ApiRecord, scripted: boolean) {\n if (!scripted) sectionHeader(\"Phase 1: Entity Details\");\n\n let entityType = opts.type;\n if (!entityType) {\n if (scripted) { entityType = \"llc\"; }\n else {\n entityType = await select({\n message: \"Entity type\",\n choices: [\n { value: \"llc\", name: \"LLC\" },\n { value: \"c_corp\", name: \"C-Corp\" },\n ],\n });\n }\n }\n\n let name = opts.name;\n if (!name) {\n if (scripted) { printError(\"--name is required in scripted mode\"); process.exit(1); }\n name = await input({ message: \"Legal name\" });\n }\n\n let jurisdiction = opts.jurisdiction;\n if (!jurisdiction) {\n const defaultJ = entityType === \"llc\" ? \"US-WY\" : \"US-DE\";\n if (scripted) { jurisdiction = defaultJ; }\n else { jurisdiction = await input({ message: \"Jurisdiction\", default: defaultJ }); }\n }\n\n let companyAddress: { street: string; city: string; state: string; zip: string } | undefined;\n if (opts.address) {\n const parts = opts.address.split(\",\").map((p) => p.trim());\n if (parts.length === 4) {\n companyAddress = { street: parts[0], city: parts[1], state: parts[2], zip: parts[3] };\n }\n }\n if (!companyAddress && !scripted) {\n const wantAddress = await confirm({ message: \"Add company address?\", default: false });\n if (wantAddress) {\n companyAddress = await promptAddress();\n }\n }\n\n const fiscalYearEnd = opts.fiscalYearEnd ?? \"12-31\";\n\n let sCorpElection = opts.sCorp ?? false;\n if (!scripted && isCorp(entityType) && opts.sCorp === undefined) {\n sCorpElection = await confirm({ message: \"S-Corp election?\", default: false });\n }\n\n return { entityType, name, jurisdiction, companyAddress, fiscalYearEnd, sCorpElection };\n}\n\n// ── Phase 2: People ────────────────────────────────────────────\n\nasync function phasePeople(\n opts: FormOptions,\n entityType: string,\n scripted: boolean,\n): Promise<FounderInfo[]> {\n if (!scripted) sectionHeader(\"Phase 2: Founders & Officers\");\n\n const founders: FounderInfo[] = [];\n\n // CLI-provided members (scripted mode)\n if (scripted) {\n try {\n return parseScriptedFounders(opts);\n } catch (err) {\n printError(String(err));\n process.exit(1);\n }\n }\n\n // Interactive mode\n const founderCount = (await number({ message: \"Number of founders (1-6)\", default: 1 })) ?? 1;\n\n for (let i = 0; i < founderCount; i++) {\n console.log(chalk.dim(`\\n Founder ${i + 1} of ${founderCount}:`));\n const name = await input({ message: ` Name` });\n const email = await input({ message: ` Email` });\n\n let role = \"member\";\n if (isCorp(entityType)) {\n role = await select({\n message: \" Role\",\n choices: [\n { value: \"director\", name: \"Director\" },\n { value: \"officer\", name: \"Officer\" },\n { value: \"member\", name: \"Shareholder only\" },\n ],\n });\n }\n\n const wantAddress = await confirm({ message: \" Add address?\", default: false });\n const address = wantAddress ? await promptAddress() : undefined;\n\n let officerTitle: string | undefined;\n if (isCorp(entityType)) {\n const wantOfficer = role === \"officer\" || await confirm({ message: \" Assign officer title?\", default: i === 0 });\n if (wantOfficer) {\n officerTitle = await select({\n message: \" Officer title\",\n choices: OfficerTitle.map((t) => ({\n value: t,\n name: officerTitleLabel(t),\n })),\n });\n }\n }\n\n let isIncorporator = false;\n if (isCorp(entityType) && i === 0 && founderCount === 1) {\n isIncorporator = true;\n } else if (isCorp(entityType)) {\n isIncorporator = await confirm({ message: \" Designate as sole incorporator?\", default: i === 0 });\n }\n\n founders.push({ name, email, role, address, officer_title: officerTitle, is_incorporator: isIncorporator });\n }\n\n return founders;\n}\n\n// ── Phase 3: Stock & Finalize ──────────────────────────────────\n\nasync function phaseStock(\n opts: FormOptions,\n entityType: string,\n founders: FounderInfo[],\n scripted: boolean,\n): Promise<{ founders: FounderInfo[]; transferRestrictions: boolean; rofr: boolean }> {\n if (!scripted) sectionHeader(\"Phase 3: Equity & Finalize\");\n\n const transferRestrictions = opts.transferRestrictions ?? (\n !scripted && isCorp(entityType)\n ? await confirm({ message: \"Transfer restrictions on shares?\", default: true })\n : isCorp(entityType)\n );\n\n const rofr = opts.rofr ?? (\n !scripted && isCorp(entityType)\n ? await confirm({ message: \"Right of first refusal?\", default: true })\n : isCorp(entityType)\n );\n\n if (!scripted) {\n for (const f of founders) {\n console.log(chalk.dim(`\\n Equity for ${f.name}:`));\n\n if (isCorp(entityType)) {\n const shares = await number({ message: ` Shares to purchase`, default: 0 });\n f.shares_purchased = shares ?? 0;\n if (f.shares_purchased === 0) {\n const pct = await number({ message: ` Ownership % (1-100)`, default: founders.length === 1 ? 100 : 0 });\n f.ownership_pct = pct ?? 0;\n }\n } else {\n const pct = await number({\n message: ` Ownership % (1-100)`,\n default: founders.length === 1 ? 100 : 0,\n });\n f.ownership_pct = pct ?? 0;\n }\n\n if (isCorp(entityType)) {\n const wantVesting = await confirm({ message: \" Add vesting schedule?\", default: false });\n if (wantVesting) {\n const totalMonths = (await number({ message: \" Total vesting months\", default: 48 })) ?? 48;\n const cliffMonths = (await number({ message: \" Cliff months\", default: 12 })) ?? 12;\n const acceleration = await select({\n message: \" Acceleration\",\n choices: [\n { value: \"none\", name: \"None\" },\n { value: \"single_trigger\", name: \"Single trigger\" },\n { value: \"double_trigger\", name: \"Double trigger\" },\n ],\n });\n f.vesting = {\n total_months: totalMonths,\n cliff_months: cliffMonths,\n acceleration: acceleration === \"none\" ? undefined : acceleration,\n };\n }\n }\n\n const wantIp = await confirm({ message: \" Contributing IP?\", default: false });\n if (wantIp) {\n f.ip_description = await input({ message: \" Describe IP being contributed\" });\n }\n }\n }\n\n return { founders, transferRestrictions, rofr };\n}\n\n// ── Summary Table ──────────────────────────────────────────────\n\nfunction printSummary(\n entityType: string,\n name: string,\n jurisdiction: string,\n fiscalYearEnd: string,\n sCorpElection: boolean,\n founders: FounderInfo[],\n transferRestrictions: boolean,\n rofr: boolean,\n): void {\n sectionHeader(\"Formation Summary\");\n\n console.log(` ${chalk.bold(\"Entity:\")} ${name}`);\n console.log(` ${chalk.bold(\"Type:\")} ${entityType}`);\n console.log(` ${chalk.bold(\"Jurisdiction:\")} ${jurisdiction}`);\n console.log(` ${chalk.bold(\"Fiscal Year End:\")} ${fiscalYearEnd}`);\n if (isCorp(entityType)) {\n console.log(` ${chalk.bold(\"S-Corp Election:\")} ${sCorpElection ? \"Yes\" : \"No\"}`);\n console.log(` ${chalk.bold(\"Transfer Restrictions:\")} ${transferRestrictions ? \"Yes\" : \"No\"}`);\n console.log(` ${chalk.bold(\"Right of First Refusal:\")} ${rofr ? \"Yes\" : \"No\"}`);\n }\n\n const table = new Table({\n head: [chalk.dim(\"Name\"), chalk.dim(\"Email\"), chalk.dim(\"Role\"), chalk.dim(\"Equity\"), chalk.dim(\"Officer\")],\n });\n for (const f of founders) {\n const equity = f.shares_purchased\n ? `${f.shares_purchased.toLocaleString()} shares`\n : f.ownership_pct\n ? `${f.ownership_pct}%`\n : \"—\";\n table.push([f.name, f.email, f.role, equity, f.officer_title ?? \"—\"]);\n }\n console.log(table.toString());\n}\n\n// ── Main Command ───────────────────────────────────────────────\n\nconst SUPPORTED_ENTITY_TYPES = [\"llc\", \"c_corp\", \"s_corp\", \"corporation\"];\n\nexport async function formCommand(opts: FormOptions): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n // Client-side type validation\n if (opts.type && !SUPPORTED_ENTITY_TYPES.includes(opts.type)) {\n printError(`Unsupported entity type '${opts.type}'. Supported types: ${SUPPORTED_ENTITY_TYPES.join(\", \")}`);\n process.exit(1);\n }\n // Client-side name validation\n if (opts.name != null && !opts.name.trim()) {\n printError(\"--name cannot be empty or whitespace\");\n process.exit(1);\n }\n\n let serverCfg: ApiRecord = {};\n try { serverCfg = await client.getConfig(); } catch { /* ignore */ }\n\n const hasMembers = Boolean(\n (opts.member && opts.member.length > 0) ||\n (opts.memberJson && opts.memberJson.length > 0) ||\n opts.membersFile,\n );\n const scripted = hasMembers || opts.json || opts.dryRun || !process.stdout.isTTY;\n\n // If non-TTY/json/dryRun and no members provided, error early instead of prompting\n if (scripted && !hasMembers) {\n printError(\"At least one --member, --member-json, or --members-file is required in non-interactive mode.\");\n process.exit(1);\n }\n\n // Phase 1: Entity Details\n const { entityType, name, jurisdiction, companyAddress, fiscalYearEnd, sCorpElection } =\n await phaseEntityDetails(opts, serverCfg, scripted);\n\n // Phase 2: People\n const founders = await phasePeople(opts, entityType, scripted);\n\n // C-Corp upfront validation — check all requirements at once\n if (isCorp(entityType) && scripted) {\n const missing: string[] = [];\n const hasAddress = founders.some((f) => f.address);\n const hasOfficer = founders.some((f) => f.officer_title);\n const hasIncorporator = founders.some((f) => f.is_incorporator);\n if (!hasAddress) missing.push(\"At least one member with an address (for incorporator filing)\");\n if (!hasOfficer) missing.push(\"At least one member with --officer-title (for initial board consent)\");\n if (!hasIncorporator && founders.length === 1) {\n // Single founder auto-marked as incorporator, no error needed\n } else if (!hasIncorporator && founders.length > 1) {\n missing.push(\"At least one member marked as --incorporator\");\n }\n if (missing.length > 0) {\n printError(\n \"C-Corp formation requires:\\n\" +\n missing.map((m) => ` - ${m}`).join(\"\\n\") + \"\\n\" +\n ' Example: --member \"Name,email,director,100,street|city|state|zip,ceo,true\"',\n );\n process.exit(1);\n }\n }\n\n // Phase 3: Stock & Finalize\n const { transferRestrictions, rofr } = await phaseStock(opts, entityType, founders, scripted);\n\n // Summary & Confirm (suppress for --json and --quiet to keep output clean)\n if (!opts.quiet && !opts.json) {\n printSummary(entityType, name, jurisdiction, fiscalYearEnd, sCorpElection, founders, transferRestrictions, rofr);\n }\n\n const shouldProceed = scripted\n ? true\n : await confirm({ message: \"Proceed with formation?\", default: true });\n\n if (!shouldProceed) {\n console.log(chalk.yellow(\"Formation cancelled.\"));\n return;\n }\n\n // Build members payload\n const members: ApiRecord[] = founders.map((f) => {\n const m: ApiRecord = {\n name: f.name,\n email: f.email,\n role: f.role,\n investor_type: \"natural_person\",\n };\n if (f.ownership_pct) m.ownership_pct = f.ownership_pct;\n if (f.shares_purchased) m.shares_purchased = f.shares_purchased;\n if (f.address) m.address = f.address;\n if (f.officer_title) m.officer_title = f.officer_title;\n if (f.is_incorporator) m.is_incorporator = true;\n if (f.vesting) m.vesting = f.vesting;\n if (f.ip_description) m.ip_description = f.ip_description;\n return m;\n });\n\n const payload: ApiRecord = {\n entity_type: entityType,\n legal_name: name,\n jurisdiction,\n members,\n workspace_id: cfg.workspace_id,\n fiscal_year_end: fiscalYearEnd,\n s_corp_election: sCorpElection,\n transfer_restrictions: transferRestrictions,\n right_of_first_refusal: rofr,\n };\n if (companyAddress) payload.company_address = companyAddress;\n // LLC: auto-set principal_name from first member if not explicitly provided\n if (entityType === \"llc\") {\n const principalName = opts.principalName ?? founders[0]?.name;\n if (principalName) payload.principal_name = principalName;\n }\n\n if (opts.dryRun) {\n printDryRun(\"formation.create_with_cap_table\", payload);\n return;\n }\n\n const result = await client.createFormationWithCapTable(payload);\n await resolver.stabilizeRecord(\"entity\", result);\n resolver.rememberFromRecord(\"entity\", result);\n\n if (result.entity_id) {\n setActiveEntityId(cfg, String(result.entity_id));\n saveConfig(cfg);\n }\n\n if (opts.quiet) {\n const id = result.entity_id ?? result.formation_id;\n if (id) console.log(String(id));\n return;\n }\n\n if (opts.json) {\n printJson(result);\n return;\n }\n\n if (result.entity_id) {\n console.log(chalk.dim(` Active entity set to ${result.entity_id}`));\n }\n\n // Output results\n printSuccess(`Formation created: ${result.formation_id ?? \"OK\"}`);\n if (result.entity_id) {\n printReferenceSummary(\"entity\", result, { showReuseHint: true });\n }\n if (result.legal_entity_id) console.log(` Legal Entity ID: ${result.legal_entity_id}`);\n if (result.instrument_id) console.log(` Instrument ID: ${result.instrument_id}`);\n\n const docIds = (result.document_ids ?? []) as string[];\n if (docIds.length > 0) {\n console.log(` Documents: ${docIds.length} generated`);\n }\n\n const holders = (result.holders ?? []) as ApiRecord[];\n if (holders.length > 0) {\n console.log();\n const table = new Table({\n head: [chalk.dim(\"Holder\"), chalk.dim(\"Shares\"), chalk.dim(\"Ownership %\")],\n });\n for (const h of holders) {\n const pct = typeof h.ownership_pct === \"number\" ? `${h.ownership_pct.toFixed(1)}%` : \"—\";\n table.push([String(h.name ?? \"?\"), String(h.shares ?? 0), pct]);\n }\n console.log(chalk.bold(\" Cap Table:\"));\n console.log(table.toString());\n }\n\n if (result.next_action) {\n const entityRef = result.entity_id ? `${result.entity_id}` : \"@last:entity\";\n const actionHint: Record<string, string> = {\n sign_documents: `corp form activate ${entityRef}`,\n submit_state_filing: `corp form activate ${entityRef}`,\n confirm_state_filing: `corp form activate ${entityRef} --filing-id \"...\"`,\n apply_for_ein: `corp form activate ${entityRef}`,\n confirm_ein: `corp form activate ${entityRef} --ein \"...\"`,\n };\n const hint = actionHint[result.next_action as string];\n if (hint) {\n console.log(chalk.yellow(`\\n Next step: ${hint}`));\n } else {\n console.log(chalk.yellow(`\\n Next: ${result.next_action}`));\n }\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes(\"exit\")) throw err;\n const msg = String(err);\n const hints: string[] = [];\n if (msg.includes(\"incorporator_address\")) {\n hints.push(\"Add an address to a founder: --member \\\"Name,email,director,100,street|city|state|zip,ceo,true\\\"\");\n }\n if (msg.includes(\"company_address\")) {\n hints.push(\"Add --address \\\"street,city,state,zip\\\" for the company address (required for C-Corps)\");\n }\n if (msg.includes(\"principal_name\")) {\n hints.push(\"Add --principal-name \\\"Manager Name\\\" (auto-set from first member for LLCs)\");\n }\n if (msg.includes(\"officers_list\") || msg.includes(\"officer\")) {\n hints.push(\"C-Corp directors need an officer_title: --member \\\"Name,email,director,100,,,ceo\\\"\");\n }\n if (hints.length > 0) {\n printError(\n `Formation failed: ${msg}\\n\\n` +\n \" Missing fields — fix all at once:\\n\" +\n hints.map((h) => ` - ${h}`).join(\"\\n\"),\n );\n } else {\n printError(`Failed to create formation: ${err}`);\n }\n process.exit(1);\n }\n}\n\n// ── Staged Formation Subcommands ─────────────────────────────\n\ninterface FormCreateOptions {\n type: string;\n name: string;\n jurisdiction?: string;\n registeredAgentName?: string;\n registeredAgentAddress?: string;\n formationDate?: string;\n fiscalYearEnd?: string;\n sCorp?: boolean;\n transferRestrictions?: boolean;\n rofr?: boolean;\n companyAddress?: string;\n dryRun?: boolean;\n json?: boolean;\n quiet?: boolean;\n}\n\nfunction parseCsvAddress(raw?: string): { street: string; city: string; state: string; zip: string } | undefined {\n if (!raw) return undefined;\n const parts = raw.split(\",\").map((p) => p.trim()).filter(Boolean);\n if (parts.length !== 4) {\n throw new Error(`Invalid address format: ${raw}. Expected 'street,city,state,zip'`);\n }\n return { street: parts[0], city: parts[1], state: parts[2], zip: parts[3] };\n}\n\nfunction shouldResolveEntityRefForDryRun(entityRef: string): boolean {\n const trimmed = entityRef.trim().toLowerCase();\n return trimmed === \"_\" || trimmed === \"@last\" || trimmed.startsWith(\"@last:\");\n}\n\nasync function resolveEntityRefForFormCommand(\n resolver: ReferenceResolver,\n entityRef: string,\n dryRun?: boolean,\n): Promise<string> {\n if (!dryRun || shouldResolveEntityRefForDryRun(entityRef)) {\n return resolver.resolveEntity(entityRef);\n }\n try {\n return await resolver.resolveEntity(entityRef);\n } catch (err) {\n if (String(err).includes(\"fetch failed\")) {\n return entityRef;\n }\n throw err;\n }\n}\n\nexport async function formCreateCommand(opts: FormCreateOptions): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n const entityType = opts.type === \"corporation\" ? \"c_corp\" : opts.type;\n const payload: ApiRecord = {\n entity_type: entityType,\n legal_name: opts.name,\n };\n if (opts.jurisdiction) payload.jurisdiction = opts.jurisdiction;\n if (opts.registeredAgentName) payload.registered_agent_name = opts.registeredAgentName;\n if (opts.registeredAgentAddress) payload.registered_agent_address = opts.registeredAgentAddress;\n if (opts.formationDate) payload.formation_date = opts.formationDate;\n if (opts.fiscalYearEnd) payload.fiscal_year_end = opts.fiscalYearEnd;\n if (opts.sCorp !== undefined) payload.s_corp_election = opts.sCorp;\n if (opts.transferRestrictions !== undefined) payload.transfer_restrictions = opts.transferRestrictions;\n if (opts.rofr !== undefined) payload.right_of_first_refusal = opts.rofr;\n const companyAddress = parseCsvAddress(opts.companyAddress);\n if (companyAddress) payload.company_address = companyAddress;\n\n if (opts.dryRun) {\n printDryRun(\"formation.create_pending\", payload);\n return;\n }\n\n const result = await client.createPendingEntity(payload);\n await resolver.stabilizeRecord(\"entity\", result);\n resolver.rememberFromRecord(\"entity\", result);\n\n if (result.entity_id) {\n setActiveEntityId(cfg, String(result.entity_id));\n saveConfig(cfg);\n }\n\n if (opts.quiet) {\n const id = result.entity_id;\n if (id) console.log(String(id));\n return;\n }\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(`Pending entity created: ${result.entity_id}`);\n printReferenceSummary(\"entity\", result, { showReuseHint: true });\n console.log(` Name: ${result.legal_name}`);\n console.log(` Type: ${result.entity_type}`);\n console.log(` Jurisdiction: ${result.jurisdiction}`);\n console.log(` Status: ${result.formation_status}`);\n console.log(chalk.yellow(`\\n Next: corp form add-founder @last:entity --name \"...\" --email \"...\" --role member --pct 50`));\n } catch (err) {\n printError(`Failed to create pending entity: ${err}`);\n process.exit(1);\n }\n}\n\ninterface FormAddFounderOptions {\n name: string;\n email: string;\n role: string;\n pct: string;\n officerTitle?: string;\n incorporator?: boolean;\n address?: string;\n dryRun?: boolean;\n json?: boolean;\n}\n\ninterface FormFinalizeOptions {\n authorizedShares?: string;\n parValue?: string;\n boardSize?: string;\n principalName?: string;\n registeredAgentName?: string;\n registeredAgentAddress?: string;\n formationDate?: string;\n fiscalYearEnd?: string;\n sCorp?: boolean;\n transferRestrictions?: boolean;\n rofr?: boolean;\n companyAddress?: string;\n incorporatorName?: string;\n incorporatorAddress?: string;\n dryRun?: boolean;\n json?: boolean;\n}\n\ninterface FormActivateOptions {\n evidenceUri?: string;\n evidenceType?: string;\n filingId?: string;\n receiptReference?: string;\n ein?: string;\n dryRun?: boolean;\n json?: boolean;\n}\n\nexport async function formAddFounderCommand(entityId: string, opts: FormAddFounderOptions): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n const resolvedEntityId = await resolveEntityRefForFormCommand(resolver, entityId, opts.dryRun);\n const payload: ApiRecord = {\n name: opts.name,\n email: opts.email,\n role: opts.role,\n ownership_pct: parseFloat(opts.pct),\n };\n if (opts.officerTitle) payload.officer_title = opts.officerTitle.toLowerCase();\n if (opts.incorporator) payload.is_incorporator = true;\n const address = parseCsvAddress(opts.address);\n if (address) payload.address = address;\n\n if (opts.dryRun) {\n printDryRun(\"formation.add_founder\", { entity_id: resolvedEntityId, ...payload });\n return;\n }\n\n const result = await client.addFounder(resolvedEntityId, payload);\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(`Founder added (${result.member_count} total)`);\n const members = (result.members ?? []) as ApiRecord[];\n for (const m of members) {\n const pct = typeof m.ownership_pct === \"number\" ? ` (${m.ownership_pct}%)` : \"\";\n console.log(` - ${m.name} <${m.email ?? \"no email\"}> [${m.role ?? \"member\"}]${pct}`);\n }\n console.log(chalk.yellow(`\\n Next: add more founders or run: corp form finalize @last:entity`));\n } catch (err) {\n printError(`Failed to add founder: ${err}`);\n process.exit(1);\n }\n}\n\nexport async function formFinalizeCommand(entityId: string, opts: FormFinalizeOptions): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n const resolvedEntityId = await resolveEntityRefForFormCommand(resolver, entityId, opts.dryRun);\n const payload: ApiRecord = {};\n if (opts.authorizedShares) {\n const authorizedShares = parseInt(opts.authorizedShares, 10);\n if (!Number.isFinite(authorizedShares)) {\n throw new Error(`Invalid authorized shares: ${opts.authorizedShares}`);\n }\n payload.authorized_shares = authorizedShares;\n }\n if (opts.parValue) payload.par_value = opts.parValue;\n if (opts.boardSize) {\n const boardSize = parseInt(opts.boardSize, 10);\n if (!Number.isFinite(boardSize) || boardSize <= 0) {\n throw new Error(`Invalid board size: ${opts.boardSize}`);\n }\n payload.board_size = boardSize;\n }\n if (opts.principalName) payload.principal_name = opts.principalName;\n if (opts.registeredAgentName) payload.registered_agent_name = opts.registeredAgentName;\n if (opts.registeredAgentAddress) payload.registered_agent_address = opts.registeredAgentAddress;\n if (opts.formationDate) payload.formation_date = opts.formationDate;\n if (opts.fiscalYearEnd) payload.fiscal_year_end = opts.fiscalYearEnd;\n if (opts.sCorp !== undefined) payload.s_corp_election = opts.sCorp;\n if (opts.transferRestrictions !== undefined) payload.transfer_restrictions = opts.transferRestrictions;\n if (opts.rofr !== undefined) payload.right_of_first_refusal = opts.rofr;\n const companyAddress = parseCsvAddress(opts.companyAddress);\n if (companyAddress) payload.company_address = companyAddress;\n if (opts.incorporatorName) payload.incorporator_name = opts.incorporatorName;\n if (opts.incorporatorAddress) payload.incorporator_address = opts.incorporatorAddress;\n\n if (opts.dryRun) {\n printDryRun(\"formation.finalize\", { entity_id: resolvedEntityId, ...payload });\n return;\n }\n\n const result = await client.finalizeFormation(resolvedEntityId, payload);\n await resolver.stabilizeRecord(\"entity\", result);\n resolver.rememberFromRecord(\"entity\", result);\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(`Formation finalized: ${result.entity_id}`);\n printReferenceSummary(\"entity\", result, { showReuseHint: true });\n if (result.legal_entity_id) console.log(` Legal Entity ID: ${result.legal_entity_id}`);\n if (result.instrument_id) console.log(` Instrument ID: ${result.instrument_id}`);\n\n const docIds = (result.document_ids ?? []) as string[];\n if (docIds.length > 0) {\n console.log(` Documents: ${docIds.length} generated`);\n }\n\n const holders = (result.holders ?? []) as ApiRecord[];\n if (holders.length > 0) {\n console.log();\n const table = new Table({\n head: [chalk.dim(\"Holder\"), chalk.dim(\"Shares\"), chalk.dim(\"Ownership %\")],\n });\n for (const h of holders) {\n const pct = typeof h.ownership_pct === \"number\" ? `${h.ownership_pct.toFixed(1)}%` : \"—\";\n table.push([String(h.name ?? \"?\"), String(h.shares ?? 0), pct]);\n }\n console.log(chalk.bold(\" Cap Table:\"));\n console.log(table.toString());\n }\n\n if (result.next_action) {\n console.log(chalk.yellow(`\\n Next: ${result.next_action}`));\n }\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"officers_list\") || msg.includes(\"officer\")) {\n printError(\n `Finalization failed: ${msg}\\n` +\n \" Hint: C-Corp entities require at least one founder with an officer_title.\\n\" +\n \" Add a founder with: corp form add-founder @last:entity --name '...' --email '...' --role director --pct 100 --officer-title ceo\",\n );\n } else {\n printError(`Failed to finalize formation: ${err}`);\n }\n process.exit(1);\n }\n}\n\nexport async function formActivateCommand(entityId: string, opts: FormActivateOptions): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n const resolvedEntityId = await resolveEntityRefForFormCommand(resolver, entityId, opts.dryRun);\n const payload: ApiRecord = { entity_id: resolvedEntityId };\n if (opts.evidenceUri) payload.evidence_uri = opts.evidenceUri;\n if (opts.evidenceType) payload.evidence_type = opts.evidenceType;\n if (opts.filingId) payload.filing_id = opts.filingId;\n if (opts.receiptReference) payload.receipt_reference = opts.receiptReference;\n if (opts.ein) payload.ein = opts.ein;\n\n if (opts.dryRun) {\n printDryRun(\"formation.activate\", payload);\n return;\n }\n\n const result = await activateFormationEntity(client, resolver, resolvedEntityId, {\n evidenceUri: opts.evidenceUri,\n evidenceType: opts.evidenceType,\n filingId: opts.filingId,\n receiptReference: opts.receiptReference,\n ein: opts.ein,\n });\n const formation = await client.getFormation(resolvedEntityId);\n await resolver.stabilizeRecord(\"entity\", formation as ApiRecord);\n resolver.rememberFromRecord(\"entity\", formation as ApiRecord);\n\n if (opts.json) {\n printJson({\n ...result,\n formation,\n });\n return;\n }\n\n printSuccess(`Formation advanced to ${result.final_status}.`);\n printReferenceSummary(\"entity\", formation as ApiRecord, { showReuseHint: true });\n if (result.steps.length > 0) {\n console.log(\" Steps:\");\n for (const step of result.steps) {\n console.log(` - ${step}`);\n }\n }\n console.log(` Signatures added: ${result.signatures_added}`);\n console.log(` Documents updated: ${result.documents_signed}`);\n } catch (err) {\n printError(`Failed to activate formation: ${err}`);\n process.exit(1);\n }\n}\n","import type { CommandDef, CommandContext } from \"./types.js\";\nimport { printDryRun, printError, printJson, printReferenceSummary, printSuccess } from \"../output.js\";\nimport { setActiveEntityId, setLastReference, saveConfig, updateConfig, requireConfig } from \"../config.js\";\nimport { activateFormationEntity } from \"../formation-automation.js\";\nimport chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport type { ApiRecord } from \"../types.js\";\n\n// ── form (one-shot formation) handler ──────────────────────────\n\nasync function formHandler(ctx: CommandContext): Promise<void> {\n const { formCommand } = await import(\"../commands/form.js\");\n // Map --entity-type / --legal-name aliases to --type / --name for formCommand\n const opts: Record<string, unknown> = { ...ctx.opts, quiet: ctx.quiet };\n if (opts.entityType && !opts.type) opts.type = opts.entityType;\n if (opts.legalName && !opts.name) opts.name = opts.legalName;\n await formCommand(opts as Parameters<typeof formCommand>[0]);\n}\n\n// ── form create handler ────────────────────────────────────────\n\nconst SUPPORTED_ENTITY_TYPES = [\"llc\", \"c_corp\", \"s_corp\", \"corporation\"];\n\nfunction parseCsvAddress(raw?: string): { street: string; city: string; state: string; zip: string } | undefined {\n if (!raw) return undefined;\n const parts = raw.split(\",\").map((p) => p.trim()).filter(Boolean);\n if (parts.length !== 4) {\n throw new Error(`Invalid address format: ${raw}. Expected 'street,city,state,zip'`);\n }\n return { street: parts[0], city: parts[1], state: parts[2], zip: parts[3] };\n}\n\nfunction shouldResolveEntityRefForDryRun(entityRef: string): boolean {\n const trimmed = entityRef.trim().toLowerCase();\n return trimmed === \"_\" || trimmed === \"@last\" || trimmed.startsWith(\"@last:\");\n}\n\nasync function resolveEntityRefForFormCommand(\n resolver: CommandContext[\"resolver\"],\n entityRef: string,\n dryRun?: boolean,\n): Promise<string> {\n if (!dryRun || shouldResolveEntityRefForDryRun(entityRef)) {\n return resolver.resolveEntity(entityRef);\n }\n try {\n return await resolver.resolveEntity(entityRef);\n } catch {\n // In dry-run mode, fall back to the raw ref if resolution fails\n // (e.g. fetch failed, auth error, network error, etc.)\n return entityRef;\n }\n}\n\nasync function formCreateHandler(ctx: CommandContext): Promise<void> {\n const opts = ctx.opts;\n // Reject options that belong to form finalize, not form create\n if (opts.shares || opts.authorizedShares) {\n ctx.writer.error(\n \"--shares / --authorized-shares is not accepted on form create.\\n\" +\n \" Set authorized shares during finalize:\\n\" +\n \" corp form finalize @last:entity --authorized-shares 10000000\",\n );\n process.exit(1);\n }\n const resolvedType = opts.type as string | undefined;\n const resolvedName = opts.name as string | undefined;\n if (!resolvedType) {\n ctx.writer.error(\"required option '--type <type>' not specified\");\n process.exit(1);\n }\n if (!SUPPORTED_ENTITY_TYPES.includes(resolvedType)) {\n ctx.writer.error(`unsupported entity type '${resolvedType}'. Supported types: ${SUPPORTED_ENTITY_TYPES.join(\", \")}`);\n process.exit(1);\n }\n if (!resolvedName) {\n ctx.writer.error(\"required option '--name <name>' not specified\");\n process.exit(1);\n }\n if (!resolvedName.trim()) {\n ctx.writer.error(\"--name cannot be empty or whitespace\");\n process.exit(1);\n }\n\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n try {\n const entityType = resolvedType === \"corporation\" ? \"c_corp\" : resolvedType;\n const payload: ApiRecord = {\n entity_type: entityType,\n legal_name: resolvedName,\n };\n if (opts.jurisdiction) payload.jurisdiction = opts.jurisdiction;\n if (opts.registeredAgentName) payload.registered_agent_name = opts.registeredAgentName;\n if (opts.registeredAgentAddress) payload.registered_agent_address = opts.registeredAgentAddress;\n if (opts.formationDate) payload.formation_date = opts.formationDate;\n if (opts.fiscalYearEnd) payload.fiscal_year_end = opts.fiscalYearEnd;\n if (opts.sCorp !== undefined) payload.s_corp_election = opts.sCorp;\n if (opts.transferRestrictions !== undefined) payload.transfer_restrictions = opts.transferRestrictions;\n if (opts.rofr !== undefined) payload.right_of_first_refusal = opts.rofr;\n const companyAddress = parseCsvAddress((opts.companyAddress ?? opts.address) as string | undefined);\n if (companyAddress) payload.company_address = companyAddress;\n\n if (ctx.dryRun) {\n printDryRun(\"formation.create_pending\", payload);\n return;\n }\n\n const result = await ctx.client.createPendingEntity(payload);\n await ctx.resolver.stabilizeRecord(\"entity\", result);\n\n if (result.entity_id) {\n const newEntityId = String(result.entity_id);\n // Use a single updateConfig to set both active entity AND @last reference\n // atomically — avoids saveConfig overwriting updateConfig's writes.\n updateConfig((freshCfg) => {\n setActiveEntityId(freshCfg, newEntityId);\n setLastReference(freshCfg, \"entity\", newEntityId);\n });\n // Also update in-memory config and resolver so subsequent calls in\n // this process see the new entity.\n setActiveEntityId(cfg, newEntityId);\n setLastReference(cfg, \"entity\", newEntityId);\n }\n\n if (ctx.quiet) {\n const id = result.entity_id;\n if (id) console.log(String(id));\n return;\n }\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(`Pending entity created: ${result.entity_id}`);\n printReferenceSummary(\"entity\", result, { showReuseHint: true });\n console.log(` Name: ${result.legal_name}`);\n console.log(` Type: ${result.entity_type}`);\n console.log(` Jurisdiction: ${result.jurisdiction}`);\n console.log(` Status: ${result.formation_status}`);\n console.log(chalk.yellow(`\\n Next: corp form add-founder @last:entity --name \"...\" --email \"...\" --role member --pct 50`));\n } catch (err) {\n printError(`Failed to create pending entity: ${err}`);\n process.exit(1);\n }\n}\n\n// ── form add-founder handler ───────────────────────────────────\n\nasync function formAddFounderHandler(ctx: CommandContext): Promise<void> {\n const entityRef = ctx.positional[0];\n const opts = ctx.opts;\n try {\n const resolvedEntityId = await resolveEntityRefForFormCommand(ctx.resolver, entityRef, ctx.dryRun);\n const rawPct = (opts.ownershipPct ?? opts.pct) as string | undefined;\n if (!rawPct) {\n ctx.writer.error(\"required option '--ownership-pct <percent>' not specified\");\n process.exit(1);\n }\n const pctValue = parseFloat(rawPct);\n if (isNaN(pctValue) || pctValue <= 0 || pctValue > 100) {\n ctx.writer.error(`--ownership-pct must be between 0 and 100 (e.g. 60 for 60%), got: ${rawPct}`);\n process.exit(1);\n }\n const payload: ApiRecord = {\n name: opts.name as string,\n email: opts.email as string,\n role: opts.role as string,\n ownership_pct: pctValue,\n };\n if (opts.officerTitle) payload.officer_title = (opts.officerTitle as string).toLowerCase();\n if (opts.incorporator) payload.is_incorporator = true;\n const address = parseCsvAddress(opts.address as string | undefined);\n if (address) payload.address = address;\n\n if (ctx.dryRun) {\n printDryRun(\"formation.add_founder\", { entity_id: resolvedEntityId, ...payload });\n return;\n }\n\n const result = await ctx.client.addFounder(resolvedEntityId, payload);\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(`Founder added (${result.member_count} total)`);\n const members = (result.members ?? []) as ApiRecord[];\n for (const m of members) {\n const pct = typeof m.ownership_pct === \"number\" ? ` (${m.ownership_pct}%)` : \"\";\n console.log(` - ${m.name} <${m.email ?? \"no email\"}> [${m.role ?? \"member\"}]${pct}`);\n }\n console.log(chalk.yellow(`\\n Next: add more founders or run: corp form finalize @last:entity`));\n } catch (err) {\n printError(`Failed to add founder: ${err}`);\n process.exit(1);\n }\n}\n\n// ── form finalize handler ──────────────────────────────────────\n\nasync function formFinalizeHandler(ctx: CommandContext): Promise<void> {\n const entityRef = ctx.positional[0];\n const opts = ctx.opts;\n try {\n const resolvedEntityId = await resolveEntityRefForFormCommand(ctx.resolver, entityRef, ctx.dryRun);\n const payload: ApiRecord = {};\n if (opts.authorizedShares) {\n const authorizedShares = parseInt(opts.authorizedShares as string, 10);\n if (!Number.isFinite(authorizedShares)) {\n throw new Error(`Invalid authorized shares: ${opts.authorizedShares}`);\n }\n payload.authorized_shares = authorizedShares;\n }\n if (opts.parValue) payload.par_value = opts.parValue;\n if (opts.boardSize) {\n const boardSize = parseInt(opts.boardSize as string, 10);\n if (!Number.isFinite(boardSize) || boardSize <= 0) {\n throw new Error(`Invalid board size: ${opts.boardSize}`);\n }\n payload.board_size = boardSize;\n }\n if (opts.principalName) payload.principal_name = opts.principalName;\n if (opts.registeredAgentName) payload.registered_agent_name = opts.registeredAgentName;\n if (opts.registeredAgentAddress) payload.registered_agent_address = opts.registeredAgentAddress;\n if (opts.formationDate) payload.formation_date = opts.formationDate;\n if (opts.fiscalYearEnd) payload.fiscal_year_end = opts.fiscalYearEnd;\n if (opts.sCorp !== undefined) payload.s_corp_election = opts.sCorp;\n if (opts.transferRestrictions !== undefined) payload.transfer_restrictions = opts.transferRestrictions;\n if (opts.rofr !== undefined) payload.right_of_first_refusal = opts.rofr;\n const companyAddress = parseCsvAddress(opts.companyAddress as string | undefined);\n if (companyAddress) payload.company_address = companyAddress;\n if (opts.incorporatorName) payload.incorporator_name = opts.incorporatorName;\n if (opts.incorporatorAddress) payload.incorporator_address = opts.incorporatorAddress;\n\n if (ctx.dryRun) {\n printDryRun(\"formation.finalize\", { entity_id: resolvedEntityId, ...payload });\n return;\n }\n\n const result = await ctx.client.finalizeFormation(resolvedEntityId, payload);\n await ctx.resolver.stabilizeRecord(\"entity\", result);\n ctx.resolver.rememberFromRecord(\"entity\", result);\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(`Formation finalized: ${result.entity_id}`);\n printReferenceSummary(\"entity\", result, { showReuseHint: true });\n if (result.legal_entity_id) console.log(` Legal Entity ID: ${result.legal_entity_id}`);\n if (result.instrument_id) console.log(` Instrument ID: ${result.instrument_id}`);\n\n const docIds = (result.document_ids ?? []) as string[];\n if (docIds.length > 0) {\n console.log(` Documents: ${docIds.length} generated`);\n }\n\n const holders = (result.holders ?? []) as ApiRecord[];\n if (holders.length > 0) {\n console.log();\n const table = new Table({\n head: [chalk.dim(\"Holder\"), chalk.dim(\"Shares\"), chalk.dim(\"Ownership %\")],\n });\n for (const h of holders) {\n const pct = typeof h.ownership_pct === \"number\" ? `${h.ownership_pct.toFixed(1)}%` : \"\\u2014\";\n table.push([String(h.name ?? \"?\"), String(h.shares ?? 0), pct]);\n }\n console.log(chalk.bold(\" Cap Table:\"));\n console.log(table.toString());\n }\n\n if (result.next_action) {\n console.log(chalk.yellow(`\\n Next: ${result.next_action}`));\n }\n } catch (err) {\n const msg = String(err);\n // Collect all missing-field hints and show them at once\n const hints: string[] = [];\n if (msg.includes(\"incorporator_address\")) {\n hints.push('--incorporator-address \"123 Main St,City,ST,12345\"');\n }\n if (msg.includes(\"company_address\")) {\n hints.push('--company-address \"123 Main St,City,ST,12345\"');\n }\n if (msg.includes(\"principal_name\")) {\n hints.push('--principal-name \"Managing Member Name\"');\n }\n if (msg.includes(\"officers_list\") || msg.includes(\"officer\")) {\n hints.push(\"Add a founder with --officer-title: corp form add-founder @last --role director --officer-title ceo ...\");\n }\n if (msg.includes(\"incorporator_name\")) {\n hints.push('--incorporator-name \"Incorporator Name\"');\n }\n if (hints.length > 0) {\n printError(\n `Finalization failed: ${msg}\\n\\n` +\n \" To fix, re-run finalize with the missing fields:\\n\" +\n hints.map((h) => ` ${h}`).join(\"\\n\") + \"\\n\\n\" +\n \" Example:\\n\" +\n ` corp form finalize @last ${hints.filter((h) => h.startsWith(\"--\")).join(\" \")}`,\n );\n } else {\n printError(`Failed to finalize formation: ${err}`);\n }\n process.exit(1);\n }\n}\n\n// ── form activate handler ──────────────────────────────────────\n\nasync function formActivateHandler(ctx: CommandContext): Promise<void> {\n const entityRef = ctx.positional[0];\n const opts = ctx.opts;\n try {\n const resolvedEntityId = await resolveEntityRefForFormCommand(ctx.resolver, entityRef, ctx.dryRun);\n const payload: ApiRecord = { entity_id: resolvedEntityId };\n if (opts.evidenceUri) payload.evidence_uri = opts.evidenceUri;\n if (opts.evidenceType) payload.evidence_type = opts.evidenceType;\n if (opts.filingId) payload.filing_id = opts.filingId;\n if (opts.receiptReference) payload.receipt_reference = opts.receiptReference;\n if (opts.ein) payload.ein = opts.ein;\n\n if (ctx.dryRun) {\n printDryRun(\"formation.activate\", payload);\n return;\n }\n\n const result = await activateFormationEntity(ctx.client, ctx.resolver, resolvedEntityId, {\n evidenceUri: opts.evidenceUri as string | undefined,\n evidenceType: opts.evidenceType as string | undefined,\n filingId: opts.filingId as string | undefined,\n receiptReference: opts.receiptReference as string | undefined,\n ein: opts.ein as string | undefined,\n });\n const formation = await ctx.client.getFormation(resolvedEntityId);\n await ctx.resolver.stabilizeRecord(\"entity\", formation as ApiRecord);\n ctx.resolver.rememberFromRecord(\"entity\", formation as ApiRecord);\n\n if (opts.json) {\n printJson({\n ...result,\n formation,\n });\n return;\n }\n\n printSuccess(`Formation advanced to ${result.final_status}.`);\n printReferenceSummary(\"entity\", formation as ApiRecord, { showReuseHint: true });\n if (result.steps.length > 0) {\n console.log(\" Steps:\");\n for (const step of result.steps) {\n console.log(` - ${step}`);\n }\n }\n console.log(` Signatures added: ${result.signatures_added}`);\n console.log(` Documents updated: ${result.documents_signed}`);\n if (result.final_status === \"active\") {\n console.log(chalk.yellow(\"\\n Next steps:\"));\n console.log(chalk.yellow(\" corp cap-table View your cap table\"));\n console.log(chalk.yellow(\" corp next See all recommended actions\"));\n }\n } catch (err) {\n printError(`Failed to activate formation: ${err}`);\n process.exit(1);\n }\n}\n\n// ── Command definitions ────────────────────────────────────────\n\nexport const formationCommands: CommandDef[] = [\n {\n name: \"form\",\n description: \"Form a new entity with founders and cap table\",\n passThroughOptions: true,\n dryRun: true,\n options: [\n { flags: \"--type <type>\", description: \"Entity type\", choices: [\"llc\", \"c_corp\", \"s_corp\"] },\n { flags: \"--entity-type <type>\", description: \"Entity type (alias for --type)\" },\n { flags: \"--name <name>\", description: \"Legal name\" },\n { flags: \"--legal-name <name>\", description: \"Legal name (alias for --name)\" },\n { flags: \"--jurisdiction <jurisdiction>\", description: \"Jurisdiction (e.g. US-DE, US-WY)\" },\n { flags: \"--member <member>\", description: \"Founder as 'name,email,role[,pct[,street|city|state|zip[,officer_title[,is_incorporator]]]]' (repeatable)\", type: \"array\", default: [] },\n { flags: \"--member-json <json>\", description: \"Founder JSON object (repeatable)\", type: \"array\", default: [] },\n { flags: \"--members-file <path>\", description: \"Path to a JSON array of founders or {\\\"members\\\": [...]}\" },\n { flags: \"--address <address>\", description: \"Company address as 'street,city,state,zip' (required for c_corp)\" },\n { flags: \"--fiscal-year-end <date>\", description: \"Fiscal year end (MM-DD)\", default: \"12-31\" },\n { flags: \"--s-corp\", description: \"Elect S-Corp status\" },\n { flags: \"--transfer-restrictions\", description: \"Enable transfer restrictions\" },\n { flags: \"--rofr\", description: \"Enable right of first refusal\" },\n { flags: \"--principal-name <name>\", description: \"Managing member name for LLCs (auto-set from first member if omitted)\" },\n ],\n handler: formHandler,\n produces: { kind: \"entity\", trackEntity: true },\n successTemplate: \"Entity formed: {legal_name}\",\n examples: [\n 'corp form --type llc --name \"My LLC\" --member \"Alice,alice@co.com,member,100\"',\n 'corp form --type c_corp --name \"Acme Inc\" --member \"Bob,bob@co.com,director,100,123 Main|City|DE|19801,ceo,true\"',\n \"corp form --type c_corp --name \\\"Acme Inc\\\" --jurisdiction US-DE --member-json '{\\\"name\\\":\\\"Bob\\\",\\\"email\\\":\\\"bob@acme.com\\\",\\\"role\\\":\\\"director\\\",\\\"pct\\\":100}'\",\n 'corp form create --type llc --name \"My LLC\"',\n 'corp form add-founder @last:entity --name \"Alice\" --email \"alice@co.com\" --role member --ownership-pct 100',\n \"corp form finalize @last:entity\",\n \"corp form activate @last:entity\",\n ],\n },\n {\n name: \"form create\",\n description: \"Create a pending entity (staged flow step 1)\",\n dryRun: true,\n options: [\n { flags: \"--type <type>\", description: \"Entity type\", choices: [\"llc\", \"c_corp\", \"s_corp\"] },\n { flags: \"--name <name>\", description: \"Legal name\" },\n { flags: \"--jurisdiction <jurisdiction>\", description: \"Jurisdiction (e.g. US-DE, US-WY)\" },\n { flags: \"--registered-agent-name <name>\", description: \"Registered agent legal name\" },\n { flags: \"--registered-agent-address <address>\", description: \"Registered agent address line\" },\n { flags: \"--formation-date <date>\", description: \"Formation date (RFC3339 or YYYY-MM-DD)\" },\n { flags: \"--fiscal-year-end <date>\", description: \"Fiscal year end (MM-DD)\" },\n { flags: \"--s-corp\", description: \"Elect S-Corp status\" },\n { flags: \"--transfer-restrictions\", description: \"Enable transfer restrictions\" },\n { flags: \"--rofr\", description: \"Enable right of first refusal\" },\n { flags: \"--company-address <address>\", description: \"Company address as 'street,city,state,zip'\" },\n { flags: \"--address <address>\", description: \"Company address (alias for --company-address)\" },\n { flags: \"--shares <count>\", description: \"\", hidden: true },\n { flags: \"--authorized-shares <count>\", description: \"\", hidden: true },\n ],\n handler: formCreateHandler,\n produces: { kind: \"entity\", trackEntity: true },\n successTemplate: \"Pending entity created: {legal_name}\",\n examples: [\n 'corp form create --type c_corp --name \"Acme Inc\" --jurisdiction US-DE --address \"123 Main,City,ST,12345\"',\n 'corp form create --type llc --name \"My LLC\" --jurisdiction US-WY --principal-name \"Carlos\"',\n ],\n },\n {\n name: \"form add-founder\",\n description: \"Add a founder to a pending entity (staged flow step 2)\",\n dryRun: true,\n args: [{ name: \"entity-ref\", required: true }],\n options: [\n { flags: \"--name <name>\", description: \"Founder name\", required: true },\n { flags: \"--email <email>\", description: \"Founder email\", required: true },\n { flags: \"--role <role>\", description: \"Founder role\", required: true, choices: [\"director\", \"officer\", \"manager\", \"member\", \"chair\"] },\n { flags: \"--ownership-pct <percent>\", description: \"Ownership percentage (e.g. 60 for 60%)\", required: true },\n { flags: \"--pct <percent>\", description: \"Alias for --ownership-pct\" },\n { flags: \"--officer-title <title>\", description: \"Officer title (corporations only)\", choices: [\"ceo\", \"cfo\", \"cto\", \"coo\", \"secretary\", \"treasurer\", \"president\", \"vp\", \"other\"] },\n { flags: \"--incorporator\", description: \"Mark as sole incorporator (corporations only)\" },\n { flags: \"--address <address>\", description: \"Founder address as 'street,city,state,zip'\" },\n ],\n handler: formAddFounderHandler,\n examples: [\n 'corp form add-founder @last --name \"Alice\" --email \"alice@co.com\" --role director --ownership-pct 60 --officer-title ceo --incorporator',\n 'corp form add-founder @last --name \"Bob\" --email \"bob@co.com\" --role member --ownership-pct 40 --address \"123 Main|City|ST|12345\"',\n ],\n },\n {\n name: \"form finalize\",\n description: \"Finalize formation and generate documents + cap table (staged flow step 3)\",\n dryRun: true,\n args: [{ name: \"entity-ref\", required: true }],\n options: [\n { flags: \"--authorized-shares <count>\", description: \"Authorized shares for corporations\" },\n { flags: \"--par-value <value>\", description: \"Par value per share, e.g. 0.0001\" },\n { flags: \"--board-size <count>\", description: \"Board size for corporations\" },\n { flags: \"--principal-name <name>\", description: \"Principal or manager name for LLCs\" },\n { flags: \"--registered-agent-name <name>\", description: \"Registered agent legal name\" },\n { flags: \"--registered-agent-address <address>\", description: \"Registered agent address line\" },\n { flags: \"--formation-date <date>\", description: \"Formation date (RFC3339 or YYYY-MM-DD)\" },\n { flags: \"--fiscal-year-end <date>\", description: \"Fiscal year end (MM-DD)\" },\n { flags: \"--s-corp\", description: \"Elect S-Corp status\" },\n { flags: \"--transfer-restrictions\", description: \"Enable transfer restrictions\" },\n { flags: \"--rofr\", description: \"Enable right of first refusal\" },\n { flags: \"--company-address <address>\", description: \"Company address as 'street,city,state,zip'\" },\n { flags: \"--incorporator-name <name>\", description: \"Incorporator legal name (overrides founder)\" },\n { flags: \"--incorporator-address <address>\", description: \"Incorporator mailing address (overrides founder)\" },\n ],\n handler: formFinalizeHandler,\n examples: [\"corp form finalize\"],\n },\n {\n name: \"form activate\",\n description: \"Programmatically sign formation documents and advance an entity to active\",\n dryRun: true,\n args: [{ name: \"entity-ref\", required: true }],\n options: [\n { flags: \"--evidence-uri <uri>\", description: \"Registered-agent consent evidence URI placeholder\" },\n { flags: \"--evidence-type <type>\", description: \"Registered-agent consent evidence type\", default: \"generated\" },\n { flags: \"--filing-id <id>\", description: \"External filing identifier to record\" },\n { flags: \"--receipt-reference <ref>\", description: \"External receipt reference to record\" },\n { flags: \"--ein <ein>\", description: \"EIN to confirm (defaults to a deterministic simulated EIN)\" },\n ],\n handler: formActivateHandler,\n examples: [\"corp form activate\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"contracts\",\n description: \"Generate a contract document\",\n route: { method: \"POST\", path: \"/v1/contracts\" },\n options: [\n { flags: \"--counterparty-name <counterparty-name>\", description: \"Counterparty Name\", required: true },\n { flags: \"--effective-date <effective-date>\", description: \"Effective Date\", required: true },\n { flags: \"--parameters <parameters>\", description: \"Parameters\" },\n { flags: \"--template-type <template-type>\", description: \"Template type for generated contracts.\", required: true, choices: [\"consulting_agreement\", \"employment_offer\", \"contractor_agreement\", \"nda\", \"safe_agreement\", \"custom\"] },\n ],\n examples: [\"corp contracts --counterparty-name 'counterparty-name' --effective-date 'effective-date' --template-type consulting_agreement\", \"corp contracts --json\"],\n successTemplate: \"Contracts created\",\n },\n {\n name: \"documents show\",\n description: \"View a document by ID\",\n route: { method: \"GET\", path: \"/v1/documents/{pos}\" },\n entity: true,\n args: [{ name: \"document-id\", required: true, description: \"Document ID\" }],\n display: { title: \"Document\", cols: [\"document_type>Type\", \"status>Status\", \"title>Title\", \"signature_count>Signatures\", \"@created_at>Created\", \"#document_id>ID\"] },\n examples: [\"corp documents show <document-id>\", \"corp documents show <document-id> --json\"],\n },\n {\n name: \"documents amendment-history\",\n description: \"View amendment history for a document\",\n route: { method: \"GET\", path: \"/v1/documents/{pos}/amendment-history\" },\n entity: true,\n args: [{ name: \"document-id\", required: true, description: \"Document ID\" }],\n display: { title: \"Documents Amendment History\", cols: [\"amended_at>Amended At\", \"description>Description\", \"version>Version\"] },\n examples: [\"corp documents amendment-history\", \"corp documents amendment-history --json\"],\n },\n {\n name: \"documents pdf\",\n description: \"Download a document as PDF\",\n route: { method: \"GET\", path: \"/v1/documents/{pos}/pdf\" },\n entity: true,\n args: [{ name: \"document-id\", required: true, description: \"Document ID\" }],\n examples: [\"corp documents pdf\", \"corp documents pdf --json\"],\n },\n {\n name: \"documents request-copy\",\n description: \"Request a certified copy of a document\",\n route: { method: \"POST\", path: \"/v1/documents/{pos}/request-copy\" },\n args: [{ name: \"document-id\", required: true, description: \"Document ID\" }],\n options: [\n { flags: \"--recipient-email <recipient-email>\", description: \"Recipient Email\" },\n ],\n examples: [\"corp documents request-copy <document-id>\", \"corp documents request-copy --json\"],\n successTemplate: \"Request Copy created\",\n },\n {\n name: \"entities list\",\n description: \"List all entities in the workspace\",\n route: { method: \"GET\", path: \"/v1/entities\" },\n display: { title: \"Entities\", cols: [\"legal_name>Name\", \"entity_type>Type\", \"formation_status>Status\", \"jurisdiction>Jurisdiction\", \"#entity_id>ID\"] },\n examples: [\"corp entities list\", \"corp entities list --json\"],\n },\n {\n name: \"entities governance-documents\",\n description: \"List governance documents for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance-documents\" },\n entity: true,\n display: { title: \"Entities Governance Documents\", cols: [\"@created_at>Created At\", \"#document_id>ID\", \"document_type>Document Type\", \"signature_count>Signature Count\", \"status>Status\", \"title>Title\"] },\n examples: [\"corp entities governance-documents\", \"corp entities governance-documents --json\"],\n },\n {\n name: \"entities governance-documents-current\",\n description: \"View current governance documents\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance-documents/current\" },\n entity: true,\n display: { title: \"Entities Governance Documents Current\", cols: [\"@created_at>Created At\", \"#document_id>ID\", \"document_type>Document Type\", \"signature_count>Signature Count\", \"status>Status\", \"title>Title\"] },\n examples: [\"corp entities governance-documents-current\", \"corp entities governance-documents-current --json\"],\n },\n {\n name: \"formations create\",\n description: \"View formation status for an entity\",\n route: { method: \"POST\", path: \"/v1/formations\" },\n options: [\n { flags: \"--authorized-shares <authorized-shares>\", description: \"Number of authorized shares\" },\n { flags: \"--company-address <company-address>\", description: \"Company mailing address\" },\n { flags: \"--entity-type <entity-type>\", description: \"The legal structure of a business entity.\", required: true, choices: [\"c_corp\", \"llc\"] },\n { flags: \"--fiscal-year-end <fiscal-year-end>\", description: \"Fiscal year end, e.g. \\\"12-31\\\". Defaults to \\\"12-31\\\".\" },\n { flags: \"--formation-date <formation-date>\", description: \"Optional formation date for importing pre-formed entities.\" },\n { flags: \"--jurisdiction <jurisdiction>\", description: \"Jurisdiction (e.g. Delaware, US-DE)\", required: true },\n { flags: \"--legal-name <legal-name>\", description: \"Legal name of the entity\", required: true },\n { flags: \"--members <members>\", description: \"LLC member entries\", required: true, type: \"array\" },\n { flags: \"--par-value <par-value>\", description: \"Par value per share\" },\n { flags: \"--registered-agent-address <registered-agent-address>\", description: \"Registered agent mailing address\" },\n { flags: \"--registered-agent-name <registered-agent-name>\", description: \"Registered agent name\" },\n { flags: \"--right-of-first-refusal <right-of-first-refusal>\", description: \"Include right of first refusal in bylaws (corp). Default true.\" },\n { flags: \"--s-corp-election <s-corp-election>\", description: \"Whether the company will elect S-Corp tax treatment.\" },\n { flags: \"--transfer-restrictions <transfer-restrictions>\", description: \"Include transfer restrictions in bylaws (corp). Default true.\" },\n ],\n examples: [\"corp formations --entity-type c_corp --jurisdiction 'jurisdiction' --legal-name 'legal-name' --members 'members'\", \"corp formations --json\"],\n successTemplate: \"Formations created\",\n },\n {\n name: \"formations pending\",\n description: \"List entities with pending formations\",\n route: { method: \"POST\", path: \"/v1/formations/pending\" },\n options: [\n { flags: \"--company-address <company-address>\", description: \"Company mailing address\" },\n { flags: \"--entity-type <entity-type>\", description: \"The legal structure of a business entity.\", required: true, choices: [\"c_corp\", \"llc\"] },\n { flags: \"--fiscal-year-end <fiscal-year-end>\", description: \"Fiscal year end (e.g. 12-31)\" },\n { flags: \"--formation-date <formation-date>\", description: \"Date of formation (ISO 8601)\" },\n { flags: \"--jurisdiction <jurisdiction>\", description: \"Jurisdiction (e.g. Delaware, US-DE)\" },\n { flags: \"--legal-name <legal-name>\", description: \"Legal name of the entity\", required: true },\n { flags: \"--registered-agent-address <registered-agent-address>\", description: \"Registered agent mailing address\" },\n { flags: \"--registered-agent-name <registered-agent-name>\", description: \"Registered agent name\" },\n { flags: \"--right-of-first-refusal <right-of-first-refusal>\", description: \"Include ROFR in bylaws (true/false)\" },\n { flags: \"--s-corp-election <s-corp-election>\", description: \"S Corp Election\" },\n { flags: \"--transfer-restrictions <transfer-restrictions>\", description: \"Transfer Restrictions\" },\n ],\n examples: [\"corp formations pending --entity-type c_corp --legal-name 'legal-name'\", \"corp formations pending --json\"],\n successTemplate: \"Pending created\",\n },\n {\n name: \"formations with-cap-table\",\n description: \"Create entity with formation and initial cap table\",\n route: { method: \"POST\", path: \"/v1/formations/with-cap-table\" },\n options: [\n { flags: \"--authorized-shares <authorized-shares>\", description: \"Number of authorized shares\" },\n { flags: \"--company-address <company-address>\", description: \"Company mailing address\" },\n { flags: \"--entity-type <entity-type>\", description: \"The legal structure of a business entity.\", required: true, choices: [\"c_corp\", \"llc\"] },\n { flags: \"--fiscal-year-end <fiscal-year-end>\", description: \"Fiscal year end, e.g. \\\"12-31\\\". Defaults to \\\"12-31\\\".\" },\n { flags: \"--formation-date <formation-date>\", description: \"Optional formation date for importing pre-formed entities.\" },\n { flags: \"--jurisdiction <jurisdiction>\", description: \"Jurisdiction (e.g. Delaware, US-DE)\", required: true },\n { flags: \"--legal-name <legal-name>\", description: \"Legal name of the entity\", required: true },\n { flags: \"--members <members>\", description: \"LLC member entries\", required: true, type: \"array\" },\n { flags: \"--par-value <par-value>\", description: \"Par value per share\" },\n { flags: \"--registered-agent-address <registered-agent-address>\", description: \"Registered agent mailing address\" },\n { flags: \"--registered-agent-name <registered-agent-name>\", description: \"Registered agent name\" },\n { flags: \"--right-of-first-refusal <right-of-first-refusal>\", description: \"Include right of first refusal in bylaws (corp). Default true.\" },\n { flags: \"--s-corp-election <s-corp-election>\", description: \"Whether the company will elect S-Corp tax treatment.\" },\n { flags: \"--transfer-restrictions <transfer-restrictions>\", description: \"Include transfer restrictions in bylaws (corp). Default true.\" },\n ],\n examples: [\"corp formations with-cap-table --entity-type c_corp --jurisdiction 'jurisdiction' --legal-name 'legal-name' --members 'members'\", \"corp formations with-cap-table --json\"],\n successTemplate: \"With Cap Table created\",\n },\n {\n name: \"formations\",\n description: \"View formation status for an entity\",\n route: { method: \"GET\", path: \"/v1/formations/{eid}\" },\n entity: true,\n display: { title: \"Formations\", cols: [\"entity_type>Entity Type\", \"formation_date>Formation Date\", \"formation_state>Formation State\", \"formation_status>Formation Status\", \"#entity_id>ID\"] },\n examples: [\"corp formations\", \"corp formations --json\"],\n },\n {\n name: \"formations apply-ein\",\n description: \"Submit EIN application\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/apply-ein\" },\n entity: true,\n examples: [\"corp formations apply-ein\"],\n successTemplate: \"Apply Ein created\",\n },\n {\n name: \"formations ein-confirmation\",\n description: \"Confirm EIN received from IRS\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/ein-confirmation\" },\n entity: true,\n options: [\n { flags: \"--ein <ein>\", description: \"Employer Identification Number\", required: true },\n ],\n examples: [\"corp formations ein-confirmation --ein 'ein'\"],\n successTemplate: \"Ein Confirmation created\",\n },\n {\n name: \"formations filing-attestation\",\n description: \"Attest to filing accuracy\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/filing-attestation\" },\n entity: true,\n options: [\n { flags: \"--consent-text <consent-text>\", description: \"Consent Text\" },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n { flags: \"--signer-email <signer-email>\", description: \"Signer Email\", required: true },\n { flags: \"--signer-name <signer-name>\", description: \"Signer Name\", required: true },\n { flags: \"--signer-role <signer-role>\", description: \"Signer Role\", required: true },\n ],\n examples: [\"corp formations filing-attestation --signer-email 'signer-email' --signer-name 'signer-name' --signer-role 'signer-role'\", \"corp formations filing-attestation --json\"],\n successTemplate: \"Filing Attestation created\",\n },\n {\n name: \"formations filing-confirmation\",\n description: \"Confirm state filing received\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/filing-confirmation\" },\n entity: true,\n options: [\n { flags: \"--external-filing-id <external-filing-id>\", description: \"External Filing Id\", required: true },\n { flags: \"--receipt-reference <receipt-reference>\", description: \"Receipt Reference\" },\n ],\n examples: [\"corp formations filing-confirmation --external-filing-id 'external-filing-id'\", \"corp formations filing-confirmation --json\"],\n successTemplate: \"Filing Confirmation created\",\n },\n {\n name: \"formations finalize\",\n description: \"Finalize a formation (lock documents)\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/finalize\" },\n entity: true,\n options: [\n { flags: \"--authorized-shares <authorized-shares>\", description: \"Number of authorized shares\" },\n { flags: \"--board-size <board-size>\", description: \"Board Size\" },\n { flags: \"--company-address <company-address>\", description: \"Company mailing address\" },\n { flags: \"--fiscal-year-end <fiscal-year-end>\", description: \"Fiscal year end (e.g. 12-31)\" },\n { flags: \"--formation-date <formation-date>\", description: \"Date of formation (ISO 8601)\" },\n { flags: \"--incorporator-address <incorporator-address>\", description: \"Incorporator Address\" },\n { flags: \"--incorporator-name <incorporator-name>\", description: \"Incorporator Name\" },\n { flags: \"--par-value <par-value>\", description: \"Par value per share\" },\n { flags: \"--principal-name <principal-name>\", description: \"Principal Name\" },\n { flags: \"--registered-agent-address <registered-agent-address>\", description: \"Registered agent mailing address\" },\n { flags: \"--registered-agent-name <registered-agent-name>\", description: \"Registered agent name\" },\n { flags: \"--right-of-first-refusal <right-of-first-refusal>\", description: \"Include ROFR in bylaws (true/false)\" },\n { flags: \"--s-corp-election <s-corp-election>\", description: \"S Corp Election\" },\n { flags: \"--transfer-restrictions <transfer-restrictions>\", description: \"Transfer Restrictions\" },\n ],\n examples: [\"corp formations finalize\", \"corp formations finalize --json\"],\n successTemplate: \"Finalize created\",\n },\n {\n name: \"formations founders\",\n description: \"Add founders to a formation\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/founders\" },\n entity: true,\n options: [\n { flags: \"--address <address>\", description: \"Address\" },\n { flags: \"--email <email>\", description: \"Email\" },\n { flags: \"--is-incorporator <is-incorporator>\", description: \"Is Incorporator\" },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--officer-title <officer-title>\", description: \"Officer Title\", choices: [\"ceo\", \"cfo\", \"cto\", \"coo\", \"secretary\", \"treasurer\", \"president\", \"vp\", \"other\"] },\n { flags: \"--ownership-pct <ownership-pct>\", description: \"Ownership Pct\" },\n { flags: \"--role <role>\", description: \"Role\", choices: [\"director\", \"officer\", \"manager\", \"member\", \"chair\"] },\n ],\n examples: [\"corp formations founders --name ceo\", \"corp formations founders --json\"],\n successTemplate: \"Founders created\",\n },\n {\n name: \"formations gates\",\n description: \"View formation gate status (checklist)\",\n route: { method: \"GET\", path: \"/v1/formations/{eid}/gates\" },\n entity: true,\n display: { title: \"Formations Gates\", cols: [\"attestation_recorded>Attestation Recorded\", \"designated_attestor_email>Designated Attestor Email\", \"designated_attestor_name>Designated Attestor Name\", \"designated_attestor_role>Designated Attestor Role\", \"#entity_id>ID\"] },\n examples: [\"corp formations gates\", \"corp formations gates --json\"],\n },\n {\n name: \"formations mark-documents-signed\",\n description: \"Mark formation documents as signed\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/mark-documents-signed\" },\n entity: true,\n examples: [\"corp formations mark-documents-signed\"],\n successTemplate: \"Mark Documents Signed created\",\n },\n {\n name: \"formations registered-agent-consent-evidence\",\n description: \"Provide registered agent consent evidence\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/registered-agent-consent-evidence\" },\n entity: true,\n options: [\n { flags: \"--evidence-type <evidence-type>\", description: \"Evidence Type\" },\n { flags: \"--evidence-uri <evidence-uri>\", description: \"Evidence Uri\", required: true },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n ],\n examples: [\"corp formations registered-agent-consent-evidence --evidence-uri 'evidence-uri'\", \"corp formations registered-agent-consent-evidence --json\"],\n successTemplate: \"Registered Agent Consent Evidence created\",\n },\n {\n name: \"formations service-agreement-execute\",\n description: \"Execute the service agreement\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/service-agreement/execute\" },\n entity: true,\n options: [\n { flags: \"--contract-id <contract-id>\", description: \"Contract Id\" },\n { flags: \"--document-id <document-id>\", description: \"Document ID\" },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n ],\n examples: [\"corp formations service-agreement-execute\", \"corp formations service-agreement-execute --json\"],\n successTemplate: \"Service Agreement Execute created\",\n },\n {\n name: \"formations submit-filing\",\n description: \"Submit state filing for a formation\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/submit-filing\" },\n entity: true,\n examples: [\"corp formations submit-filing\"],\n successTemplate: \"Submit Filing created\",\n },\n {\n name: \"governance catalog\",\n description: \"Browse the governance document catalog\",\n route: { method: \"GET\", path: \"/v1/governance/catalog\" },\n display: { title: \"Governance Catalog\", cols: [\"categories>Categories\"] },\n examples: [\"corp governance catalog\"],\n },\n {\n name: \"governance catalog-markdown\",\n description: \"View a governance document in markdown\",\n route: { method: \"GET\", path: \"/v1/governance/catalog/{pos}/markdown\" },\n args: [{ name: \"document-id\", required: true, description: \"Document ID\" }],\n display: { title: \"Governance Catalog Markdown\", cols: [\"category>Category\", \"entity_scope>Entity Scope\", \"id>Id\", \"markdown>Markdown\", \"title>Title\", \"variants>Variants\"] },\n examples: [\"corp governance catalog-markdown\"],\n },\n\n];","import chalk from \"chalk\";\nimport type { CommandDef, CommandContext } from \"./types.js\";\nimport type { ApiRecord } from \"../types.js\";\nimport {\n printCapTable,\n printInstrumentsTable,\n printReferenceSummary,\n printRoundsTable,\n printSafesTable,\n printShareClassesTable,\n printTransfersTable,\n printValuationsTable,\n} from \"../output.js\";\nimport { shortId } from \"../references.js\";\nimport {\n entityHasActiveBoard,\n issueEquity,\n issueSafe,\n} from \"@thecorporation/corp-tools\";\n\n// Helpers (normalizedGrantType, expectedInstrumentKinds, grantRequiresCurrent409a,\n// buildInstrumentCreationHint, resolveInstrumentForGrant, entityHasActiveBoard,\n// ensureIssuancePreflight) are now imported from @thecorporation/corp-tools.\n\n// ---------------------------------------------------------------------------\n// Local output helper — 409A panel\n// ---------------------------------------------------------------------------\n\nfunction print409a(data: Record<string, unknown>): void {\n console.log(chalk.green(\"\\u2500\".repeat(40)));\n console.log(chalk.green.bold(\" 409A Valuation\"));\n console.log(chalk.green(\"\\u2500\".repeat(40)));\n const fmv = typeof data.fmv_per_share_cents === \"number\" ? (data.fmv_per_share_cents as number) / 100 : data.fmv_per_share;\n const enterpriseValue = typeof data.enterprise_value_cents === \"number\"\n ? (data.enterprise_value_cents as number) / 100\n : data.enterprise_value;\n console.log(` ${chalk.bold(\"FMV/Share:\")} $${fmv ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Enterprise Value:\")} $${enterpriseValue ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Valuation Date:\")} ${data.effective_date ?? data.valuation_date ?? \"N/A\"}`);\n if (data.provider) console.log(` ${chalk.bold(\"Provider:\")} ${data.provider}`);\n console.log(chalk.green(\"\\u2500\".repeat(40)));\n}\n\n// ---------------------------------------------------------------------------\n// Cap-table registry entries\n// ---------------------------------------------------------------------------\n\nexport const capTableCommands: CommandDef[] = [\n // --- cap-table (overview) ---\n {\n name: \"cap-table\",\n description: \"Cap table, equity grants, SAFEs, transfers, and valuations\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/cap-table\" },\n entity: true,\n display: {\n title: \"Cap Table\",\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n let data: ApiRecord;\n try {\n data = await ctx.client.getCapTable(eid);\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"no linked legal entity\") || msg.includes(\"Not found\")) {\n throw new Error(\"No cap table found. Finalize formation first: corp form finalize \" + eid);\n }\n throw err;\n }\n const instruments = Array.isArray(data.instruments) ? data.instruments as ApiRecord[] : [];\n const shareClasses = Array.isArray(data.share_classes) ? data.share_classes as ApiRecord[] : [];\n await ctx.resolver.stabilizeRecords(\"instrument\", instruments, eid);\n await ctx.resolver.stabilizeRecords(\"share_class\", shareClasses, eid);\n if (ctx.opts.json) { ctx.writer.json(data); return; }\n if ((data.access_level as string) === \"none\") {\n ctx.writer.error(\"You do not have access to this entity's cap table.\");\n process.exit(1);\n }\n printCapTable(data);\n try {\n const val = await ctx.client.getCurrent409a(eid);\n if (val) print409a(val);\n } catch { /* ignore */ }\n },\n examples: [\n \"corp cap-table\",\n 'corp cap-table issue-equity --grant-type common --shares 1000000 --recipient \"Alice Smith\"',\n 'corp cap-table issue-safe --investor \"Seed Fund\" --amount-dollars 500000 --valuation-cap-dollars 10000000',\n \"corp cap-table create-valuation --type four_oh_nine_a --date 2026-01-01 --methodology market\",\n \"corp cap-table transfer --from alice --to bob --shares 1000 --share-class-id COMMON --governing-doc-type bylaws --transferee-rights full_member\",\n ],\n },\n\n // --- cap-table safes ---\n {\n name: \"cap-table safes\",\n description: \"List SAFE notes\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/safe-notes\" },\n entity: true,\n display: {\n title: \"SAFE Notes\",\n cols: [\"investor_name|investor>Investor\", \"principal_amount_cents|investment_amount|amount>Amount\", \"valuation_cap_cents|valuation_cap|cap>Cap\", \"discount_rate|discount>Discount\", \"issued_at|date|created_at>Date\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const safes = await ctx.client.getSafeNotes(eid);\n await ctx.resolver.stabilizeRecords(\"safe_note\", safes, eid);\n if (ctx.opts.json) { ctx.writer.json(safes); return; }\n if (safes.length === 0) { ctx.writer.writeln(\"No SAFE notes found.\"); return; }\n printSafesTable(safes);\n },\n examples: [\"corp cap-table safes\", \"corp cap-table safes --json\"],\n },\n\n // --- cap-table transfers ---\n {\n name: \"cap-table transfers\",\n description: \"Share transfers\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/share-transfers\" },\n entity: true,\n display: {\n title: \"Share Transfers\",\n cols: [\"from_holder|from>From\", \"to_holder|to>To\", \"shares|share_count>Shares\", \"transfer_type>Type\", \"status>Status\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const transfers = await ctx.client.getShareTransfers(eid);\n await ctx.resolver.stabilizeRecords(\"share_transfer\", transfers, eid);\n if (ctx.opts.json) { ctx.writer.json(transfers); return; }\n if (transfers.length === 0) { ctx.writer.writeln(\"No share transfers found.\"); return; }\n printTransfersTable(transfers);\n },\n examples: [\"corp cap-table transfers\", \"corp cap-table transfers --json\"],\n },\n\n // --- cap-table instruments ---\n {\n name: \"cap-table instruments\",\n description: \"Cap table instruments\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/cap-table\" },\n entity: true,\n display: {\n title: \"Instruments\",\n listKey: \"instruments\",\n cols: [\"symbol>Symbol\", \"kind>Kind\", \"authorized_units>Authorized\", \"issued_units>Issued\", \"status>Status\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const capTable = await ctx.client.getCapTable(eid);\n const instruments = Array.isArray(capTable.instruments) ? capTable.instruments as ApiRecord[] : [];\n await ctx.resolver.stabilizeRecords(\"instrument\", instruments, eid);\n if (ctx.opts.json) { ctx.writer.json(instruments); return; }\n if (instruments.length === 0) { ctx.writer.writeln(\"No instruments found.\"); return; }\n printInstrumentsTable(instruments);\n },\n examples: [\"corp cap-table instruments\", \"corp cap-table instruments --json\"],\n },\n\n // --- cap-table share-classes ---\n {\n name: \"cap-table share-classes\",\n description: \"List share classes\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/cap-table\" },\n entity: true,\n display: {\n title: \"Share Classes\",\n listKey: \"share_classes\",\n cols: [\"class_code|name|share_class>Class\", \"authorized>Authorized\", \"outstanding>Outstanding\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const capTable = await ctx.client.getCapTable(eid);\n const shareClasses = Array.isArray(capTable.share_classes) ? capTable.share_classes as ApiRecord[] : [];\n await ctx.resolver.stabilizeRecords(\"share_class\", shareClasses, eid);\n if (ctx.opts.json) { ctx.writer.json(shareClasses); return; }\n if (shareClasses.length === 0) { ctx.writer.writeln(\"No share classes found.\"); return; }\n printShareClassesTable(shareClasses);\n },\n examples: [\"corp cap-table share-classes\", \"corp cap-table share-classes --json\"],\n },\n\n // --- cap-table rounds ---\n {\n name: \"cap-table rounds\",\n description: \"Staged equity rounds\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/equity-rounds\" },\n entity: true,\n display: {\n title: \"Equity Rounds\",\n cols: [\"name>Name\", \"status>Status\", \"issuer_legal_entity_id>Issuer\", \"@created_at>Created\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const rounds = await ctx.client.listEquityRounds(eid);\n await ctx.resolver.stabilizeRecords(\"round\", rounds, eid);\n if (ctx.opts.json) { ctx.writer.json(rounds); return; }\n if (rounds.length === 0) { ctx.writer.writeln(\"No rounds found.\"); return; }\n printRoundsTable(rounds);\n },\n examples: [\"corp cap-table rounds\", \"corp cap-table rounds --json\"],\n },\n\n // --- cap-table valuations ---\n {\n name: \"cap-table valuations\",\n description: \"Valuations history\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/valuations\" },\n entity: true,\n display: {\n title: \"Valuations\",\n cols: [\"@effective_date|valuation_date|date>Date\", \"valuation_type|type>Type\", \"enterprise_value_cents|enterprise_value|valuation>Valuation\", \"fmv_per_share_cents|price_per_share|pps|fmv_per_share>PPS\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const valuations = await ctx.client.getValuations(eid);\n await ctx.resolver.stabilizeRecords(\"valuation\", valuations, eid);\n if (ctx.opts.json) { ctx.writer.json(valuations); return; }\n if (valuations.length === 0) { ctx.writer.writeln(\"No valuations found.\"); return; }\n printValuationsTable(valuations);\n },\n examples: [\"corp cap-table valuations\", \"corp cap-table valuations --json\"],\n },\n\n // --- cap-table 409a ---\n {\n name: \"cap-table 409a\",\n description: \"Current 409A valuation\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/current-409a\" },\n entity: true,\n display: { title: \"409A Valuation\" },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n try {\n const data = await ctx.client.getCurrent409a(eid);\n await ctx.resolver.stabilizeRecord(\"valuation\", data, eid);\n if (ctx.opts.json) { ctx.writer.json(data); return; }\n if (!data || Object.keys(data).length === 0) { ctx.writer.writeln(\"No 409A valuation found.\"); return; }\n print409a(data);\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"404\") || msg.includes(\"Not found\") || msg.includes(\"not found\")) {\n try {\n const valuations = await ctx.client.getValuations(eid);\n const pending409a = valuations\n .filter((valuation) => valuation.valuation_type === \"four_oh_nine_a\")\n .find((valuation) => valuation.status === \"pending_approval\");\n if (pending409a) {\n const effectiveDate = pending409a.effective_date ?? \"unknown date\";\n ctx.writer.writeln(\n `No current approved 409A valuation found. A 409A valuation is pending approval (${effectiveDate}).\\n` +\n \" Complete board approval, then re-run: corp cap-table 409a\",\n );\n } else {\n ctx.writer.writeln(\n \"No 409A valuation found for this entity. Create one with:\\n\" +\n \" corp cap-table create-valuation --type four_oh_nine_a --date YYYY-MM-DD --methodology <method>\",\n );\n }\n } catch {\n ctx.writer.writeln(\n \"No 409A valuation found for this entity. Create one with:\\n\" +\n \" corp cap-table create-valuation --type four_oh_nine_a --date YYYY-MM-DD --methodology <method>\",\n );\n }\n } else {\n ctx.writer.error(`Failed to fetch 409A valuation: ${err}`);\n }\n process.exit(1);\n }\n },\n examples: [\"corp cap-table 409a\", \"corp cap-table 409a --json\"],\n },\n\n // --- cap-table control-map ---\n {\n name: \"cap-table control-map\",\n description: \"View entity control/ownership map\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/control-map\" },\n entity: \"query\",\n display: { title: \"Control Map\" },\n options: [\n { flags: \"--root-entity-id <ref>\", description: \"Root entity for ownership tree (defaults to active entity)\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const rootEntityId = (ctx.opts.rootEntityId as string | undefined)\n ? await ctx.resolver.resolveEntity(ctx.opts.rootEntityId as string)\n : eid;\n\n let result: ApiRecord;\n try {\n result = await ctx.client.getControlMap(eid, rootEntityId);\n } catch (firstErr) {\n const msg = String(firstErr);\n if (msg.includes(\"404\") && !ctx.opts.rootEntityId) {\n try {\n const capTable = await ctx.client.getCapTable(eid);\n const issuerLegalEntityId = capTable.issuer_legal_entity_id as string | undefined;\n if (issuerLegalEntityId && issuerLegalEntityId !== eid) {\n result = await ctx.client.getControlMap(eid, issuerLegalEntityId);\n } else {\n throw firstErr;\n }\n } catch {\n throw firstErr;\n }\n } else {\n throw firstErr;\n }\n }\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.json(result);\n },\n examples: [\"corp cap-table control-map\", \"corp cap-table control-map --json\"],\n },\n\n // --- cap-table dilution ---\n {\n name: \"cap-table dilution\",\n description: \"Preview dilution impact of a round\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/dilution-preview\" },\n entity: \"query\",\n display: { title: \"Dilution Preview\" },\n options: [\n { flags: \"--round-id <ref>\", description: \"Round reference to model dilution for\", required: true },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const roundId = await ctx.resolver.resolveRound(eid, ctx.opts.roundId as string);\n const result = await ctx.client.getDilutionPreview(eid, roundId);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n if (result.round_status === \"closed\" || result.round_status === \"issued\") {\n console.log(chalk.yellow(\"Note: This round is already closed. Dilution preview reflects the finalized state, not a scenario model.\"));\n console.log(chalk.dim(\" For scenario modeling, create a new round with: corp cap-table start-round --name '...' --issuer-legal-entity-id '...'\"));\n }\n ctx.writer.json(result);\n },\n examples: [\"corp cap-table dilution\", \"corp cap-table dilution --json\"],\n },\n\n // --- cap-table create-instrument ---\n {\n name: \"cap-table create-instrument\",\n description: \"Create a cap table instrument\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/instruments\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--kind <kind>\", description: \"Instrument kind (common_equity, preferred_equity, membership_unit, option_grant, safe)\", required: true },\n { flags: \"--symbol <symbol>\", description: \"Instrument symbol\", required: true },\n { flags: \"--issuer-legal-entity-id <ref>\", description: \"Issuer legal entity reference (ID, short ID, @last, or unique name)\" },\n { flags: \"--authorized-units <n>\", description: \"Authorized units\", type: \"int\" },\n { flags: \"--issue-price-cents <n>\", description: \"Issue price in cents\", type: \"int\" },\n { flags: \"--terms-json <json>\", description: \"JSON object of instrument terms\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n let issuerLegalEntityId = ctx.opts.issuerLegalEntityId as string | undefined;\n if (!issuerLegalEntityId) {\n const capTable = await ctx.client.getCapTable(eid);\n issuerLegalEntityId = capTable.issuer_legal_entity_id as string | undefined;\n }\n if (!issuerLegalEntityId) {\n throw new Error(\"No issuer legal entity found. Has this entity been formed with a cap table?\");\n }\n issuerLegalEntityId = await ctx.resolver.resolveEntity(issuerLegalEntityId);\n\n const terms = (ctx.opts.termsJson as string | undefined)\n ? JSON.parse(ctx.opts.termsJson as string) as Record<string, unknown>\n : {};\n const payload: Record<string, unknown> = {\n entity_id: eid,\n issuer_legal_entity_id: issuerLegalEntityId,\n kind: ctx.opts.kind as string,\n symbol: ctx.opts.symbol as string,\n terms,\n };\n if (ctx.opts.authorizedUnits != null) payload.authorized_units = ctx.opts.authorizedUnits;\n if (ctx.opts.issuePriceCents != null) payload.issue_price_cents = ctx.opts.issuePriceCents;\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.create_instrument\", payload);\n return;\n }\n const result = await ctx.client.createInstrument(payload);\n await ctx.resolver.stabilizeRecord(\"instrument\", result, eid);\n ctx.resolver.rememberFromRecord(\"instrument\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Instrument created: ${result.instrument_id ?? \"OK\"}`);\n printReferenceSummary(\"instrument\", result, { showReuseHint: true });\n },\n produces: { kind: \"instrument\" },\n successTemplate: \"Instrument created: {symbol}\",\n examples: [\"corp cap-table create-instrument --kind 'kind' --symbol 'symbol'\", \"corp cap-table create-instrument --json\"],\n },\n\n // --- cap-table issue-equity ---\n {\n name: \"cap-table issue-equity\",\n description: \"Issue an equity grant (creates a round, adds security, and issues it)\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/equity-rounds\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--grant-type <type>\", description: \"Grant type (common, preferred, membership_unit, stock_option, iso, nso, rsa)\", required: true },\n { flags: \"--shares <n>\", description: \"Number of shares\", required: true, type: \"int\" },\n { flags: \"--recipient <name>\", description: \"Recipient name\", required: true },\n { flags: \"--email <email>\", description: \"Recipient email (auto-creates contact if needed)\" },\n { flags: \"--instrument-id <ref>\", description: \"Instrument reference (ID, short ID, symbol, or @last)\" },\n { flags: \"--meeting-id <ref>\", description: \"Board meeting reference required when a board approval already exists or is being recorded\" },\n { flags: \"--resolution-id <ref>\", description: \"Board resolution reference required when issuing under a board-governed entity\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const grantType = ctx.opts.grantType as string;\n const shares = ctx.opts.shares as number;\n const recipient = ctx.opts.recipient as string;\n const email = ctx.opts.email as string | undefined;\n const optInstrumentId = ctx.opts.instrumentId as string | undefined;\n const optMeetingId = ctx.opts.meetingId as string | undefined;\n const optResolutionId = ctx.opts.resolutionId as string | undefined;\n\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.issue_equity\", {\n entity_id: eid,\n grant_type: grantType,\n shares,\n recipient,\n email,\n instrument_id: optInstrumentId,\n meeting_id: optMeetingId,\n resolution_id: optResolutionId,\n });\n return;\n }\n\n // Resolve references before passing to workflow\n const instrumentId = optInstrumentId\n ? await ctx.resolver.resolveInstrument(eid, optInstrumentId)\n : undefined;\n const meetingId = optMeetingId ? await ctx.resolver.resolveMeeting(eid, optMeetingId) : undefined;\n const resolutionId = optResolutionId\n ? await ctx.resolver.resolveResolution(eid, optResolutionId, meetingId)\n : undefined;\n\n const result = await issueEquity(ctx.client, {\n entityId: eid,\n grantType,\n shares,\n recipientName: recipient,\n recipientEmail: email,\n instrumentId,\n meetingId,\n resolutionId,\n });\n\n if (!result.success) {\n let errMsg = result.error!;\n if (errMsg.includes(\"already bound\") && !errMsg.includes(\"quick-approve\")) {\n errMsg += '\\n Each issuance needs its own board approval.\\n Run: corp governance quick-approve --text \"RESOLVED: authorize equity issuance\"';\n }\n ctx.writer.error(errMsg);\n return;\n }\n\n // Track references for the created round\n const round = result.data?.round as Record<string, unknown> | undefined;\n if (round) {\n await ctx.resolver.stabilizeRecord(\"round\", round, eid);\n ctx.resolver.rememberFromRecord(\"round\", round, eid);\n }\n\n // Show instrument selection detail\n const instrStep = result.steps.find((s) => s.name === \"resolve_instrument\");\n if (instrStep && !optInstrumentId) {\n console.log(instrStep.detail);\n }\n\n if (ctx.opts.json) { ctx.writer.json(result.data); return; }\n ctx.writer.success(`Equity issued: ${shares} shares (${grantType}) to ${recipient}`);\n if (round) {\n printReferenceSummary(\"round\", round, { label: \"Round Ref:\", showReuseHint: true });\n }\n },\n produces: { kind: \"round\" },\n successTemplate: \"Equity issued: {round_name}\",\n examples: [\n 'corp cap-table issue-equity --grant-type common --shares 50000 --recipient \"Alice Smith\"',\n 'corp cap-table issue-equity --grant-type iso --shares 10000 --recipient \"Bob\" --email \"bob@co.com\"',\n ],\n },\n\n // --- cap-table issue-safe ---\n {\n name: \"cap-table issue-safe\",\n description: \"Issue a SAFE note\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/safe-notes\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--investor <name>\", description: \"Investor name\", required: true },\n { flags: \"--amount-cents <n>\", description: \"Principal amount in cents (e.g. 50000000 = $500,000)\", type: \"int\" },\n { flags: \"--amount-dollars <n>\", description: \"Principal amount in dollars (e.g. 500000 = $500,000)\", type: \"int\" },\n { flags: \"--safe-type <type>\", description: \"SAFE type\", default: \"post_money\", choices: [\"post_money\", \"pre_money\", \"mfn\"] },\n { flags: \"--valuation-cap-cents <n>\", description: \"Valuation cap in cents (e.g. 100000000 = $1M)\", type: \"int\" },\n { flags: \"--valuation-cap-dollars <n>\", description: \"Valuation cap in dollars (e.g. 1000000 = $1M)\", type: \"int\" },\n { flags: \"--meeting-id <ref>\", description: \"Board meeting reference required when issuing under a board-governed entity\" },\n { flags: \"--resolution-id <ref>\", description: \"Board resolution reference required when issuing under a board-governed entity\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const investor = ctx.opts.investor as string;\n if (ctx.opts.amountCents != null && ctx.opts.amountDollars != null) {\n throw new Error(\"--amount-cents and --amount-dollars are mutually exclusive. Use one or the other.\");\n }\n const amountCents = ctx.opts.amountCents != null\n ? (ctx.opts.amountCents as number)\n : ctx.opts.amountDollars != null ? (ctx.opts.amountDollars as number) * 100 : undefined;\n if (amountCents == null) {\n throw new Error(\"required: --amount-cents <n> or --amount-dollars <n>\");\n }\n const safeType = (ctx.opts.safeType ?? \"post_money\") as string;\n if (ctx.opts.valuationCapCents != null && ctx.opts.valuationCapDollars != null) {\n throw new Error(\"--valuation-cap-cents and --valuation-cap-dollars are mutually exclusive. Use one or the other.\");\n }\n const valuationCapCents = ctx.opts.valuationCapCents != null\n ? (ctx.opts.valuationCapCents as number)\n : ctx.opts.valuationCapDollars != null ? (ctx.opts.valuationCapDollars as number) * 100 : undefined;\n if (valuationCapCents == null) {\n throw new Error(\"required: --valuation-cap-cents <n> or --valuation-cap-dollars <n>\");\n }\n const email = ctx.opts.email as string | undefined;\n const optMeetingId = ctx.opts.meetingId as string | undefined;\n const optResolutionId = ctx.opts.resolutionId as string | undefined;\n\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.issue_safe\", {\n entity_id: eid,\n investor,\n amount_cents: amountCents,\n safe_type: safeType,\n valuation_cap_cents: valuationCapCents,\n email,\n meeting_id: optMeetingId,\n resolution_id: optResolutionId,\n });\n return;\n }\n\n // Resolve references before passing to workflow\n const meetingId = optMeetingId ? await ctx.resolver.resolveMeeting(eid, optMeetingId) : undefined;\n const resolutionId = optResolutionId\n ? await ctx.resolver.resolveResolution(eid, optResolutionId, meetingId)\n : undefined;\n\n const result = await issueSafe(ctx.client, {\n entityId: eid,\n investorName: investor,\n amountCents,\n valuationCapCents,\n safeType,\n email,\n meetingId,\n resolutionId,\n });\n\n if (!result.success) {\n let errMsg = result.error!;\n if (errMsg.includes(\"already bound\") && !errMsg.includes(\"quick-approve\")) {\n errMsg += '\\n Each issuance needs its own board approval.\\n Run: corp governance quick-approve --text \"RESOLVED: authorize SAFE issuance\"';\n }\n ctx.writer.error(errMsg);\n return;\n }\n\n await ctx.resolver.stabilizeRecord(\"safe_note\", result.data!, eid);\n ctx.resolver.rememberFromRecord(\"safe_note\", result.data!, eid);\n if (ctx.opts.json) { ctx.writer.json(result.data); return; }\n ctx.writer.success(`SAFE issued: $${(amountCents / 100).toLocaleString()} to ${investor}`);\n printReferenceSummary(\"safe_note\", result.data!, { showReuseHint: true });\n },\n produces: { kind: \"safe_note\" },\n successTemplate: \"SAFE created: {investor_name}\",\n examples: [\n 'corp cap-table issue-safe --investor \"Seed Fund\" --amount-dollars 500000 --valuation-cap-dollars 10000000',\n \"corp cap-table issue-safe --investor \\\"Angel\\\" --amount-cents 50000000 --valuation-cap-cents 1000000000\",\n ],\n },\n\n // --- cap-table transfer ---\n {\n name: \"cap-table transfer\",\n description: \"Create a share transfer workflow\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/share-transfers\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--from <ref>\", description: \"Source contact reference (from_contact_id)\", required: true },\n { flags: \"--to <ref>\", description: \"Destination contact reference (to_contact_id)\", required: true },\n { flags: \"--shares <n>\", description: \"Number of shares to transfer\", required: true, type: \"int\" },\n { flags: \"--share-class-id <ref>\", description: \"Share class reference (auto-resolved if only one exists)\" },\n { flags: \"--governing-doc-type <type>\", description: \"Governing doc type (bylaws, operating_agreement, shareholder_agreement, other)\", default: \"bylaws\" },\n { flags: \"--transferee-rights <rights>\", description: \"Transferee rights (full_member, economic_only, limited)\", default: \"full_member\" },\n { flags: \"--prepare-intent-id <id>\", description: \"Prepare intent ID (auto-created if omitted)\" },\n { flags: \"--type <type>\", description: \"Transfer type (gift, trust_transfer, secondary_sale, estate, other)\", default: \"secondary_sale\" },\n { flags: \"--price-per-share-cents <n>\", description: \"Price per share in cents\", type: \"int\" },\n { flags: \"--relationship <rel>\", description: \"Relationship to holder\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const fromContactId = await ctx.resolver.resolveContact(eid, ctx.opts.from as string);\n const toContactId = await ctx.resolver.resolveContact(eid, ctx.opts.to as string);\n let shareClassId: string;\n if (ctx.opts.shareClassId) {\n shareClassId = await ctx.resolver.resolveShareClass(eid, ctx.opts.shareClassId as string);\n } else {\n // Auto-resolve: use the only share class if there's exactly one\n const capTable = await ctx.client.getCapTable(eid);\n const instruments = (capTable.instruments ?? []) as Array<{ share_class_id?: string }>;\n const classIds = [...new Set(instruments.map((i) => i.share_class_id).filter(Boolean))] as string[];\n if (classIds.length === 1) {\n shareClassId = classIds[0];\n } else if (classIds.length === 0) {\n throw new Error(\"No share classes found. Create one first or specify --share-class-id.\");\n } else {\n throw new Error(`Multiple share classes found (${classIds.length}). Specify --share-class-id to disambiguate.`);\n }\n }\n const shares = ctx.opts.shares as number;\n const pricePerShareCents = ctx.opts.pricePerShareCents as number | undefined;\n const relationship = ctx.opts.relationship as string | undefined;\n const transferType = (ctx.opts.type ?? \"secondary_sale\") as string;\n const prepareIntentId = ctx.opts.prepareIntentId as string | undefined;\n\n if (pricePerShareCents != null && pricePerShareCents < 0) {\n throw new Error(\"price-per-share-cents cannot be negative\");\n }\n if (fromContactId === toContactId) {\n throw new Error(\"--from and --to must be different contacts\");\n }\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.transfer_shares\", {\n entity_id: eid,\n from_contact_id: fromContactId,\n to_contact_id: toContactId,\n share_count: shares,\n transfer_type: transferType,\n share_class_id: shareClassId,\n governing_doc_type: ctx.opts.governingDocType as string,\n transferee_rights: ctx.opts.transfereeRights as string,\n prepare_intent_id: prepareIntentId,\n price_per_share_cents: pricePerShareCents,\n relationship_to_holder: relationship,\n });\n return;\n }\n\n let intentId = prepareIntentId;\n if (!intentId) {\n const intent = await ctx.client.createExecutionIntent({\n entity_id: eid,\n intent_type: \"equity.transfer.prepare\",\n description: `Transfer ${shares} shares from ${fromContactId} to ${toContactId}`,\n });\n intentId = (intent.intent_id ?? intent.id) as string;\n await ctx.client.evaluateIntent(intentId, eid);\n await ctx.client.authorizeIntent(intentId, eid);\n }\n const body: Record<string, unknown> = {\n entity_id: eid,\n share_class_id: shareClassId,\n from_contact_id: fromContactId,\n to_contact_id: toContactId,\n transfer_type: transferType,\n share_count: shares,\n governing_doc_type: ctx.opts.governingDocType as string,\n transferee_rights: ctx.opts.transfereeRights as string,\n prepare_intent_id: intentId,\n };\n if (pricePerShareCents != null) body.price_per_share_cents = pricePerShareCents;\n if (relationship) body.relationship_to_holder = relationship;\n const result = await ctx.client.transferShares(body);\n await ctx.resolver.stabilizeRecord(\"share_transfer\", result, eid);\n ctx.resolver.rememberFromRecord(\"share_transfer\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Transfer workflow created: ${result.transfer_workflow_id ?? \"OK\"}`);\n printReferenceSummary(\"share_transfer\", result, { label: \"Transfer Ref:\", showReuseHint: true });\n },\n produces: { kind: \"share_transfer\" },\n successTemplate: \"Transfer created\",\n examples: [\"corp cap-table transfer --from 'ref' --to 'ref' --shares 'n' --share-class-id 'ref' --governing-doc-type 'type' --transferee-rights 'rights'\", \"corp cap-table transfer --json\"],\n },\n\n // --- cap-table distribute ---\n {\n name: \"cap-table distribute\",\n description: \"Calculate a distribution\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/distributions\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--amount-cents <n>\", description: \"Total distribution amount in cents (e.g. 100000 = $1,000.00)\", required: true, type: \"int\" },\n { flags: \"--amount-dollars <n>\", description: \"Total distribution amount in dollars (e.g. 1000 = $1,000.00)\", type: \"int\" },\n { flags: \"--type <type>\", description: \"Distribution type (dividend, return, liquidation)\", default: \"dividend\" },\n { flags: \"--description <desc>\", description: \"Distribution description\", required: true },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n if (ctx.opts.amountCents != null && ctx.opts.amountDollars != null) {\n throw new Error(\"--amount-cents and --amount-dollars are mutually exclusive. Use one or the other.\");\n }\n const amountCents = ctx.opts.amountCents != null\n ? (ctx.opts.amountCents as number)\n : ctx.opts.amountDollars != null\n ? (ctx.opts.amountDollars as number) * 100\n : undefined;\n if (amountCents == null) {\n throw new Error(\"required: --amount-cents <n> or --amount-dollars <n>\");\n }\n const distributionType = (ctx.opts.type ?? \"dividend\") as string;\n const description = ctx.opts.description as string;\n const payload = {\n entity_id: eid,\n total_amount_cents: amountCents,\n distribution_type: distributionType,\n description,\n };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.distribute\", payload);\n return;\n }\n const result = await ctx.client.calculateDistribution(payload);\n await ctx.resolver.stabilizeRecord(\"distribution\", result, eid);\n ctx.resolver.rememberFromRecord(\"distribution\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Distribution calculated: ${result.distribution_id ?? \"OK\"}`);\n printReferenceSummary(\"distribution\", result, { showReuseHint: true });\n },\n examples: [\"corp cap-table distribute --amount-cents 'n' --description 'desc'\", \"corp cap-table distribute --json\"],\n },\n\n // --- cap-table start-round ---\n {\n name: \"cap-table start-round\",\n description: \"Start a staged equity round\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/equity-rounds\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--name <name>\", description: \"Round name\", required: true },\n { flags: \"--issuer-legal-entity-id <ref>\", description: \"Issuer legal entity reference (auto-resolved from cap table if omitted)\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n let issuerLegalEntityId = ctx.opts.issuerLegalEntityId as string | undefined;\n if (!issuerLegalEntityId) {\n const capTable = await ctx.client.getCapTable(eid);\n issuerLegalEntityId = capTable.issuer_legal_entity_id as string | undefined;\n }\n if (!issuerLegalEntityId) {\n throw new Error(\"No issuer legal entity found. Provide --issuer-legal-entity-id or ensure the entity has a cap table.\");\n }\n issuerLegalEntityId = await ctx.resolver.resolveEntity(issuerLegalEntityId);\n const payload = {\n entity_id: eid,\n name: ctx.opts.name as string,\n issuer_legal_entity_id: issuerLegalEntityId,\n };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.start_round\", payload);\n return;\n }\n const result = await ctx.client.startEquityRound(payload);\n await ctx.resolver.stabilizeRecord(\"round\", result, eid);\n ctx.resolver.rememberFromRecord(\"round\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Round started: ${result.round_id ?? \"OK\"}`);\n printReferenceSummary(\"round\", result, { showReuseHint: true });\n },\n produces: { kind: \"round\" },\n successTemplate: \"Round started: {round_name}\",\n examples: [\"corp cap-table start-round --name 'name' --issuer-legal-entity-id 'ref'\"],\n },\n\n // --- cap-table add-security ---\n {\n name: \"cap-table add-security\",\n description: \"Add a security to a staged equity round\",\n route: { method: \"POST\", path: \"/v1/equity-rounds/{pos}/securities\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--round-id <ref>\", description: \"Round reference\", required: true },\n { flags: \"--instrument-id <ref>\", description: \"Instrument reference\", required: true },\n { flags: \"--quantity <n>\", description: \"Number of shares/units\", required: true, type: \"int\" },\n { flags: \"--recipient-name <name>\", description: \"Recipient display name\", required: true },\n { flags: \"--holder-id <ref>\", description: \"Existing holder reference\" },\n { flags: \"--email <email>\", description: \"Recipient email (to find or create holder)\" },\n { flags: \"--principal-cents <n>\", description: \"Principal amount in cents\", type: \"int\" },\n { flags: \"--grant-type <type>\", description: \"Grant type\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const roundId = await ctx.resolver.resolveRound(eid, ctx.opts.roundId as string);\n const instrumentId = await ctx.resolver.resolveInstrument(eid, ctx.opts.instrumentId as string);\n const body: Record<string, unknown> = {\n entity_id: eid,\n instrument_id: instrumentId,\n quantity: ctx.opts.quantity as number,\n recipient_name: ctx.opts.recipientName as string,\n };\n if (ctx.opts.holderId) body.holder_id = await ctx.resolver.resolveContact(eid, ctx.opts.holderId as string);\n if (ctx.opts.email) body.email = ctx.opts.email as string;\n if (ctx.opts.principalCents) body.principal_cents = ctx.opts.principalCents as number;\n if (ctx.opts.grantType) body.grant_type = ctx.opts.grantType as string;\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.add_security\", { round_id: roundId, ...body });\n return;\n }\n const result = await ctx.client.addRoundSecurity(roundId, body);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Security added for ${ctx.opts.recipientName}`);\n },\n examples: [\"corp cap-table add-security --round-id 'ref' --instrument-id 'ref' --quantity 'n' --recipient-name 'name'\", \"corp cap-table add-security --json\"],\n },\n\n // --- cap-table issue-round ---\n {\n name: \"cap-table issue-round\",\n description: \"Issue all securities and close a staged round\",\n route: { method: \"POST\", path: \"/v1/equity-rounds/{pos}/issue\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--round-id <ref>\", description: \"Round reference\", required: true },\n { flags: \"--meeting-id <ref>\", description: \"Board meeting reference (required if entity has an active board)\" },\n { flags: \"--resolution-id <ref>\", description: \"Board resolution reference (required if entity has an active board)\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const roundId = await ctx.resolver.resolveRound(eid, ctx.opts.roundId as string);\n const meetingId = (ctx.opts.meetingId as string | undefined)\n ? await ctx.resolver.resolveMeeting(eid, ctx.opts.meetingId as string)\n : undefined;\n const resolutionId = (ctx.opts.resolutionId as string | undefined)\n ? await ctx.resolver.resolveResolution(eid, ctx.opts.resolutionId as string, meetingId)\n : undefined;\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.issue_round\", {\n entity_id: eid,\n round_id: roundId,\n meeting_id: meetingId,\n resolution_id: resolutionId,\n });\n return;\n }\n if ((!meetingId || !resolutionId) && await entityHasActiveBoard(ctx.client, eid)) {\n throw new Error(\n \"Board approval is required before issuing this round. Pass --meeting-id and --resolution-id from a passed board vote.\\n Tip: Use 'corp governance quick-approve --text \\\"RESOLVED: ...\\\"' for one-step approval.\",\n );\n }\n const body: Record<string, unknown> = { entity_id: eid };\n if (meetingId) body.meeting_id = meetingId;\n if (resolutionId) body.resolution_id = resolutionId;\n const result = await ctx.client.issueRound(roundId, body);\n ctx.resolver.remember(\"round\", roundId, eid);\n const roundMatch = (await ctx.resolver.find(\"round\", shortId(roundId), { entityId: eid }))\n .find((match) => match.id === roundId);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(\"Round issued and closed\");\n if (roundMatch) {\n printReferenceSummary(\"round\", roundMatch.raw, { showReuseHint: true });\n }\n },\n examples: [\"corp cap-table issue-round --round-id 'ref'\", \"corp cap-table issue-round --json\"],\n },\n\n // --- cap-table create-valuation ---\n {\n name: \"cap-table create-valuation\",\n description: \"Create a valuation\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/valuations\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--type <type>\", description: \"Valuation type (four_oh_nine_a, fair_market_value, etc.)\", required: true },\n { flags: \"--date <date>\", description: \"Effective date (ISO 8601)\", required: true },\n { flags: \"--methodology <method>\", description: \"Methodology\", required: true, choices: [\"income\", \"market\", \"asset\", \"backsolve\", \"hybrid\", \"other\"] },\n { flags: \"--fmv <cents>\", description: \"FMV per share in cents\", type: \"int\" },\n { flags: \"--enterprise-value <cents>\", description: \"Enterprise value in cents\", type: \"int\" },\n { flags: \"--auto-approve\", description: \"Automatically submit and approve the valuation (skips board workflow)\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const body: Record<string, unknown> = {\n entity_id: eid,\n valuation_type: ctx.opts.type as string,\n effective_date: ctx.opts.date as string,\n methodology: ctx.opts.methodology as string,\n };\n if (ctx.opts.fmv != null) body.fmv_per_share_cents = ctx.opts.fmv;\n if (ctx.opts.enterpriseValue != null) body.enterprise_value_cents = ctx.opts.enterpriseValue;\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.create_valuation\", body);\n return;\n }\n const result = await ctx.client.createValuation(body);\n await ctx.resolver.stabilizeRecord(\"valuation\", result, eid);\n ctx.resolver.rememberFromRecord(\"valuation\", result, eid);\n\n const valuationId = String(result.valuation_id ?? result.id);\n\n if (ctx.opts.autoApprove && valuationId) {\n try {\n await ctx.client.submitValuationForApproval(valuationId, eid);\n const approved = await ctx.client.approveValuation(valuationId, eid);\n await ctx.resolver.stabilizeRecord(\"valuation\", approved, eid);\n if (ctx.opts.json) { ctx.writer.json(approved); return; }\n ctx.writer.success(`Valuation created and approved: ${valuationId}`);\n printReferenceSummary(\"valuation\", approved, { showReuseHint: true });\n return;\n } catch (err) {\n // Fall through to normal output if auto-approve fails (e.g. board required)\n if (!ctx.opts.json) {\n ctx.writer.warning(`Auto-approve failed (board approval may be required): ${err}`);\n }\n }\n }\n\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Valuation created: ${result.valuation_id ?? \"OK\"}`);\n printReferenceSummary(\"valuation\", result, { showReuseHint: true });\n },\n produces: { kind: \"valuation\" },\n successTemplate: \"Valuation created\",\n examples: [\"corp cap-table create-valuation --type 'type' --date 'date' --methodology 'method'\", \"corp cap-table create-valuation --json\"],\n },\n\n // --- cap-table submit-valuation <valuation-ref> ---\n {\n name: \"cap-table submit-valuation\",\n description: \"Submit a valuation for board approval\",\n route: { method: \"POST\", path: \"/v1/valuations/{pos}/submit\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"valuation-ref\", required: true, description: \"Valuation reference\" }],\n handler: async (ctx) => {\n const valuationRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const valuationId = await ctx.resolver.resolveValuation(eid, valuationRef);\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.submit_valuation\", { entity_id: eid, valuation_id: valuationId });\n return;\n }\n try {\n const result = await ctx.client.submitValuationForApproval(valuationId, eid);\n await ctx.resolver.stabilizeRecord(\"valuation\", result, eid);\n ctx.resolver.remember(\"valuation\", valuationId, eid);\n if (result.meeting_id) ctx.resolver.remember(\"meeting\", String(result.meeting_id), eid);\n if (result.agenda_item_id) ctx.resolver.remember(\"agenda_item\", String(result.agenda_item_id), eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Valuation submitted for approval: ${result.valuation_id ?? valuationId ?? \"OK\"}`);\n printReferenceSummary(\"valuation\", result, { showReuseHint: true });\n if (result.meeting_id) {\n const meetingMatch = (await ctx.resolver.find(\"meeting\", shortId(String(result.meeting_id)), { entityId: eid }))\n .find((match) => match.id === String(result.meeting_id));\n if (meetingMatch) {\n printReferenceSummary(\"meeting\", meetingMatch.raw, { label: \"Meeting Ref:\" });\n } else {\n printReferenceSummary(\"meeting\", { meeting_id: result.meeting_id }, { label: \"Meeting Ref:\" });\n }\n }\n if (result.agenda_item_id) {\n const agendaMatch = (await ctx.resolver.find(\"agenda_item\", shortId(String(result.agenda_item_id)), {\n entityId: eid,\n meetingId: result.meeting_id ? String(result.meeting_id) : undefined,\n }))\n .find((match) => match.id === String(result.agenda_item_id));\n if (agendaMatch) {\n printReferenceSummary(\"agenda_item\", agendaMatch.raw, { label: \"Agenda Ref:\" });\n } else {\n printReferenceSummary(\"agenda_item\", { agenda_item_id: result.agenda_item_id }, { label: \"Agenda Ref:\" });\n }\n }\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"404\") || msg.includes(\"Not found\") || msg.includes(\"not found\")) {\n ctx.writer.error(`Valuation not found. List valuations with: corp cap-table valuations`);\n } else {\n ctx.writer.error(`Failed to submit valuation: ${err}`);\n }\n process.exit(1);\n }\n },\n examples: [\"corp cap-table submit-valuation <valuation-ref>\"],\n },\n\n // --- cap-table approve-valuation <valuation-ref> ---\n {\n name: \"cap-table approve-valuation\",\n description: \"Approve a valuation\",\n route: { method: \"POST\", path: \"/v1/valuations/{pos}/approve\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"valuation-ref\", required: true, description: \"Valuation reference\" }],\n options: [\n { flags: \"--resolution-id <ref>\", description: \"Resolution reference from the board vote\" },\n ],\n handler: async (ctx) => {\n const valuationRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const valuationId = await ctx.resolver.resolveValuation(eid, valuationRef);\n const resolutionId = (ctx.opts.resolutionId as string | undefined)\n ? await ctx.resolver.resolveResolution(eid, ctx.opts.resolutionId as string)\n : undefined;\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"cap_table.approve_valuation\", {\n entity_id: eid,\n valuation_id: valuationId,\n resolution_id: resolutionId,\n });\n return;\n }\n try {\n const result = await ctx.client.approveValuation(valuationId, eid, resolutionId);\n await ctx.resolver.stabilizeRecord(\"valuation\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Valuation approved: ${result.valuation_id ?? valuationId ?? \"OK\"}`);\n printReferenceSummary(\"valuation\", result);\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"400\")) {\n ctx.writer.error(`Bad request \\u2014 a --resolution-id from a board vote may be required. Submit for approval first: corp cap-table submit-valuation <valuation-ref>`);\n } else {\n ctx.writer.error(`Failed to approve valuation: ${err}`);\n }\n process.exit(1);\n }\n },\n examples: [\"corp cap-table approve-valuation <valuation-ref>\", \"corp cap-table approve-valuation --json\"],\n },\n\n // --- cap-table preview-conversion ---\n {\n name: \"cap-table preview-conversion\",\n description: \"Preview SAFE-to-equity conversion\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/safe-conversion-preview\" },\n entity: true,\n options: [\n { flags: \"--safe-id <ref>\", description: \"SAFE note reference to convert\", required: true },\n { flags: \"--price-per-share-cents <n>\", description: \"Conversion price per share in cents\", required: true, type: \"int\" },\n ],\n display: { title: \"Conversion Preview\" },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const safeId = await ctx.resolver.resolveSafeNote(eid, ctx.opts.safeId as string);\n const result = await ctx.client.previewRoundConversion({\n entity_id: eid,\n safe_note_id: safeId,\n price_per_share_cents: ctx.opts.pricePerShareCents as number,\n } as unknown as Parameters<typeof ctx.client.previewRoundConversion>[0]);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(\"Conversion Preview:\");\n if (result.shares_issued) console.log(` Shares to issue: ${result.shares_issued}`);\n if (result.ownership_pct) console.log(` Post-conversion ownership: ${result.ownership_pct}%`);\n ctx.writer.json(result);\n },\n examples: [\"corp cap-table preview-conversion\", \"corp cap-table preview-conversion --json\"],\n },\n\n // --- cap-table convert ---\n {\n name: \"cap-table convert\",\n description: \"Execute SAFE-to-equity conversion\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/safe-conversions\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--safe-id <ref>\", description: \"SAFE note reference to convert\", required: true },\n { flags: \"--price-per-share-cents <n>\", description: \"Conversion price per share in cents\", required: true, type: \"int\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const safeId = await ctx.resolver.resolveSafeNote(eid, ctx.opts.safeId as string);\n const payload = {\n entity_id: eid,\n safe_note_id: safeId,\n price_per_share_cents: ctx.opts.pricePerShareCents as number,\n };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"equity.conversion.execute\", payload);\n return;\n }\n const result = await ctx.client.executeRoundConversion(\n payload as unknown as Parameters<typeof ctx.client.executeRoundConversion>[0],\n );\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Conversion executed for SAFE ${safeId}`);\n },\n examples: [\"corp cap-table convert --safe-id 'ref' --price-per-share-cents 'n'\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"equity control-links\",\n description: \"Create a control link between legal entities\",\n route: { method: \"POST\", path: \"/v1/equity/control-links\" },\n entity: true,\n options: [\n { flags: \"--child-legal-entity-id <child-legal-entity-id>\", description: \"Child entity in the control relationship\", required: true },\n { flags: \"--control-type <control-type>\", description: \"Type of control relationship.\", required: true, choices: [\"voting\", \"board\", \"economic\", \"contractual\"] },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n { flags: \"--parent-legal-entity-id <parent-legal-entity-id>\", description: \"Parent entity in the control relationship\", required: true },\n { flags: \"--voting-power-bps <voting-power-bps>\", description: \"Voting power in basis points (0-10000)\" },\n ],\n examples: [\"corp equity control-links --child-legal-entity-id voting --control-type voting --parent-legal-entity-id 'parent-legal-entity-id'\", \"corp equity control-links --json\"],\n successTemplate: \"Control Links created\",\n },\n {\n name: \"equity control-map\",\n description: \"View the equity control map\",\n route: { method: \"GET\", path: \"/v1/equity/control-map\" },\n entity: true,\n display: { title: \"Equity Control Map\", cols: [\"edges>Edges\", \"#root_entity_id>ID\", \"traversed_entities>Traversed Entities\"] },\n examples: [\"corp equity control-map\", \"corp equity control-map --json\"],\n },\n {\n name: \"equity conversions-execute\",\n description: \"Execute a SAFE/note conversion into equity\",\n route: { method: \"POST\", path: \"/v1/equity/conversions/execute\" },\n options: [\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n { flags: \"--round-id <round-id>\", description: \"Equity round ID\", required: true },\n { flags: \"--source-reference <source-reference>\", description: \"Source reference for the conversion\" },\n ],\n examples: [\"corp equity conversions-execute --intent-id 'intent-id' --round-id 'round-id'\", \"corp equity conversions-execute --json\"],\n successTemplate: \"Conversions Execute created\",\n },\n {\n name: \"equity conversions-preview\",\n description: \"Preview a SAFE/note conversion without executing\",\n route: { method: \"POST\", path: \"/v1/equity/conversions/preview\" },\n entity: true,\n options: [\n { flags: \"--round-id <round-id>\", description: \"Equity round ID\", required: true },\n { flags: \"--source-reference <source-reference>\", description: \"Source reference for the conversion\" },\n ],\n examples: [\"corp equity conversions-preview --round-id 'round-id'\", \"corp equity conversions-preview --json\"],\n successTemplate: \"Conversions Preview created\",\n },\n {\n name: \"equity dilution-preview\",\n description: \"Preview dilution impact of a potential issuance\",\n route: { method: \"GET\", path: \"/v1/equity/dilution/preview\" },\n entity: true,\n display: { title: \"Equity Dilution Preview\", cols: [\"#issuer_legal_entity_id>ID\", \"pre_round_outstanding_units>Pre Round Outstanding Units\", \"projected_dilution_bps>Projected Dilution Bps\", \"projected_new_units>Projected New Units\", \"projected_post_outstanding_units>Projected Post Outstanding Units\", \"#round_id>ID\"] },\n examples: [\"corp equity dilution-preview\", \"corp equity dilution-preview --json\"],\n },\n {\n name: \"equity entities\",\n description: \"Register a legal entity in the equity system\",\n route: { method: \"POST\", path: \"/v1/equity/entities\" },\n entity: true,\n options: [\n { flags: \"--linked-entity-id <linked-entity-id>\", description: \"ID of the entity to link\" },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--role <role>\", description: \"Role this legal entity plays in the ownership/control graph.\", required: true, choices: [\"operating\", \"control\", \"investment\", \"nonprofit\", \"spv\", \"other\"] },\n ],\n examples: [\"corp equity entities --name 'name' --role operating\", \"corp equity entities --json\"],\n successTemplate: \"Entities created\",\n },\n {\n name: \"equity create-fundraising-workflow\",\n description: \"Start or view a fundraising workflow\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows\" },\n options: [\n { flags: \"--conversion-target-instrument-id <conversion-target-instrument-id>\", description: \"Target instrument for conversion\" },\n { flags: \"--issuer-legal-entity-id <issuer-legal-entity-id>\", description: \"Legal entity issuing the securities\", required: true },\n { flags: \"--metadata <metadata>\", description: \"Additional metadata (JSON)\" },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--pre-money-cents <pre-money-cents>\", description: \"Pre-money valuation in cents\" },\n { flags: \"--prepare-intent-id <prepare-intent-id>\", description: \"Execution intent ID for preparation\", required: true },\n { flags: \"--round-price-cents <round-price-cents>\", description: \"Round share price in cents\" },\n { flags: \"--target-raise-cents <target-raise-cents>\", description: \"Target fundraising amount in cents\" },\n ],\n examples: [\"corp equity fundraising-workflows --issuer-legal-entity-id 'issuer-legal-entity-id' --name 'name' --prepare-intent-id 'prepare-intent-id'\", \"corp equity fundraising-workflows --json\"],\n successTemplate: \"Fundraising Workflows created\",\n },\n {\n name: \"equity fundraising-workflows\",\n description: \"Start or view a fundraising workflow\",\n route: { method: \"GET\", path: \"/v1/equity/fundraising-workflows/{pos}\" },\n entity: true,\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n display: { title: \"Equity Fundraising Workflows\", cols: [\"board_packet_documents>Board Packet Documents\", \"closing_packet_documents>Closing Packet Documents\", \"@created_at>Created At\", \"#accept_intent_id>ID\"] },\n examples: [\"corp equity fundraising-workflows\", \"corp equity fundraising-workflows --json\"],\n },\n {\n name: \"equity fundraising-workflows-apply-terms\",\n description: \"Apply term sheet to a fundraising round\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/apply-terms\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--anti-dilution-method <anti-dilution-method>\", description: \"Anti-dilution protection method\", required: true, choices: [\"none\", \"broad_based_weighted_average\", \"narrow_based_weighted_average\", \"full_ratchet\"] },\n { flags: \"--conversion-precedence <conversion-precedence>\", description: \"Conversion priority ordering\", type: \"array\" },\n { flags: \"--protective-provisions <protective-provisions>\", description: \"Protective provision terms\" },\n ],\n examples: [\"corp equity fundraising-workflows-apply-terms <workflow-id> --anti-dilution-method none\", \"corp equity fundraising-workflows-apply-terms --json\"],\n successTemplate: \"Fundraising Workflows Apply Terms created\",\n },\n {\n name: \"equity fundraising-workflows-compile-packet\",\n description: \"Compile the document packet for a fundraising round\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/compile-packet\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--phase <phase>\", description: \"Workflow phase\" },\n { flags: \"--required-signers <required-signers>\", description: \"List of required signers\", type: \"array\" },\n ],\n examples: [\"corp equity fundraising-workflows-compile-packet <workflow-id>\", \"corp equity fundraising-workflows-compile-packet --json\"],\n successTemplate: \"Fundraising Workflows Compile Packet created\",\n },\n {\n name: \"equity fundraising-workflows-finalize\",\n description: \"Finalize and close a fundraising workflow\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/finalize\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--phase <phase>\", description: \"Workflow phase\" },\n ],\n examples: [\"corp equity fundraising-workflows-finalize <workflow-id>\", \"corp equity fundraising-workflows-finalize --json\"],\n successTemplate: \"Fundraising Workflows Finalize created\",\n },\n {\n name: \"equity fundraising-workflows-generate-board-packet\",\n description: \"Generate board approval packet for fundraising\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/generate-board-packet\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--documents <documents>\", description: \"Document references or content\", type: \"array\" },\n ],\n examples: [\"corp equity fundraising-workflows-generate-board-packet <workflow-id>\", \"corp equity fundraising-workflows-generate-board-packet --json\"],\n successTemplate: \"Fundraising Workflows Generate Board Packet created\",\n },\n {\n name: \"equity fundraising-workflows-generate-closing-packet\",\n description: \"Generate closing documents for fundraising\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/generate-closing-packet\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--documents <documents>\", description: \"Document references or content\", type: \"array\" },\n ],\n examples: [\"corp equity fundraising-workflows-generate-closing-packet <workflow-id>\", \"corp equity fundraising-workflows-generate-closing-packet --json\"],\n successTemplate: \"Fundraising Workflows Generate Closing Packet created\",\n },\n {\n name: \"equity fundraising-workflows-prepare-execution\",\n description: \"Prepare fundraising for execution\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/prepare-execution\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--approval-artifact-id <approval-artifact-id>\", description: \"Approval artifact ID to bind\", required: true },\n { flags: \"--document-request-ids <document-request-ids>\", description: \"Comma-separated document request IDs\", type: \"array\" },\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n { flags: \"--phase <phase>\", description: \"Workflow phase\" },\n ],\n examples: [\"corp equity fundraising-workflows-prepare-execution <workflow-id> --approval-artifact-id 'approval-artifact-id' --intent-id 'intent-id'\", \"corp equity fundraising-workflows-prepare-execution --json\"],\n successTemplate: \"Fundraising Workflows Prepare Execution created\",\n },\n {\n name: \"equity fundraising-workflows-record-board-approval\",\n description: \"Record board approval for fundraising\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/record-board-approval\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\", required: true },\n { flags: \"--resolution-id <resolution-id>\", description: \"Resolution ID\", required: true },\n ],\n examples: [\"corp equity fundraising-workflows-record-board-approval <workflow-id> --meeting-id 'meeting-id' --resolution-id 'resolution-id'\"],\n successTemplate: \"Fundraising Workflows Record Board Approval created\",\n },\n {\n name: \"equity fundraising-workflows-record-close\",\n description: \"Record closing of a fundraising round\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/record-close\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n ],\n examples: [\"corp equity fundraising-workflows-record-close <workflow-id> --intent-id 'intent-id'\"],\n successTemplate: \"Fundraising Workflows Record Close created\",\n },\n {\n name: \"equity fundraising-workflows-record-investor-acceptance\",\n description: \"Record investor acceptance of terms\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/record-investor-acceptance\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--accepted-by-contact-id <accepted-by-contact-id>\", description: \"Contact ID of the accepting party\" },\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n ],\n examples: [\"corp equity fundraising-workflows-record-investor-acceptance <workflow-id> --intent-id 'intent-id'\", \"corp equity fundraising-workflows-record-investor-acceptance --json\"],\n successTemplate: \"Fundraising Workflows Record Investor Acceptance created\",\n },\n {\n name: \"equity fundraising-workflows-record-signature\",\n description: \"Record a signature on fundraising documents\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/record-signature\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--channel <channel>\", description: \"Approval channel (board_vote, written_consent, etc.)\" },\n { flags: \"--signer-identity <signer-identity>\", description: \"Identity of the signer\", required: true },\n ],\n examples: [\"corp equity fundraising-workflows-record-signature <workflow-id> --signer-identity 'signer-identity'\", \"corp equity fundraising-workflows-record-signature --json\"],\n successTemplate: \"Fundraising Workflows Record Signature created\",\n },\n {\n name: \"equity fundraising-workflows-start-signatures\",\n description: \"Start the signature collection process\",\n route: { method: \"POST\", path: \"/v1/equity/fundraising-workflows/{pos}/start-signatures\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n examples: [\"corp equity fundraising-workflows-start-signatures <workflow-id>\"],\n successTemplate: \"Fundraising Workflows Start Signatures created\",\n },\n {\n name: \"equity grants\",\n description: \"Issue an equity grant (options, RSUs, etc.)\",\n route: { method: \"POST\", path: \"/v1/equity/grants\" },\n entity: true,\n options: [\n { flags: \"--grant-type <grant-type>\", description: \"The type of equity grant.\", required: true, choices: [\"common\", \"common_stock\", \"preferred\", \"preferred_stock\", \"membership_unit\", \"stock_option\", \"iso\", \"nso\", \"rsa\", \"svu\"] },\n { flags: \"--recipient-name <recipient-name>\", description: \"Payment recipient name\", required: true },\n { flags: \"--shares <shares>\", description: \"Shares\", required: true, type: \"int\" },\n ],\n examples: [\"corp equity grants --grant-type common_stock --recipient-name 'recipient-name' --shares 'shares'\"],\n successTemplate: \"Grants created\",\n },\n {\n name: \"equity holders\",\n description: \"Register a new equity holder\",\n route: { method: \"POST\", path: \"/v1/equity/holders\" },\n entity: true,\n options: [\n { flags: \"--contact-id <contact-id>\", description: \"Contact ID\", required: true },\n { flags: \"--external-reference <external-reference>\", description: \"External Reference\" },\n { flags: \"--holder-type <holder-type>\", description: \"Type of holder represented in the cap table.\", required: true, choices: [\"individual\", \"organization\", \"fund\", \"nonprofit\", \"trust\", \"other\"] },\n { flags: \"--linked-entity-id <linked-entity-id>\", description: \"ID of the entity to link\" },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n ],\n examples: [\"corp equity holders --contact-id 'contact-id' --holder-type individual --name 'name'\", \"corp equity holders --json\"],\n successTemplate: \"Holders created\",\n },\n {\n name: \"equity instruments\",\n description: \"Create a new equity instrument\",\n route: { method: \"POST\", path: \"/v1/equity/instruments\" },\n entity: true,\n options: [\n { flags: \"--authorized-units <authorized-units>\", description: \"Authorized Units\" },\n { flags: \"--issue-price-cents <issue-price-cents>\", description: \"Issue Price Cents\" },\n { flags: \"--issuer-legal-entity-id <issuer-legal-entity-id>\", description: \"Legal entity issuing the securities\", required: true },\n { flags: \"--kind <kind>\", description: \"Instrument kind in the ownership model.\", required: true, choices: [\"common_equity\", \"preferred_equity\", \"membership_unit\", \"option_grant\", \"safe\", \"convertible_note\", \"warrant\"] },\n { flags: \"--symbol <symbol>\", description: \"Symbol\", required: true },\n { flags: \"--terms <terms>\", description: \"Terms\" },\n ],\n examples: [\"corp equity instruments --issuer-legal-entity-id 'issuer-legal-entity-id' --kind common_equity --symbol 'symbol'\", \"corp equity instruments --json\"],\n successTemplate: \"Instruments created\",\n },\n {\n name: \"equity positions-adjust\",\n description: \"Adjust an equity position (split, correction)\",\n route: { method: \"POST\", path: \"/v1/equity/positions/adjust\" },\n entity: true,\n options: [\n { flags: \"--holder-id <holder-id>\", description: \"Equity holder ID\", required: true },\n { flags: \"--instrument-id <instrument-id>\", description: \"Instrument Id\", required: true },\n { flags: \"--issuer-legal-entity-id <issuer-legal-entity-id>\", description: \"Legal entity issuing the securities\", required: true },\n { flags: \"--principal-delta-cents <principal-delta-cents>\", description: \"Principal Delta Cents\", type: \"int\" },\n { flags: \"--quantity-delta <quantity-delta>\", description: \"Quantity Delta\", required: true, type: \"int\" },\n { flags: \"--source-reference <source-reference>\", description: \"Source reference for the conversion\" },\n ],\n examples: [\"corp equity positions-adjust --holder-id 'holder-id' --instrument-id 'instrument-id' --issuer-legal-entity-id 'issuer-legal-entity-id' --quantity-delta 'quantity-delta'\", \"corp equity positions-adjust --json\"],\n successTemplate: \"Positions Adjust created\",\n },\n {\n name: \"equity rounds\",\n description: \"Create a new equity round (prefer cap-table start-round which auto-resolves issuer)\",\n route: { method: \"POST\", path: \"/v1/equity/rounds\" },\n entity: true,\n options: [\n { flags: \"--conversion-target-instrument-id <conversion-target-instrument-id>\", description: \"Target instrument for conversion\" },\n { flags: \"--issuer-legal-entity-id <issuer-legal-entity-id>\", description: \"Issuer legal entity (run 'corp cap-table --json' to find this)\", required: true },\n { flags: \"--metadata <metadata>\", description: \"Additional metadata (JSON)\" },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--pre-money-cents <pre-money-cents>\", description: \"Pre-money valuation in cents\" },\n { flags: \"--round-price-cents <round-price-cents>\", description: \"Round share price in cents\" },\n { flags: \"--target-raise-cents <target-raise-cents>\", description: \"Target fundraising amount in cents\" },\n ],\n examples: [\"corp equity rounds --issuer-legal-entity-id 'issuer-legal-entity-id' --name 'name'\", \"corp equity rounds --json\"],\n successTemplate: \"Rounds created\",\n },\n {\n name: \"equity rounds-staged\",\n description: \"Create a staged (draft) equity round (prefer cap-table start-round which auto-resolves issuer)\",\n route: { method: \"POST\", path: \"/v1/equity/rounds/staged\" },\n entity: true,\n options: [\n { flags: \"--issuer-legal-entity-id <issuer-legal-entity-id>\", description: \"Issuer legal entity (run 'corp cap-table --json' to find this)\", required: true },\n { flags: \"--metadata <metadata>\", description: \"Additional metadata (JSON)\" },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--pre-money-cents <pre-money-cents>\", description: \"Pre-money valuation in cents\" },\n { flags: \"--round-price-cents <round-price-cents>\", description: \"Round share price in cents\" },\n { flags: \"--target-raise-cents <target-raise-cents>\", description: \"Target fundraising amount in cents\" },\n ],\n examples: [\"corp equity rounds-staged --issuer-legal-entity-id 'issuer-legal-entity-id' --name 'name'\", \"corp equity rounds-staged --json\"],\n successTemplate: \"Rounds Staged created\",\n },\n {\n name: \"equity rounds-accept\",\n description: \"Accept terms for an equity round\",\n route: { method: \"POST\", path: \"/v1/equity/rounds/{pos}/accept\" },\n entity: true,\n args: [{ name: \"round-id\", required: true, description: \"Equity round ID\" }],\n options: [\n { flags: \"--accepted-by-contact-id <accepted-by-contact-id>\", description: \"Contact ID of the accepting party\" },\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n ],\n examples: [\"corp equity rounds-accept <round-id> --intent-id 'intent-id'\", \"corp equity rounds-accept --json\"],\n successTemplate: \"Rounds Accept created\",\n },\n {\n name: \"equity rounds-apply-terms\",\n description: \"Apply term sheet to an equity round\",\n route: { method: \"POST\", path: \"/v1/equity/rounds/{pos}/apply-terms\" },\n entity: true,\n args: [{ name: \"round-id\", required: true, description: \"Equity round ID\" }],\n options: [\n { flags: \"--anti-dilution-method <anti-dilution-method>\", description: \"Anti-dilution protection method\", required: true, choices: [\"none\", \"broad_based_weighted_average\", \"narrow_based_weighted_average\", \"full_ratchet\"] },\n { flags: \"--conversion-precedence <conversion-precedence>\", description: \"Conversion priority ordering\", type: \"array\" },\n { flags: \"--protective-provisions <protective-provisions>\", description: \"Protective provision terms\" },\n ],\n examples: [\"corp equity rounds-apply-terms <round-id> --anti-dilution-method none\", \"corp equity rounds-apply-terms --json\"],\n successTemplate: \"Rounds Apply Terms created\",\n },\n {\n name: \"equity rounds-board-approve\",\n description: \"Record board approval for an equity round\",\n route: { method: \"POST\", path: \"/v1/equity/rounds/{pos}/board-approve\" },\n entity: true,\n args: [{ name: \"round-id\", required: true, description: \"Equity round ID\" }],\n options: [\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\", required: true },\n { flags: \"--resolution-id <resolution-id>\", description: \"Resolution ID\", required: true },\n ],\n examples: [\"corp equity rounds-board-approve <round-id> --meeting-id 'meeting-id' --resolution-id 'resolution-id'\"],\n successTemplate: \"Rounds Board Approve created\",\n },\n {\n name: \"equity rounds-issue\",\n description: \"Issue shares for an equity round\",\n route: { method: \"POST\", path: \"/v1/equity/rounds/{pos}/issue\" },\n entity: true,\n args: [{ name: \"round-id\", required: true, description: \"Equity round ID\" }],\n options: [\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\" },\n { flags: \"--resolution-id <resolution-id>\", description: \"Resolution ID\" },\n ],\n examples: [\"corp equity rounds-issue <round-id>\", \"corp equity rounds-issue --json\"],\n successTemplate: \"Rounds Issue created\",\n },\n {\n name: \"equity rounds-securities\",\n description: \"Add securities to an equity round\",\n route: { method: \"POST\", path: \"/v1/equity/rounds/{pos}/securities\" },\n entity: true,\n args: [{ name: \"round-id\", required: true, description: \"Equity round ID\" }],\n options: [\n { flags: \"--email <email>\", description: \"Email\" },\n { flags: \"--grant-type <grant-type>\", description: \"Grant Type\" },\n { flags: \"--holder-id <holder-id>\", description: \"Equity holder ID\" },\n { flags: \"--instrument-id <instrument-id>\", description: \"Instrument Id\", required: true },\n { flags: \"--principal-cents <principal-cents>\", description: \"Principal Cents\", type: \"int\" },\n { flags: \"--quantity <quantity>\", description: \"Quantity\", required: true, type: \"int\" },\n { flags: \"--recipient-name <recipient-name>\", description: \"Payment recipient name\", required: true },\n ],\n examples: [\"corp equity rounds-securities <round-id> --instrument-id 'instrument-id' --quantity 'quantity' --recipient-name 'recipient-name'\", \"corp equity rounds-securities --json\"],\n successTemplate: \"Rounds Securities created\",\n },\n {\n name: \"equity create-transfer-workflow\",\n description: \"Start or view a share transfer workflow\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows\" },\n options: [\n { flags: \"--from-contact-id <from-contact-id>\", description: \"From Contact Id\", required: true },\n { flags: \"--governing-doc-type <governing-doc-type>\", description: \"The type of governing document for a share transfer.\", required: true, choices: [\"bylaws\", \"operating_agreement\", \"shareholder_agreement\", \"other\"] },\n { flags: \"--prepare-intent-id <prepare-intent-id>\", description: \"Execution intent ID for preparation\", required: true },\n { flags: \"--price-per-share-cents <price-per-share-cents>\", description: \"Price Per Share Cents\" },\n { flags: \"--relationship-to-holder <relationship-to-holder>\", description: \"Relationship To Holder\" },\n { flags: \"--share-class-id <share-class-id>\", description: \"Share class ID\", required: true },\n { flags: \"--share-count <share-count>\", description: \"Number of shares\", required: true, type: \"int\" },\n { flags: \"--to-contact-id <to-contact-id>\", description: \"To Contact Id\", required: true },\n { flags: \"--transfer-type <transfer-type>\", description: \"Type of share transfer.\", required: true, choices: [\"gift\", \"trust_transfer\", \"secondary_sale\", \"estate\", \"other\"] },\n { flags: \"--transferee-rights <transferee-rights>\", description: \"Rights granted to the transferee.\", required: true, choices: [\"full_member\", \"economic_only\", \"limited\"] },\n ],\n examples: [\"corp equity transfer-workflows --from-contact-id 'from-contact-id' --governing-doc-type bylaws --prepare-intent-id 'prepare-intent-id' --share-class-id 'share-class-id' --share-count 'share-count' --to-contact-id gift --transfer-type gift --transferee-rights full_member\", \"corp equity transfer-workflows --json\"],\n successTemplate: \"Transfer Workflows created\",\n },\n {\n name: \"equity transfer-workflows\",\n description: \"Start or view a share transfer workflow\",\n route: { method: \"GET\", path: \"/v1/equity/transfer-workflows/{pos}\" },\n entity: true,\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n display: { title: \"Equity Transfer Workflows\", cols: [\"execution_status>Execution Status\", \"generated_documents>Generated Documents\", \"last_packet_hash>Last Packet Hash\", \"@created_at>Created At\", \"#active_packet_id>ID\"] },\n examples: [\"corp equity transfer-workflows\", \"corp equity transfer-workflows --json\"],\n },\n {\n name: \"equity transfer-workflows-compile-packet\",\n description: \"Compile documents for a share transfer\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/compile-packet\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--phase <phase>\", description: \"Workflow phase\" },\n { flags: \"--required-signers <required-signers>\", description: \"List of required signers\", type: \"array\" },\n ],\n examples: [\"corp equity transfer-workflows-compile-packet <workflow-id>\", \"corp equity transfer-workflows-compile-packet --json\"],\n successTemplate: \"Transfer Workflows Compile Packet created\",\n },\n {\n name: \"equity transfer-workflows-finalize\",\n description: \"Finalize a share transfer workflow\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/finalize\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--phase <phase>\", description: \"Workflow phase\" },\n ],\n examples: [\"corp equity transfer-workflows-finalize <workflow-id>\", \"corp equity transfer-workflows-finalize --json\"],\n successTemplate: \"Transfer Workflows Finalize created\",\n },\n {\n name: \"equity transfer-workflows-generate-docs\",\n description: \"Generate documents for a share transfer\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/generate-docs\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--documents <documents>\", description: \"Document references or content\", type: \"array\" },\n ],\n examples: [\"corp equity transfer-workflows-generate-docs <workflow-id>\", \"corp equity transfer-workflows-generate-docs --json\"],\n successTemplate: \"Transfer Workflows Generate Docs created\",\n },\n {\n name: \"equity transfer-workflows-prepare-execution\",\n description: \"Prepare transfer for execution\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/prepare-execution\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--approval-artifact-id <approval-artifact-id>\", description: \"Approval artifact ID to bind\", required: true },\n { flags: \"--document-request-ids <document-request-ids>\", description: \"Comma-separated document request IDs\", type: \"array\" },\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n { flags: \"--phase <phase>\", description: \"Workflow phase\" },\n ],\n examples: [\"corp equity transfer-workflows-prepare-execution <workflow-id> --approval-artifact-id 'approval-artifact-id' --intent-id 'intent-id'\", \"corp equity transfer-workflows-prepare-execution --json\"],\n successTemplate: \"Transfer Workflows Prepare Execution created\",\n },\n {\n name: \"equity transfer-workflows-record-board-approval\",\n description: \"Record board approval for a transfer\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/record-board-approval\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\", required: true },\n { flags: \"--resolution-id <resolution-id>\", description: \"Resolution ID\", required: true },\n ],\n examples: [\"corp equity transfer-workflows-record-board-approval <workflow-id> --meeting-id 'meeting-id' --resolution-id 'resolution-id'\"],\n successTemplate: \"Transfer Workflows Record Board Approval created\",\n },\n {\n name: \"equity transfer-workflows-record-execution\",\n description: \"Record execution of a share transfer\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/record-execution\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\", required: true },\n ],\n examples: [\"corp equity transfer-workflows-record-execution <workflow-id> --intent-id 'intent-id'\"],\n successTemplate: \"Transfer Workflows Record Execution created\",\n },\n {\n name: \"equity transfer-workflows-record-review\",\n description: \"Record review of a share transfer\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/record-review\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--approved\", description: \"Approved\", required: true },\n { flags: \"--notes <notes>\", description: \"Additional notes\", required: true },\n { flags: \"--reviewer <reviewer>\", description: \"Reviewer\", required: true },\n ],\n examples: [\"corp equity transfer-workflows-record-review <workflow-id> --approved --notes 'notes' --reviewer 'reviewer'\"],\n successTemplate: \"Transfer Workflows Record Review created\",\n },\n {\n name: \"equity transfer-workflows-record-rofr\",\n description: \"Record right of first refusal waiver\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/record-rofr\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--offered\", description: \"Offered\", required: true },\n { flags: \"--waived\", description: \"Waived\", required: true },\n ],\n examples: [\"corp equity transfer-workflows-record-rofr <workflow-id> --offered --waived\"],\n successTemplate: \"Transfer Workflows Record Rofr created\",\n },\n {\n name: \"equity transfer-workflows-record-signature\",\n description: \"Record a signature on transfer documents\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/record-signature\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n options: [\n { flags: \"--channel <channel>\", description: \"Approval channel (board_vote, written_consent, etc.)\" },\n { flags: \"--signer-identity <signer-identity>\", description: \"Identity of the signer\", required: true },\n ],\n examples: [\"corp equity transfer-workflows-record-signature <workflow-id> --signer-identity 'signer-identity'\", \"corp equity transfer-workflows-record-signature --json\"],\n successTemplate: \"Transfer Workflows Record Signature created\",\n },\n {\n name: \"equity transfer-workflows-start-signatures\",\n description: \"Start signature collection for transfer\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/start-signatures\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n examples: [\"corp equity transfer-workflows-start-signatures <workflow-id>\"],\n successTemplate: \"Transfer Workflows Start Signatures created\",\n },\n {\n name: \"equity transfer-workflows-submit-review\",\n description: \"Submit a share transfer for review\",\n route: { method: \"POST\", path: \"/v1/equity/transfer-workflows/{pos}/submit-review\" },\n args: [{ name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n examples: [\"corp equity transfer-workflows-submit-review <workflow-id>\"],\n successTemplate: \"Transfer Workflows Submit Review created\",\n },\n {\n name: \"equity workflows-status\",\n description: \"Check status of an equity workflow\",\n route: { method: \"GET\", path: \"/v1/equity/workflows/{pos}/{pos2}/status\" },\n entity: true,\n args: [{ name: \"workflow-type\", required: true, description: \"Workflow Type\" }, { name: \"workflow-id\", required: true, description: \"Workflow ID\" }],\n display: { title: \"Equity Workflows Status\", cols: [\"execution_status>Execution Status\", \"fundraising_workflow>Fundraising Workflow\", \"packet>Packet\", \"transfer_workflow>Transfer Workflow\", \"#active_packet_id>ID\"] },\n examples: [\"corp equity workflows-status\", \"corp equity workflows-status --json\"],\n },\n {\n name: \"safe-notes\",\n description: \"Issue a new SAFE note\",\n route: { method: \"POST\", path: \"/v1/safe-notes\" },\n options: [\n { flags: \"--conversion-unit-type <conversion-unit-type>\", description: \"Conversion Unit Type\" },\n { flags: \"--discount-rate <discount-rate>\", description: \"SAFE discount rate (0-100)\" },\n { flags: \"--document-id <document-id>\", description: \"Document ID\" },\n { flags: \"--email <email>\", description: \"Email\" },\n { flags: \"--investor-contact-id <investor-contact-id>\", description: \"Investor Contact Id\" },\n { flags: \"--investor-name <investor-name>\", description: \"Investor name\", required: true },\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\" },\n { flags: \"--principal-amount-cents <principal-amount-cents>\", description: \"Principal Amount Cents\", required: true, type: \"int\" },\n { flags: \"--pro-rata-rights\", description: \"Pro Rata Rights\" },\n { flags: \"--resolution-id <resolution-id>\", description: \"Resolution ID\" },\n { flags: \"--safe-type <safe-type>\", description: \"Safe Type\", choices: [\"post_money\", \"pre_money\", \"mfn\"] },\n { flags: \"--valuation-cap-cents <valuation-cap-cents>\", description: \"Valuation Cap Cents\" },\n ],\n examples: [\"corp safe-notes --investor-name 'investor-name' --principal-amount-cents 'principal-amount-cents'\", \"corp safe-notes --json\"],\n successTemplate: \"Safe Notes created\",\n },\n {\n name: \"share-transfers\",\n description: \"Execute a share transfer between parties\",\n route: { method: \"POST\", path: \"/v1/share-transfers\" },\n options: [\n { flags: \"--from-holder <from-holder>\", description: \"From Holder\", required: true },\n { flags: \"--governing-doc-type <governing-doc-type>\", description: \"Governing Doc Type\", choices: [\"bylaws\", \"operating_agreement\", \"shareholder_agreement\", \"other\"] },\n { flags: \"--share-class-id <share-class-id>\", description: \"Share class ID\", required: true },\n { flags: \"--shares <shares>\", description: \"Shares\", required: true, type: \"int\" },\n { flags: \"--to-holder <to-holder>\", description: \"To Holder\", required: true },\n { flags: \"--transfer-type <transfer-type>\", description: \"Type of share transfer.\", required: true, choices: [\"gift\", \"trust_transfer\", \"secondary_sale\", \"estate\", \"other\"] },\n { flags: \"--transferee-rights <transferee-rights>\", description: \"Transferee Rights\", choices: [\"full_member\", \"economic_only\", \"limited\"] },\n ],\n examples: [\"corp share-transfers --from-holder bylaws --share-class-id 'share-class-id' --shares 'shares' --to-holder gift --transfer-type gift\", \"corp share-transfers --json\"],\n successTemplate: \"Share Transfers created\",\n },\n {\n name: \"valuations\",\n description: \"Create a new company valuation\",\n route: { method: \"POST\", path: \"/v1/valuations\" },\n options: [\n { flags: \"--dlom <dlom>\", description: \"Dlom\" },\n { flags: \"--effective-date <effective-date>\", description: \"Effective Date\", required: true },\n { flags: \"--enterprise-value-cents <enterprise-value-cents>\", description: \"Enterprise Value Cents\" },\n { flags: \"--fmv-per-share-cents <fmv-per-share-cents>\", description: \"Fmv Per Share Cents\" },\n { flags: \"--hurdle-amount-cents <hurdle-amount-cents>\", description: \"Hurdle Amount Cents\" },\n { flags: \"--methodology <methodology>\", description: \"Methodology used for a valuation.\", required: true, choices: [\"income\", \"market\", \"asset\", \"backsolve\", \"hybrid\", \"other\"] },\n { flags: \"--provider-contact-id <provider-contact-id>\", description: \"Provider Contact Id\" },\n { flags: \"--report-date <report-date>\", description: \"Report Date\" },\n { flags: \"--report-document-id <report-document-id>\", description: \"Report Document Id\" },\n { flags: \"--valuation-type <valuation-type>\", description: \"Type of 409A or equivalent valuation.\", required: true, choices: [\"four_oh_nine_a\", \"llc_profits_interest\", \"fair_market_value\", \"gift\", \"estate\", \"other\"] },\n ],\n examples: [\"corp valuations --effective-date 'effective-date' --methodology income --valuation-type four_oh_nine_a\", \"corp valuations --json\"],\n successTemplate: \"Valuations created\",\n },\n {\n name: \"valuations submit-for-approval\",\n description: \"Submit a valuation for board approval\",\n route: { method: \"POST\", path: \"/v1/valuations/{pos}/submit-for-approval\" },\n args: [{ name: \"valuation-id\", required: true, description: \"Valuation ID\" }],\n examples: [\"corp valuations submit-for-approval <valuation-id>\"],\n successTemplate: \"Submit For Approval created\",\n },\n\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n printBankAccountsTable,\n printClassificationsTable,\n printDistributionsTable,\n printError,\n printFinanceSummaryPanel,\n printInvoicesTable,\n printJson,\n printPaymentsTable,\n printPayrollRunsTable,\n printReconciliationsTable,\n printWriteResult,\n} from \"../output.js\";\nimport type { ApiRecord } from \"../types.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers (relocated from commands/finance.ts)\n// ---------------------------------------------------------------------------\n\nfunction numeric(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction sumAmounts(records: ApiRecord[], candidates: string[]): number {\n return records.reduce((sum, record) => {\n for (const key of candidates) {\n if (typeof record[key] === \"number\" && Number.isFinite(record[key])) {\n return sum + Number(record[key]);\n }\n }\n return sum;\n }, 0);\n}\n\nfunction latestDate(records: ApiRecord[], candidates: string[]): string | undefined {\n const values = records\n .flatMap((record) => candidates.map((key) => record[key]))\n .filter((value): value is string => typeof value === \"string\" && value.trim().length > 0)\n .map((value) => ({ raw: value, time: new Date(value).getTime() }))\n .filter((value) => Number.isFinite(value.time))\n .sort((a, b) => b.time - a.time);\n return values[0]?.raw;\n}\n\nfunction countByStatus(records: ApiRecord[], statuses: string[]): number {\n const expected = new Set(statuses.map((status) => status.toLowerCase()));\n return records.filter((record) => expected.has(String(record.status ?? \"\").toLowerCase())).length;\n}\n\nfunction countByField(records: ApiRecord[], field: string, values: string[]): number {\n const expected = new Set(values.map((value) => value.toLowerCase()));\n return records.filter((record) => expected.has(String(record[field] ?? \"\").toLowerCase())).length;\n}\n\n// ---------------------------------------------------------------------------\n// Finance registry entries\n// ---------------------------------------------------------------------------\n\nexport const financeCommands: CommandDef[] = [\n // --- finance (summary panel) ---\n {\n name: \"finance\",\n description: \"Invoicing, payroll, payments, banking\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/finance/summary\" },\n entity: true,\n display: { title: \"Finance Summary\" },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const [\n invoices,\n accounts,\n payments,\n payrollRuns,\n distributions,\n reconciliations,\n classifications,\n ] = await Promise.all([\n ctx.client.listInvoices(eid),\n ctx.client.listBankAccounts(eid),\n ctx.client.listPayments(eid),\n ctx.client.listPayrollRuns(eid),\n ctx.client.listDistributions(eid),\n ctx.client.listReconciliations(eid),\n ctx.client.listContractorClassifications(eid),\n ]);\n\n await Promise.all([\n ctx.resolver.stabilizeRecords(\"invoice\", invoices, eid),\n ctx.resolver.stabilizeRecords(\"bank_account\", accounts, eid),\n ctx.resolver.stabilizeRecords(\"payment\", payments, eid),\n ctx.resolver.stabilizeRecords(\"payroll_run\", payrollRuns, eid),\n ctx.resolver.stabilizeRecords(\"distribution\", distributions, eid),\n ctx.resolver.stabilizeRecords(\"reconciliation\", reconciliations, eid),\n ctx.resolver.stabilizeRecords(\"classification\", classifications, eid),\n ]);\n\n const summary: ApiRecord = {\n entity_id: eid,\n invoices: {\n count: invoices.length,\n open_count: invoices.length - countByStatus(invoices, [\"paid\", \"cancelled\", \"void\"]),\n overdue_count: countByStatus(invoices, [\"overdue\"]),\n total_amount_cents: sumAmounts(invoices, [\"amount_cents\", \"total_amount_cents\"]),\n latest_due_date: latestDate(invoices, [\"due_date\", \"created_at\"]),\n },\n bank_accounts: {\n count: accounts.length,\n active_count: countByStatus(accounts, [\"active\", \"approved\", \"open\"]),\n },\n payments: {\n count: payments.length,\n pending_count: countByStatus(payments, [\"pending\", \"submitted\", \"queued\"]),\n total_amount_cents: sumAmounts(payments, [\"amount_cents\"]),\n latest_submitted_at: latestDate(payments, [\"submitted_at\", \"created_at\"]),\n },\n payroll_runs: {\n count: payrollRuns.length,\n latest_period_end: latestDate(payrollRuns, [\"pay_period_end\", \"created_at\"]),\n },\n distributions: {\n count: distributions.length,\n total_amount_cents: sumAmounts(distributions, [\"amount_cents\", \"distribution_amount_cents\"]),\n latest_declared_at: latestDate(distributions, [\"declared_at\", \"created_at\"]),\n },\n reconciliations: {\n count: reconciliations.length,\n balanced_count: reconciliations.filter((record) => record.is_balanced === true).length,\n latest_as_of_date: latestDate(reconciliations, [\"as_of_date\", \"created_at\"]),\n },\n contractor_classifications: {\n count: classifications.length,\n high_risk_count: countByField(classifications, \"risk_level\", [\"high\"]),\n medium_risk_count: countByField(classifications, \"risk_level\", [\"medium\"]),\n },\n };\n\n if (ctx.opts.json) { ctx.writer.json(summary); return; }\n printFinanceSummaryPanel(summary);\n },\n examples: [\n \"corp finance\",\n 'corp finance invoice --customer \"Client Co\" --amount-cents 500000 --due-date 2026-04-01',\n 'corp finance pay --amount-cents 250000 --recipient \"Vendor\" --method ach',\n \"corp finance payroll --period-start 2026-03-01 --period-end 2026-03-15\",\n \"corp finance open-account --institution Mercury\",\n \"corp finance statements --period 2026-Q1\",\n ],\n },\n\n // --- finance invoices ---\n {\n name: \"finance invoices\",\n description: \"List invoices\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/invoices\" },\n entity: true,\n display: {\n title: \"Invoices\",\n cols: [\"customer_name|customer>Customer\", \"$amount_cents>Amount\", \"status>Status\", \"@due_date>Due\", \"#invoice_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const invoices = await ctx.client.listInvoices(eid);\n await ctx.resolver.stabilizeRecords(\"invoice\", invoices, eid);\n if (ctx.opts.json) { ctx.writer.json(invoices); return; }\n if (invoices.length === 0) { ctx.writer.writeln(\"No invoices found.\"); return; }\n printInvoicesTable(invoices);\n },\n examples: [\"corp finance invoices\", \"corp finance invoices --json\"],\n },\n\n // --- finance invoice (create) ---\n {\n name: \"finance invoice\",\n description: \"Create an invoice\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/invoices\" },\n entity: true,\n options: [\n { flags: \"--customer <name>\", description: \"Customer name\", required: true },\n { flags: \"--amount-cents <n>\", description: \"Amount in cents (e.g. 500000 = $5,000.00)\", type: \"int\" },\n { flags: \"--amount-dollars <n>\", description: \"Amount in dollars (e.g. 5000 = $5,000.00)\", type: \"int\" },\n { flags: \"--due-date <date>\", description: \"Due date (ISO 8601)\", required: true },\n { flags: \"--description <desc>\", description: \"Description text\", default: \"Services rendered\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n if (ctx.opts.amountCents != null && ctx.opts.amountDollars != null) {\n printError(\"--amount-cents and --amount-dollars are mutually exclusive. Use one or the other.\");\n process.exit(1);\n }\n const amountCents = (ctx.opts.amountCents as number | undefined) ?? ((ctx.opts.amountDollars as number | undefined) != null ? (ctx.opts.amountDollars as number) * 100 : undefined);\n if (amountCents == null) {\n printError(\"required: --amount-cents <n> or --amount-dollars <n>\");\n process.exit(1);\n }\n const result = await ctx.client.createInvoice({\n entity_id: eid,\n customer_name: ctx.opts.customer as string,\n amount_cents: amountCents,\n due_date: ctx.opts.dueDate as string,\n description: ctx.opts.description as string,\n });\n await ctx.resolver.stabilizeRecord(\"invoice\", result, eid);\n ctx.resolver.rememberFromRecord(\"invoice\", result, eid);\n ctx.writer.writeResult(result, `Invoice created: ${result.invoice_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"invoice\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"invoice\" },\n successTemplate: \"Invoice created: {customer_name}\",\n examples: [\"corp finance invoice --customer 'name' --due-date 'date'\", \"corp finance invoice --json\"],\n },\n\n // --- finance payments ---\n {\n name: \"finance payments\",\n description: \"List payments\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/payments\" },\n entity: true,\n display: {\n title: \"Payments\",\n cols: [\"recipient>Recipient\", \"$amount_cents>Amount\", \"status>Status\", \"@submitted_at>Submitted\", \"#payment_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const payments = await ctx.client.listPayments(eid);\n await ctx.resolver.stabilizeRecords(\"payment\", payments, eid);\n if (ctx.opts.json) { ctx.writer.json(payments); return; }\n if (payments.length === 0) { ctx.writer.writeln(\"No payments found.\"); return; }\n printPaymentsTable(payments);\n },\n examples: [\"corp finance payments\", \"corp finance payments --json\"],\n },\n\n // --- finance pay ---\n {\n name: \"finance pay\",\n description: \"Submit a payment\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/payments\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <n>\", description: \"Amount in cents (e.g. 500000 = $5,000.00)\", type: \"int\" },\n { flags: \"--amount-dollars <n>\", description: \"Amount in dollars (e.g. 5000 = $5,000.00)\", type: \"int\" },\n { flags: \"--recipient <name>\", description: \"Recipient name\", required: true },\n { flags: \"--method <method>\", description: \"Payment method\", default: \"ach\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n if (ctx.opts.amountCents != null && ctx.opts.amountDollars != null) {\n printError(\"--amount-cents and --amount-dollars are mutually exclusive. Use one or the other.\");\n process.exit(1);\n }\n const amountCents = (ctx.opts.amountCents as number | undefined) ?? ((ctx.opts.amountDollars as number | undefined) != null ? (ctx.opts.amountDollars as number) * 100 : undefined);\n if (amountCents == null) {\n printError(\"required: --amount-cents <n> or --amount-dollars <n>\");\n process.exit(1);\n }\n const method = ctx.opts.method as string;\n const result = await ctx.client.submitPayment({\n entity_id: eid,\n amount_cents: amountCents,\n recipient: ctx.opts.recipient as string,\n payment_method: method,\n description: `Payment via ${method}`,\n });\n await ctx.resolver.stabilizeRecord(\"payment\", result, eid);\n ctx.resolver.rememberFromRecord(\"payment\", result, eid);\n ctx.writer.writeResult(result, `Payment submitted: ${result.payment_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"payment\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"payment\" },\n successTemplate: \"Payment submitted: {recipient_name}\",\n examples: [\"corp finance pay --recipient 'name'\", \"corp finance pay --json\"],\n },\n\n // --- finance bank-accounts ---\n {\n name: \"finance bank-accounts\",\n description: \"List bank accounts\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/bank-accounts\" },\n entity: true,\n display: {\n title: \"Bank Accounts\",\n cols: [\"bank_name|institution>Bank\", \"status>Status\", \"#bank_account_id|account_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const accounts = await ctx.client.listBankAccounts(eid);\n await ctx.resolver.stabilizeRecords(\"bank_account\", accounts, eid);\n if (ctx.opts.json) { ctx.writer.json(accounts); return; }\n if (accounts.length === 0) { ctx.writer.writeln(\"No bank accounts found.\"); return; }\n printBankAccountsTable(accounts);\n },\n examples: [\"corp finance bank-accounts\", \"corp finance bank-accounts --json\"],\n },\n\n // --- finance open-account ---\n {\n name: \"finance open-account\",\n description: \"Open a business bank account\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/bank-accounts\" },\n entity: true,\n options: [\n { flags: \"--institution <name>\", description: \"Banking institution\", default: \"Mercury\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const result = await ctx.client.openBankAccount({ entity_id: eid, bank_name: ctx.opts.institution as string });\n await ctx.resolver.stabilizeRecord(\"bank_account\", result, eid);\n ctx.resolver.rememberFromRecord(\"bank_account\", result, eid);\n ctx.writer.writeResult(result, `Bank account opened: ${result.bank_account_id ?? result.account_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"bank_account\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"bank_account\" },\n successTemplate: \"Bank account opened: {bank_name}\",\n examples: [\"corp finance open-account\", \"corp finance open-account --json\"],\n },\n\n // --- finance activate-account <account-ref> ---\n {\n name: \"finance activate-account\",\n description: \"Activate a bank account (transitions from pending_review to active)\",\n route: { method: \"POST\", path: \"/v1/bank-accounts/{pos}/activate\" },\n entity: true,\n args: [{ name: \"account-ref\", required: true, description: \"Bank account reference\" }],\n handler: async (ctx) => {\n const accountRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedId = await ctx.resolver.resolveBankAccount(eid, accountRef);\n const result = await ctx.client.activateBankAccount(resolvedId, eid);\n await ctx.resolver.stabilizeRecord(\"bank_account\", result, eid);\n ctx.resolver.rememberFromRecord(\"bank_account\", result, eid);\n ctx.writer.writeResult(result, `Bank account activated: ${resolvedId}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"bank_account\",\n showReuseHint: true,\n });\n },\n examples: [\"corp finance activate-account <account-ref>\"],\n },\n\n // --- finance payroll-runs ---\n {\n name: \"finance payroll-runs\",\n description: \"List payroll runs\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/payroll-runs\" },\n entity: true,\n display: {\n title: \"Payroll Runs\",\n cols: [\"@pay_period_start>Period Start\", \"@pay_period_end>Period End\", \"status>Status\", \"#payroll_run_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const runs = await ctx.client.listPayrollRuns(eid);\n await ctx.resolver.stabilizeRecords(\"payroll_run\", runs, eid);\n if (ctx.opts.json) { ctx.writer.json(runs); return; }\n if (runs.length === 0) { ctx.writer.writeln(\"No payroll runs found.\"); return; }\n printPayrollRunsTable(runs);\n },\n examples: [\"corp finance payroll-runs\", \"corp finance payroll-runs --json\"],\n },\n\n // --- finance payroll ---\n {\n name: \"finance payroll\",\n description: \"Run payroll\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/payroll-runs\" },\n entity: true,\n options: [\n { flags: \"--period-start <date>\", description: \"Pay period start\", required: true },\n { flags: \"--period-end <date>\", description: \"Pay period end\", required: true },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const result = await ctx.client.runPayroll({\n entity_id: eid,\n pay_period_start: ctx.opts.periodStart as string,\n pay_period_end: ctx.opts.periodEnd as string,\n });\n await ctx.resolver.stabilizeRecord(\"payroll_run\", result, eid);\n ctx.resolver.rememberFromRecord(\"payroll_run\", result, eid);\n ctx.writer.writeResult(result, `Payroll run created: ${result.payroll_run_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"payroll_run\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"payroll_run\" },\n successTemplate: \"Payroll run created\",\n examples: [\"corp finance payroll --period-start 'date' --period-end 'date'\"],\n },\n\n // --- finance distributions ---\n {\n name: \"finance distributions\",\n description: \"List distributions\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/distributions\" },\n entity: true,\n display: {\n title: \"Distributions\",\n cols: [\"$amount_cents|distribution_amount_cents>Amount\", \"status>Status\", \"@declared_at>Declared\", \"#distribution_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const distributions = await ctx.client.listDistributions(eid);\n await ctx.resolver.stabilizeRecords(\"distribution\", distributions, eid);\n if (ctx.opts.json) { ctx.writer.json(distributions); return; }\n if (distributions.length === 0) { ctx.writer.writeln(\"No distributions found.\"); return; }\n printDistributionsTable(distributions);\n },\n examples: [\"corp finance distributions\", \"corp finance distributions --json\"],\n },\n\n // --- finance reconciliations ---\n {\n name: \"finance reconciliations\",\n description: \"List reconciliations\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/reconciliations\" },\n entity: true,\n display: {\n title: \"Reconciliations\",\n cols: [\"@as_of_date>As Of\", \"is_balanced>Balanced\", \"#reconciliation_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const reconciliations = await ctx.client.listReconciliations(eid);\n await ctx.resolver.stabilizeRecords(\"reconciliation\", reconciliations, eid);\n if (ctx.opts.json) { ctx.writer.json(reconciliations); return; }\n if (reconciliations.length === 0) { ctx.writer.writeln(\"No reconciliations found.\"); return; }\n printReconciliationsTable(reconciliations);\n },\n examples: [\"corp finance reconciliations\", \"corp finance reconciliations --json\"],\n },\n\n // --- finance reconcile ---\n {\n name: \"finance reconcile\",\n description: \"Reconcile ledger (requires --start-date and --end-date)\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/reconciliations\" },\n entity: true,\n options: [\n { flags: \"--start-date <date>\", description: \"Period start (required, ISO 8601)\", required: true },\n { flags: \"--end-date <date>\", description: \"Period end (required, ISO 8601)\", required: true },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const result = await ctx.client.reconcileLedger({\n entity_id: eid,\n start_date: ctx.opts.startDate as string,\n end_date: ctx.opts.endDate as string,\n });\n await ctx.resolver.stabilizeRecord(\"reconciliation\", result, eid);\n ctx.resolver.rememberFromRecord(\"reconciliation\", result, eid);\n ctx.writer.writeResult(result, `Ledger reconciled: ${result.reconciliation_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"reconciliation\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"reconciliation\" },\n successTemplate: \"Reconciliation created\",\n examples: [\"corp finance reconcile --start-date 'date' --end-date 'date'\"],\n },\n\n // --- finance classifications ---\n {\n name: \"finance classifications\",\n description: \"List contractor classifications\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/contractor-classifications\" },\n entity: true,\n display: {\n title: \"Contractor Classifications\",\n cols: [\"contractor_name>Contractor\", \"risk_level>Risk\", \"state>State\", \"#classification_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const classifications = await ctx.client.listContractorClassifications(eid);\n await ctx.resolver.stabilizeRecords(\"classification\", classifications, eid);\n if (ctx.opts.json) { ctx.writer.json(classifications); return; }\n if (classifications.length === 0) { ctx.writer.writeln(\"No contractor classifications found.\"); return; }\n printClassificationsTable(classifications);\n },\n examples: [\"corp finance classifications\", \"corp finance classifications --json\"],\n },\n\n // --- finance classify-contractor ---\n {\n name: \"finance classify-contractor\",\n description: \"Analyze contractor classification risk\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/contractor-classifications\" },\n entity: true,\n options: [\n { flags: \"--name <name>\", description: \"Contractor name\", required: true },\n { flags: \"--state <code>\", description: \"US state code\", required: true },\n { flags: \"--hours <n>\", description: \"Hours per week\", required: true, type: \"int\" },\n { flags: \"--exclusive\", description: \"Exclusive client\", default: false },\n { flags: \"--duration <n>\", description: \"Duration in months\", required: true, type: \"int\" },\n { flags: \"--provides-tools\", description: \"Company provides tools\", default: false },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const result = await ctx.client.classifyContractor({\n entity_id: eid,\n contractor_name: ctx.opts.name as string,\n state: ctx.opts.state as string,\n hours_per_week: ctx.opts.hours as number,\n exclusive_client: !!ctx.opts.exclusive,\n duration_months: ctx.opts.duration as number,\n provides_tools: !!ctx.opts.providesTools,\n });\n await ctx.resolver.stabilizeRecord(\"classification\", result, eid);\n ctx.resolver.rememberFromRecord(\"classification\", result, eid);\n ctx.writer.writeResult(result, `Classification: ${result.risk_level ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"classification\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"classification\" },\n successTemplate: \"Classification created: {contractor_name}\",\n examples: [\"corp finance classify-contractor --name 'name' --state 'code' --hours 'n' --duration 'n'\", \"corp finance classify-contractor --json\"],\n },\n\n // --- finance statements ---\n {\n name: \"finance statements\",\n description: \"View financial statements (P&L, balance sheet)\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/financial-statements\" },\n entity: \"query\",\n display: { title: \"Financial Statements\" },\n options: [\n { flags: \"--period <period>\", description: \"Period (e.g. 2026-Q1, 2025)\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const params: Record<string, string> = {};\n if (ctx.opts.period) params.period = ctx.opts.period as string;\n const result = await ctx.client.getFinancialStatements(eid, params);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n printJson(result);\n },\n examples: [\"corp finance statements\", \"corp finance statements --json\"],\n },\n];","import chalk from \"chalk\";\nimport type { CommandDef, CommandContext } from \"./types.js\";\nimport type { ApiRecord } from \"../types.js\";\nimport {\n printGovernanceTable,\n printSeatsTable,\n printMeetingsTable,\n printResolutionsTable,\n printAgendaItemsTable,\n printReferenceSummary,\n} from \"../output.js\";\nimport { confirm } from \"@inquirer/prompts\";\nimport { writtenConsent as writtenConsentWorkflow } from \"@thecorporation/corp-tools\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst FINALIZE_ITEM_STATUS_CHOICES = [\n \"discussed\",\n \"voted\",\n \"tabled\",\n \"withdrawn\",\n] as const;\n\n// ---------------------------------------------------------------------------\n// Governance registry entries\n// ---------------------------------------------------------------------------\n\nexport const governanceCommands: CommandDef[] = [\n // --- governance (list bodies) ---\n {\n name: \"governance\",\n description: \"Governance bodies, seats, meetings, resolutions\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance-bodies\" },\n entity: true,\n display: {\n title: \"Governance Bodies\",\n cols: [\"name>Body\", \"body_type>Type\", \"seat_count|seats>Seats\", \"meeting_count|meetings>Meetings\", \"#body_id>ID\"],\n },\n options: [\n { flags: \"--body-id <ref>\", description: \"Governance body reference\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const bodies = await ctx.client.listGovernanceBodies(eid);\n await ctx.resolver.stabilizeRecords(\"body\", bodies, eid);\n if (ctx.opts.json) { ctx.writer.json(bodies); return; }\n if (bodies.length === 0) { ctx.writer.writeln(\"No governance bodies found.\"); return; }\n printGovernanceTable(bodies);\n },\n examples: [\n \"corp governance\",\n 'corp governance create-body --name \"Board of Directors\" --body-type board_of_directors',\n 'corp governance add-seat @last:body --holder \"alice\"',\n 'corp governance convene --body board --type board_meeting --title \"Q1 Review\" --agenda \"Approve budget\"',\n \"corp governance open @last:meeting --present-seat alice-seat\",\n \"corp governance vote @last:meeting <item-ref> --voter alice --vote for\",\n 'corp governance written-consent --body board --title \"Approve Option Plan\" --description \"Board approves 2026 option plan\"',\n \"corp governance mode\",\n \"corp governance mode --set board\",\n \"corp governance resign <seat-ref>\",\n \"corp governance incidents\",\n \"corp governance profile\",\n ],\n },\n\n // --- governance seats <body-ref> ---\n {\n name: \"governance seats\",\n description: \"Seats for a governance body\",\n route: { method: \"GET\", path: \"/v1/governance-bodies/{pos}/seats\" },\n entity: \"query\",\n args: [{ name: \"body-ref\", required: true, description: \"Governance body reference\" }],\n display: {\n title: \"Seats\",\n cols: [\"holder_name|holder>Holder\", \"role>Role\", \"status>Status\", \"#seat_id>ID\"],\n },\n handler: async (ctx) => {\n const bodyRef = ctx.positional[0];\n if (!bodyRef) {\n throw new Error(\"Missing required argument <body-ref>.\\n List bodies first: corp governance\\n Then: corp governance seats <body-id>\");\n }\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedBodyId = await ctx.resolver.resolveBody(eid, bodyRef);\n const seats = await ctx.client.getGovernanceSeats(resolvedBodyId, eid);\n await ctx.resolver.stabilizeRecords(\"seat\", seats, eid);\n if (ctx.opts.json) { ctx.writer.json(seats); return; }\n if (seats.length === 0) { ctx.writer.writeln(\"No seats found.\"); return; }\n printSeatsTable(seats);\n },\n examples: [\"corp governance seats <body-ref>\", \"corp governance seats <body-ref> --json\"],\n },\n\n // --- governance meetings <body-ref> ---\n {\n name: \"governance meetings\",\n description: \"Meetings for a governance body\",\n route: { method: \"GET\", path: \"/v1/governance-bodies/{pos}/meetings\" },\n entity: \"query\",\n args: [{ name: \"body-ref\", required: true, description: \"Governance body reference\" }],\n display: {\n title: \"Meetings\",\n cols: [\"title>Title\", \"@scheduled_date>Date\", \"status>Status\", \"resolution_count|resolutions>Resolutions\", \"#meeting_id>ID\"],\n },\n handler: async (ctx) => {\n const bodyRef = ctx.positional[0];\n if (!bodyRef) {\n throw new Error(\"Missing required argument <body-ref>.\\n List bodies first: corp governance\\n Then: corp governance meetings <body-id>\");\n }\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedBodyId = await ctx.resolver.resolveBody(eid, bodyRef);\n const meetings = await ctx.client.listMeetings(resolvedBodyId, eid);\n await ctx.resolver.stabilizeRecords(\"meeting\", meetings, eid);\n if (ctx.opts.json) { ctx.writer.json(meetings); return; }\n if (meetings.length === 0) { ctx.writer.writeln(\"No meetings found.\"); return; }\n printMeetingsTable(meetings);\n },\n examples: [\"corp governance meetings <body-ref>\", \"corp governance meetings <body-ref> --json\"],\n },\n\n // --- governance resolutions <meeting-ref> ---\n {\n name: \"governance resolutions\",\n description: \"Resolutions for a meeting\",\n route: { method: \"GET\", path: \"/v1/meetings/{pos}/resolutions\" },\n entity: \"query\",\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n display: {\n title: \"Resolutions\",\n cols: [\"title>Title\", \"resolution_type>Type\", \"status>Status\", \"votes_for>For\", \"votes_against>Against\", \"#resolution_id>ID\"],\n },\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n if (!meetingRef) {\n throw new Error(\"Missing required argument <meeting-ref>.\\n List meetings first: corp governance meetings <body-ref>\\n Then: corp governance resolutions <meeting-id>\");\n }\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n const resolutions = await ctx.client.getMeetingResolutions(resolvedMeetingId, eid);\n await ctx.resolver.stabilizeRecords(\"resolution\", resolutions, eid);\n if (ctx.opts.json) { ctx.writer.json(resolutions); return; }\n if (resolutions.length === 0) { ctx.writer.writeln(\"No resolutions found.\"); return; }\n printResolutionsTable(resolutions);\n },\n examples: [\"corp governance resolutions <meeting-ref>\", \"corp governance resolutions <meeting-ref> --json\"],\n },\n\n // --- governance agenda-items <meeting-ref> ---\n {\n name: \"governance agenda-items\",\n description: \"List agenda items for a meeting\",\n route: { method: \"GET\", path: \"/v1/meetings/{pos}/agenda-items\" },\n entity: \"query\",\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n display: {\n title: \"Agenda Items\",\n cols: [\"title>Title\", \"status>Status\", \"item_type>Type\", \"#agenda_item_id>ID\"],\n },\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n if (!meetingRef) {\n throw new Error(\"Missing required argument <meeting-ref>.\\n List meetings first: corp governance meetings <body-ref>\\n Then: corp governance agenda-items <meeting-id>\");\n }\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n const items = await ctx.client.listAgendaItems(resolvedMeetingId, eid);\n await ctx.resolver.stabilizeRecords(\"agenda_item\", items, eid);\n if (ctx.opts.json) { ctx.writer.json(items); return; }\n if (items.length === 0) { ctx.writer.writeln(\"No agenda items found.\"); return; }\n printAgendaItemsTable(items);\n },\n examples: [\"corp governance agenda-items <meeting-ref>\", \"corp governance agenda-items <meeting-ref> --json\"],\n },\n\n // --- governance incidents ---\n {\n name: \"governance incidents\",\n description: \"Report a governance incident\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/incidents\" },\n entity: true,\n display: { title: \"Governance Incidents\" },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const incidents = await ctx.client.listGovernanceIncidents(eid);\n if (ctx.opts.json) { ctx.writer.json(incidents); return; }\n if (incidents.length === 0) { ctx.writer.writeln(\"No governance incidents found.\"); return; }\n for (const inc of incidents) {\n const status = String(inc.status ?? \"open\");\n const colored = status === \"resolved\" ? chalk.green(status) : chalk.red(status);\n console.log(` [${colored}] ${inc.incident_type ?? \"unknown\"}: ${inc.description ?? inc.id}`);\n }\n },\n examples: [\"corp governance incidents\", \"corp governance incidents --json\"],\n },\n\n // --- governance profile ---\n {\n name: \"governance profile\",\n description: \"View governance profile and configuration\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/profile\" },\n entity: true,\n display: { title: \"Governance Profile\" },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const profile = await ctx.client.getGovernanceProfile(eid);\n if (ctx.opts.json) { ctx.writer.json(profile); return; }\n console.log(chalk.blue(\"\\u2500\".repeat(40)));\n console.log(chalk.blue.bold(\" Governance Profile\"));\n console.log(chalk.blue(\"\\u2500\".repeat(40)));\n for (const [key, value] of Object.entries(profile)) {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n console.log(` ${chalk.bold(key.replaceAll(\"_\", \" \") + \":\")} ${value}`);\n }\n }\n console.log(chalk.blue(\"\\u2500\".repeat(40)));\n },\n examples: [\"corp governance profile\", \"corp governance profile --json\"],\n },\n\n // --- governance mode ---\n {\n name: \"governance mode\",\n description: \"View or set governance mode\",\n route: { method: \"GET\", path: \"/v1/governance/mode\" },\n entity: true,\n display: { title: \"Governance Mode\" },\n options: [\n {\n flags: \"--set <mode>\",\n description: \"Set governance mode\",\n choices: [\"founder\", \"board\", \"executive\", \"normal\", \"incident_lockdown\"],\n },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const setMode = ctx.opts.set as string | undefined;\n if (setMode) {\n const result = await ctx.client.setGovernanceMode({ entity_id: eid, mode: setMode });\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Governance mode set to: ${setMode}`);\n } else {\n const result = await ctx.client.getGovernanceMode(eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n console.log(` ${chalk.bold(\"Governance Mode:\")} ${result.mode ?? \"N/A\"}`);\n if (result.reason) console.log(` ${chalk.bold(\"Reason:\")} ${result.reason}`);\n }\n },\n examples: [\"corp governance mode\", \"corp governance mode --json\"],\n },\n\n // --- governance create-body ---\n {\n name: \"governance create-body\",\n description: \"Create a governance body\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/governance-bodies\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--name <name>\", description: \"Body name (e.g. 'Board of Directors')\", required: true },\n { flags: \"--body-type <type>\", description: \"Body type\", required: true, choices: [\"board_of_directors\", \"llc_member_vote\"] },\n { flags: \"--quorum <rule>\", description: \"Quorum rule\", default: \"majority\", choices: [\"majority\", \"supermajority\", \"unanimous\"] },\n { flags: \"--voting <method>\", description: \"Voting method\", default: \"per_capita\", choices: [\"per_capita\", \"per_unit\"] },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const payload = {\n entity_id: eid,\n body_type: ctx.opts.bodyType as string,\n name: ctx.opts.name as string,\n quorum_rule: ctx.opts.quorum as string,\n voting_method: ctx.opts.voting as string,\n };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.create_body\", payload);\n return;\n }\n const result = await ctx.client.createGovernanceBody(payload);\n await ctx.resolver.stabilizeRecord(\"body\", result, eid);\n ctx.resolver.rememberFromRecord(\"body\", result, eid);\n const bodyId = result.body_id ?? \"OK\";\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Governance body created: ${bodyId}`);\n printReferenceSummary(\"body\", result, { showReuseHint: true });\n console.log(chalk.dim(\"\\n Next steps:\"));\n console.log(chalk.dim(` corp governance add-seat @last:body --holder <contact-ref>`));\n console.log(chalk.dim(` corp governance seats @last:body`));\n },\n produces: { kind: \"body\" },\n successTemplate: \"Governance body created: {name}\",\n examples: [\"corp governance create-body --name 'name' --body-type 'type'\", \"corp governance create-body --json\"],\n },\n\n // --- governance add-seat <body-ref> ---\n {\n name: \"governance add-seat\",\n description: \"Add a seat to a governance body\",\n route: { method: \"POST\", path: \"/v1/governance-bodies/{pos}/seats\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"body-ref\", required: true, description: \"Governance body reference\" }],\n options: [\n { flags: \"--holder <contact-ref>\", description: \"Contact reference for the seat holder\", required: true },\n { flags: \"--role <role>\", description: \"Seat role (chair, member, officer, observer)\", default: \"member\" },\n ],\n handler: async (ctx) => {\n const bodyRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedBodyId = await ctx.resolver.resolveBody(eid, bodyRef);\n const resolvedHolderId = await ctx.resolver.resolveContact(eid, ctx.opts.holder as string);\n const data: Record<string, unknown> = { holder_id: resolvedHolderId, role: ctx.opts.role ?? \"member\" };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.add_seat\", { entity_id: eid, body_id: resolvedBodyId, ...data });\n return;\n }\n const result = await ctx.client.createGovernanceSeat(resolvedBodyId, eid, data);\n await ctx.resolver.stabilizeRecord(\"seat\", result, eid);\n ctx.resolver.rememberFromRecord(\"seat\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Seat added: ${result.seat_id ?? \"OK\"}`);\n printReferenceSummary(\"seat\", result, { showReuseHint: true });\n },\n produces: { kind: \"seat\" },\n successTemplate: \"Seat added to {body_id}\",\n examples: [\"corp governance add-seat <body-ref> --holder 'contact-ref'\", \"corp governance add-seat --json\"],\n },\n\n // --- governance convene ---\n {\n name: \"governance convene\",\n description: \"Convene a governance meeting\",\n route: { method: \"POST\", path: \"/v1/meetings\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--body <ref>\", description: \"Governance body reference\", required: true },\n { flags: \"--type <type>\", description: \"Meeting type (board_meeting, shareholder_meeting, member_meeting, written_consent)\", required: true },\n { flags: \"--title <title>\", description: \"Meeting title\", required: true },\n { flags: \"--date <date>\", description: \"Meeting date (ISO 8601)\" },\n { flags: \"--agenda <item>\", description: \"Agenda item (repeatable)\", type: \"array\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedBodyId = await ctx.resolver.resolveBody(eid, ctx.opts.body as string);\n const payload: Record<string, unknown> = {\n entity_id: eid,\n body_id: resolvedBodyId,\n meeting_type: ctx.opts.type as string,\n title: ctx.opts.title as string,\n agenda_item_titles: (ctx.opts.agenda as string[]) ?? [],\n };\n if (ctx.opts.date) payload.scheduled_date = ctx.opts.date as string;\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.schedule_meeting\", payload);\n return;\n }\n const result = await ctx.client.scheduleMeeting(payload);\n await ctx.resolver.stabilizeRecord(\"meeting\", result, eid);\n ctx.resolver.rememberFromRecord(\"meeting\", result, eid);\n const meetingId = result.meeting_id ?? \"OK\";\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Meeting scheduled: ${meetingId}`);\n printReferenceSummary(\"meeting\", result, { showReuseHint: true });\n console.log(chalk.dim(\"\\n Next steps:\"));\n console.log(chalk.dim(` corp governance notice @last:meeting`));\n console.log(chalk.dim(` corp governance open @last:meeting --present-seat <seat-ref>`));\n console.log(chalk.dim(` corp governance agenda-items @last:meeting`));\n },\n produces: { kind: \"meeting\" },\n successTemplate: \"Meeting scheduled: {title}\",\n examples: [\"corp governance convene --body 'ref' --type 'type' --title 'title'\", \"corp governance convene --json\"],\n },\n\n // --- governance open <meeting-ref> ---\n {\n name: \"governance open\",\n description: \"Open a scheduled meeting for voting\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/open\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n options: [\n { flags: \"--present-seat <ref>\", description: \"Seat reference present at the meeting (repeatable)\", required: true, type: \"array\" },\n ],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n const presentSeats = ctx.opts.presentSeat as string[];\n let resolvedSeats: string[];\n try {\n resolvedSeats = await Promise.all(\n presentSeats.map((seatRef) => ctx.resolver.resolveSeat(eid, seatRef)),\n );\n } catch (err) {\n throw new Error(\n `Failed to resolve seat reference: ${err}\\n` +\n \" --present-seat expects seat IDs, not contact IDs.\\n\" +\n \" Find seat IDs with: corp governance seats <body-ref>\",\n );\n }\n const payload = { present_seat_ids: resolvedSeats };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.open_meeting\", { entity_id: eid, meeting_id: resolvedMeetingId, ...payload });\n return;\n }\n const result = await ctx.client.conveneMeeting(resolvedMeetingId, eid, payload);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Meeting opened: ${resolvedMeetingId}`);\n },\n examples: [\"corp governance open <meeting-ref> --present-seat 'ref'\"],\n },\n\n // --- governance vote <meeting-ref> <item-ref> ---\n {\n name: \"governance vote\",\n description: \"Cast a vote on an agenda item\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/agenda-items/{pos}/votes\" },\n entity: true,\n dryRun: true,\n args: [\n { name: \"meeting-ref\", required: true, description: \"Meeting reference\" },\n { name: \"item-ref\", required: true, description: \"Agenda item reference\" },\n ],\n options: [\n { flags: \"--voter <ref>\", description: \"Voter contact reference\", required: true },\n { flags: \"--vote <value>\", description: \"Vote (for, against, abstain, recusal)\", required: true, choices: [\"for\", \"against\", \"abstain\", \"recusal\"] },\n ],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const itemRef = ctx.positional[1];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n const resolvedItemId = await ctx.resolver.resolveAgendaItem(eid, resolvedMeetingId, itemRef);\n const resolvedVoterId = await ctx.resolver.resolveContact(eid, ctx.opts.voter as string);\n const payload = { voter_id: resolvedVoterId, vote_value: ctx.opts.vote as string };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.cast_vote\", {\n entity_id: eid, meeting_id: resolvedMeetingId, agenda_item_id: resolvedItemId, ...payload,\n });\n return;\n }\n try {\n const result = await ctx.client.castVote(eid, resolvedMeetingId, resolvedItemId, payload);\n ctx.resolver.rememberFromRecord(\"agenda_item\", { agenda_item_id: resolvedItemId, title: itemRef }, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Vote cast: ${result.vote_id ?? \"OK\"}`);\n } catch (err) {\n const message = String(err);\n if (message.includes(\"voting session is not open\")) {\n ctx.writer.error(\n `Failed to cast vote: ${err}\\n` +\n ` Open the meeting first: corp governance open ${meetingRef} --present-seat <seat-ref>`,\n );\n } else {\n throw err;\n }\n }\n },\n examples: [\"corp governance vote <meeting-ref> <item-ref> --voter for --vote for\"],\n },\n\n // --- governance notice <meeting-ref> ---\n {\n name: \"governance notice\",\n description: \"Send meeting notice\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/notice\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.send_notice\", { entity_id: eid, meeting_id: resolvedMeetingId });\n return;\n }\n const result = await ctx.client.sendNotice(resolvedMeetingId, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Notice sent for meeting ${resolvedMeetingId}`);\n },\n examples: [\"corp governance notice <meeting-ref>\"],\n },\n\n // --- governance adjourn <meeting-ref> ---\n {\n name: \"governance adjourn\",\n description: \"Adjourn a meeting\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/adjourn\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.adjourn_meeting\", { entity_id: eid, meeting_id: resolvedMeetingId });\n return;\n }\n const result = await ctx.client.adjournMeeting(resolvedMeetingId, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Meeting ${resolvedMeetingId} adjourned`);\n },\n examples: [\"corp governance adjourn <meeting-ref>\"],\n },\n\n // --- governance reopen <meeting-ref> ---\n {\n name: \"governance reopen\",\n description: \"Re-open an adjourned meeting\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/reopen\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.reopen_meeting\", { entity_id: eid, meeting_id: resolvedMeetingId });\n return;\n }\n const result = await ctx.client.reopenMeeting(resolvedMeetingId, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Meeting ${resolvedMeetingId} re-opened`);\n },\n examples: [\"corp governance reopen <meeting-ref>\"],\n },\n\n // --- governance cancel <meeting-ref> ---\n {\n name: \"governance cancel\",\n description: \"Cancel a meeting\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/cancel\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"meeting-ref\", required: true, description: \"Meeting reference\" }],\n options: [\n { flags: \"--yes, -y\", description: \"Skip confirmation prompt\" },\n ],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.cancel_meeting\", { entity_id: eid, meeting_id: resolvedMeetingId });\n return;\n }\n if (!ctx.opts.yes) {\n const ok = await confirm({\n message: `Cancel meeting ${resolvedMeetingId}?`,\n default: false,\n });\n if (!ok) {\n ctx.writer.writeln(\"Cancelled.\");\n return;\n }\n }\n const result = await ctx.client.cancelMeeting(resolvedMeetingId, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Meeting ${resolvedMeetingId} cancelled`);\n },\n examples: [\"corp governance cancel <meeting-ref>\", \"corp governance cancel --json\"],\n },\n\n // --- governance finalize-item <meeting-ref> <item-ref> ---\n {\n name: \"governance finalize-item\",\n description: \"Finalize an agenda item\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/agenda-items/{pos}/finalize\" },\n entity: true,\n dryRun: true,\n args: [\n { name: \"meeting-ref\", required: true, description: \"Meeting reference\" },\n { name: \"item-ref\", required: true, description: \"Agenda item reference\" },\n ],\n options: [\n {\n flags: \"--status <status>\",\n description: `Status (${[...FINALIZE_ITEM_STATUS_CHOICES].join(\", \")})`,\n required: true,\n choices: [...FINALIZE_ITEM_STATUS_CHOICES],\n },\n ],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const itemRef = ctx.positional[1];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n const resolvedItemId = await ctx.resolver.resolveAgendaItem(eid, resolvedMeetingId, itemRef);\n const payload = { entity_id: eid, status: ctx.opts.status as string };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.finalize_agenda_item\", { meeting_id: resolvedMeetingId, agenda_item_id: resolvedItemId, ...payload });\n return;\n }\n const result = await ctx.client.finalizeAgendaItem(resolvedMeetingId, resolvedItemId, payload);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Agenda item ${resolvedItemId} finalized as ${ctx.opts.status}`);\n },\n examples: [\"corp governance finalize-item <meeting-ref> <item-ref>\"],\n },\n\n // --- governance resolve <meeting-ref> <item-ref> ---\n {\n name: \"governance resolve\",\n description: \"Compute a resolution for an agenda item\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/agenda-items/{pos}/resolution\" },\n entity: true,\n dryRun: true,\n args: [\n { name: \"meeting-ref\", required: true, description: \"Meeting reference\" },\n { name: \"item-ref\", required: true, description: \"Agenda item reference\" },\n ],\n options: [\n { flags: \"--text <resolution_text>\", description: \"Resolution text\", required: true },\n ],\n handler: async (ctx) => {\n const meetingRef = ctx.positional[0];\n const itemRef = ctx.positional[1];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedMeetingId = await ctx.resolver.resolveMeeting(eid, meetingRef);\n const resolvedItemId = await ctx.resolver.resolveAgendaItem(eid, resolvedMeetingId, itemRef);\n const payload = { resolution_text: ctx.opts.text as string };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.compute_resolution\", {\n entity_id: eid, meeting_id: resolvedMeetingId, agenda_item_id: resolvedItemId, ...payload,\n });\n return;\n }\n const result = await ctx.client.computeResolution(resolvedMeetingId, resolvedItemId, eid, payload);\n await ctx.resolver.stabilizeRecord(\"resolution\", result, eid);\n ctx.resolver.rememberFromRecord(\"resolution\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Resolution computed for agenda item ${itemRef}`);\n printReferenceSummary(\"resolution\", result, { showReuseHint: true });\n },\n produces: { kind: \"resolution\" },\n successTemplate: \"Resolution computed\",\n examples: [\"corp governance resolve <meeting-ref> <item-ref> --text 'resolution_text'\"],\n },\n\n // --- governance written-consent ---\n {\n name: \"governance written-consent\",\n description: \"Create a written consent action\",\n route: { method: \"POST\", path: \"/v1/governance/written-consent\" },\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--body <ref>\", description: \"Governance body reference\", required: true },\n { flags: \"--title <title>\", description: \"Title\", required: true },\n { flags: \"--description <desc>\", description: \"Description text\", required: true },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedBodyId = await ctx.resolver.resolveBody(eid, ctx.opts.body as string);\n const payload = {\n entity_id: eid, body_id: resolvedBodyId, title: ctx.opts.title as string, description: ctx.opts.description as string,\n };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.written_consent\", payload);\n return;\n }\n\n const result = await writtenConsentWorkflow(ctx.client, {\n entityId: eid,\n bodyId: resolvedBodyId,\n title: ctx.opts.title as string,\n description: ctx.opts.description as string,\n });\n\n if (!result.success) {\n ctx.writer.error(result.error!);\n return;\n }\n\n await ctx.resolver.stabilizeRecord(\"meeting\", result.data!, eid);\n ctx.resolver.rememberFromRecord(\"meeting\", result.data!, eid);\n const meetingId = String(result.data?.meeting_id ?? \"\");\n\n if (ctx.opts.json) { ctx.writer.json(result.data); return; }\n ctx.writer.success(`Written consent created: ${meetingId || \"OK\"}`);\n printReferenceSummary(\"meeting\", result.data!, { showReuseHint: true });\n console.log(chalk.dim(\"\\n Next steps:\"));\n console.log(chalk.dim(` corp governance agenda-items @last:meeting`));\n console.log(chalk.dim(` corp governance vote @last:meeting <item-ref> --voter <contact-ref> --vote for`));\n },\n produces: { kind: \"meeting\" },\n successTemplate: \"Written consent created: {title}\",\n examples: [\"corp governance written-consent --body 'ref' --title 'title' --description 'desc'\"],\n },\n\n // --- governance quick-approve ---\n {\n name: \"governance quick-approve\",\n description: \"One-step board approval: create written consent, auto-vote, return meeting + resolution IDs\",\n entity: true,\n dryRun: true,\n options: [\n { flags: \"--body <ref>\", description: \"Governance body reference (auto-detected if only one exists)\" },\n { flags: \"--text <resolution_text>\", description: \"Resolution text (e.g. 'RESOLVED: authorize SAFE issuance')\", required: true },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n\n // Auto-detect body if not specified\n let resolvedBodyId: string;\n if (ctx.opts.body) {\n resolvedBodyId = await ctx.resolver.resolveBody(eid, ctx.opts.body as string);\n } else {\n const bodies = await ctx.client.listGovernanceBodies(eid);\n const active = bodies.filter((b: ApiRecord) => b.status === \"active\");\n if (active.length === 1) {\n resolvedBodyId = String(active[0].body_id);\n } else if (active.length === 0) {\n throw new Error(\"No active governance bodies found. Create one first: corp governance create-body\");\n } else {\n throw new Error(`Multiple governance bodies found (${active.length}). Specify --body <ref>.`);\n }\n }\n\n const resolutionText = ctx.opts.text as string;\n const title = `Board Approval: ${resolutionText.slice(0, 60)}`;\n\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"governance.quick_approve\", {\n entity_id: eid, body_id: resolvedBodyId, title, resolution_text: resolutionText,\n });\n return;\n }\n\n // Step 1: Create written consent\n const consentResult = await writtenConsentWorkflow(ctx.client, {\n entityId: eid,\n bodyId: resolvedBodyId,\n title,\n description: resolutionText,\n });\n if (!consentResult.success) {\n throw new Error(`Written consent failed: ${consentResult.error}`);\n }\n const meetingId = String(consentResult.data?.meeting_id);\n ctx.resolver.remember(\"meeting\", meetingId, eid);\n\n // Step 2: Get agenda items\n const agendaItems = await ctx.client.listAgendaItems(meetingId, eid);\n if (agendaItems.length === 0) {\n throw new Error(\"Written consent created but no agenda items found.\");\n }\n const itemId = String((agendaItems[0] as ApiRecord).agenda_item_id);\n\n // Step 3: Convene (open) the meeting if not already convened\n const seats = await ctx.client.getGovernanceSeats(resolvedBodyId, eid);\n const filledSeats = seats.filter((s: ApiRecord) => s.status === \"filled\" || s.status === \"active\");\n const seatIds = filledSeats.map((s: ApiRecord) => String(s.seat_id));\n if (seatIds.length === 0) {\n throw new Error(\"No filled seats found on this governance body. Add seats first: corp governance add-seat <body-ref>\");\n }\n // Written consent creates meetings already in \"convened\" state — skip if so\n const meetingStatus = consentResult.data?.status ?? consentResult.data?.meeting_status;\n if (meetingStatus !== \"convened\") {\n await ctx.client.conveneMeeting(meetingId, eid, { present_seat_ids: seatIds });\n }\n\n // Step 4: Cast votes — each seat's holder votes \"for\"\n for (const seat of filledSeats) {\n const voterId = String(seat.holder_id);\n if (!voterId) continue;\n try {\n await ctx.client.castVote(eid, meetingId, itemId, {\n voter_id: voterId,\n vote_value: \"for\",\n });\n } catch {\n // Seat may have already voted or be ineligible — continue\n }\n }\n\n // Step 5: Compute resolution (tallies votes and determines outcome)\n const resolution = await ctx.client.computeResolution(meetingId, itemId, eid, {\n resolution_text: resolutionText,\n });\n const resolutionId = String(resolution.resolution_id);\n ctx.resolver.remember(\"resolution\", resolutionId, eid);\n\n const passed = resolution.passed === true;\n\n if (ctx.opts.json) {\n ctx.writer.json({ meeting_id: meetingId, resolution_id: resolutionId, passed, votes: filledSeats.length });\n return;\n }\n ctx.writer.success(passed ? \"Board approval completed\" : \"Board vote completed (resolution did not pass)\");\n console.log(` Meeting: ${meetingId}`);\n console.log(` Resolution: ${resolutionId}`);\n console.log(chalk.dim(\"\\n Use with:\"));\n console.log(chalk.dim(` --meeting-id ${meetingId} --resolution-id ${resolutionId}`));\n console.log(chalk.dim(` or: --meeting-id @last:meeting --resolution-id @last:resolution`));\n },\n produces: { kind: \"resolution\" },\n successTemplate: \"Board approval completed\",\n examples: [\n 'corp governance quick-approve --text \"RESOLVED: authorize SAFE issuance to Seed Fund\"',\n 'corp governance quick-approve --body @last:body --text \"RESOLVED: issue Series A equity round\"',\n ],\n },\n\n // --- governance resign <seat-ref> ---\n {\n name: \"governance resign\",\n description: \"Resign from a governance seat\",\n route: { method: \"POST\", path: \"/v1/seats/{pos}/resign\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"seat-ref\", required: true, description: \"Seat reference\" }],\n options: [\n { flags: \"--body-id <ref>\", description: \"Governance body reference\" },\n ],\n handler: async (ctx) => {\n const seatRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const seatId = await ctx.resolver.resolveSeat(eid, seatRef, ctx.opts.bodyId as string | undefined);\n const result = await ctx.client.resignSeat(seatId, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Seat ${seatId} resigned.`);\n },\n examples: [\"corp governance resign <seat-ref>\", \"corp governance resign --json\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"entities governance-audit-checkpoints\",\n description: \"List governance audit checkpoints\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/audit/checkpoints\" },\n entity: true,\n display: { title: \"Entities Governance Audit Checkpoints\", cols: [\"#checkpoint_id>ID\", \"@created_at>Created At\", \"#entity_id>ID\", \"latest_entry_hash>Latest Entry Hash\", \"#latest_entry_id>ID\", \"total_entries>Total Entries\"] },\n examples: [\"corp entities governance-audit-checkpoints\", \"corp entities governance-audit-checkpoints --json\"],\n },\n {\n name: \"entities governance-audit-entries\",\n description: \"List governance audit log entries\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/audit/entries\" },\n entity: true,\n display: { title: \"Entities Governance Audit Entries\", cols: [\"action>Action\", \"details>Details\", \"entry_hash>Entry Hash\", \"event_type>Event Type\", \"@created_at>Created At\", \"#audit_entry_id>ID\"] },\n examples: [\"corp entities governance-audit-entries\", \"corp entities governance-audit-entries --json\"],\n },\n {\n name: \"entities governance-audit-verifications\",\n description: \"List governance audit verifications\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/audit/verifications\" },\n entity: true,\n display: { title: \"Entities Governance Audit Verifications\", cols: [\"anomalies>Anomalies\", \"latest_entry_hash>Latest Entry Hash\", \"ok>Ok\", \"total_entries>Total Entries\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp entities governance-audit-verifications\", \"corp entities governance-audit-verifications --json\"],\n },\n {\n name: \"entities governance-doc-bundles\",\n description: \"List governance document bundles\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/doc-bundles\" },\n entity: true,\n display: { title: \"Entities Governance Doc Bundles\", cols: [\"document_count>Document Count\", \"entity_type>Entity Type\", \"generated_at>Generated At\", \"profile_version>Profile Version\", \"#bundle_id>ID\"] },\n examples: [\"corp entities governance-doc-bundles\", \"corp entities governance-doc-bundles --json\"],\n },\n {\n name: \"entities governance-doc-bundles-current\",\n description: \"View the current governance document bundle\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/doc-bundles/current\" },\n entity: true,\n display: { title: \"Entities Governance Doc Bundles Current\", cols: [\"#bundle_id>ID\", \"#entity_id>ID\", \"generated_at>Generated At\", \"manifest_path>Manifest Path\", \"template_version>Template Version\"] },\n examples: [\"corp entities governance-doc-bundles-current\", \"corp entities governance-doc-bundles-current --json\"],\n },\n {\n name: \"entities governance-doc-bundles-generate\",\n description: \"Generate a new governance document bundle\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/governance/doc-bundles/generate\" },\n entity: true,\n options: [\n { flags: \"--template-version <template-version>\", description: \"Template Version\" },\n ],\n examples: [\"corp entities governance-doc-bundles-generate\", \"corp entities governance-doc-bundles-generate --json\"],\n successTemplate: \"Governance Doc Bundles Generate created\",\n },\n {\n name: \"entities governance-doc-bundle\",\n description: \"List governance document bundles\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/doc-bundles/{pos}\" },\n entity: true,\n args: [{ name: \"bundle-id\", required: true, description: \"Document bundle ID\" }],\n display: { title: \"Entities Governance Doc Bundles\", cols: [\"documents>Documents\", \"entity_type>Entity Type\", \"generated_at>Generated At\", \"profile_version>Profile Version\", \"#bundle_id>ID\"] },\n examples: [\"corp entities governance-doc-bundles\", \"corp entities governance-doc-bundles --json\"],\n },\n {\n name: \"entities governance-mode-history\",\n description: \"View governance mode change history\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/mode-history\" },\n entity: true,\n display: { title: \"Entities Governance Mode History\", cols: [\"evidence_refs>Evidence Refs\", \"from_mode>From Mode\", \"incident_ids>Incident Ids\", \"reason>Reason\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp entities governance-mode-history\", \"corp entities governance-mode-history --json\"],\n },\n {\n name: \"entities governance-triggers\",\n description: \"List governance triggers for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/governance/triggers\" },\n entity: true,\n display: { title: \"Entities Governance Triggers\", cols: [\"description>Description\", \"evidence_refs>Evidence Refs\", \"idempotency_key_hash>Idempotency Key Hash\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp entities governance-triggers\", \"corp entities governance-triggers --json\"],\n },\n {\n name: \"governance-bodies\",\n description: \"List all governance bodies\",\n route: { method: \"GET\", path: \"/v1/governance-bodies\" },\n entity: true,\n display: { title: \"Governance Bodies\", cols: [\"body_type>Body Type\", \"name>Name\", \"quorum_rule>Quorum Rule\", \"status>Status\", \"@created_at>Created At\", \"#body_id>ID\"] },\n examples: [\"corp governance-bodies\", \"corp governance-bodies --json\"],\n },\n {\n name: \"governance-bodies create\",\n description: \"List all governance bodies\",\n route: { method: \"POST\", path: \"/v1/governance-bodies\" },\n options: [\n { flags: \"--body-type <body-type>\", description: \"The type of governance body.\", required: true, choices: [\"board_of_directors\", \"llc_member_vote\"] },\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--quorum-rule <quorum-rule>\", description: \"The threshold required for a vote to pass.\", required: true, choices: [\"majority\", \"supermajority\", \"unanimous\"] },\n { flags: \"--voting-method <voting-method>\", description: \"How votes are counted.\", required: true, choices: [\"per_capita\", \"per_unit\"] },\n ],\n examples: [\"corp governance-bodies --body-type board_of_directors --name majority --quorum-rule majority --voting-method per_capita\"],\n successTemplate: \"Governance Bodies created\",\n },\n {\n name: \"governance-seats scan-expired\",\n description: \"Scan for and flag expired governance seats\",\n route: { method: \"POST\", path: \"/v1/governance-seats/scan-expired\" },\n entity: true,\n examples: [\"corp governance-seats scan-expired\"],\n successTemplate: \"Scan Expired created\",\n },\n {\n name: \"governance-seats resign\",\n description: \"Resign from a governance seat\",\n route: { method: \"POST\", path: \"/v1/governance-seats/{pos}/resign\" },\n entity: true,\n args: [{ name: \"seat-id\", required: true, description: \"Governance seat ID\" }],\n examples: [\"corp governance-seats resign <seat-id>\"],\n successTemplate: \"Resign created\",\n },\n {\n name: \"governance audit-checkpoints\",\n description: \"Create a governance audit checkpoint\",\n route: { method: \"POST\", path: \"/v1/governance/audit/checkpoints\" },\n entity: true,\n examples: [\"corp governance audit-checkpoints\"],\n successTemplate: \"Audit Checkpoints created\",\n },\n {\n name: \"governance audit-events\",\n description: \"Record a governance audit event\",\n route: { method: \"POST\", path: \"/v1/governance/audit/events\" },\n entity: true,\n options: [\n { flags: \"--action <action>\", description: \"Action\", required: true },\n { flags: \"--details <details>\", description: \"Details\" },\n { flags: \"--event-type <event-type>\", description: \"Event Type\", required: true, choices: [\"mode_changed\", \"lockdown_trigger_applied\", \"manual_event\", \"checkpoint_written\", \"chain_verified\", \"chain_verification_failed\"] },\n { flags: \"--evidence-refs <evidence-refs>\", description: \"Evidence Refs\", type: \"array\" },\n { flags: \"--linked-incident-id <linked-incident-id>\", description: \"Linked Incident Id\" },\n { flags: \"--linked-intent-id <linked-intent-id>\", description: \"Linked Intent Id\" },\n { flags: \"--linked-mode-event-id <linked-mode-event-id>\", description: \"Linked Mode Event Id\" },\n { flags: \"--linked-trigger-id <linked-trigger-id>\", description: \"Linked Trigger Id\" },\n ],\n examples: [\"corp governance audit-events --action 'action' --event-type mode_changed\", \"corp governance audit-events --json\"],\n successTemplate: \"Audit Events created\",\n },\n {\n name: \"governance audit-verify\",\n description: \"Verify governance state integrity\",\n route: { method: \"POST\", path: \"/v1/governance/audit/verify\" },\n entity: true,\n examples: [\"corp governance audit-verify\"],\n successTemplate: \"Audit Verify created\",\n },\n {\n name: \"governance delegation-schedule\",\n description: \"View the current delegation schedule\",\n route: { method: \"GET\", path: \"/v1/governance/delegation-schedule\" },\n entity: true,\n display: { title: \"Governance Delegation Schedule\", cols: [\"allowed_tier1_intent_types>Allowed Tier1 Intent Types\", \"last_reauthorized_at>Last Reauthorized At\", \"next_mandatory_review_at>Next Mandatory Review At\", \"reauth_full_suspension_at_days>Reauth Full Suspension At Days\", \"@created_at>Created At\", \"#adopted_resolution_id>ID\"] },\n examples: [\"corp governance delegation-schedule\", \"corp governance delegation-schedule --json\"],\n },\n {\n name: \"governance delegation-schedule-amend\",\n description: \"Amend the delegation schedule\",\n route: { method: \"POST\", path: \"/v1/governance/delegation-schedule/amend\" },\n entity: true,\n options: [\n { flags: \"--adopted-resolution-id <adopted-resolution-id>\", description: \"Adopted Resolution Id\" },\n { flags: \"--allowed-tier1-intent-types <allowed-tier1-intent-types>\", description: \"Allowed Tier1 Intent Types\" },\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\" },\n { flags: \"--next-mandatory-review-at <next-mandatory-review-at>\", description: \"Next Mandatory Review At\" },\n { flags: \"--rationale <rationale>\", description: \"Rationale\" },\n { flags: \"--tier1-max-amount-cents <tier1-max-amount-cents>\", description: \"Tier1 Max Amount Cents\" },\n ],\n examples: [\"corp governance delegation-schedule-amend\", \"corp governance delegation-schedule-amend --json\"],\n successTemplate: \"Delegation Schedule Amend created\",\n },\n {\n name: \"governance delegation-schedule-history\",\n description: \"View delegation schedule change history\",\n route: { method: \"GET\", path: \"/v1/governance/delegation-schedule/history\" },\n entity: true,\n display: { title: \"Governance Delegation Schedule History\", cols: [\"added_tier1_intent_types>Added Tier1 Intent Types\", \"authority_expansion>Authority Expansion\", \"from_version>From Version\", \"new_tier1_max_amount_cents>New Tier1 Max Amount Cents\", \"@created_at>Created At\", \"#adopted_resolution_id>ID\"] },\n examples: [\"corp governance delegation-schedule-history\", \"corp governance delegation-schedule-history --json\"],\n },\n {\n name: \"governance delegation-schedule-reauthorize\",\n description: \"Reauthorize the delegation schedule\",\n route: { method: \"POST\", path: \"/v1/governance/delegation-schedule/reauthorize\" },\n entity: true,\n options: [\n { flags: \"--adopted-resolution-id <adopted-resolution-id>\", description: \"Adopted Resolution Id\", required: true },\n { flags: \"--meeting-id <meeting-id>\", description: \"Meeting ID\", required: true },\n { flags: \"--rationale <rationale>\", description: \"Rationale\" },\n ],\n examples: [\"corp governance delegation-schedule-reauthorize --adopted-resolution-id 'adopted-resolution-id' --meeting-id 'meeting-id'\", \"corp governance delegation-schedule-reauthorize --json\"],\n successTemplate: \"Delegation Schedule Reauthorize created\",\n },\n {\n name: \"governance evaluate\",\n description: \"Evaluate governance compliance for an action\",\n route: { method: \"POST\", path: \"/v1/governance/evaluate\" },\n entity: true,\n options: [\n { flags: \"--intent-type <intent-type>\", description: \"Type of intent\", required: true },\n { flags: \"--metadata <metadata>\", description: \"Additional metadata (JSON)\" },\n ],\n examples: [\"corp governance evaluate --intent-type 'intent-type'\", \"corp governance evaluate --json\"],\n successTemplate: \"Evaluate created\",\n },\n {\n name: \"governance report-incident\",\n description: \"Report a governance incident\",\n route: { method: \"POST\", path: \"/v1/governance/incidents\" },\n entity: true,\n options: [\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--severity <severity>\", description: \"Severity level\", required: true, choices: [\"low\", \"medium\", \"high\", \"critical\"] },\n { flags: \"--title <title>\", description: \"Title\", required: true },\n ],\n examples: [\"corp governance incidents --description low --severity low --title 'title'\"],\n successTemplate: \"Incidents created\",\n },\n {\n name: \"governance incidents-resolve\",\n description: \"Resolve a governance incident\",\n route: { method: \"POST\", path: \"/v1/governance/incidents/{pos}/resolve\" },\n entity: true,\n args: [{ name: \"incident-id\", required: true, description: \"Incident ID\" }],\n examples: [\"corp governance incidents-resolve <incident-id>\"],\n successTemplate: \"Incidents Resolve created\",\n },\n {\n name: \"meetings written-consent\",\n description: \"Create a written consent resolution (no meeting)\",\n route: { method: \"POST\", path: \"/v1/meetings/written-consent\" },\n options: [\n { flags: \"--body-id <body-id>\", description: \"Governance body ID\", required: true },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--title <title>\", description: \"Title\", required: true },\n ],\n examples: [\"corp meetings written-consent --body-id 'body-id' --description 'description' --title 'title'\"],\n successTemplate: \"Written Consent created\",\n },\n {\n name: \"meetings agenda-items-vote\",\n description: \"Cast a vote on a meeting agenda item\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/agenda-items/{pos2}/vote\" },\n entity: true,\n args: [{ name: \"meeting-id\", required: true, description: \"Meeting ID\" }, { name: \"item-id\", required: true, description: \"Agenda item ID\" }],\n options: [\n { flags: \"--vote-value <vote-value>\", description: \"How a participant voted.\", required: true, choices: [\"for\", \"against\", \"abstain\", \"recusal\"] },\n { flags: \"--voter-id <voter-id>\", description: \"Voter Id\", required: true },\n ],\n examples: [\"corp meetings agenda-items-vote <meeting-id> <item-id> --vote-value for --voter-id 'voter-id'\"],\n successTemplate: \"Agenda Items Vote created\",\n },\n {\n name: \"meetings convene\",\n description: \"Convene a scheduled meeting (start it)\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/convene\" },\n entity: true,\n args: [{ name: \"meeting-id\", required: true, description: \"Meeting ID\" }],\n options: [\n { flags: \"--present-seat-ids <present-seat-ids>\", description: \"Present Seat Ids\", required: true, type: \"array\" },\n ],\n examples: [\"corp meetings convene <meeting-id> --present-seat-ids 'present-seat-ids'\"],\n successTemplate: \"Convene created\",\n },\n {\n name: \"meetings resolutions-attach-document\",\n description: \"Attach a document to a meeting resolution\",\n route: { method: \"POST\", path: \"/v1/meetings/{pos}/resolutions/{pos2}/attach-document\" },\n args: [{ name: \"meeting-id\", required: true, description: \"Meeting ID\" }, { name: \"resolution-id\", required: true, description: \"Resolution ID\" }],\n options: [\n { flags: \"--document-id <document-id>\", description: \"Document ID\", required: true },\n ],\n examples: [\"corp meetings resolutions-attach-document <meeting-id> <resolution-id> --document-id 'document-id'\"],\n successTemplate: \"Resolutions Attach Document created\",\n },\n\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n printDocumentsTable,\n printError,\n printReferenceSummary,\n printSuccess,\n printJson,\n printWriteResult,\n} from \"../output.js\";\nimport { autoSignFormationDocument, autoSignFormationDocuments } from \"../formation-automation.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst HUMANS_APP_ORIGIN = \"https://humans.thecorporation.ai\";\n\nfunction formatSigningLink(docId: string, result: { token?: unknown; signing_url?: unknown }): string {\n if (typeof result.token === \"string\" && result.token.length > 0) {\n return `${HUMANS_APP_ORIGIN}/sign/${docId}?token=${encodeURIComponent(result.token)}`;\n }\n if (typeof result.signing_url === \"string\" && result.signing_url.length > 0) {\n if (/^https?:\\/\\//.test(result.signing_url)) {\n return result.signing_url;\n }\n const normalizedPath = result.signing_url.startsWith(\"/human/sign/\")\n ? result.signing_url.replace(\"/human/sign/\", \"/sign/\")\n : result.signing_url;\n return `${HUMANS_APP_ORIGIN}${normalizedPath.startsWith(\"/\") ? normalizedPath : `/${normalizedPath}`}`;\n }\n return `${HUMANS_APP_ORIGIN}/sign/${docId}`;\n}\n\nfunction coerceParamValue(raw: string): unknown {\n if (raw === \"true\") return true;\n if (raw === \"false\") return false;\n if (/^-?\\d+(\\.\\d+)?$/.test(raw)) return Number(raw);\n if ((raw.startsWith(\"{\") && raw.endsWith(\"}\")) || (raw.startsWith(\"[\") && raw.endsWith(\"]\"))) {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n }\n return raw;\n}\n\n// ---------------------------------------------------------------------------\n// Document registry entries\n// ---------------------------------------------------------------------------\n\nexport const documentCommands: CommandDef[] = [\n // --- documents (list) ---\n {\n name: \"documents\",\n description: \"List formation and governance documents\",\n route: { method: \"GET\", path: \"/v1/formations/{eid}/documents\" },\n entity: true,\n display: {\n title: \"Documents\",\n cols: [\"title>Title\", \"document_type>Type\", \"status>Status\", \"@created_at>Date\", \"#document_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const docs = await ctx.client.getEntityDocuments(eid);\n await ctx.resolver.stabilizeRecords(\"document\", docs, eid);\n if (ctx.opts.json) { ctx.writer.json(docs); return; }\n if (docs.length === 0) { ctx.writer.writeln(\"No documents found.\"); return; }\n printDocumentsTable(docs);\n },\n examples: [\"corp documents\", \"corp documents --json\"],\n },\n\n // --- documents signing-link <doc-ref> ---\n {\n name: \"documents signing-link\",\n description: \"Get a signing link for a document\",\n route: { method: \"GET\", path: \"/v1/sign/{pos}\" },\n entity: \"query\",\n args: [{ name: \"doc-ref\", required: true, description: \"Document reference\" }],\n display: { title: \"Signing Link\" },\n handler: async (ctx) => {\n const docRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n let resolvedDocumentId: string;\n try {\n resolvedDocumentId = await ctx.resolver.resolveDocument(eid, docRef);\n } catch {\n printError(\n `Could not resolve '${docRef}' as a document. If you just generated a contract, ` +\n \"use the document_id from the generate output, not @last (which may reference the contract_id).\\n\" +\n \" List documents with: corp documents\",\n );\n process.exit(1);\n return;\n }\n const result = await ctx.client.getSigningLink(resolvedDocumentId, eid);\n const shareUrl = formatSigningLink(resolvedDocumentId, result);\n if (process.stdout.isTTY) {\n ctx.writer.success(\"Signing link generated.\");\n const summaryRecord = await ctx.resolver.stabilizeRecord(\"document\", { document_id: resolvedDocumentId, title: docRef }, eid);\n printReferenceSummary(\"document\", summaryRecord, { label: \"Document Ref:\" });\n }\n console.log(shareUrl);\n },\n examples: [\"corp documents signing-link\", \"corp documents signing-link --json\"],\n },\n\n // --- documents sign <doc-ref> ---\n {\n name: \"documents sign\",\n description: \"Sign a formation document, or auto-sign all missing required signatures\",\n route: { method: \"POST\", path: \"/v1/documents/{pos}/sign\" },\n entity: true,\n args: [{ name: \"doc-ref\", required: true, description: \"Document reference\" }],\n options: [\n { flags: \"--signer-name <name>\", description: \"Manual signer name\" },\n { flags: \"--signer-role <role>\", description: \"Manual signer role\" },\n { flags: \"--signer-email <email>\", description: \"Manual signer email\" },\n { flags: \"--signature-text <text>\", description: \"Manual signature text (defaults to signer name)\" },\n ],\n handler: async (ctx) => {\n const docRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedDocumentId = await ctx.resolver.resolveDocument(eid, docRef);\n const signerName = ctx.opts.signerName as string | undefined;\n const signerRole = ctx.opts.signerRole as string | undefined;\n const signerEmail = ctx.opts.signerEmail as string | undefined;\n const signatureText = ctx.opts.signatureText as string | undefined;\n\n if (signerName || signerRole || signerEmail || signatureText) {\n if (!signerName || !signerRole || !signerEmail) {\n throw new Error(\"Manual signing requires --signer-name, --signer-role, and --signer-email.\");\n }\n const result = await ctx.client.signDocument(resolvedDocumentId, eid, {\n signer_name: signerName,\n signer_role: signerRole,\n signer_email: signerEmail,\n signature_text: signatureText ?? signerName,\n });\n await ctx.resolver.stabilizeRecord(\"document\", { document_id: resolvedDocumentId, title: docRef }, eid);\n ctx.writer.writeResult(result, `Document ${resolvedDocumentId} signed.`, { jsonOnly: ctx.opts.json });\n return;\n }\n\n const result = await autoSignFormationDocument(ctx.client, eid, resolvedDocumentId);\n await ctx.resolver.stabilizeRecord(\"document\", result.document, eid);\n ctx.resolver.rememberFromRecord(\"document\", result.document, eid);\n if (ctx.opts.json) {\n ctx.writer.json({\n document_id: resolvedDocumentId,\n signatures_added: result.signatures_added,\n document: result.document,\n });\n return;\n }\n ctx.writer.success(\n result.signatures_added > 0\n ? `Applied ${result.signatures_added} signature(s) to ${resolvedDocumentId}.`\n : `No signatures were needed for ${resolvedDocumentId}.`,\n );\n printReferenceSummary(\"document\", result.document, { showReuseHint: true });\n printJson(result.document);\n },\n examples: [\"corp documents sign <doc-ref>\", \"corp documents sign --json\"],\n },\n\n // --- documents sign-all ---\n {\n name: \"documents sign-all\",\n description: \"Auto-sign all outstanding formation documents for an entity\",\n route: { method: \"POST\", path: \"/v1/formations/{eid}/sign-all\" },\n entity: true,\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const result = await autoSignFormationDocuments(ctx.client, ctx.resolver, eid);\n if (ctx.opts.json) {\n ctx.writer.json(result);\n return;\n }\n ctx.writer.success(\n `Processed ${result.documents_seen} formation document(s); added ${result.signatures_added} signature(s) across ${result.documents_signed} document(s).`,\n );\n printJson(result.documents.map((document: Record<string, unknown>) => ({\n document_id: document.document_id,\n title: document.title,\n status: document.status,\n signatures: Array.isArray(document.signatures) ? document.signatures.length : document.signatures,\n })));\n },\n examples: [\"corp documents sign-all\"],\n },\n\n // --- documents generate ---\n {\n name: \"documents generate\",\n description: \"Generate a contract from a template\",\n route: { method: \"POST\", path: \"/v1/contracts/generate\" },\n entity: true,\n options: [\n { flags: \"--template <type>\", description: \"Template type (consulting_agreement, employment_offer, contractor_agreement, nda, custom)\", required: true },\n { flags: \"--counterparty <name>\", description: \"Counterparty name\", required: true },\n { flags: \"--effective-date <date>\", description: \"Effective date (ISO 8601, defaults to today)\" },\n { flags: \"--base-salary <amount>\", description: \"Employment offer base salary (for employment_offer)\" },\n { flags: \"--param <key=value>\", description: \"Additional template parameter (repeatable)\", type: \"array\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const template = ctx.opts.template as string;\n const counterparty = ctx.opts.counterparty as string;\n const baseSalary = ctx.opts.baseSalary as string | undefined;\n const paramRaw = (ctx.opts.param as string[] | undefined) ?? [];\n\n const parameters: Record<string, unknown> = {};\n if (baseSalary) parameters.base_salary = baseSalary;\n for (const raw of paramRaw) {\n const idx = raw.indexOf(\"=\");\n if (idx <= 0) throw new Error(`Invalid --param value: ${raw}. Expected key=value.`);\n const key = raw.slice(0, idx).trim();\n const value = raw.slice(idx + 1).trim();\n if (!key) throw new Error(`Invalid --param value: ${raw}. Expected key=value.`);\n parameters[key] = coerceParamValue(value);\n }\n\n // Early validation for known required template parameters\n if (template === \"employment_offer\" && !parameters.base_salary) {\n throw new Error(\n \"base_salary is required for employment_offer template.\\n\" +\n \" Use: --base-salary 150000\\n\" +\n \" Or: --param base_salary=150000\",\n );\n }\n\n try {\n const result = await ctx.client.generateContract({\n entity_id: eid,\n template_type: template,\n counterparty_name: counterparty,\n effective_date: (ctx.opts.effectiveDate as string | undefined) ?? new Date().toISOString().slice(0, 10),\n parameters,\n });\n await ctx.resolver.stabilizeRecord(\"document\", result, eid);\n ctx.resolver.rememberFromRecord(\"document\", result, eid);\n if (result.document_id) {\n ctx.resolver.remember(\"document\", String(result.document_id), eid);\n }\n ctx.writer.writeResult(result, `Contract generated: ${result.contract_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"document\",\n showReuseHint: true,\n });\n } catch (err) {\n const msg = String(err);\n if (template === \"employment_offer\" && (msg.includes(\"base_salary\") || msg.includes(\"required\"))) {\n printError(\n `Failed to generate employment_offer: ${msg}\\n` +\n \" Hint: employment_offer requires base_salary. Use:\\n\" +\n \" --base-salary 150000\\n\" +\n \" Or: --param base_salary=150000\\n\" +\n \" Optional params: position_title, start_date, work_location, classification,\\n\" +\n \" bonus_terms, equity_terms, benefits_summary, governing_law\",\n );\n } else if (template === \"safe_agreement\" && (msg.includes(\"purchase_amount\") || msg.includes(\"investment_amount\") || msg.includes(\"valuation_cap\") || msg.includes(\"investor_notice\") || msg.includes(\"required\"))) {\n printError(\n `Failed to generate safe_agreement: ${msg}\\n` +\n \" Hint: safe_agreement requires purchase_amount, valuation_cap, and investor_notice_address. Use:\\n\" +\n \" --param purchase_amount=50000000 --param valuation_cap=10000000\\n\" +\n ' --param investor_notice_address=\"123 Main St, City, ST 12345\"',\n );\n } else {\n printError(`Failed to generate contract: ${err}`);\n }\n process.exit(1);\n }\n },\n produces: { kind: \"document\" },\n successTemplate: \"Document generated: {title}\",\n examples: [\"corp documents generate --template 'type' --counterparty 'name'\", \"corp documents generate --json\"],\n },\n\n // --- documents preview-pdf ---\n {\n name: \"documents preview-pdf\",\n description: \"Validate and print the authenticated PDF preview URL for a governance document\",\n route: { method: \"GET\", path: \"/v1/documents/preview/pdf\" },\n entity: true,\n options: [\n { flags: \"--definition-id <id>\", description: \"AST document definition ID (e.g. 'bylaws')\" },\n { flags: \"--document-id <id>\", description: \"Deprecated alias for --definition-id\" },\n ],\n handler: async (ctx) => {\n const documentId = (ctx.opts.definitionId as string | undefined) ?? (ctx.opts.documentId as string | undefined);\n if (!documentId || documentId.trim().length === 0) {\n printError(\"preview-pdf requires --definition-id (or deprecated alias --document-id)\");\n process.exit(1);\n }\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n await ctx.client.validatePreviewPdf(eid, documentId);\n const url = ctx.client.getPreviewPdfUrl(eid, documentId);\n ctx.writer.success(`Preview PDF URL: ${url}`);\n console.log(\"The document definition was validated successfully. Use your API key to download the PDF.\");\n },\n examples: [\"corp documents preview-pdf\", \"corp documents preview-pdf --json\"],\n },\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n printDeadlinesTable,\n printError,\n printJson,\n printTaxFilingsTable,\n printWriteResult,\n} from \"../output.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst TAX_DOCUMENT_TYPE_DISPLAY = [\n \"1120\", \"1120s\", \"1065\", \"franchise_tax\", \"annual_report\", \"83b\",\n \"1099_nec\", \"k1\", \"941\", \"w2\",\n] as const;\n\nconst TAX_DOCUMENT_TYPE_ALIASES: Record<string, string> = {\n form_1120: \"1120\", form_1120s: \"1120s\", form_1065: \"1065\",\n form_1099_nec: \"1099_nec\", form_k1: \"k1\", form_941: \"941\", form_w2: \"w2\",\n};\n\nconst TAX_DOCUMENT_TYPE_CHOICES = [\n ...TAX_DOCUMENT_TYPE_DISPLAY,\n ...Object.keys(TAX_DOCUMENT_TYPE_ALIASES),\n];\n\nfunction normalizeRecurrence(recurrence?: string): string | undefined {\n if (!recurrence) return undefined;\n if (recurrence === \"yearly\") return \"annual\";\n return recurrence;\n}\n\n// ---------------------------------------------------------------------------\n// Tax / Compliance registry entries\n// ---------------------------------------------------------------------------\n\nexport const complianceCommands: CommandDef[] = [\n // --- tax (summary: filings + deadlines) ---\n {\n name: \"tax\",\n description: \"Tax filings and deadline tracking\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/tax-filings\" },\n entity: true,\n display: { title: \"Tax Summary\" },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const [filings, deadlines] = await Promise.all([\n ctx.client.listTaxFilings(eid),\n ctx.client.listDeadlines(eid),\n ]);\n if (ctx.opts.json) { ctx.writer.json({ filings, deadlines }); return; }\n if (filings.length === 0 && deadlines.length === 0) {\n ctx.writer.writeln(\"No tax filings or deadlines found.\");\n return;\n }\n if (filings.length > 0) printTaxFilingsTable(filings);\n if (deadlines.length > 0) printDeadlinesTable(deadlines);\n },\n examples: [\"corp tax\", \"corp tax --json\"],\n },\n\n // --- tax filings ---\n {\n name: \"tax filings\",\n description: \"Create a tax filing record\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/tax-filings\" },\n entity: true,\n display: {\n title: \"Tax Filings\",\n cols: [\"document_type>Type\", \"tax_year>Year\", \"status>Status\", \"#filing_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const filings = await ctx.client.listTaxFilings(eid);\n await ctx.resolver.stabilizeRecords(\"tax_filing\", filings, eid);\n if (ctx.opts.json) { ctx.writer.json(filings); return; }\n if (filings.length === 0) { ctx.writer.writeln(\"No tax filings found.\"); return; }\n printTaxFilingsTable(filings);\n },\n examples: [\"corp tax filings\", \"corp tax filings --json\"],\n },\n\n // --- tax file ---\n {\n name: \"tax file\",\n description: \"File a tax document\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/tax-filings\" },\n entity: true,\n options: [\n {\n flags: \"--type <type>\",\n description: `Document type (${TAX_DOCUMENT_TYPE_DISPLAY.join(\", \")})`,\n required: true,\n choices: [...TAX_DOCUMENT_TYPE_CHOICES],\n },\n { flags: \"--year <year>\", description: \"Tax year\", required: true, type: \"int\" },\n { flags: \"--filer-contact-id <ref>\", description: \"Contact reference for per-person filings (e.g. 83(b) elections)\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const rawType = ctx.opts.type as string;\n const docType = TAX_DOCUMENT_TYPE_ALIASES[rawType] ?? rawType;\n const filerContactId = (ctx.opts.filerContactId as string | undefined)\n ? await ctx.resolver.resolveContact(eid, ctx.opts.filerContactId as string)\n : undefined;\n const payload: Record<string, unknown> = {\n entity_id: eid,\n document_type: docType,\n tax_year: ctx.opts.year as number,\n };\n if (filerContactId) payload.filer_contact_id = filerContactId;\n const result = await ctx.client.fileTaxDocument(payload);\n await ctx.resolver.stabilizeRecord(\"tax_filing\", result, eid);\n ctx.resolver.rememberFromRecord(\"tax_filing\", result, eid);\n ctx.writer.writeResult(result, `Tax document filed: ${result.filing_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"tax_filing\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"tax_filing\" },\n successTemplate: \"Tax filing created\",\n examples: [\"corp tax file --year 'year'\"],\n },\n\n // --- tax deadlines ---\n {\n name: \"tax deadlines\",\n description: \"List tracked deadlines\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/deadlines\" },\n entity: true,\n display: {\n title: \"Deadlines\",\n cols: [\"deadline_type>Type\", \"@due_date>Due\", \"description>Description\", \"#deadline_id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const deadlines = await ctx.client.listDeadlines(eid);\n await ctx.resolver.stabilizeRecords(\"deadline\", deadlines, eid);\n if (ctx.opts.json) { ctx.writer.json(deadlines); return; }\n if (deadlines.length === 0) { ctx.writer.writeln(\"No deadlines found.\"); return; }\n printDeadlinesTable(deadlines);\n },\n examples: [\"corp tax deadlines\", \"corp tax deadlines --json\"],\n },\n\n // --- tax deadline ---\n {\n name: \"tax deadline\",\n description: \"Track a compliance deadline\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/deadlines\" },\n entity: true,\n options: [\n { flags: \"--type <type>\", description: \"Deadline type\", required: true },\n { flags: \"--due-date <date>\", description: \"Due date (ISO 8601)\", required: true },\n { flags: \"--description <desc>\", description: \"Description text\", required: true },\n { flags: \"--recurrence <recurrence>\", description: \"Recurrence (e.g. annual; 'yearly' is normalized). Required for annual_report type.\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n let recurrence = normalizeRecurrence(ctx.opts.recurrence as string | undefined);\n if (!recurrence && (ctx.opts.type as string) === \"annual_report\") {\n recurrence = \"annual\";\n }\n const payload: Record<string, unknown> = {\n entity_id: eid,\n deadline_type: ctx.opts.type as string,\n due_date: ctx.opts.dueDate as string,\n description: ctx.opts.description as string,\n };\n if (recurrence) payload.recurrence = recurrence;\n const result = await ctx.client.trackDeadline(payload);\n await ctx.resolver.stabilizeRecord(\"deadline\", result, eid);\n ctx.resolver.rememberFromRecord(\"deadline\", result, eid);\n ctx.writer.writeResult(result, `Deadline tracked: ${result.deadline_id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"deadline\",\n showReuseHint: true,\n });\n },\n produces: { kind: \"deadline\" },\n successTemplate: \"Deadline tracked\",\n examples: [\"corp tax deadline --type 'type' --due-date 'date' --description 'desc'\", \"corp tax deadline --json\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"compliance escalations-scan\",\n description: \"Scan for compliance issues and create escalations\",\n route: { method: \"POST\", path: \"/v1/compliance/escalations/scan\" },\n examples: [\"corp compliance escalations-scan\"],\n successTemplate: \"Escalations Scan created\",\n },\n {\n name: \"compliance escalations-resolve-with-evidence\",\n description: \"Resolve a compliance escalation with evidence\",\n route: { method: \"POST\", path: \"/v1/compliance/escalations/{pos}/resolve-with-evidence\" },\n args: [{ name: \"escalation-id\", required: true, description: \"Escalation ID\" }],\n options: [\n { flags: \"--evidence-type <evidence-type>\", description: \"Evidence Type\" },\n { flags: \"--filing-reference <filing-reference>\", description: \"Filing Reference\" },\n { flags: \"--notes <notes>\", description: \"Additional notes\" },\n { flags: \"--packet-id <packet-id>\", description: \"Document packet ID\" },\n { flags: \"--resolve-incident\", description: \"Resolve Incident\" },\n { flags: \"--resolve-obligation\", description: \"Resolve Obligation\" },\n ],\n examples: [\"corp compliance escalations-resolve-with-evidence <escalation-id>\", \"corp compliance escalations-resolve-with-evidence --json\"],\n successTemplate: \"Escalations Resolve With Evidence created\",\n },\n {\n name: \"contractors classify\",\n description: \"Classify a worker as employee or contractor\",\n route: { method: \"POST\", path: \"/v1/contractors/classify\" },\n entity: true,\n options: [\n { flags: \"--contractor-name <contractor-name>\", description: \"Contractor Name\", required: true },\n { flags: \"--duration-months <duration-months>\", description: \"Duration Months\" },\n { flags: \"--exclusive-client <exclusive-client>\", description: \"Exclusive Client\" },\n { flags: \"--factors <factors>\", description: \"Factors\" },\n { flags: \"--hours-per-week <hours-per-week>\", description: \"Hours Per Week\" },\n { flags: \"--provides-tools <provides-tools>\", description: \"Provides Tools\" },\n { flags: \"--state <state>\", description: \"State\" },\n ],\n examples: [\"corp contractors classify --contractor-name 'contractor-name'\", \"corp contractors classify --json\"],\n successTemplate: \"Classify created\",\n },\n {\n name: \"deadlines\",\n description: \"Create a compliance deadline\",\n route: { method: \"POST\", path: \"/v1/deadlines\" },\n options: [\n { flags: \"--deadline-type <deadline-type>\", description: \"Deadline Type\", required: true },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--due-date <due-date>\", description: \"Due date (ISO 8601, e.g. 2026-06-30)\", required: true },\n { flags: \"--recurrence <recurrence>\", description: \"Recurrence pattern for a deadline.\", choices: [\"one_time\", \"monthly\", \"quarterly\", \"annual\"] },\n { flags: \"--severity <severity>\", description: \"Risk severity of missing a deadline.\", choices: [\"low\", \"medium\", \"high\", \"critical\"] },\n ],\n examples: [\"corp deadlines --deadline-type 'deadline-type' --description 'description' --due-date one_time\", \"corp deadlines --json\"],\n successTemplate: \"Deadlines created\",\n },\n {\n name: \"entities compliance-escalations\",\n description: \"List compliance escalations for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/compliance/escalations\" },\n entity: true,\n display: { title: \"Entities Compliance Escalations\", cols: [\"action>Action\", \"authority>Authority\", \"milestone>Milestone\", \"@created_at>Created At\", \"#deadline_id>ID\"] },\n examples: [\"corp entities compliance-escalations\", \"corp entities compliance-escalations --json\"],\n },\n {\n name: \"tax create-filing\",\n description: \"Create a tax filing record\",\n route: { method: \"POST\", path: \"/v1/tax/filings\" },\n entity: true,\n options: [\n { flags: \"--document-type <document-type>\", description: \"Type of document required\", required: true },\n { flags: \"--tax-year <tax-year>\", description: \"Tax Year\", required: true, type: \"int\" },\n ],\n examples: [\"corp tax filings --document-type 'document-type' --tax-year 'tax-year'\"],\n successTemplate: \"Filings created\",\n },\n\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n printAgentsTable,\n printError,\n printJson,\n printReferenceSummary,\n printSuccess,\n printWriteResult,\n} from \"../output.js\";\nimport { confirm } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\nimport type { ApiRecord } from \"../types.js\";\nimport { readFileSync, realpathSync } from \"node:fs\";\nimport { relative, resolve } from \"node:path\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveTextInput(\n inlineText: string | undefined,\n filePath: string | undefined,\n label: string,\n required = false,\n): string | undefined {\n if (inlineText && filePath) {\n throw new Error(`Pass either --${label} or --${label}-file, not both.`);\n }\n if (filePath) {\n if (process.env.CORP_ALLOW_UNSAFE_FILE_INPUT === \"1\") {\n return readFileSync(filePath, \"utf8\");\n }\n const resolvedFile = realpathSync(resolve(filePath));\n const workingTreeRoot = realpathSync(process.cwd());\n const rel = relative(workingTreeRoot, resolvedFile);\n if (rel === \"\" || (!rel.startsWith(\"..\") && !rel.startsWith(\"/\"))) {\n return readFileSync(resolvedFile, \"utf8\");\n }\n throw new Error(\n `--${label}-file must stay inside the current working directory unless CORP_ALLOW_UNSAFE_FILE_INPUT=1 is set.`,\n );\n }\n if (inlineText) return inlineText;\n if (required) throw new Error(`Provide --${label} or --${label}-file.`);\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Agent registry entries\n// ---------------------------------------------------------------------------\n\nexport const agentCommands: CommandDef[] = [\n // --- agents (list) ---\n {\n name: \"agents\",\n description: \"Agent management\",\n route: { method: \"GET\", path: \"/v1/agents\" },\n display: {\n title: \"Agents\",\n cols: [\"name>Name\", \"status>Status\", \"model>Model\", \"#agent_id|id>ID\"],\n },\n handler: async (ctx) => {\n const agents = await ctx.client.listAgents();\n await ctx.resolver.stabilizeRecords(\"agent\", agents);\n if (ctx.opts.json) { ctx.writer.json(agents); return; }\n if (agents.length === 0) { ctx.writer.writeln(\"No agents found.\"); return; }\n printAgentsTable(agents);\n },\n examples: [\n \"corp agents\",\n 'corp agents create --name \"bookkeeper\" --prompt \"You manage accounts payable\"',\n 'corp agents message @last:agent --body \"Process this month\\'s invoices\"',\n 'corp agents skill @last:agent --name invoice-processing --description \"Process AP invoices\"',\n \"corp agents execution @last:agent <execution-id>\",\n \"corp agents kill @last:agent <execution-id>\",\n ],\n },\n\n // --- agents show <agent-ref> ---\n {\n name: \"agents show\",\n description: \"Show agent detail\",\n route: { method: \"GET\", path: \"/v1/agents/{pos}/resolved\" },\n args: [{ name: \"agent-ref\", required: true, description: \"Agent reference\" }],\n display: { title: \"Agent Detail\" },\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n const agent = await ctx.client.getAgent(resolvedAgentId);\n await ctx.resolver.stabilizeRecord(\"agent\", agent);\n if (ctx.opts.json) { ctx.writer.json(agent); return; }\n console.log(chalk.magenta(\"\\u2500\".repeat(40)));\n console.log(chalk.magenta.bold(\" Agent Detail\"));\n console.log(chalk.magenta(\"\\u2500\".repeat(40)));\n console.log(` ${chalk.bold(\"Name:\")} ${agent.name ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Status:\")} ${agent.status ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Model:\")} ${agent.model ?? \"N/A\"}`);\n printReferenceSummary(\"agent\", agent, { showReuseHint: true });\n if (agent.system_prompt) {\n let prompt = String(agent.system_prompt);\n if (prompt.length > 100) prompt = prompt.slice(0, 97) + \"...\";\n console.log(` ${chalk.bold(\"Prompt:\")} ${prompt}`);\n }\n if (agent.skills && Array.isArray(agent.skills) && agent.skills.length > 0) {\n console.log(` ${chalk.bold(\"Skills:\")} ${(agent.skills as Array<{ name?: string }>).map((s) => s.name ?? \"?\").join(\", \")}`);\n }\n console.log(chalk.magenta(\"\\u2500\".repeat(40)));\n },\n examples: [\"corp agents show\"],\n },\n\n // --- agents create ---\n {\n name: \"agents create\",\n description: \"Create a new agent\",\n route: { method: \"POST\", path: \"/v1/agents\" },\n options: [\n { flags: \"--name <name>\", description: \"Agent name\", required: true },\n { flags: \"--prompt <prompt>\", description: \"System prompt\", required: true },\n { flags: \"--model <model>\", description: \"LLM model name\" },\n ],\n handler: async (ctx) => {\n const data: ApiRecord = {\n name: ctx.opts.name as string,\n system_prompt: ctx.opts.prompt as string,\n };\n if (ctx.opts.model) data.model = ctx.opts.model as string;\n try {\n const result = await ctx.client.createAgent(data);\n await ctx.resolver.stabilizeRecord(\"agent\", result);\n ctx.resolver.rememberFromRecord(\"agent\", result);\n ctx.writer.writeResult(result, `Agent created: ${result.agent_id ?? result.id ?? \"OK\"}`, {\n jsonOnly: ctx.opts.json,\n referenceKind: \"agent\",\n showReuseHint: true,\n });\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"409\") || msg.includes(\"conflict\") || msg.includes(\"already exists\")) {\n printError(\n `Agent name '${ctx.opts.name}' is already in use (deleted agents still reserve their name).\\n` +\n \" Choose a different name, e.g.: corp agents create --name '...-v2' --prompt '...'\",\n );\n } else {\n printError(`Failed to create agent: ${err}`);\n }\n process.exit(1);\n }\n },\n produces: { kind: \"agent\" },\n successTemplate: \"Agent created: {name}\",\n examples: [\"corp agents create --name 'name' --prompt 'prompt'\", \"corp agents create --json\"],\n },\n\n // --- agents pause <agent-ref> ---\n {\n name: \"agents pause\",\n description: \"Pause an active agent\",\n route: { method: \"POST\", path: \"/v1/agents/{pos}/pause\" },\n args: [{ name: \"agent-ref\", required: true, description: \"Agent reference\" }],\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n const result = await ctx.client.updateAgent(resolvedAgentId, { status: \"paused\" });\n ctx.writer.writeResult(result, `Agent ${resolvedAgentId} paused.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp agents pause <agent-ref>\"],\n },\n\n // --- agents resume <agent-ref> ---\n {\n name: \"agents resume\",\n description: \"Resume a paused agent\",\n route: { method: \"POST\", path: \"/v1/agents/{pos}/resume\" },\n args: [{ name: \"agent-ref\", required: true, description: \"Agent reference\" }],\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n try {\n const result = await ctx.client.updateAgent(resolvedAgentId, { status: \"active\" });\n ctx.writer.writeResult(result, `Agent ${resolvedAgentId} resumed.`, { jsonOnly: ctx.opts.json });\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"409\") || msg.includes(\"disabled\") || msg.includes(\"deleted\")) {\n printError(\n `Cannot resume agent ${agentRef}: the agent may be disabled or deleted.\\n` +\n \" Disabled/deleted agents cannot be resumed. Create a new agent instead:\\n\" +\n \" corp agents create --name '...' --prompt '...'\",\n );\n } else {\n printError(`Failed to resume agent: ${err}`);\n }\n process.exit(1);\n }\n },\n examples: [\"corp agents resume <agent-ref>\"],\n },\n\n // --- agents delete <agent-ref> ---\n {\n name: \"agents delete\",\n description: \"Delete an agent\",\n route: { method: \"DELETE\", path: \"/v1/agents/{pos}\" },\n args: [{ name: \"agent-ref\", required: true, description: \"Agent reference\" }],\n options: [\n { flags: \"--yes, -y\", description: \"Skip confirmation prompt\" },\n ],\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n if (!ctx.opts.yes) {\n const ok = await confirm({\n message: `Delete agent ${resolvedAgentId}? This cannot be undone.`,\n default: false,\n });\n if (!ok) { console.log(\"Cancelled.\"); return; }\n }\n const result = await ctx.client.deleteAgent(resolvedAgentId);\n ctx.writer.writeResult(result, `Agent ${resolvedAgentId} deleted.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp agents delete <agent-ref>\", \"corp agents delete --json\"],\n },\n\n // --- agents message <agent-ref> ---\n {\n name: \"agents message\",\n description: \"Send a message to an agent\",\n route: { method: \"POST\", path: \"/v1/agents/{pos}/messages\" },\n args: [{ name: \"agent-ref\", required: true, description: \"Agent reference\" }],\n options: [\n { flags: \"--body <text>\", description: \"Message text\" },\n { flags: \"--body-file <path>\", description: \"Read the message body from a file\" },\n ],\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const body = resolveTextInput(ctx.opts.body as string | undefined, ctx.opts.bodyFile as string | undefined, \"body\", true);\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n try {\n const result = await ctx.client.sendAgentMessage(resolvedAgentId, body!);\n ctx.writer.writeResult(result, `Message sent. Execution: ${result.execution_id ?? \"OK\"}`, { jsonOnly: ctx.opts.json });\n } catch (err) {\n const msg = String(err);\n if (msg.includes(\"409\")) {\n printError(\n `Cannot message agent: the agent must be active or paused (not disabled/deleted).\\n` +\n \" Check agent status: corp agents show \" + agentRef + \"\\n\" +\n \" Resume a paused agent: corp agents resume \" + agentRef,\n );\n } else {\n printError(`Failed to send message: ${err}`);\n }\n process.exit(1);\n }\n },\n examples: [\"corp agents message <agent-ref>\", \"corp agents message --json\"],\n },\n\n // --- agents skill <agent-ref> ---\n {\n name: \"agents skill\",\n description: \"Add a skill to an agent\",\n route: { method: \"POST\", path: \"/v1/agents/{pos}/skills\" },\n args: [{ name: \"agent-ref\", required: true, description: \"Agent reference\" }],\n options: [\n { flags: \"--name <name>\", description: \"Skill name\", required: true },\n { flags: \"--description <desc>\", description: \"Skill description\", required: true },\n { flags: \"--instructions <text>\", description: \"Skill instructions text\" },\n { flags: \"--instructions-file <path>\", description: \"Read skill instructions from a file\" },\n ],\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const instructions = resolveTextInput(\n ctx.opts.instructions as string | undefined,\n ctx.opts.instructionsFile as string | undefined,\n \"instructions\",\n );\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n const result = await ctx.client.addAgentSkill(resolvedAgentId, {\n name: ctx.opts.name as string,\n description: ctx.opts.description as string,\n parameters: instructions ? { instructions } : {},\n });\n ctx.writer.writeResult(result, `Skill '${ctx.opts.name}' added to agent ${resolvedAgentId}.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp agents skill <agent-ref> --name 'name' --description 'desc'\", \"corp agents skill --json\"],\n },\n\n // --- agents execution <agent-ref> <execution-id> ---\n {\n name: \"agents execution\",\n description: \"Check execution status\",\n route: { method: \"GET\", path: \"/v1/agents/{pos}/executions/{pos2}\" },\n args: [\n { name: \"agent-ref\", required: true, description: \"Agent reference\" },\n { name: \"execution-id\", required: true, description: \"Execution ID\" },\n ],\n display: { title: \"Execution Status\" },\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const executionId = ctx.positional[1];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n const result = await ctx.client.getAgentExecution(resolvedAgentId, executionId);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n console.log(chalk.magenta(\"\\u2500\".repeat(40)));\n console.log(chalk.magenta.bold(\" Execution Status\"));\n console.log(chalk.magenta(\"\\u2500\".repeat(40)));\n console.log(` ${chalk.bold(\"Execution:\")} ${executionId}`);\n console.log(` ${chalk.bold(\"Agent:\")} ${resolvedAgentId}`);\n console.log(` ${chalk.bold(\"Status:\")} ${result.status ?? \"N/A\"}`);\n if (result.started_at) console.log(` ${chalk.bold(\"Started:\")} ${result.started_at}`);\n if (result.completed_at) console.log(` ${chalk.bold(\"Completed:\")} ${result.completed_at}`);\n console.log(chalk.magenta(\"\\u2500\".repeat(40)));\n },\n examples: [\"corp agents execution\"],\n },\n\n // --- agents execution-result <agent-ref> <execution-id> ---\n {\n name: \"agents execution-result\",\n description: \"Get execution result\",\n route: { method: \"GET\", path: \"/v1/agents/{pos}/executions/{pos2}/result\" },\n args: [\n { name: \"agent-ref\", required: true, description: \"Agent reference\" },\n { name: \"execution-id\", required: true, description: \"Execution ID\" },\n ],\n display: { title: \"Execution Result\" },\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const executionId = ctx.positional[1];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n const result = await ctx.client.getAgentExecutionResult(resolvedAgentId, executionId);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Result for execution ${executionId}:`);\n printJson(result);\n },\n examples: [\"corp agents execution-result\"],\n },\n\n // --- agents kill <agent-ref> <execution-id> ---\n {\n name: \"agents kill\",\n description: \"Kill a running execution\",\n route: { method: \"POST\", path: \"/v1/agents/{pos}/executions/{pos2}/kill\" },\n args: [\n { name: \"agent-ref\", required: true, description: \"Agent reference\" },\n { name: \"execution-id\", required: true, description: \"Execution ID\" },\n ],\n options: [\n { flags: \"--yes\", description: \"Skip confirmation\" },\n ],\n handler: async (ctx) => {\n const agentRef = ctx.positional[0];\n const executionId = ctx.positional[1];\n const resolvedAgentId = await ctx.resolver.resolveAgent(agentRef);\n if (!ctx.opts.yes) {\n const ok = await confirm({ message: `Kill execution ${executionId}?`, default: false });\n if (!ok) { console.log(\"Cancelled.\"); return; }\n }\n const result = await ctx.client.killAgentExecution(resolvedAgentId, executionId);\n ctx.writer.writeResult(result, `Execution ${executionId} killed.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp agents kill <agent-ref> <execution-id>\", \"corp agents kill --json\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"agents executions-logs\",\n description: \"View execution logs for an agent run\",\n route: { method: \"GET\", path: \"/v1/agents/{pos}/executions/{pos2}/logs\" },\n args: [{ name: \"agent-id\", required: true, description: \"Agent ID\" }, { name: \"execution-id\", required: true, description: \"Agent execution ID\" }],\n display: { title: \"Execution Logs\", cols: [\"@timestamp>Time\", \"level>Level\", \"message>Message\"] },\n examples: [\"corp agents executions-logs\"],\n },\n\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"agents messages\",\n description: \"View a specific agent message\",\n route: { method: \"GET\", path: \"/v1/agents/{pos}/messages/{pos2}\" },\n args: [{ name: \"agent-id\", required: true, description: \"Agent ID\" }, { name: \"message-id\", required: true, description: \"Message Id\" }],\n display: { title: \"Agent Message\" },\n examples: [\"corp agents messages\"],\n },\n\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n printReferenceSummary,\n printWorkItemsTable,\n printError,\n printJson,\n printWriteResult,\n} from \"../output.js\";\nimport { confirm } from \"@inquirer/prompts\";\nimport chalk from \"chalk\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction actorLabel(record: Record<string, unknown>, key: \"claimed_by\" | \"completed_by\" | \"created_by\"): string | undefined {\n const actor = record[`${key}_actor`];\n if (actor && typeof actor === \"object\" && !Array.isArray(actor)) {\n const label = (actor as Record<string, unknown>).label;\n const actorType = (actor as Record<string, unknown>).actor_type;\n if (typeof label === \"string\" && label.trim()) {\n return typeof actorType === \"string\" && actorType.trim()\n ? `${label} (${actorType})`\n : label;\n }\n }\n const legacy = record[key];\n return typeof legacy === \"string\" && legacy.trim() ? legacy : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Work-item registry entries\n// ---------------------------------------------------------------------------\n\nexport const workItemCommands: CommandDef[] = [\n // --- work-items (list) ---\n {\n name: \"work-items\",\n description: \"Long-term work item coordination\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/work-items\" },\n entity: true,\n optQP: [\"status\", \"category\"],\n display: {\n title: \"Work Items\",\n cols: [\"title>Title\", \"category>Category\", \"effective_status|status>Status\", \"@deadline>Deadline\", \"#work_item_id|id>ID\"],\n },\n options: [\n { flags: \"--status <status>\", description: \"Filter by status (open, claimed, completed, cancelled)\" },\n { flags: \"--category <category>\", description: \"Filter by category\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const params: Record<string, string> = {};\n if (ctx.opts.status) params.status = ctx.opts.status as string;\n if (ctx.opts.category) params.category = ctx.opts.category as string;\n const items = await ctx.client.listWorkItems(eid, Object.keys(params).length > 0 ? params : undefined);\n await ctx.resolver.stabilizeRecords(\"work_item\", items, eid);\n if (ctx.opts.json) { ctx.writer.json(items); return; }\n if (items.length === 0) { ctx.writer.writeln(\"No work items found.\"); return; }\n printWorkItemsTable(items);\n },\n examples: [\n \"corp work-items\",\n 'corp work-items create --title \"File Q1 taxes\" --category compliance --deadline 2026-04-15',\n \"corp work-items claim @last:work_item --by bookkeeper-agent\",\n 'corp work-items complete @last:work_item --by bookkeeper-agent --result \"Filed 1120 for Q1\"',\n ],\n },\n\n // --- work-items show <item-ref> ---\n {\n name: \"work-items show\",\n description: \"Show work item detail\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/work-items/{pos}\" },\n entity: true,\n args: [{ name: \"item-ref\", required: true, description: \"Work item reference\" }],\n display: { title: \"Work Item Detail\" },\n handler: async (ctx) => {\n const itemRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedWorkItemId = await ctx.resolver.resolveWorkItem(eid, itemRef);\n const w = await ctx.client.getWorkItem(eid, resolvedWorkItemId);\n await ctx.resolver.stabilizeRecord(\"work_item\", w, eid);\n if (ctx.opts.json) { ctx.writer.json(w); return; }\n console.log(chalk.cyan(\"\\u2500\".repeat(40)));\n console.log(chalk.cyan.bold(\" Work Item Detail\"));\n console.log(chalk.cyan(\"\\u2500\".repeat(40)));\n console.log(` ${chalk.bold(\"Title:\")} ${w.title ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Category:\")} ${w.category ?? \"N/A\"}`);\n console.log(` ${chalk.bold(\"Status:\")} ${w.effective_status ?? w.status ?? \"N/A\"}`);\n printReferenceSummary(\"work_item\", w, { showReuseHint: true });\n if (w.description) console.log(` ${chalk.bold(\"Description:\")} ${w.description}`);\n if (w.deadline) console.log(` ${chalk.bold(\"Deadline:\")} ${w.deadline}`);\n if (w.asap) console.log(` ${chalk.bold(\"Priority:\")} ${chalk.red.bold(\"ASAP\")}`);\n const claimedBy = actorLabel(w, \"claimed_by\");\n const completedBy = actorLabel(w, \"completed_by\");\n const createdBy = actorLabel(w, \"created_by\");\n if (claimedBy) console.log(` ${chalk.bold(\"Claimed by:\")} ${claimedBy}`);\n if (w.claimed_at) console.log(` ${chalk.bold(\"Claimed at:\")} ${w.claimed_at}`);\n if (w.claim_ttl_seconds) console.log(` ${chalk.bold(\"Claim TTL:\")} ${w.claim_ttl_seconds}s`);\n if (completedBy) console.log(` ${chalk.bold(\"Completed by:\")} ${completedBy}`);\n if (w.completed_at) console.log(` ${chalk.bold(\"Completed at:\")} ${w.completed_at}`);\n if (w.result) console.log(` ${chalk.bold(\"Result:\")} ${w.result}`);\n if (createdBy) console.log(` ${chalk.bold(\"Created by:\")} ${createdBy}`);\n console.log(` ${chalk.bold(\"Created at:\")} ${w.created_at ?? \"N/A\"}`);\n console.log(chalk.cyan(\"\\u2500\".repeat(40)));\n },\n examples: [\"corp work-items show\", \"corp work-items show --json\"],\n },\n\n // --- work-items create ---\n {\n name: \"work-items create\",\n description: \"Create a new work item\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/work-items\" },\n entity: true,\n options: [\n { flags: \"--title <title>\", description: \"Work item title\", required: true },\n { flags: \"--category <category>\", description: \"Work item category\", required: true },\n { flags: \"--description <desc>\", description: \"Description text\" },\n { flags: \"--deadline <date>\", description: \"Deadline (YYYY-MM-DD)\" },\n { flags: \"--asap\", description: \"Mark as ASAP priority\" },\n { flags: \"--created-by <name>\", description: \"Creator identifier\" },\n ],\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const category = ctx.opts.category as string | undefined;\n if (!category) {\n printError(\"required option '--category <category>' not specified\");\n process.exit(1);\n }\n const data: Record<string, unknown> = { title: ctx.opts.title as string, category };\n if (ctx.opts.description) data.description = ctx.opts.description as string;\n if (ctx.opts.deadline) data.deadline = ctx.opts.deadline as string;\n if (ctx.opts.asap) data.asap = true;\n if (ctx.opts.createdBy) data.created_by_actor = await ctx.resolver.resolveWorkItemActor(eid, ctx.opts.createdBy as string);\n const result = await ctx.client.createWorkItem(eid, data);\n await ctx.resolver.stabilizeRecord(\"work_item\", result, eid);\n ctx.resolver.rememberFromRecord(\"work_item\", result, eid);\n ctx.writer.writeResult(\n result,\n `Work item created: ${result.work_item_id ?? result.id ?? \"OK\"}`,\n { jsonOnly: ctx.opts.json, referenceKind: \"work_item\", showReuseHint: true },\n );\n },\n produces: { kind: \"work_item\" },\n successTemplate: \"Work item created: {title}\",\n examples: [\"corp work-items create --title 'title'\", \"corp work-items create --json\"],\n },\n\n // --- work-items claim <item-ref> ---\n {\n name: \"work-items claim\",\n description: \"Claim a work item\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/work-items/{pos}/claim\" },\n entity: true,\n args: [{ name: \"item-ref\", required: true, description: \"Work item reference\" }],\n options: [\n { flags: \"--by <name>\", description: \"Agent or user claiming the item (required)\" },\n { flags: \"--claimer <name>\", description: \"Alias for --by\" },\n { flags: \"--ttl <seconds>\", description: \"Auto-release TTL in seconds\", type: \"int\" },\n ],\n handler: async (ctx) => {\n const itemRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedWorkItemId = await ctx.resolver.resolveWorkItem(eid, itemRef);\n const claimedBy = (ctx.opts.by as string | undefined) ?? (ctx.opts.claimer as string | undefined);\n if (!claimedBy) {\n printError(\"required option '--by <name>' not specified\");\n process.exit(1);\n }\n const data: Record<string, unknown> = {\n claimed_by_actor: await ctx.resolver.resolveWorkItemActor(eid, claimedBy),\n };\n if (ctx.opts.ttl != null) data.ttl_seconds = ctx.opts.ttl as number;\n const result = await ctx.client.claimWorkItem(eid, resolvedWorkItemId, data);\n ctx.writer.writeResult(result, `Work item ${resolvedWorkItemId} claimed by ${claimedBy}.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp work-items claim <item-ref>\", \"corp work-items claim --json\"],\n },\n\n // --- work-items complete <item-ref> ---\n {\n name: \"work-items complete\",\n description: \"Mark a work item as completed\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/work-items/{pos}/complete\" },\n entity: true,\n args: [{ name: \"item-ref\", required: true, description: \"Work item reference\" }],\n options: [\n { flags: \"--by <name>\", description: \"Agent or user completing the item (required)\" },\n { flags: \"--completed-by <name>\", description: \"Alias for --by\" },\n { flags: \"--result <text>\", description: \"Completion result or notes\" },\n { flags: \"--notes <text>\", description: \"Alias for --result\" },\n ],\n handler: async (ctx) => {\n const itemRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedWorkItemId = await ctx.resolver.resolveWorkItem(eid, itemRef);\n const completedBy = (ctx.opts.by as string | undefined) ?? (ctx.opts.completedBy as string | undefined);\n if (!completedBy) {\n printError(\"required option '--by <name>' not specified\");\n process.exit(1);\n }\n const data: Record<string, unknown> = {\n completed_by_actor: await ctx.resolver.resolveWorkItemActor(eid, completedBy),\n };\n const resultText = (ctx.opts.result as string | undefined) ?? (ctx.opts.notes as string | undefined);\n if (resultText) data.result = resultText;\n const result = await ctx.client.completeWorkItem(eid, resolvedWorkItemId, data);\n ctx.writer.writeResult(result, `Work item ${resolvedWorkItemId} completed.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp work-items complete <item-ref>\", \"corp work-items complete --json\"],\n },\n\n // --- work-items release <item-ref> ---\n {\n name: \"work-items release\",\n description: \"Release a claimed work item\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/work-items/{pos}/release\" },\n entity: true,\n args: [{ name: \"item-ref\", required: true, description: \"Work item reference\" }],\n handler: async (ctx) => {\n const itemRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedWorkItemId = await ctx.resolver.resolveWorkItem(eid, itemRef);\n const result = await ctx.client.releaseWorkItem(eid, resolvedWorkItemId);\n ctx.writer.writeResult(result, `Work item ${resolvedWorkItemId} claim released.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp work-items release <item-ref>\"],\n },\n\n // --- work-items cancel <item-ref> ---\n {\n name: \"work-items cancel\",\n description: \"Cancel a work item\",\n route: { method: \"POST\", path: \"/v1/entities/{eid}/work-items/{pos}/cancel\" },\n entity: true,\n args: [{ name: \"item-ref\", required: true, description: \"Work item reference\" }],\n options: [\n { flags: \"--yes, -y\", description: \"Skip confirmation prompt\" },\n ],\n handler: async (ctx) => {\n const itemRef = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const resolvedWorkItemId = await ctx.resolver.resolveWorkItem(eid, itemRef);\n if (!ctx.opts.yes) {\n const ok = await confirm({\n message: `Cancel work item ${resolvedWorkItemId}?`,\n default: false,\n });\n if (!ok) { console.log(\"Cancelled.\"); return; }\n }\n const result = await ctx.client.cancelWorkItem(eid, resolvedWorkItemId);\n ctx.writer.writeResult(result, `Work item ${resolvedWorkItemId} cancelled.`, { jsonOnly: ctx.opts.json });\n },\n examples: [\"corp work-items cancel <item-ref>\", \"corp work-items cancel --json\"],\n },\n];","import type { CommandDef, CommandContext } from \"./types.js\";\nimport {\n printServiceCatalogTable,\n printServiceRequestsTable,\n printDryRun,\n printError,\n printJson,\n printReferenceSummary,\n printSuccess,\n printWriteResult,\n} from \"../output.js\";\nimport chalk from \"chalk\";\n\n// ---------------------------------------------------------------------------\n// Service registry entries\n// ---------------------------------------------------------------------------\n\nexport const serviceCommands: CommandDef[] = [\n // --- services (alias to catalog) ---\n {\n name: \"services\",\n description: \"Service catalog and fulfillment\",\n route: { method: \"GET\", path: \"/v1/services/catalog\" },\n entity: true,\n display: {\n title: \"Service Catalog\",\n cols: [\"name>Name\", \"slug>Slug\", \"$price_cents>Price\", \"#service_id|id>ID\"],\n },\n handler: async (ctx) => {\n const items = await ctx.client.listServiceCatalog();\n if (ctx.opts.json) { ctx.writer.json(items); return; }\n printServiceCatalogTable(items);\n },\n examples: [\"corp services\", \"corp services --json\"],\n },\n\n // --- services catalog ---\n {\n name: \"services catalog\",\n description: \"List the service catalog\",\n route: { method: \"GET\", path: \"/v1/services/catalog\" },\n display: {\n title: \"Service Catalog\",\n cols: [\"name>Name\", \"slug>Slug\", \"$price_cents>Price\", \"#service_id|id>ID\"],\n },\n handler: async (ctx) => {\n const items = await ctx.client.listServiceCatalog();\n if (ctx.opts.json) { ctx.writer.json(items); return; }\n printServiceCatalogTable(items);\n },\n examples: [\"corp services catalog\"],\n },\n\n // --- services list ---\n {\n name: \"services list\",\n description: \"List service requests for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/service-requests\" },\n entity: true,\n display: {\n title: \"Service Requests\",\n cols: [\"service_slug>Service\", \"status>Status\", \"@created_at>Created\", \"#request_id|id>ID\"],\n },\n handler: async (ctx) => {\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const requests = await ctx.client.listServiceRequests(eid);\n const stable = await ctx.resolver.stabilizeRecords(\"service_request\", requests, eid);\n if (ctx.opts.json) { ctx.writer.json(stable); return; }\n printServiceRequestsTable(stable);\n },\n examples: [\"corp services list\", \"corp services list --json\"],\n },\n\n // --- services show <ref> ---\n {\n name: \"services show\",\n description: \"Show service request detail\",\n route: { method: \"GET\", path: \"/v1/service-requests/{pos}\" },\n entity: true,\n args: [{ name: \"ref\", required: true, description: \"Service request reference\" }],\n display: { title: \"Service Request Detail\" },\n handler: async (ctx) => {\n const ref_ = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const requestId = await ctx.resolver.resolveServiceRequest(eid, ref_);\n const result = await ctx.client.getServiceRequest(requestId, eid);\n await ctx.resolver.stabilizeRecord(\"service_request\", result, eid);\n ctx.resolver.rememberFromRecord(\"service_request\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n printReferenceSummary(\"service_request\", result);\n printJson(result);\n },\n examples: [\"corp services show\", \"corp services show --json\"],\n },\n\n // --- services buy <slug> ---\n {\n name: \"services buy\",\n description: \"Purchase a service from the catalog\",\n route: { method: \"POST\", path: \"/v1/service-requests\" },\n entity: true,\n dryRun: true,\n args: [{ name: \"slug\", required: true, description: \"Service catalog slug\" }],\n handler: async (ctx) => {\n const slug = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const payload = { entity_id: eid, service_slug: slug };\n if (ctx.dryRun) {\n ctx.writer.dryRun(\"services.create_request\", payload);\n return;\n }\n const result = await ctx.client.createServiceRequest(payload);\n await ctx.resolver.stabilizeRecord(\"service_request\", result, eid);\n ctx.resolver.rememberFromRecord(\"service_request\", result, eid);\n\n // Auto-begin checkout to get the URL.\n const requestId = String(result.request_id ?? result.id ?? \"\");\n if (requestId) {\n const checkout = await ctx.client.beginServiceCheckout(requestId, { entity_id: eid });\n if (ctx.opts.json) { ctx.writer.json(checkout); return; }\n ctx.writer.success(`Service request created: ${requestId}`);\n printReferenceSummary(\"service_request\", result, { showReuseHint: true });\n if (checkout.checkout_url) {\n console.log(`\\n ${chalk.bold(\"Checkout URL:\")} ${checkout.checkout_url}`);\n }\n console.log(chalk.dim(\"\\n Next steps:\"));\n console.log(chalk.dim(\" Complete payment at the checkout URL above\"));\n console.log(chalk.dim(\" corp services list --entity-id <id>\"));\n } else {\n ctx.writer.writeResult(result, \"Service request created\", {\n referenceKind: \"service_request\",\n showReuseHint: true,\n });\n }\n },\n produces: { kind: \"service_request\" },\n successTemplate: \"Service request created\",\n examples: [\"corp services buy <slug>\"],\n },\n\n // --- services fulfill <ref> ---\n {\n name: \"services fulfill\",\n description: \"Mark a service request as fulfilled (operator)\",\n route: { method: \"POST\", path: \"/v1/service-requests/{pos}/fulfill\" },\n entity: true,\n args: [{ name: \"ref\", required: true, description: \"Service request reference\" }],\n options: [\n { flags: \"--note <note>\", description: \"Fulfillment note\" },\n ],\n handler: async (ctx) => {\n const ref_ = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const requestId = await ctx.resolver.resolveServiceRequest(eid, ref_);\n const result = await ctx.client.fulfillServiceRequest(requestId, {\n entity_id: eid,\n note: ctx.opts.note as string | undefined,\n });\n await ctx.resolver.stabilizeRecord(\"service_request\", result, eid);\n ctx.resolver.rememberFromRecord(\"service_request\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Service request fulfilled: ${requestId}`);\n printReferenceSummary(\"service_request\", result, { showReuseHint: true });\n printJson(result);\n },\n examples: [\"corp services fulfill <ref>\", \"corp services fulfill --json\"],\n },\n\n // --- services cancel <ref> ---\n {\n name: \"services cancel\",\n description: \"Cancel a service request\",\n route: { method: \"POST\", path: \"/v1/service-requests/{pos}/cancel\" },\n entity: true,\n args: [{ name: \"ref\", required: true, description: \"Service request reference\" }],\n handler: async (ctx) => {\n const ref_ = ctx.positional[0];\n const eid = await ctx.resolver.resolveEntity(ctx.opts.entityId as string | undefined);\n const requestId = await ctx.resolver.resolveServiceRequest(eid, ref_);\n const result = await ctx.client.cancelServiceRequest(requestId, {\n entity_id: eid,\n });\n await ctx.resolver.stabilizeRecord(\"service_request\", result, eid);\n ctx.resolver.rememberFromRecord(\"service_request\", result, eid);\n if (ctx.opts.json) { ctx.writer.json(result); return; }\n ctx.writer.success(`Service request cancelled: ${requestId}`);\n printReferenceSummary(\"service_request\", result, { showReuseHint: true });\n printJson(result);\n },\n examples: [\"corp services cancel <ref>\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"services create-request\",\n description: \"Submit a new service request\",\n route: { method: \"POST\", path: \"/v1/services/requests\" },\n options: [\n { flags: \"--obligation-id <obligation-id>\", description: \"Obligation ID\" },\n { flags: \"--service-slug <service-slug>\", description: \"Service Slug\", required: true },\n ],\n examples: [\"corp services requests --service-slug 'service-slug'\", \"corp services requests --json\"],\n successTemplate: \"Requests created\",\n },\n {\n name: \"services requests\",\n description: \"Submit a new service request\",\n route: { method: \"GET\", path: \"/v1/services/requests/{pos}\" },\n entity: true,\n args: [{ name: \"request-id\", required: true, description: \"Document request ID\" }],\n display: { title: \"Services Requests\", cols: [\"amount_cents>Amount Cents\", \"checkout_url>Checkout Url\", \"failed_at>Failed At\", \"fulfilled_at>Fulfilled At\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp services requests\", \"corp services requests --json\"],\n },\n {\n name: \"services requests-cancel\",\n description: \"Cancel a service request\",\n route: { method: \"POST\", path: \"/v1/services/requests/{pos}/cancel\" },\n args: [{ name: \"request-id\", required: true, description: \"Document request ID\" }],\n examples: [\"corp services requests-cancel <request-id>\"],\n successTemplate: \"Requests Cancel created\",\n },\n {\n name: \"services requests-checkout\",\n description: \"Start checkout for a service request\",\n route: { method: \"POST\", path: \"/v1/services/requests/{pos}/checkout\" },\n args: [{ name: \"request-id\", required: true, description: \"Document request ID\" }],\n examples: [\"corp services requests-checkout <request-id>\"],\n successTemplate: \"Requests Checkout created\",\n },\n {\n name: \"services requests-fulfill\",\n description: \"Fulfill a service request\",\n route: { method: \"POST\", path: \"/v1/services/requests/{pos}/fulfill\" },\n args: [{ name: \"request-id\", required: true, description: \"Document request ID\" }],\n options: [\n { flags: \"--note <note>\", description: \"Note\" },\n ],\n examples: [\"corp services requests-fulfill <request-id>\", \"corp services requests-fulfill --json\"],\n successTemplate: \"Requests Fulfill created\",\n },\n\n];","import { input, confirm, select } from \"@inquirer/prompts\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { existsSync, mkdirSync, readdirSync } from \"node:fs\";\nimport { loadConfig, saveConfig, validateApiUrl } from \"../config.js\";\nimport { provisionWorkspace } from \"../api-client.js\";\nimport {\n generateSecret,\n generateFernetKey,\n processRequest,\n} from \"@thecorporation/corp-tools\";\nimport { printSuccess, printError } from \"../output.js\";\n\nconst CLOUD_API_URL = \"https://api.thecorporation.ai\";\nconst DEFAULT_DATA_DIR = join(homedir(), \".corp\", \"data\");\n\n// ── Magic link auth (unchanged) ─────────────────────────────────────\n\nasync function requestMagicLink(\n apiUrl: string,\n email: string,\n tosAccepted: boolean\n): Promise<void> {\n const resp = await fetch(`${apiUrl}/v1/auth/magic-link`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email, tos_accepted: tosAccepted }),\n });\n if (!resp.ok) {\n const data = await resp.json().catch(() => ({}));\n const detail =\n (data as Record<string, unknown>)?.error ??\n (data as Record<string, unknown>)?.message ??\n resp.statusText;\n throw new Error(\n typeof detail === \"string\" ? detail : JSON.stringify(detail)\n );\n }\n}\n\nasync function verifyMagicLinkCode(\n apiUrl: string,\n code: string\n): Promise<{ api_key: string; workspace_id: string }> {\n const resp = await fetch(`${apiUrl}/v1/auth/magic-link/verify`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code, client: \"cli\" }),\n });\n const data = (await resp.json().catch(() => ({}))) as Record<string, unknown>;\n if (!resp.ok) {\n const detail = data?.error ?? data?.message ?? resp.statusText;\n throw new Error(\n typeof detail === \"string\" ? detail : JSON.stringify(detail)\n );\n }\n if (!data.api_key || !data.workspace_id) {\n throw new Error(\"Unexpected response — missing api_key or workspace_id\");\n }\n return {\n api_key: data.api_key as string,\n workspace_id: data.workspace_id as string,\n };\n}\n\nfunction isCloudApi(url: string): boolean {\n return url.replace(/\\/+$/, \"\").includes(\"thecorporation.ai\");\n}\n\nasync function magicLinkAuth(\n apiUrl: string,\n email: string\n): Promise<{ api_key: string; workspace_id: string }> {\n console.log(\"\\nSending magic link to \" + email + \"...\");\n await requestMagicLink(apiUrl, email, true);\n console.log(\"Check your email for a sign-in link from TheCorporation.\");\n console.log(\n \"Copy the code from the URL (the ?code=... part) and paste it below.\\n\"\n );\n\n const code = await input({ message: \"Paste your magic link code\" });\n const trimmed = code.trim().replace(/^.*[?&]code=/, \"\");\n if (!trimmed) {\n throw new Error(\"No code provided\");\n }\n\n console.log(\"Verifying...\");\n return verifyMagicLinkCode(apiUrl, trimmed);\n}\n\n// ── Local provisioning ──────────────────────────────────────────────\n\nfunction setupDataDir(dirPath: string): { isNew: boolean } {\n if (!existsSync(dirPath)) {\n mkdirSync(dirPath, { recursive: true });\n return { isNew: true };\n }\n try {\n const entries = readdirSync(dirPath);\n if (entries.length > 0) {\n console.log(\"Found existing data, reusing.\");\n return { isNew: false };\n }\n } catch {\n // empty or unreadable\n }\n return { isNew: true };\n}\n\nasync function localProvision(\n dataDir: string,\n name: string\n): Promise<{ api_key: string; workspace_id: string }> {\n const resp = processRequest(\n \"process://\",\n \"POST\",\n \"/v1/workspaces/provision\",\n { \"Content-Type\": \"application/json\" },\n JSON.stringify({ name }),\n { dataDir },\n );\n\n if (!resp.ok) {\n const detail = await resp.text();\n throw new Error(`Provision failed: HTTP ${resp.status} — ${detail}`);\n }\n\n const body = (await resp.json()) as Record<string, unknown>;\n if (!body.api_key || !body.workspace_id) {\n throw new Error(\"Provision response missing api_key or workspace_id\");\n }\n return {\n api_key: body.api_key as string,\n workspace_id: body.workspace_id as string,\n };\n}\n\n// ── Main setup ──────────────────────────────────────────────────────\n\nexport async function setupCommand(): Promise<void> {\n const cfg = loadConfig();\n console.log(\"Welcome to corp — corporate governance from the terminal.\\n\");\n\n // User info\n console.log(\"--- User Info ---\");\n const user = cfg.user ?? { name: \"\", email: \"\" };\n user.name = await input({\n message: \"Your name\",\n default: user.name || undefined,\n });\n user.email = await input({\n message: \"Your email\",\n default: user.email || undefined,\n });\n cfg.user = user;\n\n // Hosting mode\n console.log(\"\\n--- Hosting Mode ---\");\n const hostingMode = await select({\n message: \"How would you like to run corp?\",\n choices: [\n { value: \"local\", name: \"Local (your machine)\" },\n { value: \"cloud\", name: \"TheCorporation cloud\" },\n { value: \"self-hosted\", name: \"Self-hosted server (custom URL)\" },\n ],\n default: cfg.hosting_mode || \"local\",\n });\n cfg.hosting_mode = hostingMode;\n\n if (hostingMode === \"local\") {\n // Data directory\n const dataDir = await input({\n message: \"Data directory\",\n default: cfg.data_dir || DEFAULT_DATA_DIR,\n });\n cfg.data_dir = dataDir;\n cfg.api_url = \"process://\";\n\n const { isNew } = setupDataDir(dataDir);\n\n // Generate server secrets\n const serverSecrets = {\n jwt_secret: generateSecret(),\n secrets_master_key: generateFernetKey(),\n internal_worker_token: generateSecret(),\n };\n\n // Inject into process.env so processRequest can use them immediately\n process.env.JWT_SECRET = serverSecrets.jwt_secret;\n process.env.SECRETS_MASTER_KEY = serverSecrets.secrets_master_key;\n process.env.INTERNAL_WORKER_TOKEN = serverSecrets.internal_worker_token;\n\n // Store secrets via _server_secrets (picked up by serializeAuth)\n (cfg as Record<string, unknown>)._server_secrets = serverSecrets;\n\n if (isNew || !cfg.workspace_id) {\n console.log(\"\\nProvisioning workspace...\");\n try {\n const result = await localProvision(dataDir, `${user.name}'s workspace`);\n cfg.api_key = result.api_key;\n cfg.workspace_id = result.workspace_id;\n printSuccess(`Local workspace ready: ${result.workspace_id}`);\n } catch (err) {\n printError(`Workspace provisioning failed: ${err}`);\n console.log(\"You can retry with 'corp setup'.\");\n }\n } else {\n console.log(\"\\nExisting workspace found.\");\n }\n } else if (hostingMode === \"cloud\") {\n cfg.api_url = CLOUD_API_URL;\n cfg.data_dir = \"\";\n\n const needsAuth = !cfg.api_key || !cfg.workspace_id;\n if (needsAuth) {\n try {\n const result = await magicLinkAuth(cfg.api_url, user.email);\n cfg.api_key = result.api_key;\n cfg.workspace_id = result.workspace_id;\n printSuccess(`Authenticated. Workspace: ${result.workspace_id}`);\n } catch (err) {\n printError(`Authentication failed: ${err}`);\n console.log(\n \"You can manually set credentials with: corp config set api_key <key>\"\n );\n }\n } else {\n console.log(\"\\nExisting credentials found. Run 'corp status' to verify.\");\n }\n } else {\n // Self-hosted\n const url = await input({\n message: \"Server URL\",\n default:\n cfg.api_url !== CLOUD_API_URL && !cfg.api_url.startsWith(\"process://\")\n ? cfg.api_url\n : undefined,\n });\n try {\n cfg.api_url = validateApiUrl(url);\n } catch (err) {\n printError(`Invalid URL: ${err}`);\n process.exit(1);\n }\n cfg.data_dir = \"\";\n\n const needsAuth = !cfg.api_key || !cfg.workspace_id;\n if (needsAuth) {\n console.log(\"\\nProvisioning workspace...\");\n try {\n const result = await provisionWorkspace(\n cfg.api_url,\n `${user.name}'s workspace`\n );\n cfg.api_key = result.api_key as string;\n cfg.workspace_id = result.workspace_id as string;\n console.log(`Workspace provisioned: ${result.workspace_id}`);\n } catch (err) {\n printError(`Auto-provision failed: ${err}`);\n console.log(\n \"You can manually set credentials with: corp config set api_key <key>\"\n );\n }\n }\n }\n\n saveConfig(cfg);\n console.log(\"\\nSettings saved to ~/.corp/config.json\");\n console.log(\"Credentials saved to ~/.corp/auth.json\");\n console.log(\"Run 'corp status' to verify your connection.\");\n}\n","import { configForDisplay, getValue, loadConfig, requireConfig, setValue, updateConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printJson } from \"../output.js\";\nimport { ReferenceResolver } from \"../references.js\";\n\nfunction looksLikeCanonicalId(value: string): boolean {\n const trimmed = value.trim();\n return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(trimmed)\n || /^ent_[a-z0-9-]+$/i.test(trimmed);\n}\n\nexport async function configSetCommand(\n key: string,\n value: string,\n options: { force?: boolean } = {},\n): Promise<void> {\n let resolvedValue = value;\n try {\n if (key === \"active_entity_id\" && !looksLikeCanonicalId(value)) {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n resolvedValue = await resolver.resolveEntity(value);\n }\n updateConfig((cfg) => {\n setValue(cfg as unknown as Record<string, unknown>, key, resolvedValue, {\n forceSensitive: options.force,\n });\n });\n } catch (err) {\n printError(`Failed to update config: ${err}`);\n process.exit(1);\n }\n\n if (key === \"api_key\" || key === \"llm.api_key\") {\n console.log(`${key} updated.`);\n return;\n }\n if (key === \"active_entity_id\") {\n console.log(`${key} updated to ${resolvedValue}.`);\n return;\n }\n console.log(`${key} updated.`);\n}\n\nexport function configGetCommand(key: string): void {\n const cfg = loadConfig();\n const val = getValue(cfg as unknown as Record<string, unknown>, key);\n if (val === undefined) {\n printError(`Key not found: ${key}`);\n process.exit(1);\n }\n if (typeof val === \"object\" && val !== null) {\n printJson(val);\n } else {\n console.log(String(val));\n }\n}\n\nexport function configListCommand(): void {\n const cfg = loadConfig();\n printJson(configForDisplay(cfg));\n}\n","import { resolve } from \"node:path\";\nimport type { ChildProcess } from \"node:child_process\";\nimport { ensureEnvFile, loadEnvFile } from \"@thecorporation/corp-tools\";\n\ninterface ServeOptions {\n port: string;\n dataDir: string;\n}\n\nexport async function serveCommand(opts: ServeOptions): Promise<void> {\n let server: { getBinaryPath: () => string | null; isAvailable: () => boolean; startServer: (options: Record<string, unknown>) => ChildProcess };\n try {\n // @ts-expect-error — optional dependency, handled by catch block\n server = await import(\"@thecorporation/server\");\n } catch {\n console.error(\n \"Error: @thecorporation/server is not installed.\\n\\n\" +\n \"Install it with:\\n\" +\n \" npm install @thecorporation/server\\n\\n\" +\n \"Or run the Rust binary directly:\\n\" +\n \" cd services/api-rs && cargo run\"\n );\n process.exit(1);\n }\n\n if (!server.isAvailable()) {\n console.error(\n \"Error: No server binary available for this platform.\\n\\n\" +\n \"Pre-built binaries are available for:\\n\" +\n \" - linux-x64, linux-arm64\\n\" +\n \" - darwin-x64, darwin-arm64\\n\" +\n \" - win32-x64\\n\\n\" +\n \"You can build from source:\\n\" +\n \" cd services/api-rs && cargo build --release\"\n );\n process.exit(1);\n }\n\n const port = parseInt(opts.port, 10);\n if (isNaN(port) || port > 65535) {\n console.error(`Error: Invalid port \"${opts.port}\"`);\n process.exit(1);\n }\n\n // Load .env file, generating one if it doesn't exist\n const envPath = resolve(process.cwd(), \".env\");\n ensureEnvFile(envPath);\n loadEnvFile(envPath);\n\n const localUrl = `http://localhost:${port}`;\n console.log(`Starting server on port ${port}...`);\n console.log(`Data directory: ${opts.dataDir}`);\n console.log(`CLI API URL remains unchanged.`);\n console.log(` Use CORP_API_URL=${localUrl} for commands against this local server.\\n`);\n\n const child = server.startServer({\n port,\n dataDir: opts.dataDir,\n });\n\n const shutdown = () => {\n console.log(\"\\nShutting down server...\");\n child.kill(\"SIGTERM\");\n };\n\n process.on(\"SIGINT\", shutdown);\n process.on(\"SIGTERM\", shutdown);\n\n child.on(\"exit\", (code) => {\n process.exit(code ?? 0);\n });\n}\n","import { requireConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printJson, printReferenceSummary, printSuccess } from \"../output.js\";\nimport { withSpinner } from \"../spinner.js\";\nimport { ReferenceResolver } from \"../references.js\";\nimport { activateFormationEntity } from \"../formation-automation.js\";\nimport type { ApiRecord } from \"../types.js\";\n\ntype DemoOptions = {\n name: string;\n scenario?: string;\n minimal?: boolean;\n json?: boolean;\n};\n\nfunction scenarioConfig(name: string, scenario: string): ApiRecord {\n switch (scenario) {\n case \"llc\":\n return {\n entity_type: \"llc\",\n legal_name: name,\n jurisdiction: \"US-WY\",\n members: [\n {\n name: \"Alice Chen\",\n email: \"alice@example.com\",\n role: \"member\",\n investor_type: \"natural_person\",\n ownership_pct: 60,\n address: {\n street: \"251 Little Falls Dr\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19808\",\n },\n },\n {\n name: \"Bob Martinez\",\n email: \"bob@example.com\",\n role: \"member\",\n investor_type: \"natural_person\",\n ownership_pct: 40,\n address: {\n street: \"251 Little Falls Dr\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19808\",\n },\n },\n ],\n fiscal_year_end: \"12-31\",\n company_address: {\n street: \"251 Little Falls Dr\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19808\",\n },\n };\n case \"restaurant\":\n return {\n entity_type: \"llc\",\n legal_name: name,\n jurisdiction: \"US-DE\",\n members: [\n {\n name: \"Rosa Alvarez\",\n email: \"rosa@example.com\",\n role: \"manager\",\n investor_type: \"natural_person\",\n ownership_pct: 55,\n address: {\n street: \"18 Market St\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19801\",\n },\n },\n {\n name: \"Noah Patel\",\n email: \"noah@example.com\",\n role: \"member\",\n investor_type: \"natural_person\",\n ownership_pct: 45,\n address: {\n street: \"18 Market St\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19801\",\n },\n },\n ],\n fiscal_year_end: \"12-31\",\n company_address: {\n street: \"18 Market St\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19801\",\n },\n };\n case \"startup\":\n default:\n return {\n entity_type: \"c_corp\",\n legal_name: name,\n jurisdiction: \"US-DE\",\n authorized_shares: 10_000_000,\n par_value: \"0.0001\",\n transfer_restrictions: true,\n right_of_first_refusal: true,\n members: [\n {\n name: \"Alice Chen\",\n email: \"alice@example.com\",\n role: \"chair\",\n investor_type: \"natural_person\",\n shares_purchased: 6_000_000,\n officer_title: \"ceo\",\n is_incorporator: true,\n address: {\n street: \"251 Little Falls Dr\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19808\",\n },\n },\n {\n name: \"Bob Martinez\",\n email: \"bob@example.com\",\n role: \"director\",\n investor_type: \"natural_person\",\n shares_purchased: 4_000_000,\n officer_title: \"cto\",\n address: {\n street: \"251 Little Falls Dr\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19808\",\n },\n },\n ],\n fiscal_year_end: \"12-31\",\n company_address: {\n street: \"251 Little Falls Dr\",\n city: \"Wilmington\",\n state: \"DE\",\n zip: \"19808\",\n },\n };\n }\n}\n\nfunction meetingTypeForBody(body: ApiRecord): string {\n return String(body.body_type) === \"llc_member_vote\" ? \"member_meeting\" : \"board_meeting\";\n}\n\nexport async function demoCommand(opts: DemoOptions): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n const scenario = opts.scenario ?? \"startup\";\n\n try {\n if (opts.minimal) {\n const result = await withSpinner(\"Loading\", () => client.seedDemo({\n name: opts.name,\n scenario,\n }));\n if (opts.json) {\n printJson(result);\n return;\n }\n printSuccess(\"Minimal demo seeded.\");\n printJson(result);\n return;\n }\n\n const formationPayload = scenarioConfig(opts.name, scenario);\n const created = await withSpinner(\"Creating demo entity\", () =>\n client.createFormationWithCapTable(formationPayload),\n );\n const entityId = String(created.entity_id ?? created.formation_id ?? \"\");\n if (!entityId) {\n throw new Error(\"demo formation did not return an entity_id\");\n }\n\n await resolver.stabilizeRecord(\"entity\", created as ApiRecord);\n resolver.rememberFromRecord(\"entity\", created as ApiRecord);\n\n const activation = await withSpinner(\"Activating formation\", () =>\n activateFormationEntity(client, resolver, entityId),\n );\n\n const agent = await withSpinner(\"Creating demo agent\", () =>\n client.createAgent({\n name: `${opts.name} Operator`,\n entity_id: entityId,\n system_prompt: `Operate ${opts.name} and keep the workspace data clean.`,\n scopes: [],\n }),\n );\n await resolver.stabilizeRecord(\"agent\", agent);\n resolver.rememberFromRecord(\"agent\", agent);\n\n const bodies = await client.listGovernanceBodies(entityId);\n await resolver.stabilizeRecords(\"body\", bodies as ApiRecord[], entityId);\n\n let meeting: ApiRecord | undefined;\n if (bodies.length > 0) {\n meeting = await client.scheduleMeeting({\n entity_id: entityId,\n body_id: (bodies[0] as ApiRecord).body_id,\n meeting_type: meetingTypeForBody(bodies[0] as ApiRecord),\n title: \"Demo kickoff meeting\",\n agenda_item_titles: [\n \"Approve demo operating budget\",\n \"Review founder vesting and cap table\",\n ],\n });\n await resolver.stabilizeRecord(\"meeting\", meeting, entityId);\n resolver.rememberFromRecord(\"meeting\", meeting, entityId);\n }\n\n const workItem = await client.createWorkItem(entityId, {\n title: \"Review demo workspace\",\n description: \"Check documents, governance, cap table, and treasury setup.\",\n category: \"ops\",\n created_by_actor: {\n actor_type: \"agent\",\n actor_id: String(agent.agent_id),\n },\n });\n await resolver.stabilizeRecord(\"work_item\", workItem, entityId);\n resolver.rememberFromRecord(\"work_item\", workItem, entityId);\n\n const claimedWorkItem = await client.claimWorkItem(entityId, String(workItem.work_item_id), {\n claimed_by_actor: {\n actor_type: \"agent\",\n actor_id: String(agent.agent_id),\n },\n });\n\n const bankAccount = await client.openBankAccount({\n entity_id: entityId,\n bank_name: \"Mercury\",\n });\n await resolver.stabilizeRecord(\"bank_account\", bankAccount, entityId);\n resolver.rememberFromRecord(\"bank_account\", bankAccount, entityId);\n\n const invoice = await client.createInvoice({\n entity_id: entityId,\n customer_name: \"Acme Customer\",\n amount_cents: 250000,\n due_date: \"2026-04-01\",\n description: \"Demo advisory services\",\n });\n await resolver.stabilizeRecord(\"invoice\", invoice, entityId);\n resolver.rememberFromRecord(\"invoice\", invoice, entityId);\n\n const contract = await client.generateContract({\n entity_id: entityId,\n template_type: \"nda\",\n counterparty_name: \"Example Counterparty\",\n effective_date: \"2026-03-12\",\n parameters: {},\n });\n await resolver.stabilizeRecord(\"document\", contract, entityId);\n resolver.rememberFromRecord(\"document\", contract, entityId);\n\n const result: ApiRecord = {\n scenario,\n entity: created,\n activation,\n agent,\n meeting,\n work_item: claimedWorkItem,\n bank_account: bankAccount,\n invoice,\n contract,\n };\n\n if (opts.json) {\n printJson(result);\n return;\n }\n\n printSuccess(`Demo environment created for ${opts.name}.`);\n printReferenceSummary(\"entity\", created as ApiRecord, { showReuseHint: true });\n printReferenceSummary(\"agent\", agent, { showReuseHint: true });\n if (meeting) {\n printReferenceSummary(\"meeting\", meeting, { showReuseHint: true });\n }\n printReferenceSummary(\"work_item\", claimedWorkItem, { showReuseHint: true });\n printReferenceSummary(\"invoice\", invoice, { showReuseHint: true });\n printReferenceSummary(\"bank_account\", bankAccount, { showReuseHint: true });\n printJson(result);\n } catch (err) {\n printError(`Failed to seed demo: ${err}`);\n process.exit(1);\n }\n}\n","import type { ToolCall, LLMResponse } from \"./types.js\";\nimport type OpenAI from \"openai\";\nimport type { ChatCompletionCreateParamsNonStreaming } from \"openai/resources/chat/completions.js\";\n\nconst PROVIDER_BASE_URLS: Record<string, string> = {\n openrouter: \"https://openrouter.ai/api/v1\",\n};\n\nexport async function chat(\n messages: Record<string, unknown>[],\n tools?: Record<string, unknown>[],\n provider = \"openrouter\",\n apiKey = \"\",\n model = \"\",\n baseUrl?: string,\n): Promise<LLMResponse> {\n const effectiveUrl = baseUrl ?? PROVIDER_BASE_URLS[provider] ?? PROVIDER_BASE_URLS.openrouter;\n const { default: OpenAIClient } = await import(\"openai\");\n const client = new OpenAIClient({ apiKey, baseURL: effectiveUrl });\n\n const params: ChatCompletionCreateParamsNonStreaming = {\n model: model || \"gpt-4o\",\n messages: messages as unknown as OpenAI.ChatCompletionMessageParam[],\n max_tokens: 4096,\n };\n if (tools?.length) {\n params.tools = tools as unknown as OpenAI.ChatCompletionTool[];\n params.tool_choice = \"auto\";\n }\n\n const response = await client.chat.completions.create(params);\n const choice = response.choices[0];\n const message = choice.message;\n\n const toolCallsOut: ToolCall[] = [];\n if (message.tool_calls) {\n for (const tc of message.tool_calls) {\n let args: Record<string, unknown>;\n try {\n args = JSON.parse(tc.function.arguments);\n } catch {\n args = { _raw: tc.function.arguments };\n }\n toolCallsOut.push({ id: tc.id, name: tc.function.name, arguments: args });\n }\n }\n\n return {\n content: message.content,\n tool_calls: toolCallsOut,\n usage: {\n prompt_tokens: response.usage?.prompt_tokens ?? 0,\n completion_tokens: response.usage?.completion_tokens ?? 0,\n total_tokens: response.usage?.total_tokens ?? 0,\n },\n finish_reason: choice.finish_reason ?? null,\n };\n}\n","import {\n TOOL_DEFINITIONS as _TOOL_DEFINITIONS,\n isWriteTool as _isWriteTool,\n executeTool as _executeTool,\n} from \"@thecorporation/corp-tools\";\nimport type { CorpAPIClient } from \"@thecorporation/corp-tools\";\nimport { setActiveEntityId, updateConfig } from \"./config.js\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\n\nexport const TOOL_DEFINITIONS = _TOOL_DEFINITIONS;\nexport const isWriteTool: (name: string, args?: Record<string, unknown>) => boolean = _isWriteTool;\n\nexport async function executeTool(\n name: string,\n args: Record<string, unknown>,\n client: CorpAPIClient,\n): Promise<string> {\n return _executeTool(name, args, client, {\n dataDir: join(homedir(), \".corp\"),\n onEntityFormed: (entityId) => {\n try {\n updateConfig((cfg) => {\n setActiveEntityId(cfg, entityId);\n });\n } catch { /* ignore */ }\n },\n });\n}\n","import { createInterface } from \"node:readline\";\nimport chalk from \"chalk\";\nimport { requireConfig, configForDisplay, getValue, setValue, saveConfig } from \"./config.js\";\nimport { CorpAPIClient } from \"./api-client.js\";\nimport { chat as llmChat } from \"./llm.js\";\nimport { TOOL_DEFINITIONS, executeTool, isWriteTool } from \"./tools.js\";\nimport { printError, printStatusPanel, printObligationsTable, printJson } from \"./output.js\";\nimport type { CorpConfig, LLMResponse, ToolCall } from \"./types.js\";\n\nconst SYSTEM_PROMPT = `You are **corp**, an AI assistant for corporate governance.\nYou help users manage their companies — entities, cap tables, compliance, governance, finances, and more.\nYou have tools to read and write corporate data. Use them to fulfill user requests.\nFor write operations, confirm with the user before proceeding.\nMonetary values are in cents (e.g. 100000 = $1,000.00).\nDocuments must be signed by the human — you cannot sign on their behalf.\nAfter completing actions, suggest logical next steps.`;\n\nexport async function chatCommand(): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\", \"llm.api_key\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n\n const messages: Record<string, unknown>[] = [{ role: \"system\", content: SYSTEM_PROMPT }];\n let totalTokens = 0;\n\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const prompt = () => new Promise<string>((resolve) => rl.question(chalk.green.bold(\"> \"), resolve));\n\n console.log(chalk.blue.bold(\"corp chat\") + \" — type /help for commands, /quit to exit\\n\");\n\n const slashHandlers: Record<string, (args: string) => void> = {\n \"/status\": async () => {\n try { printStatusPanel(await client.getStatus()); } catch (e) { printError(`Status error: ${e}`); }\n },\n \"/obligations\": async () => {\n try {\n const data = await client.getObligations();\n const obls = (data.obligations ?? []) as Record<string, unknown>[];\n if (obls.length) printObligationsTable(obls);\n else console.log(chalk.dim(\"No obligations found.\"));\n } catch (e) { printError(`Obligations error: ${e}`); }\n },\n \"/digest\": async () => {\n try {\n const digests = await client.listDigests();\n if (digests.length) printJson(digests);\n else console.log(chalk.dim(\"No digest history.\"));\n } catch (e) { printError(`Digest error: ${e}`); }\n },\n \"/config\": () => printJson(configForDisplay(cfg)),\n \"/model\": (args: string) => {\n const model = args.trim();\n if (!model) { console.log(`Current model: ${getValue(cfg as unknown as Record<string, unknown>, \"llm.model\")}`); return; }\n setValue(cfg as unknown as Record<string, unknown>, \"llm.model\", model);\n saveConfig(cfg);\n console.log(`Model switched to: ${model}`);\n },\n \"/cost\": () => console.log(`Session tokens used: ${totalTokens.toLocaleString()}`),\n \"/clear\": () => {\n messages.length = 0;\n messages.push({ role: \"system\", content: SYSTEM_PROMPT });\n totalTokens = 0;\n console.log(chalk.dim(\"Conversation cleared.\"));\n },\n \"/help\": () => {\n console.log(`\n${chalk.bold(\"Chat Slash Commands\")}\n /status Show workspace status\n /obligations List obligations\n /digest Show digest history\n /config Show current config (masked keys)\n /model <name> Switch LLM model\n /cost Show token usage\n /clear Clear conversation\n /help Show this help\n /quit Exit chat`);\n },\n };\n\n try {\n while (true) {\n let userInput: string;\n try {\n userInput = (await prompt()).trim();\n } catch {\n console.log(\"\\n\" + chalk.dim(\"Goodbye.\"));\n break;\n }\n\n if (!userInput) continue;\n\n if (userInput.startsWith(\"/\")) {\n const [cmd, ...rest] = userInput.split(/\\s+/);\n const args = rest.join(\" \");\n if (cmd === \"/quit\" || cmd === \"/exit\") {\n console.log(chalk.dim(\"Goodbye.\"));\n break;\n }\n const handler = slashHandlers[cmd.toLowerCase()];\n if (handler) { await handler(args); continue; }\n printError(`Unknown command: ${cmd}. Type /help for available commands.`);\n continue;\n }\n\n messages.push({ role: \"user\", content: userInput });\n\n const llmCfg = cfg.llm;\n while (true) {\n let response: LLMResponse;\n try {\n response = await llmChat(\n messages, TOOL_DEFINITIONS, llmCfg.provider, llmCfg.api_key, llmCfg.model, llmCfg.base_url,\n );\n } catch (err) {\n printError(`LLM error: ${err}`);\n break;\n }\n\n totalTokens += response.usage.total_tokens;\n\n const assistantMsg: Record<string, unknown> = { role: \"assistant\", content: response.content };\n if (response.tool_calls.length > 0) {\n assistantMsg.tool_calls = response.tool_calls.map((tc) => ({\n id: tc.id, type: \"function\",\n function: { name: tc.name, arguments: JSON.stringify(tc.arguments) },\n }));\n if (!response.content) assistantMsg.content = null;\n }\n messages.push(assistantMsg);\n\n if (response.tool_calls.length === 0) {\n if (response.content) console.log(\"\\n\" + response.content + \"\\n\");\n break;\n }\n\n for (const tc of response.tool_calls) {\n console.log(chalk.dim(` ${isWriteTool(tc.name, tc.arguments) ? \"\\u2699\" : \"\\u2139\"} ${tc.name}(${JSON.stringify(tc.arguments).slice(0, 80)})`));\n const result = await executeTool(tc.name, tc.arguments, client);\n const short = result.length > 200 ? result.slice(0, 197) + \"...\" : result;\n console.log(chalk.dim(` => ${short}`));\n messages.push({ role: \"tool\", tool_call_id: tc.id, content: result });\n }\n }\n }\n } finally {\n rl.close();\n }\n}\n","import { confirm } from \"@inquirer/prompts\";\nimport { requireConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printJson, printSuccess, printWriteResult } from \"../output.js\";\n\nexport async function apiKeysListCommand(opts: { json?: boolean }): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n try {\n const keys = await client.listApiKeys();\n if (opts.json) { printJson(keys); return; }\n if (keys.length === 0) { console.log(\"No API keys found.\"); return; }\n for (const k of keys) {\n const name = k.name ?? k.label ?? \"unnamed\";\n const id = k.key_id ?? k.id;\n const scopes = Array.isArray(k.scopes) ? (k.scopes as string[]).join(\", \") : \"all\";\n console.log(` ${name} [${id}] scopes: ${scopes}`);\n }\n } catch (err) { printError(`Failed to list API keys: ${err}`); process.exit(1); }\n}\n\nexport async function apiKeysCreateCommand(opts: {\n name: string; scopes?: string; json?: boolean;\n}): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n try {\n const data: Record<string, unknown> = { name: opts.name };\n if (opts.scopes) data.scopes = opts.scopes.split(\",\").map((s) => s.trim());\n const result = await client.createApiKey(data);\n printWriteResult(result, `API key created: ${result.key_id ?? \"OK\"}`, opts.json);\n if (!opts.json && result.api_key) {\n printSuccess(`Key: ${result.api_key}`);\n console.log(\" Save this key — it will not be shown again.\");\n }\n } catch (err) { printError(`Failed to create API key: ${err}`); process.exit(1); }\n}\n\nexport async function apiKeysRevokeCommand(keyId: string, opts: {\n yes?: boolean; json?: boolean;\n}): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n try {\n if (!opts.yes) {\n const ok = await confirm({ message: `Revoke API key ${keyId}? This cannot be undone.`, default: false });\n if (!ok) { console.log(\"Cancelled.\"); return; }\n }\n await client.revokeApiKey(keyId);\n if (opts.json) { printJson({ revoked: true, key_id: keyId }); return; }\n printSuccess(`API key ${keyId} revoked.`);\n } catch (err) { printError(`Failed to revoke API key: ${err}`); process.exit(1); }\n}\n\nexport async function apiKeysRotateCommand(keyId: string, opts: {\n json?: boolean;\n}): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n try {\n const result = await client.rotateApiKey(keyId);\n printWriteResult(result, `API key ${keyId} rotated.`, opts.json);\n if (!opts.json && result.api_key) {\n printSuccess(`New key: ${result.api_key}`);\n console.log(\" Save this key — it will not be shown again.\");\n }\n } catch (err) { printError(`Failed to rotate API key: ${err}`); process.exit(1); }\n}\n","import { requireConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printSuccess } from \"../output.js\";\n\nexport async function linkCommand(opts: { externalId: string; provider: string }): Promise<void> {\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n try {\n const data = await client.createLink(opts.externalId, opts.provider);\n printSuccess(`Workspace linked to ${opts.provider} (external ID: ${opts.externalId})`);\n if (data.workspace_id) console.log(` Workspace: ${data.workspace_id}`);\n } catch (err) {\n printError(`${err}`);\n process.exit(1);\n }\n}\n","import { loadConfig, saveConfig } from \"../config.js\";\nimport { printError } from \"../output.js\";\n\nexport async function claimCommand(code: string): Promise<void> {\n const cfg = loadConfig();\n const apiUrl = (cfg.api_url || \"https://api.thecorporation.ai\").replace(/\\/+$/, \"\");\n if (apiUrl.startsWith(\"process://\")) {\n printError(\n \"Claim codes require a remote API server.\\n\" +\n \" Run: npx corp config set api_url https://api.thecorporation.ai --force\\n\" +\n \" Or use: npx corp setup\",\n );\n process.exit(1);\n }\n try {\n const resp = await fetch(`${apiUrl}/v1/workspaces/claim`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ code }),\n });\n if (!resp.ok) {\n let detail = \"\";\n try { const body = await resp.json() as Record<string, string>; detail = body.detail ?? \"\"; } catch { /* ignore */ }\n printError(detail || `${resp.status} ${resp.statusText}`);\n process.exit(1);\n }\n const data = await resp.json() as Record<string, string>;\n cfg.api_key = data.api_key;\n cfg.workspace_id = data.workspace_id;\n saveConfig(cfg);\n console.log(`Workspace joined: ${data.workspace_id}`);\n console.log(\"Credentials saved to ~/.corp/auth.json\");\n console.log(\"Settings remain in ~/.corp/config.json\");\n } catch (err) {\n printError(`${err}`);\n process.exit(1);\n }\n}\n","import { requireConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printJson } from \"../output.js\";\nimport chalk from \"chalk\";\n\ninterface FeedbackOptions {\n category?: string;\n email?: string;\n json?: boolean;\n}\n\nconst MAX_FEEDBACK_LENGTH = 10_000;\n\nexport async function feedbackCommand(message: string, opts: FeedbackOptions): Promise<void> {\n if (!message || message.trim().length === 0) {\n printError(\"Feedback message cannot be empty\");\n process.exit(1);\n }\n if (message.length > MAX_FEEDBACK_LENGTH) {\n printError(`Feedback message must be at most ${MAX_FEEDBACK_LENGTH} characters (got ${message.length})`);\n process.exit(1);\n }\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n try {\n const result = await client.submitFeedback(message, opts.category, opts.email);\n if (opts.json) {\n printJson(result);\n return;\n }\n console.log(`\\n${chalk.green(\"✓\")} Feedback submitted (${chalk.dim(result.feedback_id)})`);\n } catch (err: any) {\n const detail = String(err);\n if (detail.includes(\"404\") || detail.includes(\"Not found\") || detail.includes(\"not found\")) {\n printError(\n `Failed to submit feedback: ${detail}\\n` +\n \" This server does not expose /v1/feedback. Local api-rs dev servers currently do not support feedback submission.\",\n );\n } else {\n printError(`Failed to submit feedback: ${detail}`);\n }\n process.exit(1);\n }\n}\n","import { requireConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printJson } from \"../output.js\";\nimport { ReferenceResolver, shortId, type ResourceKind } from \"../references.js\";\n\nconst KINDS = new Set<ResourceKind>([\n \"entity\",\n \"contact\",\n \"share_transfer\",\n \"invoice\",\n \"bank_account\",\n \"payment\",\n \"payroll_run\",\n \"distribution\",\n \"reconciliation\",\n \"tax_filing\",\n \"deadline\",\n \"classification\",\n \"body\",\n \"meeting\",\n \"seat\",\n \"agenda_item\",\n \"resolution\",\n \"document\",\n \"work_item\",\n \"agent\",\n \"valuation\",\n \"safe_note\",\n \"instrument\",\n \"share_class\",\n \"round\",\n]);\n\nconst ENTITY_SCOPED_KINDS = new Set<ResourceKind>([\n \"contact\",\n \"share_transfer\",\n \"invoice\",\n \"bank_account\",\n \"payment\",\n \"payroll_run\",\n \"distribution\",\n \"reconciliation\",\n \"tax_filing\",\n \"deadline\",\n \"classification\",\n \"body\",\n \"meeting\",\n \"seat\",\n \"agenda_item\",\n \"resolution\",\n \"document\",\n \"work_item\",\n \"valuation\",\n \"safe_note\",\n \"instrument\",\n \"share_class\",\n \"round\",\n]);\n\nexport async function resolveCommand(\n kind: string,\n ref: string,\n opts: { entityId?: string; bodyId?: string; meetingId?: string },\n): Promise<void> {\n const normalizedKind = kind.trim().toLowerCase() as ResourceKind;\n if (!KINDS.has(normalizedKind)) {\n printError(`Unsupported resolve kind: ${kind}`);\n process.exit(1);\n }\n\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n const entityId = ENTITY_SCOPED_KINDS.has(normalizedKind) || opts.entityId || opts.bodyId || opts.meetingId\n ? await resolver.resolveEntity(opts.entityId)\n : undefined;\n const bodyId = entityId && opts.bodyId ? await resolver.resolveBody(entityId, opts.bodyId) : undefined;\n const meetingId = entityId && opts.meetingId\n ? await resolver.resolveMeeting(entityId, opts.meetingId, bodyId)\n : undefined;\n\n let resolvedId: string;\n switch (normalizedKind) {\n case \"entity\":\n resolvedId = await resolver.resolveEntity(ref);\n break;\n case \"contact\":\n resolvedId = await resolver.resolveContact(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"share_transfer\":\n resolvedId = await resolver.resolveShareTransfer(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"invoice\":\n resolvedId = await resolver.resolveInvoice(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"bank_account\":\n resolvedId = await resolver.resolveBankAccount(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"payment\":\n resolvedId = await resolver.resolvePayment(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"payroll_run\":\n resolvedId = await resolver.resolvePayrollRun(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"distribution\":\n resolvedId = await resolver.resolveDistribution(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"reconciliation\":\n resolvedId = await resolver.resolveReconciliation(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"tax_filing\":\n resolvedId = await resolver.resolveTaxFiling(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"deadline\":\n resolvedId = await resolver.resolveDeadline(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"classification\":\n resolvedId = await resolver.resolveClassification(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"body\":\n resolvedId = await resolver.resolveBody(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"meeting\":\n resolvedId = await resolver.resolveMeeting(requiredEntity(entityId, normalizedKind), ref, bodyId);\n break;\n case \"seat\":\n resolvedId = await resolver.resolveSeat(requiredEntity(entityId, normalizedKind), ref, bodyId);\n break;\n case \"agenda_item\":\n resolvedId = await resolver.resolveAgendaItem(\n requiredEntity(entityId, normalizedKind),\n requiredMeeting(meetingId, normalizedKind),\n ref,\n );\n break;\n case \"resolution\":\n resolvedId = await resolver.resolveResolution(requiredEntity(entityId, normalizedKind), ref, meetingId);\n break;\n case \"document\":\n resolvedId = await resolver.resolveDocument(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"work_item\":\n resolvedId = await resolver.resolveWorkItem(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"agent\":\n resolvedId = await resolver.resolveAgent(ref);\n break;\n case \"valuation\":\n resolvedId = await resolver.resolveValuation(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"safe_note\":\n resolvedId = await resolver.resolveSafeNote(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"instrument\":\n resolvedId = await resolver.resolveInstrument(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"share_class\":\n resolvedId = await resolver.resolveShareClass(requiredEntity(entityId, normalizedKind), ref);\n break;\n case \"round\":\n resolvedId = await resolver.resolveRound(requiredEntity(entityId, normalizedKind), ref);\n break;\n default:\n throw new Error(`Unhandled resolve kind: ${normalizedKind}`);\n }\n\n printJson({\n kind: normalizedKind,\n input: ref,\n resolved_id: resolvedId,\n short_id: shortId(resolvedId),\n ...(entityId ? { entity_id: entityId } : {}),\n ...(bodyId ? { body_id: bodyId } : {}),\n ...(meetingId ? { meeting_id: meetingId } : {}),\n });\n } catch (err) {\n printError(`Failed to resolve reference: ${err}`);\n process.exit(1);\n }\n}\n\nfunction requiredEntity(entityId: string | undefined, kind: ResourceKind): string {\n if (!entityId) {\n throw new Error(`--entity-id is required to resolve ${kind}.`);\n }\n return entityId;\n}\n\nfunction requiredMeeting(meetingId: string | undefined, kind: ResourceKind): string {\n if (!meetingId) {\n throw new Error(`--meeting-id is required to resolve ${kind}.`);\n }\n return meetingId;\n}\n","import chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport { requireConfig } from \"../config.js\";\nimport { CorpAPIClient } from \"../api-client.js\";\nimport { printError, printJson } from \"../output.js\";\nimport { ReferenceResolver, type ResourceKind } from \"../references.js\";\n\nconst KINDS = new Set<ResourceKind>([\n \"entity\",\n \"contact\",\n \"share_transfer\",\n \"invoice\",\n \"bank_account\",\n \"payment\",\n \"payroll_run\",\n \"distribution\",\n \"reconciliation\",\n \"tax_filing\",\n \"deadline\",\n \"classification\",\n \"body\",\n \"meeting\",\n \"seat\",\n \"agenda_item\",\n \"resolution\",\n \"document\",\n \"work_item\",\n \"agent\",\n \"valuation\",\n \"safe_note\",\n \"instrument\",\n \"share_class\",\n \"round\",\n]);\n\nconst ENTITY_SCOPED_KINDS = new Set<ResourceKind>([\n \"contact\",\n \"share_transfer\",\n \"invoice\",\n \"bank_account\",\n \"payment\",\n \"payroll_run\",\n \"distribution\",\n \"reconciliation\",\n \"tax_filing\",\n \"deadline\",\n \"classification\",\n \"body\",\n \"meeting\",\n \"seat\",\n \"agenda_item\",\n \"resolution\",\n \"document\",\n \"work_item\",\n \"valuation\",\n \"safe_note\",\n \"instrument\",\n \"share_class\",\n \"round\",\n]);\n\nexport async function findCommand(\n kind: string,\n query: string,\n opts: { entityId?: string; bodyId?: string; meetingId?: string; json?: boolean },\n): Promise<void> {\n const normalizedKind = kind.trim().toLowerCase() as ResourceKind;\n if (!KINDS.has(normalizedKind)) {\n printError(`Unsupported find kind: ${kind}`);\n process.exit(1);\n }\n\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n try {\n const entityId = ENTITY_SCOPED_KINDS.has(normalizedKind) || opts.entityId || opts.bodyId || opts.meetingId\n ? await resolver.resolveEntity(opts.entityId)\n : undefined;\n const bodyId = entityId && opts.bodyId ? await resolver.resolveBody(entityId, opts.bodyId) : undefined;\n const meetingId = entityId && opts.meetingId\n ? await resolver.resolveMeeting(entityId, opts.meetingId, bodyId)\n : undefined;\n\n const matches = await resolver.find(normalizedKind, query, { entityId, bodyId, meetingId });\n if (opts.json) {\n printJson({\n kind: normalizedKind,\n query,\n ...(entityId ? { entity_id: entityId } : {}),\n ...(bodyId ? { body_id: bodyId } : {}),\n ...(meetingId ? { meeting_id: meetingId } : {}),\n matches: matches.map((match) => ({\n kind: match.kind,\n id: match.id,\n short_id: match.short_id,\n alias: match.alias,\n label: match.label,\n })),\n });\n return;\n }\n\n if (matches.length === 0) {\n console.log(`No ${normalizedKind.replaceAll(\"_\", \" \")} matches for \"${query}\".`);\n return;\n }\n\n const table = new Table({\n head: [\n chalk.dim(\"Short\"),\n chalk.dim(\"Alias\"),\n chalk.dim(\"Label\"),\n chalk.dim(\"ID\"),\n ],\n });\n for (const match of matches) {\n table.push([\n match.short_id,\n match.alias ?? \"\",\n match.label,\n match.id,\n ]);\n }\n console.log(table.toString());\n } catch (err) {\n printError(`Failed to find references: ${err}`);\n process.exit(1);\n }\n}\n","import type { CommandDef } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Admin / utility commands\n// ---------------------------------------------------------------------------\n\nexport const adminCommands: CommandDef[] = [\n // ── setup (local, interactive) ──────────────────────────────────────\n {\n name: \"setup\",\n description: \"Interactive setup wizard\",\n local: true,\n handler: async () => {\n const { setupCommand } = await import(\"../commands/setup.js\");\n await setupCommand();\n },\n examples: [\"corp setup\"],\n },\n\n // ── config (local) ──────────────────────────────────────────────────\n {\n name: \"config\",\n description: \"Manage configuration\",\n local: true,\n examples: [\"corp config\"],\n },\n {\n name: \"config set\",\n description: \"Set a config value (dot-path)\",\n local: true,\n args: [\n { name: \"key\", required: true, description: \"Config key (dot-path)\" },\n { name: \"value\", required: true, description: \"Value to set\" },\n ],\n options: [\n { flags: \"--force\", description: \"Allow updating a security-sensitive config key\" },\n ],\n handler: async (ctx) => {\n const { configSetCommand } = await import(\"../commands/config.js\");\n await configSetCommand(\n ctx.positional[0],\n ctx.positional[1],\n { force: ctx.opts.force as boolean | undefined },\n );\n },\n examples: [\"corp config set\"],\n },\n {\n name: \"config get\",\n description: \"Get a config value (dot-path)\",\n local: true,\n args: [\n { name: \"key\", required: true, description: \"Config key (dot-path)\" },\n ],\n handler: async (ctx) => {\n const { configGetCommand } = await import(\"../commands/config.js\");\n configGetCommand(ctx.positional[0]);\n },\n examples: [\"corp config get\"],\n },\n {\n name: \"config list\",\n description: \"List all config (API keys masked)\",\n local: true,\n handler: async () => {\n const { configListCommand } = await import(\"../commands/config.js\");\n configListCommand();\n },\n examples: [\"corp config list\"],\n },\n\n // ── schema (local, special) ─────────────────────────────────────────\n {\n name: \"schema\",\n description: \"Dump the CLI command catalog as JSON\",\n local: true,\n options: [\n { flags: \"--compact\", description: \"Emit compact JSON\" },\n { flags: \"--web-routes\", description: \"Emit web-routes manifest instead of command schema\" },\n ],\n handler: async (ctx) => {\n const { registry, generateWebRoutes, generateSchema } = await import(\"../registry/index.js\");\n if (ctx.opts.webRoutes) {\n const manifest = generateWebRoutes(registry);\n console.log(JSON.stringify(manifest));\n return;\n }\n const { createRequire } = await import(\"node:module\");\n const require = createRequire(import.meta.url);\n let pkg: { version: string };\n try { pkg = require(\"../../package.json\"); } catch { pkg = require(\"../package.json\"); }\n const schema = generateSchema(registry, \"corp\", pkg.version);\n if (ctx.opts.compact) {\n console.log(JSON.stringify(schema));\n } else {\n ctx.writer.json(schema);\n }\n },\n examples: [\"corp schema\"],\n },\n\n // ── serve (local, complex) ──────────────────────────────────────────\n {\n name: \"serve\",\n description: \"Start the API server locally\",\n local: true,\n options: [\n { flags: \"--port <port>\", description: \"Port to listen on\", default: \"8000\" },\n { flags: \"--data-dir <path>\", description: \"Data directory\", default: \"./data/repos\" },\n ],\n handler: async (ctx) => {\n const { serveCommand } = await import(\"../commands/serve.js\");\n await serveCommand({\n port: (ctx.opts.port as string) ?? \"8000\",\n dataDir: (ctx.opts.dataDir as string) ?? \"./data/repos\",\n });\n },\n examples: [\"corp serve\"],\n },\n\n // ── demo (complex, uses API) ────────────────────────────────────────\n {\n name: \"demo\",\n description: \"Create a usable demo workspace environment\",\n local: true,\n options: [\n { flags: \"--name <name>\", description: \"Corporation name\", required: true },\n { flags: \"--scenario <scenario>\", description: \"Scenario to create (startup, llc, restaurant)\", default: \"startup\" },\n { flags: \"--minimal\", description: \"Use the minimal server-side demo seed instead of the full CLI workflow\" },\n { flags: \"--json\", description: \"Output as JSON\" },\n ],\n handler: async (ctx) => {\n const { demoCommand } = await import(\"../commands/demo.js\");\n await demoCommand({\n name: ctx.opts.name as string,\n scenario: ctx.opts.scenario as string | undefined,\n minimal: ctx.opts.minimal as boolean | undefined,\n json: ctx.opts.json as boolean | undefined,\n });\n },\n examples: [\"corp demo\"],\n },\n\n // ── chat (local, interactive) ───────────────────────────────────────\n {\n name: \"chat\",\n description: \"Interactive LLM chat session\",\n local: true,\n handler: async () => {\n const { chatCommand } = await import(\"../chat.js\");\n await chatCommand();\n },\n examples: [\"corp chat\"],\n },\n\n // ── api-keys (API, parent + subcommands) ────────────────────────────\n {\n name: \"api-keys\",\n description: \"API key management\",\n route: { method: \"GET\", path: \"/v1/api-keys\" },\n display: {\n title: \"API Keys\",\n cols: [\"name>Name\", \"key_prefix|prefix>Prefix\", \"@created_at>Created\", \"#api_key_id>ID\"],\n },\n handler: async (ctx) => {\n const { apiKeysListCommand } = await import(\"../commands/api-keys.js\");\n await apiKeysListCommand({ json: ctx.opts.json as boolean | undefined });\n },\n examples: [\"corp api-keys\"],\n },\n {\n name: \"api-keys create\",\n description: \"Create a new API key\",\n route: { method: \"POST\", path: \"/v1/api-keys\" },\n options: [\n { flags: \"--name <name>\", description: \"Key name/label\", required: true },\n { flags: \"--scopes <scopes>\", description: \"Comma-separated scopes\" },\n { flags: \"--json\", description: \"Output as JSON\" },\n ],\n handler: async (ctx) => {\n const { apiKeysCreateCommand } = await import(\"../commands/api-keys.js\");\n await apiKeysCreateCommand({\n name: ctx.opts.name as string,\n scopes: ctx.opts.scopes as string | undefined,\n json: ctx.opts.json as boolean | undefined,\n });\n },\n produces: { kind: \"api_key\" },\n successTemplate: \"API key created\",\n examples: [\"corp api-keys create --name 'name'\", \"corp api-keys create --json\"],\n },\n {\n name: \"api-keys revoke\",\n description: \"Revoke an API key\",\n route: { method: \"DELETE\", path: \"/v1/api-keys/{pos}\" },\n args: [\n { name: \"key-id\", required: true, description: \"API key ID to revoke\" },\n ],\n options: [\n { flags: \"--yes\", description: \"Skip confirmation\" },\n { flags: \"--json\", description: \"Output as JSON\" },\n ],\n handler: async (ctx) => {\n const { apiKeysRevokeCommand } = await import(\"../commands/api-keys.js\");\n await apiKeysRevokeCommand(ctx.positional[0], {\n yes: ctx.opts.yes as boolean | undefined,\n json: ctx.opts.json as boolean | undefined,\n });\n },\n examples: [\"corp api-keys revoke <key-id>\", \"corp api-keys revoke --json\"],\n },\n {\n name: \"api-keys rotate\",\n description: \"Rotate an API key (returns new key)\",\n route: { method: \"POST\", path: \"/v1/api-keys/{pos}/rotate\" },\n args: [\n { name: \"key-id\", required: true, description: \"API key ID to rotate\" },\n ],\n options: [\n { flags: \"--json\", description: \"Output as JSON\" },\n ],\n handler: async (ctx) => {\n const { apiKeysRotateCommand } = await import(\"../commands/api-keys.js\");\n await apiKeysRotateCommand(ctx.positional[0], {\n json: ctx.opts.json as boolean | undefined,\n });\n },\n produces: { kind: \"api_key\" },\n successTemplate: \"API key rotated\",\n examples: [\"corp api-keys rotate <key-id>\", \"corp api-keys rotate --json\"],\n },\n\n // ── link (API, write) ───────────────────────────────────────────────\n {\n name: \"link\",\n description: \"Link workspace to an external provider\",\n route: { method: \"POST\", path: \"/v1/workspaces/link\" },\n options: [\n { flags: \"--external-id <id>\", description: \"External ID to link\", required: true },\n { flags: \"--provider <provider>\", description: \"Provider name (e.g. stripe, github)\", required: true },\n ],\n handler: async (ctx) => {\n const { linkCommand } = await import(\"../commands/link.js\");\n await linkCommand({\n externalId: ctx.opts.externalId as string,\n provider: ctx.opts.provider as string,\n });\n },\n examples: [\"corp link --external-id 'id' --provider 'provider'\"],\n },\n\n // ── claim (API, write) ──────────────────────────────────────────────\n {\n name: \"claim\",\n description: \"Redeem a claim code to join a workspace\",\n route: { method: \"POST\", path: \"/v1/entities/claim\" },\n args: [\n { name: \"code\", required: true, description: \"Claim code to redeem\" },\n ],\n handler: async (ctx) => {\n const { claimCommand } = await import(\"../commands/claim.js\");\n await claimCommand(ctx.positional[0]);\n },\n produces: { kind: \"entity\", trackEntity: true },\n examples: [\"corp claim <code>\"],\n },\n\n // ── feedback (API, write) ───────────────────────────────────────────\n {\n name: \"feedback\",\n description: \"Submit feedback to TheCorporation\",\n route: { method: \"POST\", path: \"/v1/feedback\" },\n args: [\n { name: \"message\", required: true, description: \"Feedback message\" },\n ],\n options: [\n { flags: \"--category <category>\", description: \"Category (e.g. bug, feature, general)\", default: \"general\" },\n { flags: \"--email <email>\", description: \"Your email address (to receive a copy)\" },\n ],\n handler: async (ctx) => {\n const { feedbackCommand } = await import(\"../commands/feedback.js\");\n await feedbackCommand(ctx.positional[0], {\n category: ctx.opts.category as string | undefined,\n email: ctx.opts.email as string | undefined,\n json: ctx.opts.json as boolean | undefined,\n });\n },\n examples: [\"corp feedback <message>\", \"corp feedback --json\"],\n },\n\n // ── resolve (API, read) ─────────────────────────────────────────────\n {\n name: \"resolve\",\n description: \"Resolve a human-friendly reference to a canonical ID\",\n args: [\n { name: \"kind\", required: true, description: \"Resource kind to resolve\" },\n { name: \"ref\", required: true, description: \"Human-friendly reference\" },\n ],\n options: [\n { flags: \"--entity-id <ref>\", description: \"Entity reference for entity-scoped resources\" },\n { flags: \"--body-id <ref>\", description: \"Governance body reference for body-scoped resources\" },\n { flags: \"--meeting-id <ref>\", description: \"Meeting reference for meeting-scoped resources\" },\n ],\n handler: async (ctx) => {\n const { resolveCommand } = await import(\"../commands/resolve.js\");\n await resolveCommand(ctx.positional[0], ctx.positional[1], {\n entityId: ctx.opts.entityId as string | undefined,\n bodyId: ctx.opts.bodyId as string | undefined,\n meetingId: ctx.opts.meetingId as string | undefined,\n });\n },\n examples: [\"corp resolve\"],\n },\n\n // ── find (API, read) ────────────────────────────────────────────────\n {\n name: \"find\",\n description: \"List matching references for a resource kind\",\n args: [\n { name: \"kind\", required: true, description: \"Resource kind to search\" },\n { name: \"query\", required: true, description: \"Fuzzy search query\" },\n ],\n options: [\n { flags: \"--entity-id <ref>\", description: \"Entity reference for entity-scoped resources\" },\n { flags: \"--body-id <ref>\", description: \"Governance body reference for body-scoped resources\" },\n { flags: \"--meeting-id <ref>\", description: \"Meeting reference for meeting-scoped resources\" },\n { flags: \"--json\", description: \"Output as JSON\" },\n ],\n handler: async (ctx) => {\n const { findCommand } = await import(\"../commands/find.js\");\n await findCommand(ctx.positional[0], ctx.positional[1], {\n entityId: ctx.opts.entityId as string | undefined,\n bodyId: ctx.opts.bodyId as string | undefined,\n meetingId: ctx.opts.meetingId as string | undefined,\n json: ctx.opts.json as boolean | undefined,\n });\n },\n examples: [\"corp find\"],\n },\n\n // ── approvals (informational) ───────────────────────────────────────\n {\n name: \"approvals\",\n description: \"Approvals are managed through governance meetings and execution intents\",\n local: true,\n handler: async () => {\n process.stderr.write(\n \"Approvals are managed through governance meetings and execution intents.\\n\" +\n \"Use these commands to manage approvals:\\n\\n\" +\n \" Board approval via meeting vote:\\n\" +\n ' corp governance convene --body <body> --type board_meeting --title \"Approve X\"\\n' +\n \" corp governance vote <meeting> <item> --voter <contact> --vote for\\n\\n\" +\n \" Written consent (no meeting needed):\\n\" +\n ' corp governance written-consent --body <body> --title \"Approve X\" --description \"...\"\\n\\n' +\n \" View pending items:\\n\" +\n \" corp governance meetings <body> # see scheduled meetings\\n\" +\n \" corp governance agenda-items <meeting> # see items awaiting votes\\n\" +\n \" corp cap-table valuations # see pending valuations\\n\",\n );\n process.exit(1);\n },\n examples: [\"corp approvals\"],\n },\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"admin audit-events\",\n description: \"View audit log of workspace events\",\n route: { method: \"GET\", path: \"/v1/admin/audit-events\" },\n display: { title: \"Admin Audit Events\", cols: [\"details>Details\", \"#event_id>ID\", \"event_type>Event Type\", \"timestamp>Timestamp\"] },\n examples: [\"corp admin audit-events\"],\n },\n {\n name: \"admin system-health\",\n description: \"Check API server health and uptime\",\n route: { method: \"GET\", path: \"/v1/admin/system-health\" },\n display: { title: \"Admin System Health\", cols: [\"git_storage>Git Storage\", \"status>Status\", \"uptime_seconds>Uptime Seconds\", \"version>Version\", \"workspace_count>Workspace Count\"] },\n examples: [\"corp admin system-health\"],\n },\n {\n name: \"admin workspaces\",\n description: \"List all workspaces (admin)\",\n route: { method: \"GET\", path: \"/v1/admin/workspaces\" },\n display: { title: \"Admin Workspaces\", cols: [\"entity_count>Entity Count\", \"name>Name\", \"#workspace_id>ID\"] },\n examples: [\"corp admin workspaces\"],\n },\n {\n name: \"billing plans\",\n description: \"View available billing plans\",\n route: { method: \"GET\", path: \"/v1/billing/plans\" },\n display: { title: \"Billing Plans\", cols: [\"plans>Plans\"] },\n examples: [\"corp billing plans\"],\n },\n {\n name: \"billing status\",\n description: \"Check current billing and subscription status\",\n route: { method: \"GET\", path: \"/v1/billing/status\" },\n display: { title: \"Billing Status\", cols: [\"current_period_end>Current Period End\", \"plan>Plan\", \"status>Status\", \"#workspace_id>ID\"] },\n examples: [\"corp billing status\"],\n },\n {\n name: \"server-config\",\n description: \"View server configuration (environment, version, features)\",\n route: { method: \"GET\", path: \"/v1/config\" },\n display: { title: \"Server Config\", cols: [\"environment>Environment\", \"version>Version\", \"features>Features\"] },\n examples: [\"corp server-config\", \"corp server-config --json\"],\n },\n {\n name: \"demo seed\",\n description: \"Seed a demo workspace with sample data\",\n route: { method: \"POST\", path: \"/v1/demo/seed\" },\n options: [\n { flags: \"--name <name>\", description: \"Display name\" },\n { flags: \"--scenario <scenario>\", description: \"Demo scenario to use\" },\n ],\n examples: [\"corp demo seed\", \"corp demo seed --json\"],\n successTemplate: \"Seed created\",\n },\n {\n name: \"digests trigger\",\n description: \"Trigger digest generation now\",\n route: { method: \"POST\", path: \"/v1/digests/trigger\" },\n examples: [\"corp digests trigger\"],\n successTemplate: \"Trigger created\",\n },\n {\n name: \"digests\",\n description: \"View a specific digest by key\",\n route: { method: \"GET\", path: \"/v1/digests/{pos}\" },\n args: [{ name: \"digest-key\", required: true, description: \"Digest key\" }],\n display: { title: \"Digest\" },\n examples: [\"corp digests\"],\n },\n {\n name: \"service-token\",\n description: \"Get a service authentication token\",\n route: { method: \"GET\", path: \"/v1/service-token\" },\n display: { title: \"Service Token\", cols: [\"#api_key_id>ID\", \"expires_in>Expires In\", \"token>Token\", \"token_type>Token Type\"] },\n examples: [\"corp service-token\"],\n },\n {\n name: \"workspace entities\",\n description: \"List entities in current workspace\",\n route: { method: \"GET\", path: \"/v1/workspace/entities\" },\n display: { title: \"Workspace Entities\", cols: [\"#entity_id>ID\"] },\n examples: [\"corp workspace entities\"],\n },\n {\n name: \"workspace status\",\n description: \"Show current workspace status\",\n route: { method: \"GET\", path: \"/v1/workspace/status\" },\n display: { title: \"Workspace Status\", cols: [\"entity_count>Entity Count\", \"name>Name\", \"status>Status\", \"#workspace_id>ID\"] },\n examples: [\"corp workspace status\"],\n },\n {\n name: \"workspaces claim\",\n description: \"Claim a workspace using a claim token\",\n route: { method: \"POST\", path: \"/v1/workspaces/claim\" },\n options: [\n { flags: \"--claim-token <claim-token>\", description: \"Workspace claim token\", required: true },\n ],\n examples: [\"corp workspaces claim --claim-token 'claim-token'\"],\n successTemplate: \"Claim created\",\n },\n {\n name: \"workspaces contacts\",\n description: \"List contacts across the workspace\",\n route: { method: \"GET\", path: \"/v1/workspaces/{workspace_id}/contacts\" },\n display: { title: \"Workspaces Contacts\", cols: [\"#contact_id>ID\", \"#entity_id>ID\"] },\n examples: [\"corp workspaces contacts\"],\n },\n {\n name: \"workspaces entities\",\n description: \"List all entities in a workspace\",\n route: { method: \"GET\", path: \"/v1/workspaces/{workspace_id}/entities\" },\n display: { title: \"Workspaces Entities\", cols: [\"#entity_id>ID\"] },\n examples: [\"corp workspaces entities\"],\n },\n\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"auth token-exchange\",\n description: \"Exchange an API key for a short-lived JWT\",\n route: { method: \"POST\", path: \"/v1/auth/token-exchange\" },\n options: [\n { flags: \"--api-key <api-key>\", description: \"API key (starts with sk_)\", required: true },\n { flags: \"--ttl-seconds <ttl-seconds>\", description: \"Token TTL in seconds (60-86400)\", type: \"int\" },\n ],\n examples: [\"corp auth token-exchange --api-key 'api-key'\", \"corp auth token-exchange --json\"],\n successTemplate: \"Token Exchange created\",\n },\n {\n name: \"ssh-keys\",\n description: \"List registered SSH public keys\",\n route: { method: \"GET\", path: \"/v1/ssh-keys\" },\n display: { title: \"SSH Keys\", cols: [\"name>Name\", \"algorithm>Algorithm\", \"fingerprint>Fingerprint\", \"@created_at>Created\", \"#key_id>ID\"] },\n examples: [\"corp ssh-keys\"],\n },\n {\n name: \"ssh-keys add\",\n description: \"Register a new SSH public key\",\n route: { method: \"POST\", path: \"/v1/ssh-keys\" },\n options: [\n { flags: \"--name <name>\", description: \"Key name/label\", required: true },\n { flags: \"--public-key <key>\", description: \"SSH public key in OpenSSH format\", required: true },\n { flags: \"--scopes <scopes>\", description: \"Comma-separated scopes (e.g. git_read,git_write)\", type: \"array\" },\n { flags: \"--entity-ids <ids>\", description: \"Restrict key to specific entity IDs\" },\n { flags: \"--contact-id <id>\", description: \"Associate with a contact\" },\n ],\n examples: [\"corp ssh-keys add --name laptop --public-key 'ssh-ed25519 AAAA...'\", \"corp ssh-keys add --name ci --public-key 'ssh-ed25519 AAAA...' --scopes git_read,git_write\"],\n successTemplate: \"SSH key {name} added ({fingerprint})\",\n },\n {\n name: \"ssh-keys revoke\",\n description: \"Revoke an SSH public key\",\n route: { method: \"DELETE\", path: \"/v1/ssh-keys/{pos}\" },\n args: [{ name: \"key-id\", required: true, description: \"SSH key ID to revoke\" }],\n examples: [\"corp ssh-keys revoke <key-id>\"],\n successTemplate: \"SSH key revoked\",\n },\n {\n name: \"workspaces provision\",\n description: \"Provision a new workspace\",\n route: { method: \"POST\", path: \"/v1/workspaces/provision\" },\n options: [\n { flags: \"--name <name>\", description: \"Display name\", required: true },\n { flags: \"--owner-email <owner-email>\", description: \"Workspace owner email address\" },\n ],\n examples: [\"corp workspaces provision --name 'name'\", \"corp workspaces provision --json\"],\n successTemplate: \"Provision created\",\n },\n\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"references sync\",\n description: \"Sync reference aliases for a resource kind\",\n route: { method: \"POST\", path: \"/v1/references/sync\" },\n options: [\n { flags: \"--items <items>\", description: \"Items to sync (JSON array)\", required: true, type: \"array\" },\n { flags: \"--kind <kind>\", description: \"Resource kind\", required: true, choices: [\"entity\", \"contact\", \"share_transfer\", \"invoice\", \"bank_account\", \"payment\", \"payroll_run\", \"distribution\", \"reconciliation\", \"tax_filing\", \"deadline\", \"classification\", \"body\", \"meeting\", \"seat\", \"agenda_item\", \"resolution\", \"document\", \"work_item\", \"agent\", \"valuation\", \"safe_note\", \"instrument\", \"share_class\", \"round\"] },\n ],\n examples: [\"corp references sync --items 'items' --kind 'kind'\"],\n successTemplate: \"Sync created\",\n },\n\n\n // ── Auto-generated from OpenAPI ──────────────────────────────\n {\n name: \"secrets interpolate\",\n description: \"Interpolate secrets into a template string\",\n route: { method: \"POST\", path: \"/v1/secrets/interpolate\" },\n options: [\n { flags: \"--execution-id <execution-id>\", description: \"Agent execution ID\", required: true },\n { flags: \"--template <template>\", description: \"Template string with {{secret}} placeholders\", required: true },\n ],\n examples: [\"corp secrets interpolate --execution-id 'execution-id' --template 'template'\"],\n successTemplate: \"Interpolate created\",\n },\n {\n name: \"secrets resolve\",\n description: \"Resolve a secrets token to its values\",\n route: { method: \"POST\", path: \"/v1/secrets/resolve\" },\n options: [\n { flags: \"--token <token>\", description: \"Secrets access token\", required: true },\n ],\n examples: [\"corp secrets resolve --token 'token'\"],\n successTemplate: \"Resolve created\",\n },\n\n {\n name: \"documents validate-preview\",\n description: \"Validate a document preview without generating PDF\",\n route: { method: \"GET\", path: \"/v1/documents/preview/pdf/validate\" },\n entity: true,\n display: { title: \"Document Preview Validation\" },\n examples: [\"corp documents validate-preview\", \"corp documents validate-preview --json\"],\n },\n];\n","import type { CommandDef } from \"./types.js\";\n\nexport const executionCommands: CommandDef[] = [\n {\n name: \"document-requests fulfill\",\n description: \"Fulfill a document request with uploaded content\",\n route: { method: \"PATCH\", path: \"/v1/document-requests/{pos}/fulfill\" },\n entity: true,\n args: [{ name: \"request-id\", required: true, description: \"Document request ID\" }],\n examples: [\"corp document-requests fulfill <request-id>\"],\n successTemplate: \"Fulfill updated\",\n },\n {\n name: \"document-requests not-applicable\",\n description: \"Mark a document request as not applicable\",\n route: { method: \"PATCH\", path: \"/v1/document-requests/{pos}/not-applicable\" },\n entity: true,\n args: [{ name: \"request-id\", required: true, description: \"Document request ID\" }],\n examples: [\"corp document-requests not-applicable <request-id>\"],\n successTemplate: \"Not Applicable updated\",\n },\n {\n name: \"entities approval-artifacts\",\n description: \"List approval artifacts for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/approval-artifacts\" },\n entity: true,\n display: { title: \"Entities Approval Artifacts\", cols: [\"approved_at>Approved At\", \"approver_identity>Approver Identity\", \"channel>Channel\", \"expires_at>Expires At\", \"@created_at>Created At\", \"#approval_artifact_id>ID\"] },\n examples: [\"corp entities approval-artifacts\", \"corp entities approval-artifacts --json\"],\n },\n {\n name: \"entities intents\",\n description: \"List execution intents for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/intents\" },\n entity: true,\n display: { title: \"Entities Intents\", cols: [\"authority_tier>Authority Tier\", \"authorized_at>Authorized At\", \"bound_document_request_ids>Bound Document Request Ids\", \"cancelled_at>Cancelled At\", \"@created_at>Created At\", \"#bound_approval_artifact_id>ID\"] },\n examples: [\"corp entities intents\", \"corp entities intents --json\"],\n },\n {\n name: \"entities obligations\",\n description: \"List obligations for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/obligations\" },\n entity: true,\n display: { title: \"Entities Obligations\", cols: [\"assignee_type>Assignee Type\", \"description>Description\", \"expired_at>Expired At\", \"fulfilled_at>Fulfilled At\", \"@created_at>Created At\", \"#assignee_id>ID\"] },\n examples: [\"corp entities obligations\", \"corp entities obligations --json\"],\n },\n {\n name: \"entities obligations-human\",\n description: \"List human-actionable obligations for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/obligations/human\" },\n entity: true,\n display: { title: \"Entities Obligations Human\", cols: [\"assignee_type>Assignee Type\", \"description>Description\", \"expired_at>Expired At\", \"fulfilled_at>Fulfilled At\", \"@created_at>Created At\", \"#assignee_id>ID\"] },\n examples: [\"corp entities obligations-human\", \"corp entities obligations-human --json\"],\n },\n {\n name: \"entities obligations-summary\",\n description: \"View obligation summary (pending/fulfilled/expired)\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/obligations/summary\" },\n entity: true,\n display: { title: \"Entities Obligations Summary\", cols: [\"expired>Expired\", \"fulfilled>Fulfilled\", \"pending>Pending\", \"total>Total\", \"waived>Waived\"] },\n examples: [\"corp entities obligations-summary\", \"corp entities obligations-summary --json\"],\n },\n {\n name: \"entities packets\",\n description: \"List document packets for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/packets\" },\n entity: true,\n display: { title: \"Entities Packets\", cols: [\"finalized_at>Finalized At\", \"items>Items\", \"manifest_hash>Manifest Hash\", \"required_signers>Required Signers\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp entities packets\", \"corp entities packets --json\"],\n },\n {\n name: \"execution approval-artifacts\",\n description: \"Create an approval artifact (e.g. board vote record)\",\n route: { method: \"POST\", path: \"/v1/execution/approval-artifacts\" },\n entity: true,\n options: [\n { flags: \"--approved-at <approved-at>\", description: \"Timestamp of approval (ISO 8601)\" },\n { flags: \"--approver-identity <approver-identity>\", description: \"Identity of the approver\", required: true },\n { flags: \"--channel <channel>\", description: \"Approval channel (board_vote, written_consent, etc.)\", required: true },\n { flags: \"--expires-at <expires-at>\", description: \"Expiration timestamp (ISO 8601)\" },\n { flags: \"--explicit\", description: \"Whether approval is explicit (vs implied)\" },\n { flags: \"--intent-type <intent-type>\", description: \"Type of intent\", required: true },\n { flags: \"--max-amount-cents <max-amount-cents>\", description: \"Maximum authorized amount in cents\" },\n { flags: \"--scope <scope>\", description: \"Authorization scope\", required: true },\n ],\n examples: [\"corp execution approval-artifacts --approver-identity 'approver-identity' --channel 'channel' --intent-type 'intent-type' --scope 'scope'\", \"corp execution approval-artifacts --json\"],\n successTemplate: \"Approval Artifacts created\",\n },\n {\n name: \"execution intents\",\n description: \"Create an execution intent (action requiring authorization)\",\n route: { method: \"POST\", path: \"/v1/execution/intents\" },\n entity: true,\n options: [\n { flags: \"--authority-tier <authority-tier>\", description: \"Authority tier required (tier_1, tier_2, tier_3)\", choices: [\"tier_1\", \"tier_2\", \"tier_3\"] },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--intent-type <intent-type>\", description: \"Type of intent\", required: true },\n { flags: \"--metadata <metadata>\", description: \"Additional metadata (JSON)\" },\n ],\n examples: [\"corp execution intents --description 'description' --intent-type 'intent-type'\", \"corp execution intents --json\"],\n successTemplate: \"Intents created\",\n },\n {\n name: \"execution obligations\",\n description: \"Create an obligation (task assigned to a party)\",\n route: { method: \"POST\", path: \"/v1/execution/obligations\" },\n entity: true,\n options: [\n { flags: \"--assignee-id <assignee-id>\", description: \"ID of the party to assign to\" },\n { flags: \"--assignee-type <assignee-type>\", description: \"Who is responsible for fulfilling an obligation.\", required: true, choices: [\"internal\", \"third_party\", \"human\"] },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--due-date <due-date>\", description: \"Due date (ISO 8601, e.g. 2026-06-30)\" },\n { flags: \"--intent-id <intent-id>\", description: \"Execution intent ID\" },\n { flags: \"--obligation-type <obligation-type>\", description: \"Type of obligation\", required: true },\n ],\n examples: [\"corp execution obligations --assignee-type internal --description 'description' --obligation-type 'obligation-type'\", \"corp execution obligations --json\"],\n successTemplate: \"Obligations created\",\n },\n {\n name: \"execution packets\",\n description: \"View a document packet\",\n route: { method: \"GET\", path: \"/v1/execution/packets/{pos}\" },\n entity: true,\n args: [{ name: \"packet-id\", required: true, description: \"Document packet ID\" }],\n display: { title: \"Execution Packets\", cols: [\"finalized_at>Finalized At\", \"items>Items\", \"manifest_hash>Manifest Hash\", \"required_signers>Required Signers\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp execution packets\", \"corp execution packets --json\"],\n },\n {\n name: \"intents authorize\",\n description: \"Authorize an execution intent\",\n route: { method: \"POST\", path: \"/v1/intents/{pos}/authorize\" },\n entity: true,\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n examples: [\"corp intents authorize <intent-id>\"],\n successTemplate: \"Authorize created\",\n },\n {\n name: \"intents bind-approval-artifact\",\n description: \"Bind an approval artifact to an intent\",\n route: { method: \"POST\", path: \"/v1/intents/{pos}/bind-approval-artifact\" },\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n options: [\n { flags: \"--approval-artifact-id <approval-artifact-id>\", description: \"Approval artifact ID to bind\", required: true },\n ],\n examples: [\"corp intents bind-approval-artifact <intent-id> --approval-artifact-id 'approval-artifact-id'\"],\n successTemplate: \"Bind Approval Artifact created\",\n },\n {\n name: \"intents bind-document-request\",\n description: \"Bind a document request to an intent\",\n route: { method: \"POST\", path: \"/v1/intents/{pos}/bind-document-request\" },\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n options: [\n { flags: \"--request-id <request-id>\", description: \"Document request ID\", required: true },\n ],\n examples: [\"corp intents bind-document-request <intent-id> --request-id 'request-id'\"],\n successTemplate: \"Bind Document Request created\",\n },\n {\n name: \"intents cancel\",\n description: \"Cancel an execution intent\",\n route: { method: \"POST\", path: \"/v1/intents/{pos}/cancel\" },\n entity: true,\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n examples: [\"corp intents cancel <intent-id>\"],\n successTemplate: \"Cancel created\",\n },\n {\n name: \"intents evaluate\",\n description: \"Evaluate whether an intent meets its requirements\",\n route: { method: \"POST\", path: \"/v1/intents/{pos}/evaluate\" },\n entity: true,\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n examples: [\"corp intents evaluate <intent-id>\"],\n successTemplate: \"Evaluate created\",\n },\n {\n name: \"intents execute\",\n description: \"Execute an authorized intent\",\n route: { method: \"POST\", path: \"/v1/intents/{pos}/execute\" },\n entity: true,\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n examples: [\"corp intents execute <intent-id>\"],\n successTemplate: \"Execute created\",\n },\n {\n name: \"intents receipts\",\n description: \"View execution receipts for an intent\",\n route: { method: \"GET\", path: \"/v1/intents/{pos}/receipts\" },\n entity: true,\n args: [{ name: \"intent-id\", required: true, description: \"Execution intent ID\" }],\n display: { title: \"Intents Receipts\", cols: [\"executed_at>Executed At\", \"idempotency_key>Idempotency Key\", \"request_hash>Request Hash\", \"response_hash>Response Hash\", \"@created_at>Created At\", \"#intent_id>ID\"] },\n examples: [\"corp intents receipts\", \"corp intents receipts --json\"],\n },\n {\n name: \"obligations assign\",\n description: \"Assign an obligation to a party\",\n route: { method: \"POST\", path: \"/v1/obligations/{pos}/assign\" },\n entity: true,\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n options: [\n { flags: \"--assignee-id <assignee-id>\", description: \"ID of the party to assign to\", required: true },\n ],\n examples: [\"corp obligations assign <obligation-id> --assignee-id 'assignee-id'\"],\n successTemplate: \"Assign created\",\n },\n {\n name: \"obligations document-requests\",\n description: \"List or create document requests for an obligation\",\n route: { method: \"GET\", path: \"/v1/obligations/{pos}/document-requests\" },\n entity: true,\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n display: { title: \"Obligations Document Requests\", cols: [\"description>Description\", \"document_type>Document Type\", \"fulfilled_at>Fulfilled At\", \"not_applicable_at>Not Applicable At\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp obligations document-requests\", \"corp obligations document-requests --json\"],\n },\n {\n name: \"obligations create-document-request\",\n description: \"List or create document requests for an obligation\",\n route: { method: \"POST\", path: \"/v1/obligations/{pos}/document-requests\" },\n entity: true,\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n options: [\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--document-type <document-type>\", description: \"Type of document required\", required: true },\n ],\n examples: [\"corp obligations document-requests <obligation-id> --description 'description' --document-type 'document-type'\"],\n successTemplate: \"Document Requests created\",\n },\n {\n name: \"obligations expire\",\n description: \"Mark an obligation as expired\",\n route: { method: \"POST\", path: \"/v1/obligations/{pos}/expire\" },\n entity: true,\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n examples: [\"corp obligations expire <obligation-id>\"],\n successTemplate: \"Expire created\",\n },\n {\n name: \"obligations fulfill\",\n description: \"Mark an obligation as fulfilled\",\n route: { method: \"POST\", path: \"/v1/obligations/{pos}/fulfill\" },\n entity: true,\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n examples: [\"corp obligations fulfill <obligation-id>\"],\n successTemplate: \"Fulfill created\",\n },\n {\n name: \"obligations waive\",\n description: \"Waive an obligation\",\n route: { method: \"POST\", path: \"/v1/obligations/{pos}/waive\" },\n entity: true,\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n examples: [\"corp obligations waive <obligation-id>\"],\n successTemplate: \"Waive created\",\n },\n {\n name: \"receipts\",\n description: \"View an execution receipt\",\n route: { method: \"GET\", path: \"/v1/receipts/{pos}\" },\n entity: true,\n args: [{ name: \"receipt-id\", required: true, description: \"Execution receipt ID\" }],\n display: { title: \"Receipts\", cols: [\"executed_at>Executed At\", \"idempotency_key>Idempotency Key\", \"request_hash>Request Hash\", \"response_hash>Response Hash\", \"@created_at>Created At\", \"#intent_id>ID\"] },\n examples: [\"corp receipts\", \"corp receipts --json\"],\n },\n\n // ── Human obligations ───────────────────────────────────────────────\n {\n name: \"human-obligations\",\n description: \"List obligations requiring human action (signing, upload)\",\n route: { method: \"GET\", path: \"/v1/human-obligations\" },\n display: {\n title: \"Human Obligations\",\n cols: [\"obligation_type>Type\", \"status>Status\", \"@due_at>Due\", \"#obligation_id>ID\"],\n },\n examples: [\"corp human-obligations\"],\n },\n {\n name: \"human-obligations fulfill\",\n description: \"Fulfill a human obligation\",\n route: { method: \"POST\", path: \"/v1/human-obligations/{pos}/fulfill\" },\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n successTemplate: \"Obligation fulfilled\",\n examples: [\"corp human-obligations fulfill <obligation-id>\"],\n },\n {\n name: \"human-obligations signer-token\",\n description: \"Get a signing token for a human obligation\",\n route: { method: \"POST\", path: \"/v1/human-obligations/{pos}/signer-token\" },\n args: [{ name: \"obligation-id\", required: true, description: \"Obligation ID\" }],\n successTemplate: \"Signer token issued\",\n examples: [\"corp human-obligations signer-token <obligation-id>\"],\n },\n];","import type { CommandDef } from \"./types.js\";\n\nexport const secretProxyCommands: CommandDef[] = [\n {\n name: \"secret-proxies\",\n description: \"List secret proxies for the workspace\",\n route: { method: \"GET\", path: \"/v1/workspaces/{wid}/secret-proxies\" },\n display: {\n title: \"Secret Proxies\",\n cols: [\"name>Name\", \"url>URL\", \"description>Description\", \"secret_count>Secrets\", \"@created_at>Created\"],\n },\n examples: [\"corp secret-proxies\"],\n },\n {\n name: \"secret-proxies create\",\n description: \"Create a secret proxy\",\n route: { method: \"POST\", path: \"/v1/workspaces/{wid}/secret-proxies\" },\n options: [\n { flags: \"--name <name>\", description: \"Proxy name\", required: true },\n { flags: \"--url <url>\", description: \"Proxy URL (or 'self' for local encrypted secrets)\", required: true },\n { flags: \"--description <desc>\", description: \"Description text\" },\n ],\n successTemplate: \"Secret proxy {name} created\",\n examples: [\"corp secret-proxies create --name 'name' --url 'url'\", \"corp secret-proxies create --json\"],\n },\n {\n name: \"secret-proxies show\",\n description: \"Show a secret proxy\",\n route: { method: \"GET\", path: \"/v1/workspaces/{wid}/secret-proxies/{pos}\" },\n args: [{ name: \"proxy-name\", required: true, description: \"Proxy name\" }],\n display: {\n title: \"Secret Proxy\",\n cols: [\"name>Name\", \"url>URL\", \"description>Description\", \"secret_count>Secrets\", \"@created_at>Created\"],\n },\n examples: [\"corp secret-proxies show\"],\n },\n {\n name: \"secret-proxies secrets\",\n description: \"List secret names in a proxy\",\n route: { method: \"GET\", path: \"/v1/workspaces/{wid}/secret-proxies/{pos}/secrets\" },\n args: [{ name: \"proxy-name\", required: true, description: \"Proxy name\" }],\n display: {\n title: \"Secrets\",\n cols: [\"names>Secret Names\", \"proxy_name>Proxy\"],\n },\n examples: [\"corp secret-proxies secrets\"],\n },\n {\n name: \"secret-proxies set-secrets\",\n description: \"Set secrets in a proxy (key-value pairs, server encrypts)\",\n route: { method: \"PUT\", path: \"/v1/workspaces/{wid}/secret-proxies/{pos}/secrets\" },\n args: [{ name: \"proxy-name\", required: true, description: \"Proxy name\" }],\n options: [\n { flags: \"--secrets <json>\", description: \"JSON object of key-value secret pairs\", required: true },\n ],\n successTemplate: \"Secrets updated for {proxy_name}\",\n examples: [\"corp secret-proxies set-secrets <proxy-name> --secrets 'json'\"],\n },\n];","import type { CommandDef } from \"./types.js\";\n\nexport const treasuryCommands: CommandDef[] = [\n {\n name: \"bank-accounts close\",\n description: \"Close a bank account\",\n route: { method: \"POST\", path: \"/v1/bank-accounts/{pos}/close\" },\n entity: true,\n args: [{ name: \"bank-account-id\", required: true, description: \"Bank account ID\" }],\n examples: [\"corp bank-accounts close <bank-account-id>\"],\n successTemplate: \"Close created\",\n },\n {\n name: \"distributions\",\n description: \"Record a distribution (dividend, member draw)\",\n route: { method: \"POST\", path: \"/v1/distributions\" },\n options: [\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--distribution-type <distribution-type>\", description: \"Type of distribution.\", choices: [\"dividend\", \"return\", \"liquidation\"] },\n { flags: \"--total-amount-cents <total-amount-cents>\", description: \"Total Amount Cents\", required: true, type: \"int\" },\n ],\n examples: [\"corp distributions --description dividend --total-amount-cents 'total-amount-cents'\", \"corp distributions --json\"],\n successTemplate: \"Distributions created\",\n },\n {\n name: \"entities accounts\",\n description: \"List ledger accounts for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/accounts\" },\n entity: true,\n display: { title: \"Entities Accounts\", cols: [\"account_code>Account Code\", \"account_name>Account Name\", \"account_type>Account Type\", \"currency>Currency\", \"@created_at>Created At\", \"#account_id>ID\"] },\n examples: [\"corp entities accounts\", \"corp entities accounts --json\"],\n },\n {\n name: \"entities journal-entries\",\n description: \"List journal entries for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/journal-entries\" },\n entity: true,\n display: { title: \"Entities Journal Entries\", cols: [\"description>Description\", \"effective_date>Effective Date\", \"status>Status\", \"total_credits_cents>Total Credits Cents\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp entities journal-entries\", \"corp entities journal-entries --json\"],\n },\n {\n name: \"entities spending-limits\",\n description: \"List spending limits for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/spending-limits\" },\n entity: true,\n display: { title: \"Entities Spending Limits\", cols: [\"amount_cents>Amount Cents\", \"category>Category\", \"@created_at>Created At\", \"#entity_id>ID\", \"period>Period\", \"#spending_limit_id>ID\"] },\n examples: [\"corp entities spending-limits\", \"corp entities spending-limits --json\"],\n },\n {\n name: \"entities stripe-account\",\n description: \"View Stripe account for an entity\",\n route: { method: \"GET\", path: \"/v1/entities/{eid}/stripe-account\" },\n entity: true,\n display: { title: \"Entities Stripe Account\", cols: [\"@created_at>Created At\", \"#entity_id>ID\", \"status>Status\", \"#stripe_account_id>ID\"] },\n examples: [\"corp entities stripe-account\", \"corp entities stripe-account --json\"],\n },\n {\n name: \"invoices from-agent-request\",\n description: \"Create an invoice from an agent request\",\n route: { method: \"POST\", path: \"/v1/invoices/from-agent-request\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--customer-name <customer-name>\", description: \"Customer name for the invoice\", required: true },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--due-date <due-date>\", description: \"Due date (ISO 8601, e.g. 2026-06-30)\", required: true },\n ],\n examples: [\"corp invoices from-agent-request --amount-cents 'amount-cents' --customer-name 'customer-name' --description 'description' --due-date 'due-date'\"],\n successTemplate: \"From Agent Request created\",\n },\n {\n name: \"invoices\",\n description: \"Create a new invoice\",\n route: { method: \"GET\", path: \"/v1/invoices/{pos}\" },\n entity: true,\n args: [{ name: \"invoice-id\", required: true, description: \"Invoice ID\" }],\n display: { title: \"Invoices\", cols: [\"amount_cents>Amount Cents\", \"customer_name>Customer Name\", \"description>Description\", \"status>Status\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp invoices\", \"corp invoices --json\"],\n },\n {\n name: \"invoices mark-paid\",\n description: \"Mark an invoice as paid\",\n route: { method: \"POST\", path: \"/v1/invoices/{pos}/mark-paid\" },\n entity: true,\n args: [{ name: \"invoice-id\", required: true, description: \"Invoice ID\" }],\n examples: [\"corp invoices mark-paid <invoice-id>\"],\n successTemplate: \"Mark Paid created\",\n },\n {\n name: \"invoices pay-instructions\",\n description: \"Get payment instructions for an invoice\",\n route: { method: \"GET\", path: \"/v1/invoices/{pos}/pay-instructions\" },\n entity: true,\n args: [{ name: \"invoice-id\", required: true, description: \"Invoice ID\" }],\n display: { title: \"Invoices Pay Instructions\", cols: [\"amount_cents>Amount Cents\", \"currency>Currency\", \"instructions>Instructions\", \"#invoice_id>ID\", \"payment_method>Payment Method\"] },\n examples: [\"corp invoices pay-instructions\", \"corp invoices pay-instructions --json\"],\n },\n {\n name: \"invoices send\",\n description: \"Send an invoice to the recipient\",\n route: { method: \"POST\", path: \"/v1/invoices/{pos}/send\" },\n entity: true,\n args: [{ name: \"invoice-id\", required: true, description: \"Invoice ID\" }],\n examples: [\"corp invoices send <invoice-id>\"],\n successTemplate: \"Send created\",\n },\n {\n name: \"invoices status\",\n description: \"Check invoice payment status\",\n route: { method: \"GET\", path: \"/v1/invoices/{pos}/status\" },\n entity: true,\n args: [{ name: \"invoice-id\", required: true, description: \"Invoice ID\" }],\n display: { title: \"Invoices Status\", cols: [\"amount_cents>Amount Cents\", \"customer_name>Customer Name\", \"description>Description\", \"status>Status\", \"@created_at>Created At\", \"#entity_id>ID\"] },\n examples: [\"corp invoices status\", \"corp invoices status --json\"],\n },\n {\n name: \"journal-entries post\",\n description: \"Post a journal entry (make it permanent)\",\n route: { method: \"POST\", path: \"/v1/journal-entries/{pos}/post\" },\n entity: true,\n args: [{ name: \"entry-id\", required: true, description: \"Journal entry ID\" }],\n examples: [\"corp journal-entries post <entry-id>\"],\n successTemplate: \"Post created\",\n },\n {\n name: \"journal-entries void\",\n description: \"Void a journal entry\",\n route: { method: \"POST\", path: \"/v1/journal-entries/{pos}/void\" },\n entity: true,\n args: [{ name: \"entry-id\", required: true, description: \"Journal entry ID\" }],\n examples: [\"corp journal-entries void <entry-id>\"],\n successTemplate: \"Void created\",\n },\n {\n name: \"ledger reconcile\",\n description: \"Reconcile the ledger\",\n route: { method: \"POST\", path: \"/v1/ledger/reconcile\" },\n entity: true,\n options: [\n { flags: \"--as-of-date <as-of-date>\", description: \"As Of Date\" },\n { flags: \"--end-date <end-date>\", description: \"End Date\" },\n { flags: \"--start-date <start-date>\", description: \"Start Date\" },\n ],\n examples: [\"corp ledger reconcile\", \"corp ledger reconcile --json\"],\n successTemplate: \"Reconcile created\",\n },\n {\n name: \"payments\",\n description: \"Record a new payment\",\n route: { method: \"POST\", path: \"/v1/payments\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--payment-method <payment-method>\", description: \"How a payment is made or received.\", choices: [\"bank_transfer\", \"card\", \"check\", \"wire\", \"ach\"] },\n { flags: \"--recipient <recipient>\", description: \"Recipient\", required: true },\n ],\n examples: [\"corp payments --amount-cents 'amount-cents' --description bank_transfer --recipient 'recipient'\", \"corp payments --json\"],\n successTemplate: \"Payments created\",\n },\n {\n name: \"payments execute\",\n description: \"Execute a pending payment\",\n route: { method: \"POST\", path: \"/v1/payments/execute\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--payment-method <payment-method>\", description: \"How a payment is made or received.\", choices: [\"bank_transfer\", \"card\", \"check\", \"wire\", \"ach\"] },\n { flags: \"--recipient <recipient>\", description: \"Recipient\", required: true },\n ],\n examples: [\"corp payments execute --amount-cents 'amount-cents' --description bank_transfer --recipient 'recipient'\", \"corp payments execute --json\"],\n successTemplate: \"Execute created\",\n },\n {\n name: \"payroll runs\",\n description: \"Create a payroll run\",\n route: { method: \"POST\", path: \"/v1/payroll/runs\" },\n entity: true,\n options: [\n { flags: \"--pay-period-end <pay-period-end>\", description: \"Pay Period End\", required: true },\n { flags: \"--pay-period-start <pay-period-start>\", description: \"Pay Period Start\", required: true },\n ],\n examples: [\"corp payroll runs --pay-period-end 'pay-period-end' --pay-period-start 'pay-period-start'\"],\n successTemplate: \"Runs created\",\n },\n {\n name: \"spending-limits\",\n description: \"Set a spending limit\",\n route: { method: \"POST\", path: \"/v1/spending-limits\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--category <category>\", description: \"Category\", required: true },\n { flags: \"--period <period>\", description: \"Period\", required: true },\n ],\n examples: [\"corp spending-limits --amount-cents 'amount-cents' --category 'category' --period 'period'\"],\n successTemplate: \"Spending Limits created\",\n },\n {\n name: \"treasury accounts\",\n description: \"Create a new ledger account\",\n route: { method: \"POST\", path: \"/v1/treasury/accounts\" },\n entity: true,\n options: [\n { flags: \"--account-code <account-code>\", description: \"Standard GL account codes with integer discriminants matching the code number.\", required: true, choices: [\"Cash\", \"AccountsReceivable\", \"AccountsPayable\", \"AccruedExpenses\", \"FounderCapital\", \"Revenue\", \"OperatingExpenses\", \"Cogs\"] },\n ],\n examples: [\"corp treasury accounts --account-code Cash\"],\n successTemplate: \"Accounts created\",\n },\n {\n name: \"treasury bank-accounts\",\n description: \"Register a new bank account\",\n route: { method: \"POST\", path: \"/v1/treasury/bank-accounts\" },\n entity: true,\n options: [\n { flags: \"--account-type <account-type>\", description: \"Account type (checking, savings)\", choices: [\"checking\", \"savings\"] },\n { flags: \"--bank-name <bank-name>\", description: \"Bank name\", required: true },\n ],\n examples: [\"corp treasury bank-accounts --bank-name 'bank-name'\", \"corp treasury bank-accounts --json\"],\n successTemplate: \"Bank Accounts created\",\n },\n {\n name: \"treasury chart-of-accounts\",\n description: \"View chart of accounts for an entity\",\n route: { method: \"GET\", path: \"/v1/treasury/chart-of-accounts/{eid}\" },\n entity: true,\n display: { title: \"Treasury Chart Of Accounts\", cols: [\"accounts>Accounts\", \"#entity_id>ID\"] },\n examples: [\"corp treasury chart-of-accounts\", \"corp treasury chart-of-accounts --json\"],\n },\n {\n name: \"treasury invoices\",\n description: \"Create a new invoice\",\n route: { method: \"POST\", path: \"/v1/treasury/invoices\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--customer-name <customer-name>\", description: \"Customer name for the invoice\", required: true },\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--due-date <due-date>\", description: \"Due date (ISO 8601, e.g. 2026-06-30)\", required: true },\n ],\n examples: [\"corp treasury invoices --amount-cents 'amount-cents' --customer-name 'customer-name' --description 'description' --due-date 'due-date'\"],\n successTemplate: \"Invoices created\",\n },\n {\n name: \"treasury journal-entries\",\n description: \"Create a journal entry\",\n route: { method: \"POST\", path: \"/v1/treasury/journal-entries\" },\n entity: true,\n options: [\n { flags: \"--description <description>\", description: \"Description text\", required: true },\n { flags: \"--effective-date <effective-date>\", description: \"Effective Date\", required: true },\n { flags: \"--lines <lines>\", description: \"Lines\", required: true, type: \"array\" },\n ],\n examples: [\"corp treasury journal-entries --description 'description' --effective-date 'effective-date' --lines 'lines'\"],\n successTemplate: \"Journal Entries created\",\n },\n {\n name: \"treasury payment-intents\",\n description: \"Create a payment intent\",\n route: { method: \"POST\", path: \"/v1/treasury/payment-intents\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--currency <currency>\", description: \"Currency code (e.g. USD)\" },\n { flags: \"--description <description>\", description: \"Description text\" },\n ],\n examples: [\"corp treasury payment-intents --amount-cents 'amount-cents'\", \"corp treasury payment-intents --json\"],\n successTemplate: \"Payment Intents created\",\n },\n {\n name: \"treasury payouts\",\n description: \"Create a payout\",\n route: { method: \"POST\", path: \"/v1/treasury/payouts\" },\n entity: true,\n options: [\n { flags: \"--amount-cents <amount-cents>\", description: \"Amount in cents\", required: true, type: \"int\" },\n { flags: \"--description <description>\", description: \"Description text\" },\n { flags: \"--destination <destination>\", description: \"Destination\", required: true },\n ],\n examples: [\"corp treasury payouts --amount-cents 'amount-cents' --destination 'destination'\", \"corp treasury payouts --json\"],\n successTemplate: \"Payouts created\",\n },\n {\n name: \"treasury seed-chart-of-accounts\",\n description: \"Initialize chart of accounts for an entity\",\n route: { method: \"POST\", path: \"/v1/treasury/seed-chart-of-accounts\" },\n entity: true,\n options: [\n { flags: \"--template <template>\", description: \"Template string with {{secret}} placeholders\" },\n ],\n examples: [\"corp treasury seed-chart-of-accounts\", \"corp treasury seed-chart-of-accounts --json\"],\n successTemplate: \"Seed Chart Of Accounts created\",\n },\n {\n name: \"treasury stripe-accounts\",\n description: \"Register a Stripe account\",\n route: { method: \"POST\", path: \"/v1/treasury/stripe-accounts\" },\n entity: true,\n examples: [\"corp treasury stripe-accounts\"],\n successTemplate: \"Stripe Accounts created\",\n },\n\n];","import type { CommandDef } from \"./types.js\";\n\nexport const branchCommands: CommandDef[] = [\n {\n name: \"branches\",\n description: \"List branches for an entity repo\",\n route: { method: \"GET\", path: \"/v1/branches\" },\n entity: \"query\",\n display: {\n title: \"Branches\",\n cols: [\"name>Branch\", \"head_oid>HEAD\"],\n },\n examples: [\"corp branches\", \"corp branches --json\"],\n },\n {\n name: \"branches create\",\n description: \"Create a new branch from an existing one\",\n route: { method: \"POST\", path: \"/v1/branches\" },\n entity: \"query\",\n options: [\n { flags: \"--name <name>\", description: \"Branch name\", required: true },\n { flags: \"--from <branch>\", description: \"Base branch (default: main)\", default: \"main\" },\n ],\n successTemplate: \"Branch {branch} created at {base_commit}\",\n examples: [\"corp branches create --name 'name'\", \"corp branches create --json\"],\n },\n {\n name: \"branches merge\",\n description: \"Merge a branch into another (default: main)\",\n route: { method: \"POST\", path: \"/v1/branches/{pos}/merge\" },\n entity: \"query\",\n args: [{ name: \"branch\", required: true, description: \"Branch to merge\" }],\n options: [\n { flags: \"--into <branch>\", description: \"Target branch (default: main)\", default: \"main\" },\n { flags: \"--squash\", description: \"Squash merge (default: true)\" },\n ],\n successTemplate: \"Merge {strategy}: {commit}\",\n examples: [\"corp branches merge <branch>\", \"corp branches merge --json\"],\n },\n {\n name: \"branches delete\",\n description: \"Delete a branch\",\n route: { method: \"DELETE\", path: \"/v1/branches/{pos}\" },\n entity: \"query\",\n args: [{ name: \"branch\", required: true, description: \"Branch to delete\" }],\n successTemplate: \"Branch deleted\",\n examples: [\"corp branches delete <branch>\"],\n },\n {\n name: \"branches prune\",\n description: \"Prune a merged branch\",\n route: { method: \"POST\", path: \"/v1/branches/{pos}/prune\" },\n entity: \"query\",\n args: [{ name: \"branch\", required: true, description: \"Branch to prune\" }],\n successTemplate: \"Branch pruned\",\n examples: [\"corp branches prune <branch>\"],\n },\n];","import type { CommandDef, WebRouteEntry } from \"./types.js\";\n\n// Domain registries — uncomment as they're created\nimport { workspaceCommands } from \"./workspace.js\";\nimport { entityCommands } from \"./entities.js\";\nimport { formationCommands } from \"./formation.js\";\nimport { capTableCommands } from \"./cap-table.js\";\nimport { financeCommands } from \"./finance.js\";\nimport { governanceCommands } from \"./governance.js\";\nimport { documentCommands } from \"./documents.js\";\nimport { complianceCommands } from \"./compliance.js\";\nimport { agentCommands } from \"./agents.js\";\nimport { workItemCommands } from \"./work-items.js\";\nimport { serviceCommands } from \"./services.js\";\nimport { adminCommands } from \"./admin.js\";\nimport { executionCommands } from \"./execution.js\";\nimport { secretProxyCommands } from \"./secret-proxies.js\";\nimport { treasuryCommands } from \"./treasury.js\";\nimport { branchCommands } from \"./branches.js\";\n\nexport const registry: CommandDef[] = [\n ...workspaceCommands,\n ...entityCommands,\n ...formationCommands,\n ...capTableCommands,\n ...financeCommands,\n ...governanceCommands,\n ...documentCommands,\n ...complianceCommands,\n ...agentCommands,\n ...workItemCommands,\n ...serviceCommands,\n ...adminCommands,\n ...executionCommands,\n ...secretProxyCommands,\n ...treasuryCommands,\n ...branchCommands,\n];\n\n/** Attach produces/successTemplate to a web-route entry if present on the CommandDef */\nfunction attachProducesFields(entry: WebRouteEntry, cmd: CommandDef): WebRouteEntry {\n if (cmd.produces) entry.produces = cmd.produces;\n if (cmd.successTemplate) entry.successTemplate = cmd.successTemplate;\n return entry;\n}\n\n/** Generate web-routes.json manifest from registry */\nexport function generateWebRoutes(commands: CommandDef[]): { commands: Record<string, WebRouteEntry> } {\n const entries: Record<string, WebRouteEntry> = {};\n for (const cmd of commands) {\n if (cmd.hidden) continue;\n if (cmd.local) {\n entries[cmd.name] = { local: true };\n continue;\n }\n const entry: WebRouteEntry = {};\n // Route info — always emit path when available so the web generic executor can use it\n if (cmd.route) {\n entry.method = cmd.route.method;\n entry.path = cmd.route.path;\n if (cmd.route.method !== \"GET\") entry.write = true;\n }\n // Entity scoping\n if (cmd.entity !== undefined) entry.entity = cmd.entity;\n // Display metadata\n if (cmd.display) {\n entry.title = cmd.display.title;\n if (cmd.display.cols) entry.cols = cmd.display.cols;\n if (cmd.display.listKey) entry.listKey = cmd.display.listKey;\n }\n if (cmd.optQP) entry.optQP = cmd.optQP;\n // Custom handler flag — tells web CLI a CUSTOM handler should override generic\n if (cmd.handler) entry.custom = true;\n // Skip commands with no route and no handler (nothing the web CLI can do)\n if (!cmd.route && !cmd.handler) continue;\n entries[cmd.name] = attachProducesFields(entry, cmd);\n }\n return { commands: entries };\n}\n\n/** Generate cli-schema.json from registry (for tab completion) */\nexport function generateSchema(commands: CommandDef[], programName: string, version: string): unknown {\n // Build hierarchical structure from flat command list\n // Group by parent: \"governance seats\" -> parent \"governance\", child \"seats\"\n\n interface SchemaCmd {\n path: string;\n name: string;\n description: string;\n aliases: string[];\n arguments: { name: string; required: boolean; variadic: boolean }[];\n options: {\n flags: string;\n name: string;\n description: string;\n required: boolean;\n mandatory: boolean;\n variadic: boolean;\n choices?: string[];\n }[];\n examples?: string[];\n subcommands: SchemaCmd[];\n }\n\n const parentMap = new Map<string, SchemaCmd>();\n const topLevel: SchemaCmd[] = [];\n\n for (const cmd of commands) {\n if (cmd.hidden) continue;\n const parts = cmd.name.split(\" \");\n const entry: SchemaCmd = {\n path: `${programName} ${cmd.name}`,\n name: parts[parts.length - 1],\n description: cmd.description,\n aliases: cmd.aliases || [],\n arguments: (cmd.args || []).map((a) => ({\n name: a.name,\n required: a.required ?? false,\n variadic: a.variadic ?? false,\n })),\n options: [\n // Always include --json\n {\n flags: \"--json\",\n name: \"json\",\n description: \"Output as JSON\",\n required: false,\n mandatory: false,\n variadic: false,\n },\n // Entity option if applicable\n ...(cmd.entity\n ? [\n {\n flags: \"--entity-id <ref>\",\n name: \"entityId\",\n description: \"Entity reference\",\n required: false,\n mandatory: false,\n variadic: false,\n },\n ]\n : []),\n // Dry run if applicable\n ...(cmd.dryRun\n ? [\n {\n flags: \"--dry-run\",\n name: \"dryRun\",\n description: \"Preview without executing\",\n required: false,\n mandatory: false,\n variadic: false,\n },\n ]\n : []),\n // Command-specific options\n ...(cmd.options || []).map((o) => ({\n flags: o.flags,\n name: o.flags.replace(/^--/, \"\").split(/[\\s,<]/)[0],\n description: o.description,\n required: o.required ?? false,\n mandatory: o.required ?? false,\n variadic: false,\n ...(o.choices && { choices: o.choices }),\n })),\n ],\n ...(cmd.examples?.length ? { examples: cmd.examples } : {}),\n subcommands: [],\n };\n\n if (parts.length === 1) {\n topLevel.push(entry);\n parentMap.set(parts[0], entry);\n } else {\n const parentName = parts[0];\n let parent = parentMap.get(parentName);\n if (!parent) {\n // Auto-create parent stub\n parent = {\n path: `${programName} ${parentName}`,\n name: parentName,\n description: \"\",\n aliases: [],\n arguments: [],\n options: [],\n subcommands: [],\n };\n topLevel.push(parent);\n parentMap.set(parentName, parent);\n }\n parent.subcommands.push(entry);\n }\n }\n\n return {\n name: programName,\n version,\n description: \"corp — Corporate governance from the terminal\",\n generated_at: new Date().toISOString(),\n commands: topLevel,\n };\n}\n","import { createRequire } from \"node:module\";\nimport { buildCLI } from \"./cli.js\";\nimport { registry } from \"./registry/index.js\";\n\nconst require = createRequire(import.meta.url);\nconst pkg = require(\"../package.json\");\n\nconst program = buildCLI(registry, pkg.version);\nprogram.parseAsync(process.argv).catch((err) => {\n console.error(err);\n process.exit(1);\n});\n","import { Command, Option } from \"commander\";\nimport type { CommandDef, CommandContext } from \"./registry/types.js\";\nimport { executeGenericRead, executeGenericWrite } from \"./generic-executor.js\";\nimport { createWriter } from \"./writer.js\";\nimport { requireConfig, resolveEntityId } from \"./config.js\";\nimport { CorpAPIClient } from \"./api-client.js\";\nimport { ReferenceResolver } from \"./references.js\";\n\n/**\n * Build a Commander program from a flat array of CommandDef objects.\n *\n * Top-level commands (name has no space) are added directly to the program.\n * Sub-commands (e.g. \"governance seats\") are grouped under a parent command\n * whose name is the first word.\n */\nexport function buildCLI(commands: CommandDef[], version: string): Command {\n const program = new Command();\n program\n .name(\"corp\")\n .description(\"corp — Corporate governance from the terminal\")\n .version(version)\n .enablePositionalOptions();\n program.option(\"-q, --quiet\", \"Only output the resource ID (for scripting)\");\n program.action(() => {\n program.outputHelp();\n });\n program.addHelpText(\n \"after\",\n '\\nTip: Run \"corp next\" to see your recommended next actions.\\n',\n );\n\n // ── Group commands: top-level vs subcommands ──────────────────────────────\n\n const topLevel: CommandDef[] = [];\n const children = new Map<string, CommandDef[]>();\n\n for (const def of commands) {\n const parts = def.name.split(\" \");\n if (parts.length === 1) {\n topLevel.push(def);\n } else {\n const parent = parts[0];\n if (!children.has(parent)) children.set(parent, []);\n children.get(parent)!.push(def);\n }\n }\n\n // ── Create top-level commands ─────────────────────────────────────────────\n\n const parentCmds = new Map<string, Command>();\n for (const def of topLevel) {\n const cmd = wireCommand(program, def);\n parentCmds.set(def.name, cmd);\n }\n\n // ── Create subcommands ────────────────────────────────────────────────────\n\n for (const [parentName, childDefs] of children) {\n let parentCmd = parentCmds.get(parentName);\n if (!parentCmd) {\n // Parent not explicitly defined — create a stub so children have a home.\n const parentDescriptions: Record<string, string> = {\n workspaces: \"Workspace management\",\n workspace: \"Workspace settings\",\n equity: \"Equity system (low-level grants, holders, instruments)\",\n execution: \"Execution intents, obligations, and approval artifacts\",\n meetings: \"Meeting management (convene, adjourn, notice)\",\n compliance: \"Compliance escalations and monitoring\",\n contractors: \"Contractor classification\",\n admin: \"Admin tools (audit, billing, SSH keys, secrets)\",\n auth: \"Authentication and API key management\",\n references: \"Reference tracking and sync\",\n secrets: \"Secret management and proxy configuration\",\n \"document-requests\": \"Document request fulfillment\",\n intents: \"Execution intent management\",\n \"bank-accounts\": \"Bank account management\",\n \"journal-entries\": \"Ledger journal entries\",\n ledger: \"Ledger operations and reconciliation\",\n payroll: \"Payroll runs\",\n payments: \"Payment submission and tracking\",\n invoices: \"Invoice management\",\n treasury: \"Treasury, invoices, payments, and payouts\",\n \"governance-seats\": \"Governance seat management\",\n \"governance-bodies\": \"Governance body management\",\n \"human-obligations\": \"Human obligation fulfillment\",\n \"ssh-keys\": \"SSH key management\",\n \"secret-proxies\": \"Secret proxy configuration\",\n formations: \"Formation workflows (low-level API)\",\n valuations: \"Valuation management\",\n branches: \"Git branch management\",\n digests: \"Digest generation and viewing\",\n obligations: \"Obligation tracking and fulfillment\",\n \"spending-limits\": \"Spending limit management\",\n receipts: \"Execution receipts\",\n \"share-transfers\": \"Share transfer workflows\",\n \"safe-notes\": \"SAFE note management\",\n distributions: \"Distribution management\",\n deadlines: \"Compliance deadline management\",\n };\n parentCmd = program.command(parentName).description(parentDescriptions[parentName] ?? \"\");\n parentCmds.set(parentName, parentCmd);\n }\n for (const def of childDefs) {\n const childName = def.name.split(\" \").slice(1).join(\" \");\n wireCommand(parentCmd, { ...def, name: childName });\n }\n }\n\n return program;\n}\n\n// ── Internal: attach a single CommandDef to a parent Command ────────────────\n\nfunction wireCommand(parent: Command, def: CommandDef): Command {\n // Build command string with positional args\n let cmdStr = def.name;\n for (const arg of def.args || []) {\n if (arg.variadic) {\n cmdStr += arg.required ? ` <${arg.name}...>` : ` [${arg.name}...]`;\n } else {\n cmdStr += arg.required ? ` <${arg.name}>` : ` [${arg.name}]`;\n }\n }\n\n const cmd = def.hidden\n ? parent.command(cmdStr, { hidden: true }).description(def.description)\n : parent.command(cmdStr).description(def.description);\n\n // Aliases\n for (const alias of def.aliases || []) {\n cmd.alias(alias);\n }\n\n // Standard options — every command gets --json (unless already defined in options)\n const definedFlags = new Set((def.options || []).map((o) => o.flags));\n if (!definedFlags.has(\"--json\")) {\n cmd.option(\"--json\", \"Output as JSON\");\n }\n\n // Entity-scoped commands get --entity-id\n if (def.entity && !definedFlags.has(\"--entity-id <ref>\")) {\n cmd.option(\n \"--entity-id <ref>\",\n \"Entity reference (overrides active entity and parent command)\",\n );\n }\n\n // Dry-run support\n if (def.dryRun && !definedFlags.has(\"--dry-run\")) {\n cmd.option(\"--dry-run\", \"Preview the request without executing\");\n }\n\n // Command-specific options\n for (const opt of def.options || []) {\n let coerce: ((val: string, prev?: unknown) => unknown) | undefined;\n if (opt.type === \"int\") coerce = (v) => parseInt(v, 10);\n else if (opt.type === \"float\") coerce = (v) => parseFloat(v);\n else if (opt.type === \"array\")\n coerce = (v: string, prev: unknown) => [\n ...((prev as string[]) || []),\n v,\n ];\n\n // Hidden options: accepted by parser but not shown in --help\n if (opt.hidden) {\n const o = new Option(opt.flags, opt.description);\n o.hideHelp();\n if (coerce) o.argParser(coerce as (value: string, previous: unknown) => unknown);\n cmd.addOption(o);\n continue;\n }\n\n // When choices are specified, use Commander's Option class with .choices()\n // so Commander validates the value at parse time.\n if (opt.choices && opt.choices.length > 0) {\n const o = new Option(opt.flags, opt.description);\n o.choices(opt.choices);\n if (opt.required) o.makeOptionMandatory(true);\n if (opt.default !== undefined) o.default(opt.default);\n if (coerce) o.argParser(coerce as (value: string, previous: unknown) => unknown);\n cmd.addOption(o);\n } else {\n const defaultVal = opt.default as string | boolean | string[] | undefined;\n if (opt.required) {\n if (coerce) cmd.requiredOption(opt.flags, opt.description, coerce, opt.default);\n else cmd.requiredOption(opt.flags, opt.description, defaultVal);\n } else {\n if (coerce) cmd.option(opt.flags, opt.description, coerce, opt.default);\n else cmd.option(opt.flags, opt.description, defaultVal);\n }\n }\n }\n\n // Help text — examples\n if (def.examples?.length) {\n cmd.addHelpText(\n \"after\",\n \"\\nExamples:\\n\" + def.examples.map((e) => ` $ ${e}`).join(\"\\n\") + \"\\n\",\n );\n }\n\n // Pass-through options (e.g. for commands that forward unknown flags)\n if (def.passThroughOptions) {\n cmd.enablePositionalOptions().passThroughOptions();\n }\n\n // ── Action handler ──────────────────────────────────────────────────────\n\n cmd.action(async (...actionArgs: unknown[]) => {\n // Commander passes: (positionalArg1, ..., positionalArgN, opts, command)\n const cmdInstance = actionArgs[actionArgs.length - 1] as Command;\n const opts = actionArgs[actionArgs.length - 2] as Record<string, unknown>;\n const positional = actionArgs.slice(0, -2).map(String);\n\n // Merge parent opts (child values take precedence over parent)\n const parentOpts = cmdInstance.parent?.opts() ?? {};\n const mergedOpts: Record<string, unknown> = { ...parentOpts, ...opts };\n // Inherit specific options from parent when child doesn't set them\n for (const key of [\"json\", \"entityId\", \"dryRun\", \"quiet\"]) {\n if (mergedOpts[key] === undefined && parentOpts[key] !== undefined) {\n mergedOpts[key] = parentOpts[key];\n }\n }\n\n const quiet = !!mergedOpts.quiet;\n const dryRun = !!mergedOpts.dryRun;\n const writer = createWriter();\n\n // ── Local commands: no API client needed ───────────────────────────\n\n if (def.local) {\n if (def.handler) {\n try {\n await def.handler({\n client: null as unknown as CommandContext[\"client\"],\n positional,\n opts: mergedOpts,\n resolver: null as unknown as CommandContext[\"resolver\"],\n writer,\n quiet,\n dryRun,\n });\n } catch (err: unknown) {\n writer.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n }\n return;\n }\n\n // ── API commands: set up client + resolver ─────────────────────────\n\n const cfg = requireConfig(\"api_url\", \"api_key\", \"workspace_id\");\n const client = new CorpAPIClient(cfg.api_url, cfg.api_key, cfg.workspace_id);\n const resolver = new ReferenceResolver(client, cfg);\n\n // Resolve entity ID for entity-scoped commands.\n // For generic reads (display without handler), let the generic executor\n // handle missing entity gracefully rather than hard-exiting here.\n let entityId: string | undefined;\n if (def.entity) {\n const explicitEid = mergedOpts.entityId as string | undefined;\n if (def.handler) {\n // Custom handler — use resolveEntityId which exits on missing\n entityId = resolveEntityId(cfg, explicitEid);\n } else {\n // Generic read — soft resolve; executor handles missing entity\n entityId = explicitEid || (cfg.active_entity_id || undefined);\n if (!entityId && cfg.workspace_id && cfg.active_entity_ids?.[cfg.workspace_id]) {\n entityId = cfg.active_entity_ids[cfg.workspace_id];\n }\n }\n }\n\n const ctx: CommandContext = {\n client,\n positional,\n opts: mergedOpts,\n entityId,\n resolver,\n writer,\n quiet,\n dryRun,\n };\n\n try {\n if (def.handler) {\n await def.handler(ctx);\n } else if (def.display) {\n await executeGenericRead(def, ctx);\n } else if (def.route && def.route.method !== \"GET\") {\n await executeGenericWrite(def, ctx);\n } else {\n writer.error(`Command \"${def.name}\" has no handler or display config`);\n process.exit(1);\n }\n\n // After generic write commands with produces metadata, print a @last hint.\n // Skip for commands with custom handlers — they manage their own output.\n if (def.produces?.kind && !def.handler && !quiet && !mergedOpts.json) {\n const kind = def.produces.kind as string;\n const lastId = resolver.getLastId(kind as Parameters<typeof resolver.getLastId>[0]);\n if (lastId) {\n const shortRef = lastId.length > 12 ? lastId.slice(0, 8) + \"…\" : lastId;\n console.log(` Ref: @last:${kind} → ${shortRef}`);\n }\n }\n } catch (err: unknown) {\n writer.error(`Failed: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n });\n\n return cmd;\n}\n","import type { CommandDef, CommandContext } from \"./registry/types.js\";\nimport { withSpinner } from \"./spinner.js\";\n\n// ── Formatting helpers (local versions matching output.ts private helpers) ──\n\nfunction s(val: unknown, maxLen?: number): string {\n const str = val == null ? \"\" : String(val);\n if (maxLen && str.length > maxLen) return str.slice(0, maxLen);\n return str;\n}\n\nfunction money(val: unknown): string {\n if (typeof val === \"number\") {\n const dollars = val / 100;\n return `$${dollars.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;\n }\n return s(val);\n}\n\nfunction fmtDate(val: unknown): string {\n const str = s(val);\n if (!str) return \"\";\n const parsed = new Date(str);\n return Number.isNaN(parsed.getTime()) ? str : parsed.toISOString().slice(0, 10);\n}\n\nfunction shortId(val: string): string {\n return val.length > 8 ? val.slice(0, 8) + \"\\u2026\" : val;\n}\n\n// ── Column spec parsing ──\n\ninterface ColSpec {\n keys: string[];\n label: string;\n fmt: \"money\" | \"date\" | \"id\" | null;\n}\n\nfunction parseCol(spec: string): ColSpec {\n let fmt: ColSpec[\"fmt\"] = null;\n let rest = spec;\n if (rest[0] === \"$\") {\n fmt = \"money\";\n rest = rest.slice(1);\n } else if (rest[0] === \"@\") {\n fmt = \"date\";\n rest = rest.slice(1);\n } else if (rest[0] === \"#\") {\n fmt = \"id\";\n rest = rest.slice(1);\n }\n const [fieldPart, label] = rest.split(\">\");\n return { keys: fieldPart.split(\"|\"), label: label || fieldPart, fmt };\n}\n\nfunction getField(obj: Record<string, unknown>, keys: string[]): unknown {\n for (const k of keys) {\n if (obj[k] != null) return obj[k];\n }\n return null;\n}\n\nfunction fmtField(val: unknown, fmt: ColSpec[\"fmt\"]): string {\n if (val == null) return \"\";\n if (fmt === \"money\") return money(val);\n if (fmt === \"date\") return fmtDate(val);\n if (fmt === \"id\") return shortId(String(val));\n return String(val);\n}\n\n// ── Auto-detect columns from first item ──\n\nfunction autoCols(items: unknown[]): ColSpec[] {\n if (!items.length) return [];\n const sample = items[0];\n if (typeof sample !== \"object\" || sample === null) return [];\n\n const keys = Object.keys(sample as Record<string, unknown>);\n const priority = [\n \"name\", \"legal_name\", \"title\", \"slug\", \"symbol\", \"type\", \"kind\",\n \"entity_type\", \"body_type\", \"status\", \"effective_status\", \"category\", \"email\",\n \"description\", \"amount_cents\", \"total_cents\", \"due_date\", \"due_at\", \"created_at\", \"date\",\n ];\n\n const picked: ColSpec[] = [];\n for (const p of priority) {\n if (keys.includes(p) && picked.length < 5) {\n let fmt: ColSpec[\"fmt\"] = null;\n if (p.endsWith(\"_cents\")) fmt = \"money\";\n else if (p.includes(\"date\") || p.endsWith(\"_at\")) fmt = \"date\";\n const label = p\n .replace(/_cents$/, \"\")\n .replace(/_/g, \" \")\n .replace(/\\b\\w/g, (ch) => ch.toUpperCase());\n picked.push({ keys: [p], label, fmt });\n }\n }\n\n // Add an ID column if available\n const idKeys = keys.filter((k) => k.endsWith(\"_id\") && k !== \"workspace_id\" && k !== \"entity_id\");\n if (idKeys.length && picked.length < 6) {\n picked.push({ keys: [idKeys[0]], label: \"ID\", fmt: \"id\" });\n }\n\n return picked;\n}\n\n// ── Panel display for single objects ──\n\nfunction displayPanel(data: Record<string, unknown>, title: string, ctx: CommandContext): void {\n const entries = Object.entries(data).filter(\n ([k, v]) => v != null && typeof v !== \"object\" && k !== \"workspace_id\",\n );\n const lines = entries.slice(0, 15).map(([k, v]) => {\n const label = k\n .replace(/_/g, \" \")\n .replace(/\\b\\w/g, (ch) => ch.toUpperCase());\n let formatted: string;\n if (k.endsWith(\"_cents\") && typeof v === \"number\") formatted = money(v);\n else if ((k.includes(\"date\") || k.endsWith(\"_at\")) && v) formatted = fmtDate(v);\n else if (k.endsWith(\"_id\")) formatted = shortId(String(v));\n else formatted = String(v);\n return `${label}: ${formatted}`;\n });\n ctx.writer.panel(title, \"blue\", lines);\n}\n\n// ── Main executor ──\n\nexport async function executeGenericRead(def: CommandDef, ctx: CommandContext): Promise<void> {\n if (!def.route?.path) {\n ctx.writer.error(\"No route defined for this command\");\n return;\n }\n\n let path = def.route.path;\n const qp: Record<string, string> = {};\n let posIdx = 0;\n\n // Resolve {eid}\n if (def.entity) {\n let eid: string | undefined;\n const explicitEid = ctx.opts[\"entity-id\"] as string | undefined;\n\n if (explicitEid) {\n eid = await ctx.resolver.resolveEntity(explicitEid);\n } else if (def.entity === true && !path.includes(\"{pos}\") && ctx.positional[posIdx]) {\n eid = await ctx.resolver.resolveEntity(ctx.positional[posIdx++]);\n } else {\n eid = ctx.entityId; // active entity from config\n }\n\n if (eid) {\n path = path.replace(\"{eid}\", encodeURIComponent(eid));\n if (def.entity === \"query\") qp.entity_id = eid;\n } else if (path.includes(\"{eid}\")) {\n ctx.writer.error(\"Entity ID required. Use --entity-id or set active entity with 'corp use <name>'.\");\n return;\n }\n }\n\n // Resolve {pos}\n if (path.includes(\"{pos}\")) {\n if (!ctx.positional[posIdx]) {\n ctx.writer.error(\"Missing required argument (ID or reference).\");\n return;\n }\n path = path.replace(\"{pos}\", encodeURIComponent(ctx.positional[posIdx++]));\n }\n\n // Resolve workspace ID placeholders\n path = path.replace(\"{wid}\", encodeURIComponent(ctx.client.workspaceId));\n path = path.replace(\"{workspace_id}\", encodeURIComponent(ctx.client.workspaceId));\n\n // Forward optQP options as query params\n if (def.optQP) {\n for (const optName of def.optQP) {\n const val = ctx.opts[optName];\n if (val) qp[optName] = String(val);\n }\n }\n\n // Fetch\n const data = await withSpinner(\n \"Loading\",\n () => ctx.client.fetchJSON(path, Object.keys(qp).length ? qp : undefined),\n ctx.opts.json as boolean,\n );\n\n // JSON output\n if (ctx.opts.json) {\n ctx.writer.json(data);\n return;\n }\n\n // Unwrap listKey\n let items = data;\n if (def.display?.listKey && data && !Array.isArray(data)) {\n items = (data as Record<string, unknown>)[def.display.listKey] || [];\n }\n\n // Display\n const title = def.display?.title || def.name;\n\n if (Array.isArray(items)) {\n const cols = def.display?.cols ? def.display.cols.map(parseCol) : autoCols(items);\n if (!cols.length && items.length) {\n ctx.writer.json(items); // fallback when no columns can be determined\n return;\n }\n const headers = cols.map((c) => c.label);\n const rows = items.map((item) =>\n cols.map((col) => fmtField(getField(item as Record<string, unknown>, col.keys), col.fmt)),\n );\n ctx.writer.table(title, headers, rows);\n } else if (data && typeof data === \"object\") {\n // Single object -> panel\n displayPanel(data as Record<string, unknown>, title, ctx);\n } else {\n ctx.writer.json(data);\n }\n}\n\n/**\n * Generic write executor for POST/PATCH/DELETE commands that lack a custom handler.\n * Resolves path placeholders, collects option values as the body, and calls submitJSON.\n */\nexport async function executeGenericWrite(def: CommandDef, ctx: CommandContext): Promise<void> {\n if (!def.route?.path || !def.route?.method) {\n ctx.writer.error(\"No route defined for this command\");\n return;\n }\n\n let path = def.route.path;\n let posIdx = 0;\n\n // Resolve {eid}\n if (def.entity) {\n let eid: string | undefined;\n const explicitEid = ctx.opts[\"entity-id\"] as string | undefined;\n if (explicitEid) {\n eid = await ctx.resolver.resolveEntity(explicitEid);\n } else if (def.entity === true && !path.includes(\"{pos}\") && ctx.positional[posIdx]) {\n eid = await ctx.resolver.resolveEntity(ctx.positional[posIdx++]);\n } else {\n eid = ctx.entityId;\n }\n if (eid) {\n path = path.replace(\"{eid}\", encodeURIComponent(eid));\n } else if (path.includes(\"{eid}\")) {\n ctx.writer.error(\"Entity ID required. Use --entity-id or set active entity with 'corp use <name>'.\");\n return;\n }\n }\n\n // Resolve {pos} and {pos2}\n if (path.includes(\"{pos}\")) {\n if (!ctx.positional[posIdx]) {\n ctx.writer.error(\"Missing required argument (ID or reference).\");\n return;\n }\n path = path.replace(\"{pos}\", encodeURIComponent(ctx.positional[posIdx++]));\n }\n if (path.includes(\"{pos2}\")) {\n if (!ctx.positional[posIdx]) {\n ctx.writer.error(\"Missing required second argument (ID or reference).\");\n return;\n }\n path = path.replace(\"{pos2}\", encodeURIComponent(ctx.positional[posIdx++]));\n }\n\n // Resolve workspace placeholders\n path = path.replace(\"{wid}\", encodeURIComponent(ctx.client.workspaceId));\n path = path.replace(\"{workspace_id}\", encodeURIComponent(ctx.client.workspaceId));\n\n // Build body from defined options\n const body: Record<string, unknown> = {};\n if (def.entity && ctx.entityId) {\n body.entity_id = ctx.entityId;\n }\n for (const opt of def.options ?? []) {\n // Extract camelCase key from flags like \"--foo-bar <val>\"\n const match = opt.flags.match(/^--([a-z0-9-]+)/);\n if (!match) continue;\n const camelKey = match[1].replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());\n const val = ctx.opts[camelKey];\n if (val != null && camelKey !== \"entityId\" && camelKey !== \"json\") {\n body[match[1].replace(/-/g, \"_\")] = val;\n }\n }\n\n if (ctx.dryRun) {\n ctx.writer.dryRun(def.name.replace(/ /g, \".\"), body);\n return;\n }\n\n const data = await withSpinner(\n \"Submitting\",\n () => ctx.client.submitJSON(def.route!.method, path, Object.keys(body).length ? body : undefined),\n ctx.opts.json as boolean,\n );\n\n if (ctx.opts.json) {\n ctx.writer.json(data);\n return;\n }\n\n // Try to extract an ID from the response for a friendly message\n const result = data as Record<string, unknown> | null;\n const idKey = result ? Object.keys(result).find((k) => k.endsWith(\"_id\")) : undefined;\n const idVal = idKey && result ? result[idKey] : undefined;\n ctx.writer.success(`${def.description ?? def.name}: ${idVal ?? \"OK\"}`);\n}\n","import chalk from \"chalk\";\nimport Table from \"cli-table3\";\nimport { printError, printSuccess, printWarning, printJson, printWriteResult, printDryRun } from \"./output.js\";\nimport type { OutputWriter } from \"./registry/types.js\";\n\nexport function createWriter(): OutputWriter {\n return {\n writeln(text = \"\") {\n console.log(text);\n },\n json(data) {\n printJson(data);\n },\n table(title, columns, rows) {\n if (rows.length === 0) {\n console.log(`No ${title.toLowerCase()} found.`);\n return;\n }\n console.log(`\\n${chalk.bold(title)}`);\n const table = new Table({ head: columns.map((c) => chalk.dim(c)) });\n for (const row of rows) table.push(row.map((cell) => String(cell ?? \"\")));\n console.log(table.toString());\n },\n panel(title, color, lines) {\n const colorFn = (chalk as unknown as Record<string, typeof chalk.blue>)[color] || chalk.blue;\n const w = 50;\n console.log(colorFn(\"─\".repeat(w)));\n console.log(colorFn.bold(` ${title}`));\n console.log(colorFn(\"─\".repeat(w)));\n for (const l of lines) console.log(` ${l}`);\n console.log(colorFn(\"─\".repeat(w)));\n },\n error(msg) {\n printError(msg);\n },\n success(msg) {\n printSuccess(msg);\n },\n warning(msg) {\n printWarning(msg);\n },\n writeResult(result, message, options) {\n printWriteResult(result, message, options ?? {});\n },\n quietId(id) {\n console.log(id);\n },\n dryRun(operation, payload) {\n printDryRun(operation, payload);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AA4FO,SAAS,YAAY,OAAuB;AACjD,QAAM,OAAmB,CAAC;AAC1B,WAAS,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;AACzC,UAAM,WAAW,UAAU,CAAC;AAC5B,UAAM,IAAI,SAAS;AACnB,UAAM,U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ACtB,cAAM,mBAAmB,KAAK,GAAG;AAAA,MACnC,WAAW,IAAI,SAAS,IAAI,MAAM,WAAW,OAAO;AAClD,cAAM,oBAAoB,KAAK,GAAG;AAAA,MACpC,OAAO;AACL,eAAO,MAAM,YAAY,IAAI,IAAI,oCAAoC;AACrE,gBAAQ,KAAK,CAAC;AAAA,MAChB;AAIA,UAAI,IAAI,UAAU,QAAQ,CAAC,IAAI,WAAW,CAAC,SAAS,CAAC,WAAW,MAAM;AACpE,cAAM,OAAO,IAAI,SAAS;AAC1B,cAAM,SAAS,SAAS,UAAU,IAAgD;AAClF,YAAI,QAAQ;AACV,gBAAM,WAAW,OAAO,SAAS,KAAK,OAAO,MAAM,GAAG,CAAC,IAAI,WAAM;AACjE,kBAAQ,IAAI,gBAAgB,IAAI,WAAM,QAAQ,EAAE;AAAA,QAClD;AAAA,MACF;AAAA,IACF,SAAS,KAAc;AACrB,aAAO,MAAM,WAAW,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE;AAC1E,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF,CAAC;AAED,SAAO;AACT;;;ADxTA;AAEA,IAAMC,WAAU,cAAc,YAAY,GAAG;AAC7C,IAAM,MAAMA,SAAQ,iBAAiB;AAErC,IAAM,UAAU,SAAS,UAAU,IAAI,OAAO;AAC9C,QAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,QAAQ;AAC9C,UAAQ,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["shortId","describeReferenceRecord","getReferenceAlias","shortId","s","money","holders","chalk","chalk","confirm","chalk","Table","readFileSync","input","chalk","Table","formCommand","parseCsvAddress","shouldResolveEntityRefForDryRun","resolveEntityRefForFormCommand","SUPPORTED_ENTITY_TYPES","chalk","s","shortId","chalk","confirm","s","result","confirm","chalk","readFileSync","realpathSync","relative","resolve","s","confirm","chalk","actorLabel","chalk","input","select","homedir","join","existsSync","mkdirSync","init_config","resolve","result","join","homedir","chalk","resolve","confirm","s","chalk","shortId","chalk","Table","KINDS","ENTITY_SCOPED_KINDS","setupCommand","configSetCommand","configGetCommand","configListCommand","registry","generateWebRoutes","generateSchema","createRequire","require","pkg","serveCommand","demoCommand","chatCommand","apiKeysListCommand","apiKeysCreateCommand","apiKeysRevokeCommand","apiKeysRotateCommand","linkCommand","claimCommand","feedbackCommand","resolveCommand","findCommand","chalk","Table","program","require"]}