1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
use clap::{Parser, Subcommand, builder::styling};
use eyre::Result;
use kibana_object_manager::{
cli::{
add_objects_to_manifest, bundle_to_ndjson, init_from_export, load_kibana_client,
pull_saved_objects, push_saved_objects, version_warning_message,
},
migration::{MigrationResult, migrate_to_multispace_unified},
};
use owo_colors::OwoColorize;
use std::fmt;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use tracing::field::{Field, Visit};
use tracing_subscriber::{
field::RecordFields,
fmt::{FormatFields, format::Writer},
};
fn init_logging(filter: &str) {
let _ = tracing_log::LogTracer::init();
let use_ansi = std::env::var_os("NO_COLOR").is_none()
&& (std::io::stderr().is_terminal()
|| std::env::var_os("FORCE_COLOR").is_some()
|| std::env::var_os("CLICOLOR_FORCE").is_some());
let _ = tracing_subscriber::fmt()
.fmt_fields(AnsiPassthroughFields)
.with_env_filter(tracing_subscriber::EnvFilter::new(filter))
.with_target(false)
.with_ansi(use_ansi)
.try_init();
}
#[derive(Debug, Clone, Copy)]
struct AnsiPassthroughFields;
impl<'writer> FormatFields<'writer> for AnsiPassthroughFields {
fn format_fields<R: RecordFields>(&self, writer: Writer<'writer>, fields: R) -> fmt::Result {
let mut visitor = AnsiPassthroughVisitor {
writer,
is_empty: true,
result: Ok(()),
};
fields.record(&mut visitor);
visitor.result
}
}
struct AnsiPassthroughVisitor<'writer> {
writer: Writer<'writer>,
is_empty: bool,
result: fmt::Result,
}
impl AnsiPassthroughVisitor<'_> {
fn record_value(&mut self, field: &Field, value: impl FnOnce(&mut Writer<'_>) -> fmt::Result) {
if field.name().starts_with("log.") {
return;
}
if self.result.is_err() {
return;
}
self.result = (|| {
if !self.is_empty {
write!(self.writer, " ")?;
}
if field.name() != "message" {
write!(self.writer, "{}=", field.name())?;
}
value(&mut self.writer)?;
self.is_empty = false;
Ok(())
})();
}
}
impl Visit for AnsiPassthroughVisitor<'_> {
fn record_f64(&mut self, field: &Field, value: f64) {
self.record_value(field, |writer| write!(writer, "{value}"));
}
fn record_i64(&mut self, field: &Field, value: i64) {
self.record_value(field, |writer| write!(writer, "{value}"));
}
fn record_u64(&mut self, field: &Field, value: u64) {
self.record_value(field, |writer| write!(writer, "{value}"));
}
fn record_i128(&mut self, field: &Field, value: i128) {
self.record_value(field, |writer| write!(writer, "{value}"));
}
fn record_u128(&mut self, field: &Field, value: u128) {
self.record_value(field, |writer| write!(writer, "{value}"));
}
fn record_bool(&mut self, field: &Field, value: bool) {
self.record_value(field, |writer| write!(writer, "{value}"));
}
fn record_str(&mut self, field: &Field, value: &str) {
self.record_value(field, |writer| write!(writer, "{value}"));
}
fn record_bytes(&mut self, field: &Field, value: &[u8]) {
self.record_value(field, |writer| write!(writer, "{value:?}"));
}
fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
self.record_value(field, |writer| write!(writer, "{value}"));
}
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
self.record_value(field, |writer| write!(writer, "{value:?}"));
}
}
// CLI Styling
const STYLES: styling::Styles = styling::Styles::styled()
.header(styling::AnsiColor::BrightWhite.on_default())
.usage(styling::AnsiColor::BrightWhite.on_default())
.literal(styling::AnsiColor::Green.on_default())
.placeholder(styling::AnsiColor::Cyan.on_default());
/// Kibana Object Manager: --{kibob}-> Git-inspired CLI for managing Kibana saved objects in version control
///
/// Manage dashboards, visualizations, and saved objects with a familiar Git-like workflow.
/// Version control your Kibana artifacts, deploy across environments, and collaborate with Git.
///
/// Environment Variables:
/// KIBANA_URL Kibana base URL (required)
/// KIBANA_USERNAME Basic auth username (optional)
/// KIBANA_PASSWORD Basic auth password (optional)
/// KIBANA_APIKEY API key authentication (optional, conflicts with user/pass)
/// KIBANA_SPACE Kibana space ID (default: 'default')
///
/// Examples:
/// kibob auth Test connection to Kibana
/// kibob init export.ndjson ./dashboards Initialize project from export
/// kibob pull . Fetch objects from Kibana
/// kibob push . --managed true Deploy to Kibana as managed objects
#[derive(Parser)]
#[command(name = "kibob", version, styles = STYLES, about, long_about)]
struct Cli {
/// Dotenv file to load environment variables from
#[arg(short, long, global = true, default_value = ".env")]
env: String,
/// Enable verbose logging (debug level)
#[arg(long, global = true)]
debug: bool,
/// Command to execute
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Initialize a new project from a Kibana export file
///
/// Creates a manifest and extracts objects into organized directories.
/// The export file is typically downloaded from Kibana UI (Stack Management → Saved Objects → Export).
///
/// Example:
/// kibob init export.ndjson ./my-dashboards
Init {
/// NDJSON export file or directory containing export.ndjson
#[arg(default_value = "export.ndjson")]
export: String,
/// Output directory for manifest and objects
#[arg(default_value = "manifest.json")]
manifest: String,
},
/// Test connection and authentication to Kibana
///
/// Verifies that your credentials and connection are working.
/// Requires KIBANA_URL and either KIBANA_USERNAME/KIBANA_PASSWORD or KIBANA_APIKEY.
///
/// Example:
/// kibob auth
Auth,
/// Pull (fetch) saved objects from Kibana to local files
///
/// Downloads objects specified in the manifest from Kibana and saves them locally.
/// Objects are organized by type in the objects/ directory.
///
/// Examples:
/// kibob pull ./my-dashboards
/// kibob pull ./my-dashboards --space esdiag
/// kibob pull ./my-dashboards --api tools,agents
/// kibob pull ./my-dashboards --force # Bypass version checks (warning)
Pull {
/// Project directory containing manifest (default: current directory)
#[arg(default_value = ".")]
output_dir: String,
/// Kibana space(s) to pull from (comma-separated, overrides KIBANA_SPACE env var)
#[arg(long, value_delimiter = ',')]
space: Option<Vec<String>>,
/// Comma-separated APIs to pull with min versions:
/// saved_objects (8.0+), spaces (8.0+), agents (9.2+ tech preview), tools (9.2+ tech preview), workflows (9.3+ tech preview), skills (9.4+ experimental)
#[arg(long, value_delimiter = ',')]
api: Option<Vec<String>>,
/// Bypass version compatibility checks and attempt API calls anyway (prints warning)
#[arg(long)]
force: bool,
},
/// Push (upload) local saved objects to Kibana
///
/// Uploads objects from local files to Kibana. Use --managed true (default) to make
/// objects read-only in Kibana UI, or --managed false to allow editing.
///
/// Examples:
/// kibob push . --managed true # Read-only in Kibana (recommended for production)
/// kibob push . --managed false # Editable in Kibana
/// kibob push . --space esdiag # Push to specific space
/// kibob push . --api tools # Push only tools
/// kibob push . --force # Bypass version checks (warning)
Push {
/// Project directory containing objects to upload
#[arg(default_value = ".")]
input_dir: String,
/// Make objects read-only in Kibana UI (managed: true)
#[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
managed: bool,
/// Kibana space(s) to push to (comma-separated, overrides KIBANA_SPACE env var)
#[arg(long, value_delimiter = ',')]
space: Option<Vec<String>>,
/// Comma-separated APIs to push with min versions:
/// saved_objects (8.0+), spaces (8.0+), agents (9.2+ tech preview), tools (9.2+ tech preview), workflows (9.3+ tech preview), skills (9.4+ experimental)
#[arg(long, value_delimiter = ',')]
api: Option<Vec<String>>,
/// Bypass version compatibility checks and attempt API calls anyway (prints warning)
#[arg(long)]
force: bool,
},
/// Add items to an existing manifest
///
/// Discovers and adds items via search API or reads from a file.
/// Supports: objects, workflows, spaces, agents, tools, skills
/// Skills are experimental as of Kibana 9.4 and are stored as
/// skills/{skill-directory}/SKILL.md with YAML frontmatter fields:
/// id, name, description, tool_ids, and experimental.
/// Referenced content is projected from all files under the skill directory.
/// Local experimental metadata is omitted from API create/update bodies.
///
/// Examples:
/// kibob add workflows . # Search all workflows in default space
/// kibob add workflows . --space marketing # Search in specific space
/// kibob add workflows . --query "alert" # Search for workflows matching "alert"
/// kibob add workflows . --include "^prod" # Include names matching regex "^prod"
/// kibob add workflows . --exclude "test" # Exclude names matching regex "test"
/// kibob add workflows . --file export.json # Add from API response file
/// kibob add workflows . --file export.ndjson # Add from bundle file
/// kibob add spaces . # Fetch all spaces
/// kibob add spaces . --include "prod|staging" # Include spaces matching pattern
/// kibob add agents . # Fetch all agents
/// kibob add agents . --include "^support" # Include agents matching pattern
/// kibob add tools . # Fetch all tools
/// kibob add tools . --include "^search" # Include tools matching pattern
/// kibob add skill threat-hunting # Fetch a skill by ID into the current directory
/// kibob add skills . --query "threat-hunting" # Fetch a skill by ID
/// kibob add skills . --include "^triage" # Include skills matching pattern
/// kibob add objects . --objects "dashboard=abc" # Legacy: add specific objects by ID
/// kibob add workflows . --force # Bypass version checks (warning)
Add {
/// API to add to:
/// objects (8.0+), spaces (8.0+), agents (9.2+ tech preview), tools (9.2+ tech preview), workflows (9.3+ tech preview), skills (9.4+ experimental)
api: String,
/// Project directory with existing manifest
#[arg(default_value = ".")]
output_dir: String,
/// Search query term for API
#[arg(short, long, conflicts_with_all = &["file", "objects"])]
query: Option<String>,
/// Include items matching regex pattern (applied to name field)
#[arg(short, long)]
include: Option<String>,
/// Exclude items matching regex pattern (applied to name field, after include)
#[arg(short, long)]
exclude: Option<String>,
/// File to read from (.json or .ndjson)
#[arg(long, conflicts_with_all = &["query", "objects"])]
file: Option<String>,
/// [objects only] Comma-separated "type=id" pairs to add
#[arg(short = 'o', long, conflicts_with_all = &["query", "file"])]
objects: Option<Vec<String>>,
/// Kibana space(s) to add to/filter by (comma-separated, defaults to "default" for non-space APIs)
#[arg(long, value_delimiter = ',')]
space: Option<Vec<String>>,
/// Exclude dependencies of added items (agents, tools, workflows, skills)
#[arg(long)]
exclude_dependencies: bool,
/// Bypass version compatibility checks and attempt API calls anyway (prints warning)
#[arg(long)]
force: bool,
},
/// Bundle objects into distributable NDJSON files
///
/// Creates a bundle/ directory with NDJSON files for each API:
/// - bundle/{space_id}/saved_objects.ndjson - Saved objects per space
/// - bundle/{space_id}/workflows.ndjson - Workflows per space
/// - bundle/{space_id}/agents.ndjson - Agents per space
/// - bundle/{space_id}/tools.ndjson - Tools per space
/// - bundle/{space_id}/skills.ndjson - Skills per space
/// - bundle/spaces.ndjson - Spaces (if manifest/spaces.yml exists)
///
/// Skill JSON is generated from skills/{skill-directory}/SKILL.md and
/// referenced markdown files only when bundling.
///
/// The bundle directory can be easily zipped for distribution.
///
/// Example:
/// kibob togo ./my-dashboards
/// kibob togo ./my-dashboards --space default
/// zip -r dashboards.zip my-dashboards/bundle/
Togo {
/// Project directory containing objects to bundle
#[arg(default_value = ".")]
input_dir: String,
/// Set managed flag in bundled objects
#[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
managed: bool,
/// Kibana space(s) to bundle (comma-separated, e.g., "default,marketing")
#[arg(long, value_delimiter = ',')]
space: Option<Vec<String>>,
/// Comma-separated list of APIs to bundle (e.g., "saved_objects,workflows,agents,tools,skills,spaces")
#[arg(long, value_delimiter = ',')]
api: Option<Vec<String>>,
},
/// Migrate legacy structure to multi-space format
///
/// Converts either:
/// - Legacy manifest.json → manifest/default/saved_objects.json
/// - Old manifest/saved_objects.json → manifest/default/saved_objects.json
///
/// This is a single-step migration that moves all content to the 'default' space.
/// Creates a backup by default unless --no-backup is specified.
///
/// Example:
/// kibob migrate ./old-project
Migrate {
/// Project directory containing legacy manifest.json
#[arg(default_value = ".")]
project_dir: String,
/// Create backup of old manifest.json
#[arg(short, long, default_value_t = true, action = clap::ArgAction::Set)]
backup: bool,
},
}
fn resolve_env_path(env: &str) -> PathBuf {
let env_path = Path::new(env);
if env == ".env" || env.contains(std::path::MAIN_SEPARATOR) || env.starts_with('.') {
return env_path.to_path_buf();
}
if env_path.exists() {
return env_path.to_path_buf();
}
PathBuf::from(format!(".env.{}", env))
}
fn is_skill_id_shortcut_arg(value: &str) -> bool {
!value.is_empty()
&& value != "."
&& value != ".."
&& !value.contains('/')
&& !value.contains('\\')
}
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
let resolved_env = resolve_env_path(&cli.env);
if let Err(e) = dotenvy::from_filename(&resolved_env) {
log::warn!(
"Failed to load environment variables from {}: {}",
resolved_env.display(),
e
);
}
let log_level = match cli.debug {
true => "debug",
false => "info",
};
let filter = std::env::var("LOG_LEVEL").unwrap_or_else(|_| log_level.to_string());
init_logging(&filter);
match cli.command {
Commands::Init { export, manifest } => {
log::info!(
"Initializing from {} and building manifest in {}",
export.bright_black(),
manifest.bright_black()
);
// Determine if export is a file or directory
let export_path = std::path::Path::new(&export);
let export_file = if export_path.is_dir() {
export_path.join("export.ndjson")
} else {
export_path.to_path_buf()
};
if !export_file.exists() {
log::error!("Export file not found: {}", export_file.display());
return Err(eyre::eyre!(
"Export file not found: {}",
export_file.display()
));
}
match init_from_export(&export_file, &manifest).await {
Ok(count) => {
log::info!("✓ Initialized {} object(s)", count);
}
Err(e) => {
log::error!("Init failed: {}", e);
return Err(e);
}
}
}
Commands::Auth => {
log::info!("Testing authorization to Kibana");
match load_kibana_client(".") {
Ok(client) => match client.test_connection().await {
Ok(response) => {
if response.status().is_success() {
log::info!("✓ Authorization successful");
log::info!(
" Connected to: {}",
std::env::var("KIBANA_URL")
.unwrap_or_else(|_| "unknown".to_string())
.green()
);
} else {
log::error!("✗ Authorization failed: {}", response.status());
return Err(eyre::eyre!(
"Authorization failed with status: {}",
response.status()
));
}
}
Err(e) => {
log::error!("✗ Connection test failed: {}", e);
return Err(e.into());
}
},
Err(e) => {
log::error!("✗ Failed to create Kibana client: {}", e);
return Err(e);
}
}
}
Commands::Pull {
output_dir,
space,
api,
force,
} => {
log::info!("Pulling objects to: {}", output_dir.bright_black());
if let Some(spaces) = &space {
log::info!("Filtering to space(s): {}", spaces.join(", ").cyan());
}
if let Some(apis) = &api {
log::info!("Filtering to API(s): {}", apis.join(", ").cyan());
}
match pull_saved_objects(&output_dir, space.as_deref(), api.as_deref(), force).await {
Ok(count) => {
log::info!("✓ Successfully pulled {} object(s)", count);
}
Err(e) => {
if let Some(message) = version_warning_message(&e) {
log::warn!("{}", message);
std::process::exit(2);
}
log::error!("Pull failed: {}", e);
return Err(e);
}
}
}
Commands::Push {
input_dir,
managed,
space,
api,
force,
} => {
log::info!(
"Pushing {} objects from: {}",
match managed {
true => "managed",
false => "unmanaged",
}
.cyan(),
input_dir.bright_black(),
);
if let Some(spaces) = &space {
log::info!("Filtering to space(s): {}", spaces.join(", ").cyan());
}
if let Some(apis) = &api {
log::info!("Filtering to API(s): {}", apis.join(", ").cyan());
}
match push_saved_objects(&input_dir, managed, space.as_deref(), api.as_deref(), force)
.await
{
Ok(count) => {
log::info!("✓ Successfully pushed {} object(s)", count);
}
Err(e) => {
if let Some(message) = version_warning_message(&e) {
log::warn!("{}", message);
std::process::exit(2);
}
log::error!("Push failed: {}", e);
return Err(e);
}
}
}
Commands::Add {
api,
output_dir,
query,
include,
exclude,
file,
objects,
space,
exclude_dependencies,
force,
} => {
log::info!("Adding {} to {}", api.cyan(), output_dir.bright_black());
// Route to appropriate handler based on API type
let count_result: Result<usize> = match api.as_str() {
"objects" => {
// Legacy objects support: --objects flag or --file
let target_space = space
.as_ref()
.and_then(|s| s.first())
.map(|s| s.as_str())
.unwrap_or("default");
log::info!("Using space: {}", target_space.cyan());
add_objects_to_manifest(&output_dir, target_space, objects, file, force).await
}
"workflows" => {
// Workflows support: --query, --include, --exclude, or --file
let target_space = space
.as_ref()
.and_then(|s| s.first())
.map(|s| s.as_str())
.unwrap_or("default");
log::info!("Using space: {}", target_space.cyan());
use kibana_object_manager::cli::add_workflows_to_manifest;
add_workflows_to_manifest(
&output_dir,
target_space,
query,
include,
exclude,
file,
exclude_dependencies,
force,
)
.await
}
"spaces" => {
// Spaces support: --query (ignored), --include, --exclude, or --file
// and --space ID filtering
use kibana_object_manager::cli::add_spaces_to_manifest;
add_spaces_to_manifest(
&output_dir,
space.as_deref(),
query,
include,
exclude,
file,
force,
)
.await
}
"agents" => {
// Agents support: --query (ignored), --include, --exclude, or --file
let target_space = space
.as_ref()
.and_then(|s| s.first())
.map(|s| s.as_str())
.unwrap_or("default");
log::info!("Using space: {}", target_space.cyan());
use kibana_object_manager::cli::add_agents_to_manifest;
add_agents_to_manifest(
&output_dir,
target_space,
query,
include,
exclude,
file,
exclude_dependencies,
force,
)
.await
}
"tools" => {
// Tools support: --query (ignored), --include, --exclude, or --file
let target_space = space
.as_ref()
.and_then(|s| s.first())
.map(|s| s.as_str())
.unwrap_or("default");
log::info!("Using space: {}", target_space.cyan());
use kibana_object_manager::cli::add_tools_to_manifest;
add_tools_to_manifest(
&output_dir,
target_space,
query,
include,
exclude,
file,
exclude_dependencies,
force,
)
.await
}
"skills" | "skill" => {
// Skills support: --query exact ID, --include, --exclude, or --file
let singular_id_shortcut = api == "skill"
&& query.is_none()
&& file.is_none()
&& output_dir != "."
&& is_skill_id_shortcut_arg(&output_dir)
&& !Path::new(&output_dir).exists();
if api == "skill" && query.is_none() && file.is_none() && !singular_id_shortcut
{
return Err(eyre::eyre!(
"kibob add skill requires a skill id. For an existing project directory, use: kibob add skill <project_dir> --query <skill-id>. If the skill id matches a local path, use: kibob add skill . --query <skill-id>"
));
}
let effective_output_dir;
let effective_query;
let (project_dir, query) = if singular_id_shortcut {
effective_output_dir = ".".to_string();
effective_query = Some(output_dir.clone());
(effective_output_dir.as_str(), effective_query)
} else {
(output_dir.as_str(), query)
};
let target_space = space
.as_ref()
.and_then(|s| s.first())
.map(|s| s.as_str())
.unwrap_or("default");
log::info!("Using space: {}", target_space.cyan());
use kibana_object_manager::cli::add_skills_to_manifest;
add_skills_to_manifest(
project_dir,
target_space,
query,
include,
exclude,
file,
exclude_dependencies,
force,
)
.await
}
_ => {
log::error!("Unknown API: {}", api);
return Err(eyre::eyre!(
"Unknown API '{}'. Supported: objects, workflows, spaces, agents, tools, skills",
api
));
}
};
match count_result {
Ok(count) => log::info!("✓ Added {} item(s)", count),
Err(e) => {
if let Some(message) = version_warning_message(&e) {
log::warn!("{}", message);
std::process::exit(2);
}
return Err(e);
}
}
}
Commands::Togo {
input_dir,
managed,
space,
api,
} => {
log::info!(
"Creating to-go bundle from: {}, managed: {}",
input_dir.bright_black(),
managed.cyan()
);
if let Some(spaces) = &space {
log::info!("Filtering to space(s): {}", spaces.join(", ").cyan());
}
if let Some(apis) = &api {
log::info!("Filtering to API(s): {}", apis.join(", ").cyan());
}
// Create bundle directory
let bundle_dir = std::path::Path::new(&input_dir).join("bundle");
std::fs::create_dir_all(&bundle_dir)?;
log::info!("Bundle directory: {}", bundle_dir.display());
// Bundle saved objects (now creates per-space bundles)
let saved_objects_file = bundle_dir.join("saved_objects.ndjson");
match bundle_to_ndjson(
&input_dir,
&saved_objects_file,
managed,
space.as_deref(),
api.as_deref(),
)
.await
{
Ok(count) => {
log::info!("✓ Bundled {} saved object(s)", count);
}
Err(e) => {
log::error!("Bundle failed: {}", e);
return Err(e);
}
}
log::info!("✓ Bundle created at {}", bundle_dir.display());
}
Commands::Migrate {
project_dir,
backup,
} => {
log::info!(
"Migrating project to multi-space structure: {}",
project_dir.bright_black()
);
match migrate_to_multispace_unified(&project_dir, backup, Some(&resolved_env)).await? {
MigrationResult::MigratedWithBackup(backup_path) => {
let target_space = std::env::var("kibana_space")
.or_else(|_| std::env::var("KIBANA_SPACE"))
.unwrap_or_else(|_| "default".to_string());
log::info!("✓ Migration completed successfully!");
log::info!(
" New manifest: {}",
format!(
"{}/{}/manifest/saved_objects.json",
project_dir, target_space
)
.green()
);
log::info!(
" Backup saved: {}",
backup_path.display().to_string().cyan()
);
}
MigrationResult::MigratedWithoutBackup => {
let target_space = std::env::var("kibana_space")
.or_else(|_| std::env::var("KIBANA_SPACE"))
.unwrap_or_else(|_| "default".to_string());
log::info!("✓ Migration completed successfully!");
log::info!(
" New manifest: {}",
format!(
"{}/{}/manifest/saved_objects.json",
project_dir, target_space
)
.green()
);
log::info!(" Old files removed (no backup)");
}
MigrationResult::NoLegacyManifest => {
log::warn!("No legacy structure found in {}", project_dir);
log::info!("Nothing to migrate.");
}
MigrationResult::AlreadyMigrated => {
let target_space = std::env::var("kibana_space")
.or_else(|_| std::env::var("KIBANA_SPACE"))
.unwrap_or_else(|_| "default".to_string());
log::info!("✓ Project is already using multi-space structure!");
log::info!(" {}/manifest/ already exists", target_space);
}
}
}
}
Ok(())
}