ijima-server 0.3.0

HTTP daemon and store backends for the Ijima centralized agentic memory backend
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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
// Copyright (C) 2026 Industrial Algebra
// SPDX-License-Identifier: Apache-2.0

//! `ijima` — the Ijima daemon and admin CLI.
//!
//! Today: `ijima token issue` mints a Schubert grant token from the
//! persistent issuer key (see [`ijima_server::key_store`]). The HTTP
//! daemon (`ijima serve`) lands once the store + auth HTTP routes are
//! wired.

use std::path::PathBuf;
use std::process::ExitCode;

use clap::{Args, Parser, Subcommand};

#[cfg(feature = "backend-sqlite")]
use ijima_core::NamespaceId;
use ijima_core::capabilities::ALL_CAPABILITIES;
use ijima_server::{IjimaAuth, key_store};

#[derive(Parser)]
#[command(
    name = "ijima",
    version,
    about = "Ijima — centralized agentic memory backend (admin CLI)"
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Mint and inspect Schubert capability tokens.
    Token {
        #[command(subcommand)]
        action: TokenAction,
    },
    /// Manage shared-namespace membership (WS3 org walls) on a running
    /// daemon. Requires an admin bearer.
    Namespace {
        #[command(subcommand)]
        action: NamespaceAction,
    },
    /// Ingest doctrine from a seed-pack directory into a running daemon.
    Doctrine {
        #[command(subcommand)]
        action: DoctrineAction,
    },
    /// Run the HTTP daemon.
    Serve(ServeArgs),
    /// Hard-delete a knowledge-graph triple in a namespace (v0.3.0 U5,
    /// the misplaced-data cleanup tool; admin bearer required).
    KgDelete(KgDeleteArgs),
    /// Export memories as JSONL through the daemon API (admin).
    Export(ExportArgs),
    /// Migrate the legacy pi-mempalace / ZeroClaw SQLite corpora into the
    /// SurrealDB store (one-time import).
    #[cfg(feature = "backend-sqlite")]
    Migrate(MigrateArgs),
    /// Import an external SQLite corpus into a running daemon over HTTP
    /// (WS2 multi-source import: per-source namespace, provenance
    /// tagging, dedup pre-checks).
    #[cfg(feature = "backend-sqlite")]
    Import(ImportArgs),
}

/// Arguments to `ijima export`.
#[derive(Args, Debug)]
struct ExportArgs {
    /// Daemon base URL (e.g. `http://127.0.0.1:7373`) — export runs
    /// through the daemon API (v0.3.0 U6), never by opening the store
    /// directly (the LOCK race that made the old SQL dump unusable
    /// against a running daemon).
    #[arg(long, value_name = "URL")]
    url: String,
    /// Admin bearer token.
    #[arg(long, value_name = "TOKEN")]
    token: String,
    /// Restrict the export to one namespace (default: every namespace).
    #[arg(long, value_name = "NAMESPACE")]
    namespace: Option<String>,
    /// Output file (default: stdout).
    #[arg(long, value_name = "FILE")]
    out: Option<std::path::PathBuf>,
}

/// Which SQLite corpus `ijima import` reads.
#[derive(clap::ValueEnum, Clone, Copy, Debug)]
enum ImportKind {
    /// pi-mempalace `memories.db` (memories + knowledge graph rows).
    Mempalace,
    /// ZeroClaw `brain.db` (Sara's Discord memories).
    Zeroclaw,
}

/// Arguments to `ijima import <kind>`.
#[derive(Args, Debug)]
struct ImportArgs {
    /// Source corpus kind to read.
    #[arg(value_enum)]
    kind: ImportKind,
    /// Path to the source SQLite database.
    #[arg(long, value_name = "PATH")]
    db: std::path::PathBuf,
    /// Source name: stamped as the `origin` provenance of every imported
    /// memory and used to derive the default target namespace
    /// (`ns_import_<source>`).
    #[arg(long, value_name = "NAME")]
    source: String,
    /// Target namespace override (default: `ns_import_<source>`).
    #[arg(long, value_name = "NS")]
    namespace: Option<String>,
    /// Daemon base URL (default: `$IJIMA_URL` or
    /// `http://127.0.0.1:7373`).
    #[arg(long, value_name = "URL")]
    url: Option<String>,
    /// Bearer grant with memory:write (default: `$IJIMA_TOKEN`).
    #[arg(long, value_name = "TOKEN")]
    token: Option<String>,
}

/// Arguments to `ijima migrate`.
#[derive(Args, Debug)]
struct MigrateArgs {
    /// pi-mempalace `memories.db` path (imports memories + KG).
    #[arg(long, value_name = "PATH")]
    palace: Option<std::path::PathBuf>,
    /// ZeroClaw `brain.db` path (imports Sara's Discord memories).
    #[arg(long, value_name = "PATH")]
    brain: Option<std::path::PathBuf>,
    /// Re-embed every imported memory with the candle embedder at write
    /// time (slow for large corpora; without it, search is unavailable
    /// until a later re-embed pass).
    #[arg(long)]
    embed: bool,
    /// Target namespace for imported memories (default: `global`, the
    /// pi-mempalace commons). Use a principal's private namespace
    /// (e.g. `ns_elliott_private`) so migrated history lives where new
    /// pi writes land.
    #[arg(long, value_name = "NS", default_value = "global")]
    namespace: String,
}

#[derive(Subcommand)]
enum DoctrineAction {
    /// Read `*.md` files from a directory and POST them as doctrine
    /// entries to a daemon's `/doctrine` endpoint.
    Ingest(IngestArgs),
}

#[derive(Args)]
struct KgDeleteArgs {
    /// Triple id to hard-delete (percent-encoded ids are accepted as-is).
    #[arg(long, value_name = "ID")]
    id: String,
    /// Namespace holding the triple — REQUIRED (destructive ops are
    /// explicit; private walls are valid targets).
    #[arg(long, value_name = "NAMESPACE")]
    namespace: String,
    /// Daemon base URL (e.g. `http://127.0.0.1:7373`).
    #[arg(long, value_name = "URL")]
    url: String,
    /// Admin bearer token.
    #[arg(long, value_name = "TOKEN")]
    token: String,
}

#[derive(clap::Args)]
struct IngestArgs {
    /// Flat directory of `*.md` doctrine files (frontmatter + body).
    #[arg(long, value_name = "DIR", group = "source")]
    dir: Option<PathBuf>,
    /// Tree mode: walk this corpus root, synthesizing stable ids for
    /// id-less files (upsert-safe re-runs). Mutually exclusive with
    /// `--dir`.
    #[arg(long, value_name = "TREE", group = "source")]
    root: Option<PathBuf>,
    /// fnmatch include against the posix relpath (repeatable; default
    /// all `*.md`). `*` crosses `/`. Tree mode only.
    #[arg(long, value_name = "GLOB")]
    include: Vec<String>,
    /// fnmatch exclude against the posix relpath (repeatable; wins over
    /// includes). Tree mode only.
    #[arg(long, value_name = "GLOB")]
    exclude: Vec<String>,
    /// Print the ingestion plan without contacting the daemon.
    #[arg(long)]
    dry_run: bool,
    /// Target namespace (default: the global curated `ns_doctrine`).
    /// Retarget to a wall for org-scoped corpora (admin still required).
    #[arg(long, value_name = "NAMESPACE")]
    namespace: Option<String>,
    /// Daemon base URL (e.g. `http://127.0.0.1:7373`). Optional with
    /// `--dry-run`.
    #[arg(long, value_name = "URL")]
    url: Option<String>,
    /// Admin bearer token (`ijima token issue --capability admin`).
    /// Optional with `--dry-run`.
    #[arg(long, value_name = "TOKEN")]
    token: Option<String>,
}

#[derive(Args)]
struct ServeArgs {
    /// Bind host (default: $IJIMA_HOST or 127.0.0.1).
    #[arg(long)]
    host: Option<String>,
    /// Bind port (default: $IJIMA_PORT or 7373).
    #[arg(long)]
    port: Option<u16>,
}

#[derive(Subcommand)]
enum TokenAction {
    /// Issue a bearer grant token for a principal.
    Issue(IssueArgs),
    /// Revoke a grant token on a running daemon (the kill-switch).
    /// Requires an admin bearer.
    Revoke(RevokeArgs),
    /// List recorded token revocations on a running daemon.
    Revocations(RevocationsArgs),
}

/// `ijima namespace <action>` — org-wall membership management (WS3).
#[derive(Subcommand, Debug)]
enum NamespaceAction {
    /// Grant a principal membership in a shared namespace.
    Grant(NsMembershipArgs),
    /// Revoke a principal's membership (idempotent).
    Revoke(NsMembershipArgs),
    /// List a namespace's members, oldest grant first.
    Members(NsMembersArgs),
}

#[derive(Args, Debug)]
struct NsMembershipArgs {
    /// The shared namespace (e.g. `ns_ia_shared`).
    namespace: String,
    /// The principal to grant or revoke.
    principal: String,
    /// Daemon base URL.
    #[arg(long, default_value = "http://127.0.0.1:7373")]
    url: String,
    /// Admin bearer token.
    #[arg(long)]
    auth: String,
}

#[derive(Args, Debug)]
struct NsMembersArgs {
    /// The shared namespace to list.
    namespace: String,
    /// Daemon base URL.
    #[arg(long, default_value = "http://127.0.0.1:7373")]
    url: String,
    /// Admin bearer token.
    #[arg(long)]
    auth: String,
}

#[derive(Args)]
struct IssueArgs {
    /// The principal to issue the token to (e.g. `elliott`, `tsume-discord`).
    #[arg(long)]
    principal: String,
    /// The single capability to grant (use `--capabilities` for a
    /// multi-capability grant token). One of the Ijima vocabulary
    /// (memory:read, memory:write, ...). See `ijima-core::capabilities`.
    #[arg(long)]
    capability: Option<String>,
    /// Comma-separated capabilities for a multi-capability grant token,
    /// e.g. `memory:read,memory:write,knowledge:read`. Exactly one of
    /// `--capability` / `--capabilities` is required.
    #[arg(long, value_name = "CSV")]
    capabilities: Option<String>,
    /// Path to the issuance policy TOML (Schubert 0.5 #20.3). Default
    /// resolution: `$IJIMA_POLICY` > `$IJIMA_DIR/policy.toml` > the
    /// embedded policy. The policy must entitle the principal to every
    /// requested capability — issuance fails closed otherwise.
    #[arg(long, value_name = "PATH")]
    policy: Option<PathBuf>,
    /// Grant lifetime in seconds; the grant dies when `now >= now +
    /// seconds` (inclusive, Schubert ADR-0001). Omit for a never-expiring
    /// grant (pre-0.5 behavior). Service principals should always carry
    /// an expiry.
    #[arg(long, value_name = "SECONDS")]
    expires_in: Option<u64>,
    /// Path to the issuer key file. Defaults to `$IJIMA_DIR/issuer.key`
    /// or `~/.ijima/issuer.key`. Created with a fresh seed on first use.
    #[arg(long, value_name = "PATH")]
    key_file: Option<PathBuf>,
    /// Emit a JSON object (token, principal, capabilities, public_key)
    /// instead of just the bearer string.
    #[arg(long)]
    json: bool,
}

#[derive(Args)]
struct RevokeArgs {
    /// The bearer token to revoke — raw or full `Bearer ...` form.
    #[arg(long)]
    token: String,
    /// Daemon base URL.
    #[arg(long, default_value = "http://127.0.0.1:7373")]
    url: String,
    /// Admin bearer token.
    #[arg(long)]
    auth: String,
    /// Operator note recorded with the revocation (e.g. `"leaked in CI log"`).
    #[arg(long)]
    reason: Option<String>,
}

#[derive(Args)]
struct RevocationsArgs {
    /// Daemon base URL.
    #[arg(long, default_value = "http://127.0.0.1:7373")]
    url: String,
    /// Admin bearer token.
    #[arg(long)]
    auth: String,
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    ijima_server::server::init_tracing();
    match cli.command {
        Command::Namespace { action } => match action {
            NamespaceAction::Grant(args) => {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .expect("tokio runtime");
                match rt.block_on(run_ns_grant(args)) {
                    Ok(()) => ExitCode::SUCCESS,
                    Err(e) => {
                        tracing::error!(error = %e, "namespace grant failed");
                        ExitCode::FAILURE
                    }
                }
            }
            NamespaceAction::Revoke(args) => {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .expect("tokio runtime");
                match rt.block_on(run_ns_revoke(args)) {
                    Ok(()) => ExitCode::SUCCESS,
                    Err(e) => {
                        tracing::error!(error = %e, "namespace revoke failed");
                        ExitCode::FAILURE
                    }
                }
            }
            NamespaceAction::Members(args) => {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .expect("tokio runtime");
                match rt.block_on(run_ns_members(args)) {
                    Ok(()) => ExitCode::SUCCESS,
                    Err(e) => {
                        tracing::error!(error = %e, "namespace members failed");
                        ExitCode::FAILURE
                    }
                }
            }
        },
        Command::Token { action } => match action {
            TokenAction::Issue(args) => match run_issue(args) {
                Ok(()) => ExitCode::SUCCESS,
                Err(e) => {
                    tracing::error!(error = %e, "token issue failed");
                    ExitCode::FAILURE
                }
            },
            TokenAction::Revoke(args) => {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .expect("tokio runtime");
                match rt.block_on(run_revoke(args)) {
                    Ok(()) => ExitCode::SUCCESS,
                    Err(e) => {
                        tracing::error!(error = %e, "token revoke failed");
                        ExitCode::FAILURE
                    }
                }
            }
            TokenAction::Revocations(args) => {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .expect("tokio runtime");
                match rt.block_on(run_revocations(args)) {
                    Ok(()) => ExitCode::SUCCESS,
                    Err(e) => {
                        tracing::error!(error = %e, "token revocations failed");
                        ExitCode::FAILURE
                    }
                }
            }
        },
        Command::Doctrine { action } => match action {
            DoctrineAction::Ingest(args) => {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build();
                match rt {
                    Ok(rt) => match rt.block_on(run_doctrine_ingest(args)) {
                        Ok(n) => {
                            tracing::info!(entries = n, "doctrine ingest finished");
                            ExitCode::SUCCESS
                        }
                        Err(e) => {
                            tracing::error!(error = %e, "doctrine ingest failed");
                            ExitCode::FAILURE
                        }
                    },
                    Err(e) => {
                        tracing::error!(error = %e, "runtime build failed");
                        ExitCode::FAILURE
                    }
                }
            }
        },
        Command::KgDelete(args) => {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build();
            match rt {
                Ok(rt) => match rt.block_on(run_kg_delete(args)) {
                    Ok(()) => ExitCode::SUCCESS,
                    Err(e) => {
                        tracing::error!(error = %e, "kg delete failed");
                        ExitCode::FAILURE
                    }
                },
                Err(e) => {
                    tracing::error!(error = %e, "runtime build failed");
                    ExitCode::FAILURE
                }
            }
        }
        Command::Serve(args) => {
            let mut config = ijima_server::server::DaemonConfig::default();
            if let Some(h) = args.host {
                config.host = h;
            }
            if let Some(p) = args.port {
                config.port = p;
            }
            let rt = tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .build();
            match rt {
                Ok(rt) => match rt.block_on(ijima_server::server::serve(&config)) {
                    Ok(()) => ExitCode::SUCCESS,
                    Err(e) => {
                        tracing::error!(error = %e, "serve failed");
                        ExitCode::FAILURE
                    }
                },
                Err(e) => {
                    tracing::error!(error = %e, "runtime build failed");
                    ExitCode::FAILURE
                }
            }
        }
        Command::Export(args) => {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build();
            match rt {
                Ok(rt) => match rt.block_on(run_export(args)) {
                    Ok(()) => ExitCode::SUCCESS,
                    Err(e) => {
                        eprintln!("ijima: {e}");
                        ExitCode::FAILURE
                    }
                },
                Err(e) => {
                    eprintln!("ijima: runtime: {e}");
                    ExitCode::FAILURE
                }
            }
        }
        #[cfg(feature = "backend-sqlite")]
        Command::Import(args) => {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build();
            match rt {
                Ok(rt) => match rt.block_on(run_import(args)) {
                    Ok(()) => ExitCode::SUCCESS,
                    Err(e) => {
                        eprintln!("ijima: import failed: {e}");
                        ExitCode::FAILURE
                    }
                },
                Err(e) => {
                    eprintln!("ijima: runtime: {e}");
                    ExitCode::FAILURE
                }
            }
        }
        #[cfg(feature = "backend-sqlite")]
        Command::Migrate(args) => {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build();
            match rt {
                Ok(rt) => match rt.block_on(run_migrate(args)) {
                    Ok(report) => {
                        tracing::info!(
                            attempted = report.attempted,
                            imported = report.imported,
                            skipped = report.skipped,
                            "migration complete"
                        );
                        eprintln!(
                            "ijima: migrated {} imported, {} skipped (of {} attempted)",
                            report.imported, report.skipped, report.attempted
                        );
                        ExitCode::SUCCESS
                    }
                    Err(e) => {
                        eprintln!("ijima: {e}");
                        ExitCode::FAILURE
                    }
                },
                Err(e) => {
                    eprintln!("ijima: runtime: {e}");
                    ExitCode::FAILURE
                }
            }
        }
    }
}

fn run_issue(args: IssueArgs) -> ijima_core::Result<()> {
    // Exactly one of --capability / --capabilities.
    let caps: Vec<String> = match (args.capability.as_deref(), args.capabilities.as_deref()) {
        (Some(_), Some(_)) => {
            return Err(ijima_core::IjimaError::invalid_input(
                "pass either --capability or --capabilities, not both",
            ));
        }
        (Some(c), None) => vec![c.to_string()],
        (None, Some(csv)) => csv
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect(),
        (None, None) => {
            return Err(ijima_core::IjimaError::invalid_input(
                "missing required --capability (or --capabilities for a multi-cap grant)",
            ));
        }
    };
    for cap in &caps {
        validate_capability(cap)?;
    }
    let cap_refs: Vec<&str> = caps.iter().map(String::as_str).collect();

    let key_path = match args.key_file {
        Some(p) => p,
        None => key_store::default_key_path()?,
    };
    let seed = key_store::load_or_create(&key_path)?;
    let auth = IjimaAuth::from_embedded_policy_with_seed(seed)?;

    // Policy-constrained issuance (Schubert 0.5 #20.3): the resolved
    // policy must entitle the principal to every requested capability —
    // fails closed, no geometry smuggling under an allowed id.
    let policy_toml = IjimaAuth::resolve_issuance_policy(args.policy.as_deref())?;
    let policy_cfg = IjimaAuth::issuance_policy_from_source(&policy_toml)?;
    let grant_policy = schubert::crypto::GrantPolicy::from_policy(&policy_cfg)
        .map_err(|e| ijima_core::IjimaError::invalid_input(format!("grant policy: {e}")))?;
    let expires_at = args.expires_in.map(|secs| {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs() + secs)
            .unwrap_or(secs)
    });
    let token = auth.issue_grant_bearer_under_policy(
        args.principal.as_str(),
        &cap_refs,
        &grant_policy,
        expires_at,
    )?;
    let public_key = auth.issuer_public_key_hex();

    if args.json {
        let caps_json = caps.join(",");
        match expires_at {
            Some(at) => println!(
                "{{\"token\":\"{token}\",\"principal\":\"{}\",\"capabilities\":\"{caps_json}\",\"expires_at_unix\":{at},\"public_key\":\"{public_key}\"}}",
                args.principal
            ),
            None => println!(
                "{{\"token\":\"{token}\",\"principal\":\"{}\",\"capabilities\":\"{caps_json}\",\"public_key\":\"{public_key}\"}}",
                args.principal
            ),
        }
    } else {
        println!("{token}");
    }
    Ok(())
}

fn validate_capability(cap: &str) -> ijima_core::Result<()> {
    if ALL_CAPABILITIES.contains(&cap) {
        Ok(())
    } else {
        Err(ijima_core::IjimaError::invalid_input(format!(
            "unknown capability '{cap}'. Valid: {}",
            ALL_CAPABILITIES.join(", ")
        )))
    }
}

/// `ijima token revoke` — kills a bearer on a running daemon (admin).
/// `ijima namespace grant <ns> <principal>` — WS3 org-wall grant (admin).
async fn run_ns_grant(args: NsMembershipArgs) -> ijima_core::Result<()> {
    let client = reqwest::Client::new();
    let endpoint = format!("{}/namespaces/grant", args.url.trim_end_matches('/'));
    let resp = client
        .post(&endpoint)
        .bearer_auth(args.auth.trim())
        .json(&serde_json::json!({
            "namespace": args.namespace,
            "principal": args.principal,
        }))
        .send()
        .await
        .map_err(|e| ijima_core::IjimaError::Transport {
            detail: format!("namespace grant: {e}"),
        })?;
    match resp.status() {
        reqwest::StatusCode::OK => {
            eprintln!(
                "ijima: `{}` is now a member of `{}`.",
                args.principal, args.namespace
            );
            Ok(())
        }
        reqwest::StatusCode::FORBIDDEN => Err(ijima_core::IjimaError::invalid_input(
            "daemon rejected: the --auth token does not carry admin",
        )),
        status => Err(ijima_core::IjimaError::Transport {
            detail: format!("daemon returned {status}"),
        }),
    }
}

/// `ijima namespace revoke <ns> <principal>` — WS3 org-wall revoke (admin).
async fn run_ns_revoke(args: NsMembershipArgs) -> ijima_core::Result<()> {
    let client = reqwest::Client::new();
    let endpoint = format!("{}/namespaces/revoke", args.url.trim_end_matches('/'));
    let resp = client
        .post(&endpoint)
        .bearer_auth(args.auth.trim())
        .json(&serde_json::json!({
            "namespace": args.namespace,
            "principal": args.principal,
        }))
        .send()
        .await
        .map_err(|e| ijima_core::IjimaError::Transport {
            detail: format!("namespace revoke: {e}"),
        })?;
    match resp.status() {
        reqwest::StatusCode::NO_CONTENT => {
            eprintln!(
                "ijima: `{}` membership in `{}` revoked.",
                args.principal, args.namespace
            );
            Ok(())
        }
        reqwest::StatusCode::FORBIDDEN => Err(ijima_core::IjimaError::invalid_input(
            "daemon rejected: the --auth token does not carry admin",
        )),
        status => Err(ijima_core::IjimaError::Transport {
            detail: format!("daemon returned {status}"),
        }),
    }
}

/// `ijima namespace members <ns>` — WS3 membership listing (admin).
async fn run_ns_members(args: NsMembersArgs) -> ijima_core::Result<()> {
    let client = reqwest::Client::new();
    let endpoint = format!(
        "{}/namespaces/members?namespace={}",
        args.url.trim_end_matches('/'),
        args.namespace
    );
    let resp = client
        .get(&endpoint)
        .bearer_auth(args.auth.trim())
        .send()
        .await
        .map_err(|e| ijima_core::IjimaError::Transport {
            detail: format!("namespace members: {e}"),
        })?;
    match resp.status() {
        reqwest::StatusCode::OK => {
            let members: serde_json::Value =
                resp.json()
                    .await
                    .map_err(|e| ijima_core::IjimaError::Transport {
                        detail: format!("members decode: {e}"),
                    })?;
            println!(
                "{}",
                serde_json::to_string_pretty(&members).unwrap_or_default()
            );
            Ok(())
        }
        reqwest::StatusCode::FORBIDDEN => Err(ijima_core::IjimaError::invalid_input(
            "daemon rejected: the --auth token does not carry admin",
        )),
        status => Err(ijima_core::IjimaError::Transport {
            detail: format!("daemon returned {status}"),
        }),
    }
}

async fn run_revoke(args: RevokeArgs) -> ijima_core::Result<()> {
    let client = reqwest::Client::new();
    let endpoint = format!("{}/tokens/revoke", args.url.trim_end_matches('/'));
    let resp = client
        .post(&endpoint)
        .bearer_auth(args.auth.trim())
        .json(&serde_json::json!({
            "token": args.token,
            "reason": args.reason,
        }))
        .send()
        .await
        .map_err(|e| ijima_core::IjimaError::Transport {
            detail: format!("revoke: {e}"),
        })?;
    match resp.status() {
        reqwest::StatusCode::NO_CONTENT => {
            eprintln!(
                "ijima: token revoked (hash {}).",
                ijima_server::auth::bearer_hash(&args.token)
            );
            Ok(())
        }
        reqwest::StatusCode::FORBIDDEN => Err(ijima_core::IjimaError::invalid_input(
            "daemon rejected: the --auth token does not carry admin",
        )),
        status => Err(ijima_core::IjimaError::Transport {
            detail: format!("daemon returned {status}"),
        }),
    }
}

/// `ijima token revocations` — lists the kill-switch ledger (admin).
async fn run_revocations(args: RevocationsArgs) -> ijima_core::Result<()> {
    let client = reqwest::Client::new();
    let endpoint = format!("{}/tokens/revocations", args.url.trim_end_matches('/'));
    let resp = client
        .get(&endpoint)
        .bearer_auth(args.auth.trim())
        .send()
        .await
        .map_err(|e| ijima_core::IjimaError::Transport {
            detail: format!("revocations: {e}"),
        })?;
    match resp.status() {
        reqwest::StatusCode::OK => {
            let revs: Vec<ijima_core::TokenRevocation> =
                resp.json()
                    .await
                    .map_err(|e| ijima_core::IjimaError::Transport {
                        detail: format!("decode: {e}"),
                    })?;
            if revs.is_empty() {
                eprintln!("ijima: no revocations recorded.");
            }
            for r in revs {
                let reason = r.reason.as_deref().unwrap_or("-");
                eprintln!("{}\t{}\t{}", r.revoked_at_unix, r.token_hash, reason);
            }
            Ok(())
        }
        reqwest::StatusCode::FORBIDDEN => Err(ijima_core::IjimaError::invalid_input(
            "daemon rejected: the --auth token does not carry admin",
        )),
        status => Err(ijima_core::IjimaError::Transport {
            detail: format!("daemon returned {status}"),
        }),
    }
}

async fn run_kg_delete(args: KgDeleteArgs) -> ijima_core::Result<()> {
    let config =
        ijima_client::ClientConfig::new(args.url.clone(), ijima_core::harness::Harness::Other)
            .with_token(args.token.clone());
    let client = ijima_client::Client::new(config);
    client.delete_triple_in(&args.namespace, &args.id).await
}

async fn run_doctrine_ingest(args: IngestArgs) -> ijima_core::Result<usize> {
    let entries: Vec<ijima_server::doctrine::TreeEntry> = if let Some(root) = &args.root {
        ijima_server::doctrine::read_doctrine_tree(root, &args.include, &args.exclude)?
    } else if let Some(dir) = &args.dir {
        ijima_server::doctrine::read_doctrine_dir(dir)?
            .into_iter()
            .map(|(path, entry)| (path, entry, true))
            .collect()
    } else {
        return Err(ijima_core::IjimaError::invalid_input(
            "one of --dir or --root is required",
        ));
    };
    if args.dry_run {
        for (path, entry, verbatim) in &entries {
            let kind = if *verbatim { "keep" } else { "wrap " };
            println!(
                "{kind} {} [{}/{}] {}",
                entry.id,
                entry.project,
                entry.topic,
                path.display()
            );
        }
        println!("files matched: {}", entries.len());
        return Ok(entries.len());
    }
    if entries.is_empty() {
        tracing::warn!(?args.root, ?args.dir, "no *.md doctrine files matched");
        return Ok(0);
    }
    tracing::info!(entries = entries.len(), "ingesting doctrine");
    let (url, token) = match (args.url.as_deref(), args.token.as_deref()) {
        (Some(u), Some(t)) => (u, t),
        _ => {
            return Err(ijima_core::IjimaError::invalid_input(
                "--url and --token are required (only --dry-run may omit them)",
            ));
        }
    };
    let parsed: Vec<_> = entries.iter().map(|(_, e, _)| e.clone()).collect();
    ijima_server::doctrine::ingest_to_daemon(url, token, &parsed, args.namespace.as_deref()).await
}

async fn run_export(args: ExportArgs) -> ijima_core::Result<()> {
    let config =
        ijima_client::ClientConfig::new(args.url.clone(), ijima_core::harness::Harness::Other)
            .with_token(args.token.clone());
    let client = ijima_client::Client::new(config);
    let body = client.export(args.namespace.as_deref()).await?;
    let lines = body.lines().filter(|l| !l.trim().is_empty()).count();
    match &args.out {
        Some(path) => {
            std::fs::write(path, &body).map_err(|e| ijima_core::IjimaError::Store {
                detail: format!("write {}: {e}", path.display()),
            })?;
            eprintln!("ijima: exported {lines} memories to {}", path.display());
        }
        None => {
            print!("{body}");
            eprintln!("ijima: exported {lines} memories",);
        }
    }
    Ok(())
}

/// One-time corpus migration: read the legacy SQLite stores and import
/// them into the SurrealDB palace under the `global` namespace.
/// `ijima import <kind> --db <path> --source <name>` — WS2 multi-source
/// import against a running daemon over HTTP. Reads the source SQLite
/// rows, retags provenance (origin = source, AutoCapture trust), and
/// streams them through the daemon's dedup-checked store path into
/// `ns_import_<source>` (or `--namespace`).
async fn run_import(args: ImportArgs) -> ijima_core::Result<()> {
    use ijima_server::migration::{
        default_import_ns, map_pipalace_kg, map_pipalace_memory, map_zeroclaw_memory,
        read_pipalace_kg, read_pipalace_memories, read_zeroclaw_memories, retag_imported,
    };

    let url = args
        .url
        .or_else(|| std::env::var("IJIMA_URL").ok())
        .unwrap_or_else(|| "http://127.0.0.1:7373".to_string());
    let token = args
        .token
        .or_else(|| std::env::var("IJIMA_TOKEN").ok())
        .ok_or_else(|| {
            ijima_core::IjimaError::invalid_input(
                "import needs --token or $IJIMA_TOKEN (a memory:write grant)",
            )
        })?;

    let memories: Vec<_> = match args.kind {
        ImportKind::Mempalace => {
            let rows = read_pipalace_memories(&args.db.to_string_lossy())?;
            eprintln!("ijima: read {} rows from {}", rows.len(), args.db.display());
            rows.iter().map(map_pipalace_memory).collect::<Vec<_>>()
        }
        ImportKind::Zeroclaw => {
            let rows = read_zeroclaw_memories(&args.db.to_string_lossy())?;
            eprintln!("ijima: read {} rows from {}", rows.len(), args.db.display());
            rows.iter().map(map_zeroclaw_memory).collect::<Vec<_>>()
        }
    }
    .into_iter()
    .map(|m| retag_imported(m, &args.source))
    .collect();

    let ns = args
        .namespace
        .unwrap_or_else(|| default_import_ns(&args.source).as_str().to_string());

    let client = ijima_client::Client::new(
        ijima_client::ClientConfig::new(url, ijima_core::harness::Harness::Pi).with_token(token),
    );
    eprintln!(
        "ijima: importing {} memories from `{}` into namespace `{ns}`…",
        memories.len(),
        args.source
    );
    let counts = client.import_memories(&ns, memories).await?;
    eprintln!(
        "ijima: import `{}` complete — {} added, {} deduped, {} skipped (of {} attempted)",
        args.source, counts.added, counts.deduped, counts.skipped, counts.attempted
    );

    // Knowledge graph (pi-mempalace corpora only — ZeroClaw predated the
    // KG). Entities are re-addressed from opaque `ent_*` ids to Ijima's
    // id-is-name convention; triples with unmappable references are
    // counted as unmapped, not imported.
    let mut kg_counts = ijima_core::KgImportCounts::default();
    let mut kg_unmapped = 0usize;
    if matches!(args.kind, ImportKind::Mempalace) {
        let (entities, triples) = read_pipalace_kg(&args.db.to_string_lossy())?;
        let kg = map_pipalace_kg(&entities, &triples);
        kg_unmapped = kg.unmapped;
        eprintln!(
            "ijima: importing knowledge graph — {} triples ({} unmapped) from {} entities…",
            kg.triples.len(),
            kg.unmapped,
            entities.len()
        );
        kg_counts = client.import_kg(&ns, kg.triples).await?;
        eprintln!(
            "ijima: kg import complete — {} added, {} skipped (of {} attempted)",
            kg_counts.added, kg_counts.skipped, kg_counts.attempted
        );
    }

    println!(
        "{}",
        serde_json::to_string_pretty(&serde_json::json!({
            "memories": counts,
            "knowledge": kg_counts,
            "unmapped": kg_unmapped,
        }))
        .unwrap_or_default()
    );
    Ok(())
}

#[cfg(feature = "backend-sqlite")]
async fn run_migrate(
    args: MigrateArgs,
) -> ijima_core::Result<ijima_server::migration::ImportReport> {
    use ijima_server::migration::{
        import_memories, map_pipalace_memory, map_zeroclaw_memory, read_pipalace_memories,
        read_zeroclaw_memories,
    };

    if args.palace.is_none() && args.brain.is_none() {
        return Err(ijima_core::IjimaError::invalid_input(
            "migrate needs at least one of --palace <memories.db> or --brain <brain.db>",
        ));
    }

    let data_dir = ijima_server::config::resolve_data_dir()?;
    let db_path = data_dir.join("ijima.db");

    // Open the store, optionally with the candle embedder so imported
    // memories are embedded at write time (slow for large corpora).
    #[cfg(feature = "embeddings-candle")]
    let store = if args.embed {
        let embedder: std::sync::Arc<dyn ijima_core::Embedder> =
            std::sync::Arc::new(ijima_server::embeddings_candle::CandleEmbedder::from_env()?);
        ijima_server::SurrealStore::open_persistent_with(&db_path, embedder).await?
    } else {
        ijima_server::SurrealStore::open_persistent(&db_path).await?
    };
    #[cfg(not(feature = "embeddings-candle"))]
    let store = ijima_server::SurrealStore::open_persistent(&db_path).await?;

    let ns = NamespaceId::new(&args.namespace);
    let mut all: Vec<ijima_core::Memory> = Vec::new();

    if let Some(palace) = &args.palace {
        let rows = read_pipalace_memories(&palace.to_string_lossy())?;
        eprintln!("ijima: read {} rows from {}", rows.len(), palace.display());
        all.extend(rows.iter().map(map_pipalace_memory));
    }
    if let Some(brain) = &args.brain {
        let rows = read_zeroclaw_memories(&brain.to_string_lossy())?;
        eprintln!("ijima: read {} rows from {}", rows.len(), brain.display());
        all.extend(rows.iter().map(map_zeroclaw_memory));
    }

    eprintln!(
        "ijima: importing {} memories into namespace `{}`…",
        all.len(),
        ns.as_str()
    );
    let report = import_memories(&store, &ns, all).await?;
    Ok(report)
}