optimal-cli 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/dist/bin/optimal.d.ts +2 -0
  2. package/dist/bin/optimal.js +1590 -0
  3. package/dist/lib/assets/index.d.ts +79 -0
  4. package/dist/lib/assets/index.js +153 -0
  5. package/dist/lib/assets.d.ts +20 -0
  6. package/dist/lib/assets.js +112 -0
  7. package/dist/lib/auth/index.d.ts +83 -0
  8. package/dist/lib/auth/index.js +146 -0
  9. package/dist/lib/board/index.d.ts +39 -0
  10. package/dist/lib/board/index.js +285 -0
  11. package/dist/lib/board/types.d.ts +111 -0
  12. package/dist/lib/board/types.js +1 -0
  13. package/dist/lib/bot/claim.d.ts +3 -0
  14. package/dist/lib/bot/claim.js +20 -0
  15. package/dist/lib/bot/coordinator.d.ts +27 -0
  16. package/dist/lib/bot/coordinator.js +178 -0
  17. package/dist/lib/bot/heartbeat.d.ts +6 -0
  18. package/dist/lib/bot/heartbeat.js +30 -0
  19. package/dist/lib/bot/index.d.ts +9 -0
  20. package/dist/lib/bot/index.js +6 -0
  21. package/dist/lib/bot/protocol.d.ts +12 -0
  22. package/dist/lib/bot/protocol.js +74 -0
  23. package/dist/lib/bot/reporter.d.ts +3 -0
  24. package/dist/lib/bot/reporter.js +27 -0
  25. package/dist/lib/bot/skills.d.ts +26 -0
  26. package/dist/lib/bot/skills.js +69 -0
  27. package/dist/lib/budget/projections.d.ts +115 -0
  28. package/dist/lib/budget/projections.js +384 -0
  29. package/dist/lib/budget/scenarios.d.ts +93 -0
  30. package/dist/lib/budget/scenarios.js +214 -0
  31. package/dist/lib/cms/publish-blog.d.ts +62 -0
  32. package/dist/lib/cms/publish-blog.js +74 -0
  33. package/dist/lib/cms/strapi-client.d.ts +123 -0
  34. package/dist/lib/cms/strapi-client.js +213 -0
  35. package/dist/lib/config/registry.d.ts +17 -0
  36. package/dist/lib/config/registry.js +182 -0
  37. package/dist/lib/config/schema.d.ts +31 -0
  38. package/dist/lib/config/schema.js +25 -0
  39. package/dist/lib/config.d.ts +55 -0
  40. package/dist/lib/config.js +206 -0
  41. package/dist/lib/errors.d.ts +25 -0
  42. package/dist/lib/errors.js +91 -0
  43. package/dist/lib/format.d.ts +28 -0
  44. package/dist/lib/format.js +98 -0
  45. package/dist/lib/infra/deploy.d.ts +29 -0
  46. package/dist/lib/infra/deploy.js +58 -0
  47. package/dist/lib/infra/migrate.d.ts +34 -0
  48. package/dist/lib/infra/migrate.js +103 -0
  49. package/dist/lib/newsletter/distribute.d.ts +52 -0
  50. package/dist/lib/newsletter/distribute.js +193 -0
  51. package/{lib/newsletter/generate-insurance.ts → dist/lib/newsletter/generate-insurance.d.ts} +7 -24
  52. package/dist/lib/newsletter/generate-insurance.js +36 -0
  53. package/dist/lib/newsletter/generate.d.ts +104 -0
  54. package/dist/lib/newsletter/generate.js +571 -0
  55. package/dist/lib/returnpro/anomalies.d.ts +64 -0
  56. package/dist/lib/returnpro/anomalies.js +166 -0
  57. package/dist/lib/returnpro/audit.d.ts +32 -0
  58. package/dist/lib/returnpro/audit.js +147 -0
  59. package/dist/lib/returnpro/diagnose.d.ts +52 -0
  60. package/dist/lib/returnpro/diagnose.js +281 -0
  61. package/dist/lib/returnpro/kpis.d.ts +32 -0
  62. package/dist/lib/returnpro/kpis.js +192 -0
  63. package/dist/lib/returnpro/templates.d.ts +48 -0
  64. package/dist/lib/returnpro/templates.js +229 -0
  65. package/dist/lib/returnpro/upload-income.d.ts +25 -0
  66. package/dist/lib/returnpro/upload-income.js +235 -0
  67. package/dist/lib/returnpro/upload-netsuite.d.ts +37 -0
  68. package/dist/lib/returnpro/upload-netsuite.js +566 -0
  69. package/dist/lib/returnpro/upload-r1.d.ts +48 -0
  70. package/dist/lib/returnpro/upload-r1.js +398 -0
  71. package/dist/lib/returnpro/validate.d.ts +37 -0
  72. package/dist/lib/returnpro/validate.js +124 -0
  73. package/dist/lib/social/meta.d.ts +90 -0
  74. package/dist/lib/social/meta.js +160 -0
  75. package/dist/lib/social/post-generator.d.ts +83 -0
  76. package/dist/lib/social/post-generator.js +333 -0
  77. package/dist/lib/social/publish.d.ts +66 -0
  78. package/dist/lib/social/publish.js +226 -0
  79. package/dist/lib/social/scraper.d.ts +67 -0
  80. package/dist/lib/social/scraper.js +361 -0
  81. package/dist/lib/supabase.d.ts +4 -0
  82. package/dist/lib/supabase.js +20 -0
  83. package/dist/lib/transactions/delete-batch.d.ts +60 -0
  84. package/dist/lib/transactions/delete-batch.js +203 -0
  85. package/dist/lib/transactions/ingest.d.ts +43 -0
  86. package/dist/lib/transactions/ingest.js +555 -0
  87. package/dist/lib/transactions/stamp.d.ts +51 -0
  88. package/dist/lib/transactions/stamp.js +524 -0
  89. package/package.json +3 -4
  90. package/bin/optimal.ts +0 -1731
  91. package/lib/assets/index.ts +0 -225
  92. package/lib/assets.ts +0 -124
  93. package/lib/auth/index.ts +0 -189
  94. package/lib/board/index.ts +0 -309
  95. package/lib/board/types.ts +0 -124
  96. package/lib/bot/claim.ts +0 -43
  97. package/lib/bot/coordinator.ts +0 -254
  98. package/lib/bot/heartbeat.ts +0 -37
  99. package/lib/bot/index.ts +0 -9
  100. package/lib/bot/protocol.ts +0 -99
  101. package/lib/bot/reporter.ts +0 -42
  102. package/lib/bot/skills.ts +0 -81
  103. package/lib/budget/projections.ts +0 -561
  104. package/lib/budget/scenarios.ts +0 -312
  105. package/lib/cms/publish-blog.ts +0 -129
  106. package/lib/cms/strapi-client.ts +0 -302
  107. package/lib/config/registry.ts +0 -228
  108. package/lib/config/schema.ts +0 -58
  109. package/lib/config.ts +0 -247
  110. package/lib/errors.ts +0 -129
  111. package/lib/format.ts +0 -120
  112. package/lib/infra/.gitkeep +0 -0
  113. package/lib/infra/deploy.ts +0 -70
  114. package/lib/infra/migrate.ts +0 -141
  115. package/lib/newsletter/.gitkeep +0 -0
  116. package/lib/newsletter/distribute.ts +0 -256
  117. package/lib/newsletter/generate.ts +0 -735
  118. package/lib/returnpro/.gitkeep +0 -0
  119. package/lib/returnpro/anomalies.ts +0 -258
  120. package/lib/returnpro/audit.ts +0 -194
  121. package/lib/returnpro/diagnose.ts +0 -400
  122. package/lib/returnpro/kpis.ts +0 -255
  123. package/lib/returnpro/templates.ts +0 -323
  124. package/lib/returnpro/upload-income.ts +0 -311
  125. package/lib/returnpro/upload-netsuite.ts +0 -696
  126. package/lib/returnpro/upload-r1.ts +0 -563
  127. package/lib/returnpro/validate.ts +0 -154
  128. package/lib/social/meta.ts +0 -228
  129. package/lib/social/post-generator.ts +0 -468
  130. package/lib/social/publish.ts +0 -301
  131. package/lib/social/scraper.ts +0 -503
  132. package/lib/supabase.ts +0 -25
  133. package/lib/transactions/delete-batch.ts +0 -258
  134. package/lib/transactions/ingest.ts +0 -659
  135. package/lib/transactions/stamp.ts +0 -654
@@ -0,0 +1,31 @@
1
+ export type ConfigSchemaVersion = '1.0.0';
2
+ export interface OptimalConfigV1 {
3
+ version: ConfigSchemaVersion;
4
+ profile: {
5
+ name: string;
6
+ owner: string;
7
+ updated_at: string;
8
+ };
9
+ providers: {
10
+ supabase: {
11
+ project_ref: string;
12
+ url: string;
13
+ anon_key_present: boolean;
14
+ };
15
+ strapi: {
16
+ base_url: string;
17
+ token_present: boolean;
18
+ };
19
+ };
20
+ defaults: {
21
+ brand: string;
22
+ timezone: string;
23
+ };
24
+ features: {
25
+ cms: boolean;
26
+ tasks: boolean;
27
+ deploy: boolean;
28
+ };
29
+ }
30
+ export declare function isOptimalConfigV1(value: unknown): value is OptimalConfigV1;
31
+ export declare function assertOptimalConfigV1(value: unknown): OptimalConfigV1;
@@ -0,0 +1,25 @@
1
+ export function isOptimalConfigV1(value) {
2
+ if (!value || typeof value !== 'object')
3
+ return false;
4
+ const v = value;
5
+ return (v.version === '1.0.0' &&
6
+ typeof v.profile?.name === 'string' &&
7
+ typeof v.profile?.owner === 'string' &&
8
+ typeof v.profile?.updated_at === 'string' &&
9
+ typeof v.providers?.supabase?.project_ref === 'string' &&
10
+ typeof v.providers?.supabase?.url === 'string' &&
11
+ typeof v.providers?.supabase?.anon_key_present === 'boolean' &&
12
+ typeof v.providers?.strapi?.base_url === 'string' &&
13
+ typeof v.providers?.strapi?.token_present === 'boolean' &&
14
+ typeof v.defaults?.brand === 'string' &&
15
+ typeof v.defaults?.timezone === 'string' &&
16
+ typeof v.features?.cms === 'boolean' &&
17
+ typeof v.features?.tasks === 'boolean' &&
18
+ typeof v.features?.deploy === 'boolean');
19
+ }
20
+ export function assertOptimalConfigV1(value) {
21
+ if (!isOptimalConfigV1(value)) {
22
+ throw new Error('Invalid optimal config payload (v1)');
23
+ }
24
+ return value;
25
+ }
@@ -0,0 +1,55 @@
1
+ interface ConfigRecord {
2
+ id: string;
3
+ agent_name: string;
4
+ config_json: Record<string, unknown>;
5
+ version: string;
6
+ created_at: string;
7
+ updated_at: string;
8
+ }
9
+ /**
10
+ * Initialize local config directory
11
+ */
12
+ export declare function initConfigDir(): void;
13
+ /**
14
+ * Load local openclaw.json
15
+ */
16
+ export declare function loadLocalConfig(): Record<string, unknown> | null;
17
+ /**
18
+ * Save config to local openclaw.json
19
+ */
20
+ export declare function saveLocalConfig(config: Record<string, unknown>): void;
21
+ /**
22
+ * Push current openclaw.json to Supabase
23
+ */
24
+ export declare function pushConfig(agentName: string): Promise<{
25
+ id: string;
26
+ version: string;
27
+ }>;
28
+ /**
29
+ * Pull config from Supabase and save to local openclaw.json
30
+ */
31
+ export declare function pullConfig(agentName: string): Promise<ConfigRecord>;
32
+ /**
33
+ * List all saved agent configs
34
+ */
35
+ export declare function listConfigs(): Promise<Array<{
36
+ agent_name: string;
37
+ version: string;
38
+ updated_at: string;
39
+ }>>;
40
+ /**
41
+ * Compare local config with cloud version
42
+ */
43
+ export declare function diffConfig(agentName: string): Promise<{
44
+ local: Record<string, unknown> | null;
45
+ cloud: ConfigRecord | null;
46
+ differences: string[];
47
+ }>;
48
+ /**
49
+ * Sync config (two-way merge)
50
+ */
51
+ export declare function syncConfig(agentName: string): Promise<{
52
+ action: 'pushed' | 'pulled' | 'merged' | 'none';
53
+ message: string;
54
+ }>;
55
+ export {};
@@ -0,0 +1,206 @@
1
+ import { createClient } from '@supabase/supabase-js';
2
+ import { readFileSync, writeFileSync, existsSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ const CONFIG_DIR = join(homedir(), '.optimal');
6
+ const LOCAL_CONFIG_PATH = join(CONFIG_DIR, 'config.json');
7
+ const OPENCLAW_CONFIG_PATH = join(homedir(), '.openclaw', 'openclaw.json');
8
+ // Get Supabase client for OptimalOS instance (stores CLI configs)
9
+ function getOptimalSupabase() {
10
+ const url = process.env.OPTIMAL_SUPABASE_URL;
11
+ const key = process.env.OPTIMAL_SUPABASE_SERVICE_KEY;
12
+ if (!url || !key) {
13
+ throw new Error('OPTIMAL_SUPABASE_URL and OPTIMAL_SUPABASE_SERVICE_KEY must be set');
14
+ }
15
+ return createClient(url, key);
16
+ }
17
+ /**
18
+ * Initialize local config directory
19
+ */
20
+ export function initConfigDir() {
21
+ if (!existsSync(CONFIG_DIR)) {
22
+ import('node:fs').then(fs => fs.mkdirSync(CONFIG_DIR, { recursive: true }));
23
+ }
24
+ }
25
+ /**
26
+ * Load local openclaw.json
27
+ */
28
+ export function loadLocalConfig() {
29
+ if (!existsSync(OPENCLAW_CONFIG_PATH)) {
30
+ return null;
31
+ }
32
+ try {
33
+ const raw = readFileSync(OPENCLAW_CONFIG_PATH, 'utf-8');
34
+ return JSON.parse(raw);
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ /**
41
+ * Save config to local openclaw.json
42
+ */
43
+ export function saveLocalConfig(config) {
44
+ writeFileSync(OPENCLAW_CONFIG_PATH, JSON.stringify(config, null, 2));
45
+ }
46
+ /**
47
+ * Push current openclaw.json to Supabase
48
+ */
49
+ export async function pushConfig(agentName) {
50
+ const supabase = getOptimalSupabase();
51
+ const config = loadLocalConfig();
52
+ if (!config) {
53
+ throw new Error(`No config found at ${OPENCLAW_CONFIG_PATH}`);
54
+ }
55
+ // Generate version timestamp
56
+ const version = new Date().toISOString();
57
+ // Check if config exists for this agent
58
+ const { data: existing } = await supabase
59
+ .from('agent_configs')
60
+ .select('id')
61
+ .eq('agent_name', agentName)
62
+ .single();
63
+ let result;
64
+ if (existing) {
65
+ // Update existing
66
+ const { data, error } = await supabase
67
+ .from('agent_configs')
68
+ .update({
69
+ config_json: config,
70
+ version,
71
+ updated_at: version,
72
+ })
73
+ .eq('id', existing.id)
74
+ .select()
75
+ .single();
76
+ if (error)
77
+ throw error;
78
+ result = data;
79
+ }
80
+ else {
81
+ // Insert new
82
+ const { data, error } = await supabase
83
+ .from('agent_configs')
84
+ .insert({
85
+ agent_name: agentName,
86
+ config_json: config,
87
+ version,
88
+ })
89
+ .select()
90
+ .single();
91
+ if (error)
92
+ throw error;
93
+ result = data;
94
+ }
95
+ return { id: result.id, version };
96
+ }
97
+ /**
98
+ * Pull config from Supabase and save to local openclaw.json
99
+ */
100
+ export async function pullConfig(agentName) {
101
+ const supabase = getOptimalSupabase();
102
+ const { data, error } = await supabase
103
+ .from('agent_configs')
104
+ .select('*')
105
+ .eq('agent_name', agentName)
106
+ .order('updated_at', { ascending: false })
107
+ .limit(1)
108
+ .single();
109
+ if (error) {
110
+ throw new Error(`No config found for agent: ${agentName}`);
111
+ }
112
+ // Save to local
113
+ saveLocalConfig(data.config_json);
114
+ return data;
115
+ }
116
+ /**
117
+ * List all saved agent configs
118
+ */
119
+ export async function listConfigs() {
120
+ const supabase = getOptimalSupabase();
121
+ const { data, error } = await supabase
122
+ .from('agent_configs')
123
+ .select('agent_name, version, updated_at')
124
+ .order('updated_at', { ascending: false });
125
+ if (error) {
126
+ throw new Error(`Failed to list configs: ${error.message}`);
127
+ }
128
+ return data || [];
129
+ }
130
+ /**
131
+ * Compare local config with cloud version
132
+ */
133
+ export async function diffConfig(agentName) {
134
+ const local = loadLocalConfig();
135
+ let cloud = null;
136
+ try {
137
+ const supabase = getOptimalSupabase();
138
+ const { data } = await supabase
139
+ .from('agent_configs')
140
+ .select('*')
141
+ .eq('agent_name', agentName)
142
+ .single();
143
+ cloud = data;
144
+ }
145
+ catch {
146
+ // Cloud config doesn't exist
147
+ }
148
+ const differences = [];
149
+ if (!local && !cloud) {
150
+ differences.push('No local or cloud config found');
151
+ }
152
+ else if (!local) {
153
+ differences.push('No local config (cloud exists)');
154
+ }
155
+ else if (!cloud) {
156
+ differences.push('No cloud config (local exists)');
157
+ }
158
+ else {
159
+ // Simple diff on top-level keys
160
+ const localKeys = Object.keys(local).sort();
161
+ const cloudKeys = Object.keys(cloud.config_json).sort();
162
+ if (JSON.stringify(localKeys) !== JSON.stringify(cloudKeys)) {
163
+ differences.push('Top-level keys differ');
164
+ }
165
+ // Check version
166
+ const localMeta = local.meta;
167
+ if (localMeta?.lastTouchedVersion !== cloud.version) {
168
+ differences.push(`Version mismatch: local=${localMeta?.lastTouchedVersion}, cloud=${cloud.version}`);
169
+ }
170
+ }
171
+ return { local, cloud, differences };
172
+ }
173
+ /**
174
+ * Sync config (two-way merge)
175
+ */
176
+ export async function syncConfig(agentName) {
177
+ const { local, cloud, differences } = await diffConfig(agentName);
178
+ if (!local && !cloud) {
179
+ return { action: 'none', message: 'No configs to sync' };
180
+ }
181
+ if (!cloud) {
182
+ // Only local exists - push
183
+ const result = await pushConfig(agentName);
184
+ return { action: 'pushed', message: `Pushed to cloud (version ${result.version})` };
185
+ }
186
+ if (!local) {
187
+ // Only cloud exists - pull
188
+ await pullConfig(agentName);
189
+ return { action: 'pulled', message: `Pulled from cloud (version ${cloud.version})` };
190
+ }
191
+ // Both exist - compare timestamps
192
+ const localTime = local.meta?.lastTouchedAt || '1970-01-01';
193
+ const localVersion = local.meta?.lastTouchedVersion || 'unknown';
194
+ const cloudTime = cloud.updated_at;
195
+ if (localTime > cloudTime) {
196
+ const result = await pushConfig(agentName);
197
+ return { action: 'pushed', message: `Local is newer - pushed to cloud (version ${result.version})` };
198
+ }
199
+ else if (cloudTime > localTime) {
200
+ await pullConfig(agentName);
201
+ return { action: 'pulled', message: `Cloud is newer - pulled from cloud (version ${cloud.version})` };
202
+ }
203
+ else {
204
+ return { action: 'none', message: 'Configs are in sync' };
205
+ }
206
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Centralized error handling for the Optimal CLI.
3
+ *
4
+ * Provides a typed CliError class, a user-friendly formatter,
5
+ * and a wrapCommand helper for Commander action handlers.
6
+ */
7
+ export type ErrorCode = 'MISSING_ENV' | 'NOT_FOUND' | 'SUPABASE_ERROR' | 'VALIDATION_ERROR' | 'AUTH_ERROR' | 'NETWORK_ERROR' | 'FILE_ERROR' | 'UNKNOWN';
8
+ export declare class CliError extends Error {
9
+ code: ErrorCode;
10
+ suggestion?: string | undefined;
11
+ constructor(message: string, code: ErrorCode, suggestion?: string | undefined);
12
+ }
13
+ /**
14
+ * Format an error for CLI output, print it to stderr, and exit with code 1.
15
+ */
16
+ export declare function handleError(err: unknown): never;
17
+ /**
18
+ * Wrap a Commander action handler so any thrown error is routed through
19
+ * handleError, giving the user a consistent, friendly message instead of
20
+ * an unhandled-rejection stack trace.
21
+ *
22
+ * Usage:
23
+ * .action(wrapCommand(async (opts) => { ... }))
24
+ */
25
+ export declare function wrapCommand<A extends unknown[]>(fn: (...args: A) => Promise<void>): (...args: A) => Promise<void>;
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Centralized error handling for the Optimal CLI.
3
+ *
4
+ * Provides a typed CliError class, a user-friendly formatter,
5
+ * and a wrapCommand helper for Commander action handlers.
6
+ */
7
+ // ── CliError ─────────────────────────────────────────────────────────────────
8
+ export class CliError extends Error {
9
+ code;
10
+ suggestion;
11
+ constructor(message, code, suggestion) {
12
+ super(message);
13
+ this.code = code;
14
+ this.suggestion = suggestion;
15
+ this.name = 'CliError';
16
+ }
17
+ }
18
+ // ── Helpers ──────────────────────────────────────────────────────────────────
19
+ const SUGGESTIONS = {
20
+ MISSING_ENV: 'Ensure the required environment variables are set in your .env file or shell.',
21
+ NOT_FOUND: 'Double-check the identifier (slug, ID, or name) and try again.',
22
+ SUPABASE_ERROR: 'Verify your Supabase URL and service key are correct and the database is reachable.',
23
+ VALIDATION_ERROR: 'Review the command options with --help.',
24
+ AUTH_ERROR: 'Check your API token or credentials and make sure they have not expired.',
25
+ NETWORK_ERROR: 'Check your internet connection and verify the remote service is available.',
26
+ FILE_ERROR: 'Verify the file path exists and you have read/write permissions.',
27
+ };
28
+ function classifyError(err) {
29
+ if (err instanceof CliError) {
30
+ return { code: err.code, message: err.message };
31
+ }
32
+ if (err instanceof Error) {
33
+ const msg = err.message;
34
+ // Supabase / fetch errors
35
+ if (msg.includes('PGRST') || msg.includes('supabase') || msg.includes('relation')) {
36
+ return { code: 'SUPABASE_ERROR', message: msg };
37
+ }
38
+ if (msg.includes('ENOENT') || msg.includes('no such file')) {
39
+ return { code: 'FILE_ERROR', message: msg };
40
+ }
41
+ if (msg.includes('ECONNREFUSED') || msg.includes('fetch failed') || msg.includes('ETIMEDOUT')) {
42
+ return { code: 'NETWORK_ERROR', message: msg };
43
+ }
44
+ if (msg.includes('OPTIMAL_SUPABASE_URL') ||
45
+ msg.includes('OPTIMAL_SUPABASE_SERVICE_KEY') ||
46
+ msg.includes('env')) {
47
+ return { code: 'MISSING_ENV', message: msg };
48
+ }
49
+ return { code: 'UNKNOWN', message: msg };
50
+ }
51
+ return { code: 'UNKNOWN', message: String(err) };
52
+ }
53
+ // ── handleError ──────────────────────────────────────────────────────────────
54
+ /**
55
+ * Format an error for CLI output, print it to stderr, and exit with code 1.
56
+ */
57
+ export function handleError(err) {
58
+ const { code, message } = classifyError(err);
59
+ const suggestion = err instanceof CliError && err.suggestion
60
+ ? err.suggestion
61
+ : SUGGESTIONS[code] ?? '';
62
+ const lines = [
63
+ '',
64
+ ` Error [${code}]: ${message}`,
65
+ ];
66
+ if (suggestion) {
67
+ lines.push(` Suggestion: ${suggestion}`);
68
+ }
69
+ lines.push('');
70
+ process.stderr.write(lines.join('\n'));
71
+ process.exit(1);
72
+ }
73
+ // ── wrapCommand ──────────────────────────────────────────────────────────────
74
+ /**
75
+ * Wrap a Commander action handler so any thrown error is routed through
76
+ * handleError, giving the user a consistent, friendly message instead of
77
+ * an unhandled-rejection stack trace.
78
+ *
79
+ * Usage:
80
+ * .action(wrapCommand(async (opts) => { ... }))
81
+ */
82
+ export function wrapCommand(fn) {
83
+ return async (...args) => {
84
+ try {
85
+ await fn(...args);
86
+ }
87
+ catch (err) {
88
+ handleError(err);
89
+ }
90
+ };
91
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Lightweight CLI output formatting — ANSI colors, tables, badges.
3
+ * Zero external dependencies. Respects NO_COLOR env var.
4
+ */
5
+ type Color = 'red' | 'green' | 'yellow' | 'blue' | 'cyan' | 'gray' | 'bold' | 'dim';
6
+ /**
7
+ * Wrap text in ANSI escape codes for the given color/style.
8
+ * Returns plain text when NO_COLOR env var is set.
9
+ */
10
+ export declare function colorize(text: string, color: Color): string;
11
+ /**
12
+ * Render a bordered ASCII table with auto-sized columns.
13
+ * Headers are rendered in bold.
14
+ */
15
+ export declare function table(headers: string[], rows: string[][]): string;
16
+ /** Return a colored status string (e.g. "done" in green). */
17
+ export declare function statusBadge(status: string): string;
18
+ /** Return a colored priority label (e.g. "P1" in red). */
19
+ export declare function priorityBadge(p: number): string;
20
+ /** Print a green success message with a check mark prefix. */
21
+ export declare function success(msg: string): void;
22
+ /** Print a red error message with an X prefix. */
23
+ export declare function error(msg: string): void;
24
+ /** Print a yellow warning message with a warning prefix. */
25
+ export declare function warn(msg: string): void;
26
+ /** Print a blue info message with an info prefix. */
27
+ export declare function info(msg: string): void;
28
+ export {};
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Lightweight CLI output formatting — ANSI colors, tables, badges.
3
+ * Zero external dependencies. Respects NO_COLOR env var.
4
+ */
5
+ // ── ANSI escape codes ───────────────────────────────────────────────
6
+ const CODES = {
7
+ red: [31, 39],
8
+ green: [32, 39],
9
+ yellow: [33, 39],
10
+ blue: [34, 39],
11
+ cyan: [36, 39],
12
+ gray: [90, 39],
13
+ bold: [1, 22],
14
+ dim: [2, 22],
15
+ };
16
+ /**
17
+ * Wrap text in ANSI escape codes for the given color/style.
18
+ * Returns plain text when NO_COLOR env var is set.
19
+ */
20
+ export function colorize(text, color) {
21
+ if (process.env.NO_COLOR !== undefined)
22
+ return text;
23
+ const [open, close] = CODES[color];
24
+ return `\x1b[${open}m${text}\x1b[${close}m`;
25
+ }
26
+ // ── Table rendering ─────────────────────────────────────────────────
27
+ /** Strip ANSI escape sequences to measure visible string width. */
28
+ function stripAnsi(s) {
29
+ return s.replace(/\x1b\[\d+m/g, '');
30
+ }
31
+ /**
32
+ * Render a bordered ASCII table with auto-sized columns.
33
+ * Headers are rendered in bold.
34
+ */
35
+ export function table(headers, rows) {
36
+ // Compute column widths from headers and all rows
37
+ const colWidths = headers.map((h, i) => {
38
+ let max = stripAnsi(h).length;
39
+ for (const row of rows) {
40
+ const cell = row[i] ?? '';
41
+ const len = stripAnsi(cell).length;
42
+ if (len > max)
43
+ max = len;
44
+ }
45
+ return max;
46
+ });
47
+ function padCell(cell, width) {
48
+ const visible = stripAnsi(cell).length;
49
+ return cell + ' '.repeat(Math.max(0, width - visible));
50
+ }
51
+ const sep = '+-' + colWidths.map(w => '-'.repeat(w)).join('-+-') + '-+';
52
+ const headerRow = '| ' + headers.map((h, i) => padCell(colorize(h, 'bold'), colWidths[i])).join(' | ') + ' |';
53
+ const bodyRows = rows.map(row => '| ' + row.map((cell, i) => padCell(cell ?? '', colWidths[i])).join(' | ') + ' |');
54
+ return [sep, headerRow, sep, ...bodyRows, sep].join('\n');
55
+ }
56
+ // ── Status & priority badges ────────────────────────────────────────
57
+ const STATUS_COLORS = {
58
+ done: 'green',
59
+ in_progress: 'blue',
60
+ blocked: 'red',
61
+ ready: 'cyan',
62
+ backlog: 'gray',
63
+ cancelled: 'dim',
64
+ review: 'yellow',
65
+ };
66
+ /** Return a colored status string (e.g. "done" in green). */
67
+ export function statusBadge(status) {
68
+ const color = STATUS_COLORS[status] ?? 'dim';
69
+ return colorize(status, color);
70
+ }
71
+ const PRIORITY_COLORS = {
72
+ 1: 'red',
73
+ 2: 'yellow',
74
+ 3: 'blue',
75
+ 4: 'gray',
76
+ };
77
+ /** Return a colored priority label (e.g. "P1" in red). */
78
+ export function priorityBadge(p) {
79
+ const color = PRIORITY_COLORS[p] ?? 'gray';
80
+ return colorize(`P${p}`, color);
81
+ }
82
+ // ── Logging helpers ─────────────────────────────────────────────────
83
+ /** Print a green success message with a check mark prefix. */
84
+ export function success(msg) {
85
+ console.log(`${colorize('\u2713', 'green')} ${msg}`);
86
+ }
87
+ /** Print a red error message with an X prefix. */
88
+ export function error(msg) {
89
+ console.error(`${colorize('\u2717', 'red')} ${msg}`);
90
+ }
91
+ /** Print a yellow warning message with a warning prefix. */
92
+ export function warn(msg) {
93
+ console.warn(`${colorize('\u26a0', 'yellow')} ${msg}`);
94
+ }
95
+ /** Print a blue info message with an info prefix. */
96
+ export function info(msg) {
97
+ console.log(`${colorize('\u2139', 'blue')} ${msg}`);
98
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * List all available app names that can be deployed.
3
+ */
4
+ export declare function listApps(): string[];
5
+ /**
6
+ * Resolve an app name to its absolute filesystem path.
7
+ * Throws if the app name is unknown.
8
+ */
9
+ export declare function getAppPath(appName: string): string;
10
+ /**
11
+ * Deploy an app to Vercel using the `vercel` CLI.
12
+ *
13
+ * Uses `execFile` (not `exec`) to avoid shell injection.
14
+ * The `--cwd` flag tells Vercel which project directory to deploy.
15
+ *
16
+ * @param appName - Short name from APP_PATHS (e.g. 'portfolio', 'dashboard-returnpro')
17
+ * @param prod - If true, deploys to production (--prod flag). Otherwise preview.
18
+ * @returns The deployment URL printed by Vercel CLI.
19
+ */
20
+ export declare function deploy(appName: string, prod?: boolean): Promise<string>;
21
+ /**
22
+ * Run the Optimal workstation health check script.
23
+ *
24
+ * Checks: n8n, Affine (Docker + HTTP), Strapi CMS (systemd + HTTP),
25
+ * Git repo sync status, Docker containers, and OptimalOS dev server.
26
+ *
27
+ * @returns The full text output of the health check script.
28
+ */
29
+ export declare function healthCheck(): Promise<string>;
@@ -0,0 +1,58 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ const run = promisify(execFile);
4
+ /** Map of short app names to absolute filesystem paths. */
5
+ const APP_PATHS = {
6
+ 'dashboard-returnpro': '/home/optimal/dashboard-returnpro',
7
+ 'optimalos': '/home/optimal/optimalos',
8
+ 'portfolio': '/home/optimal/portfolio-2026',
9
+ 'newsletter-preview': '/home/optimal/projects/newsletter-preview',
10
+ 'wes': '/home/optimal/wes-dashboard',
11
+ };
12
+ /**
13
+ * List all available app names that can be deployed.
14
+ */
15
+ export function listApps() {
16
+ return Object.keys(APP_PATHS);
17
+ }
18
+ /**
19
+ * Resolve an app name to its absolute filesystem path.
20
+ * Throws if the app name is unknown.
21
+ */
22
+ export function getAppPath(appName) {
23
+ const appPath = APP_PATHS[appName];
24
+ if (!appPath) {
25
+ throw new Error(`Unknown app: ${appName}. Available: ${Object.keys(APP_PATHS).join(', ')}`);
26
+ }
27
+ return appPath;
28
+ }
29
+ /**
30
+ * Deploy an app to Vercel using the `vercel` CLI.
31
+ *
32
+ * Uses `execFile` (not `exec`) to avoid shell injection.
33
+ * The `--cwd` flag tells Vercel which project directory to deploy.
34
+ *
35
+ * @param appName - Short name from APP_PATHS (e.g. 'portfolio', 'dashboard-returnpro')
36
+ * @param prod - If true, deploys to production (--prod flag). Otherwise preview.
37
+ * @returns The deployment URL printed by Vercel CLI.
38
+ */
39
+ export async function deploy(appName, prod = false) {
40
+ const appPath = getAppPath(appName);
41
+ const args = prod
42
+ ? ['--prod', '--cwd', appPath]
43
+ : ['--cwd', appPath];
44
+ const { stdout } = await run('vercel', args, { timeout: 120_000 });
45
+ return stdout.trim();
46
+ }
47
+ /**
48
+ * Run the Optimal workstation health check script.
49
+ *
50
+ * Checks: n8n, Affine (Docker + HTTP), Strapi CMS (systemd + HTTP),
51
+ * Git repo sync status, Docker containers, and OptimalOS dev server.
52
+ *
53
+ * @returns The full text output of the health check script.
54
+ */
55
+ export async function healthCheck() {
56
+ const { stdout } = await run('bash', ['/home/optimal/scripts/health-check.sh'], { timeout: 30_000 });
57
+ return stdout.trim();
58
+ }
@@ -0,0 +1,34 @@
1
+ import 'dotenv/config';
2
+ export interface MigrateOptions {
3
+ target: 'returnpro' | 'optimalos';
4
+ dryRun?: boolean;
5
+ }
6
+ export interface MigrateResult {
7
+ success: boolean;
8
+ target: string;
9
+ output: string;
10
+ errors: string;
11
+ }
12
+ /**
13
+ * Run `supabase db push --linked` (or `--dry-run` if requested) against the
14
+ * given target project directory.
15
+ *
16
+ * Uses `execFile` (not `exec`) to avoid shell injection.
17
+ * The `cwd` option switches the Supabase CLI into the correct project.
18
+ */
19
+ export declare function migrateDb(opts: MigrateOptions): Promise<MigrateResult>;
20
+ /**
21
+ * List migration `.sql` files in the target's `supabase/migrations/` directory,
22
+ * sorted chronologically (by filename, which starts with a YYYYMMDDHHMMSS prefix).
23
+ *
24
+ * Returns only filenames, not full paths.
25
+ */
26
+ export declare function listPendingMigrations(target: 'returnpro' | 'optimalos'): Promise<string[]>;
27
+ /**
28
+ * Create a new empty migration file in the target's `supabase/migrations/`
29
+ * directory.
30
+ *
31
+ * The filename format is `{YYYYMMDDHHMMSS}_{name}.sql` (UTC timestamp).
32
+ * Returns the full absolute path of the created file.
33
+ */
34
+ export declare function createMigration(target: 'returnpro' | 'optimalos', name: string): Promise<string>;