agentstatedeveloper-cli 1.4.9

asd CLI — command-line interface for AgentStateDeveloper
Documentation
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
//! `asd ledger …` — append ledger entries against a symbol.

use std::path::PathBuf;

use anyhow::Result;
use clap::{Args, Subcommand, ValueEnum};

use agentstatedeveloper_core::{
    AsgIndexStore, AsgLedgerStore, AuditEvent, Author, AuthorKind, Decision, Engine, IndexStore,
    LedgerEntry, LedgerKind, LedgerStore, Situation, actions, emit_audit, event_types,
};

use serde_json::json;

use crate::config::Config;

/// Open the engine with optional policy + audit wiring based on cfg.
/// If the process has installed a sink override (see
/// `crate::set_audit_sink_override`), that sink is used. Otherwise
/// events are swallowed by the default `NullSink`; when a log path
/// was configured we surface a warning so the OSS user knows their
/// `--audit-log` was a no-op.
fn open_engine(cfg: &Config) -> anyhow::Result<Engine> {
    let mut engine = Engine::open_sqlite(&cfg.db_path)?;
    if let Some(ref p) = cfg.policy_path {
        engine
            .load_policy_file(p)
            .map_err(|e| anyhow::anyhow!("failed to load policy file {}: {e}", p.display()))?;
    }
    if let Some(sink) = crate::audit_sink_override() {
        engine.set_audit_sink(sink);
    } else if cfg.audit_log_path.is_some() {
        eprintln!(
            "warning: audit log path configured but tamper-evident \
             logging is a commercial feature — install asd-pro \
             (Enterprise tier) to enable. Running with in-memory \
             NullSink."
        );
    }
    if let Some(ratify) = crate::ratify_ops_override() {
        engine.set_ratify_ops(ratify);
    }
    Ok(engine)
}

/// Public variant of [`open_engine`] for downstream crates that want
/// to reuse the same policy + audit wiring. Used by `asd-pro`'s
/// commercial subcommand handlers.
pub fn open_engine_public(cfg: &Config) -> anyhow::Result<Engine> {
    open_engine(cfg)
}

#[derive(Debug, Subcommand)]
pub enum LedgerCmd {
    /// Append a new ledger entry for a symbol.
    Append(AppendArgs),

    /// Approve an entry currently tagged `awaiting-approval`.
    Approve(ApproveArgs),

    /// Reject an entry currently tagged `awaiting-approval`.
    Reject(RejectArgs),

    /// Withdraw an awaiting-approval entry — must be called by the
    /// original author.
    Withdraw(WithdrawArgs),

    /// Write a new entry that supersedes one or more existing entries.
    /// Non-superseded entries remain; superseded ones are filtered out
    /// of the default `list_entries` view.
    Supersede(SupersedeArgs),

    /// Record that a symbol was renamed/moved so its ledger history follows.
    /// Writes a rebind record and re-parents all ledger entries to the new
    /// symbol_id. Use this when you rename a function/class with an ASD-aware
    /// tool so context doesn't become orphaned.
    Rebind(RebindArgs),
}

#[derive(Debug, Args)]
pub struct ApproveArgs {
    /// Entry id (e.g., `led_abc…`) to approve.
    pub entry_id: String,

    /// Approver identifier. Recorded as `approved-by:<id>`.
    #[arg(long)]
    pub approver: String,

    /// Approver kind. Must match one of the `approver:*` tags unless
    /// the id itself matches.
    #[arg(long, default_value = "human")]
    pub approver_kind: String,

    /// Optional rationale — appended to the entry body as an
    /// "Approver note" section.
    #[arg(long)]
    pub message: Option<String>,
}

#[derive(Debug, Args)]
pub struct RejectArgs {
    /// Entry id to reject.
    pub entry_id: String,

    /// Reviewer identifier. Recorded as `rejected-by:<id>`.
    #[arg(long)]
    pub reviewer: String,

    /// Reviewer kind. Same approver-match rule as approve.
    #[arg(long, default_value = "human")]
    pub reviewer_kind: String,

    /// Rejection reason (required). Appended to the entry body.
    #[arg(long)]
    pub reason: String,
}

#[derive(Debug, Args)]
pub struct WithdrawArgs {
    /// Entry id to withdraw.
    pub entry_id: String,

    /// Author id — must match `entry.author.id`.
    #[arg(long)]
    pub author_id: String,
}

#[derive(Debug, Args)]
pub struct SupersedeArgs {
    /// Qname the new entry attaches to.
    pub qname: String,

    /// One or more entry ids to supersede. All must belong to the same
    /// symbol as `qname`.
    #[arg(long = "supersede", required = true)]
    pub supersedes: Vec<String>,

    /// Ledger kind for the new entry.
    #[arg(long, value_enum)]
    pub kind: CliLedgerKind,

    /// One-line summary for the new entry.
    #[arg(long)]
    pub summary: String,

    /// Optional body file.
    #[arg(long)]
    pub body: Option<PathBuf>,

    /// Author kind.
    #[arg(long, value_enum, default_value_t = CliAuthorKind::Agent)]
    pub author_kind: CliAuthorKind,

    /// Author id.
    #[arg(long, default_value = "asd-cli-user")]
    pub author_id: String,
}

#[derive(Debug, Args)]
pub struct RebindArgs {
    /// The symbol whose ledger history should move: its symbol_id
    /// (`sym_abc123…`) — the only handle on an orphaned symbol, which is no
    /// longer in the index — or its qualified name.
    #[arg(
        long,
        required_unless_present = "map",
        requires = "to",
        conflicts_with = "map"
    )]
    pub from: Option<String>,

    /// The qualified name the history moves to. Must exist in the index.
    #[arg(long, requires = "from", conflicts_with = "map")]
    pub to: Option<String>,

    /// A JSON file of many rebinds at once: `{"<symbol_id or qname>": "<qname
    /// it moves to>", …}`. Every source and target is checked before anything
    /// is written, and all of them land in one commit.
    #[arg(long, value_name = "FILE")]
    pub map: Option<PathBuf>,

    /// Author/agent performing the rebind.
    #[arg(long, default_value = "asd-cli-user")]
    pub agent_id: String,
}

#[derive(Debug, Args)]
pub struct AppendArgs {
    /// Fully-qualified symbol name.
    pub qname: String,

    /// Ledger kind.
    #[arg(long, value_enum)]
    pub kind: CliLedgerKind,

    /// One-line summary.
    #[arg(long)]
    pub summary: String,

    /// Optional path to a body file (markdown or plain text).
    #[arg(long)]
    pub body: Option<PathBuf>,

    /// Author kind — `agent` or `human`.
    #[arg(long, value_enum, default_value_t = CliAuthorKind::Agent)]
    pub author_kind: CliAuthorKind,

    /// Author identifier (email, agent-slug, etc.).
    #[arg(long, default_value = "asd-cli-user")]
    pub author_id: String,

    /// Plan B t-002: classification role/intent tag (e.g. "diagnostic-test",
    /// "fast-test", "fixture-path", "stale-api"). Optional; most meaningful
    /// for kind=ownership/concept entries.
    #[arg(long)]
    pub role: Option<String>,

    /// Plan B t-002: canonical reproduction or validation command
    /// (e.g. "swift test --filter SongPlayersTests"). Optional; most
    /// meaningful for kind=validation_scenario/proof/follow_up entries.
    #[arg(long)]
    pub command: Option<String>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum CliLedgerKind {
    Decision,
    Assumption,
    Constraint,
    Rationale,
    Hazard,
    Tradeoff,
    /// Invariant that must always hold at this symbol.
    Invariant,
    /// Ownership: which subsystem/team owns this symbol.
    Ownership,
    /// Proof that an invariant holds (test, review, trace).
    Proof,
    /// Concrete scenario to validate (behaviour + expected outcome).
    #[value(name = "validation_scenario")]
    ValidationScenario,
    /// Known bug or defect not yet fixed.
    #[value(name = "known_bug")]
    KnownBug,
    /// Domain concept (e.g. "Drift Pad clip playhead") — first-class queryable entity.
    Concept,
    /// Plan B t-002: replacement-coverage mapping ("legacy X is covered by new Y").
    Mapping,
    /// Plan B t-002: open follow-up tied to an external task.
    #[value(name = "follow_up")]
    FollowUp,
}

impl From<CliLedgerKind> for LedgerKind {
    fn from(k: CliLedgerKind) -> Self {
        match k {
            CliLedgerKind::Decision => LedgerKind::Decision,
            CliLedgerKind::Assumption => LedgerKind::Assumption,
            CliLedgerKind::Constraint => LedgerKind::Constraint,
            CliLedgerKind::Rationale => LedgerKind::Rationale,
            CliLedgerKind::Hazard => LedgerKind::Hazard,
            CliLedgerKind::Tradeoff => LedgerKind::Tradeoff,
            CliLedgerKind::Invariant => LedgerKind::Invariant,
            CliLedgerKind::Ownership => LedgerKind::Ownership,
            CliLedgerKind::Proof => LedgerKind::Proof,
            CliLedgerKind::ValidationScenario => LedgerKind::ValidationScenario,
            CliLedgerKind::KnownBug => LedgerKind::KnownBug,
            CliLedgerKind::Concept => LedgerKind::Concept,
            CliLedgerKind::Mapping => LedgerKind::Mapping,
            CliLedgerKind::FollowUp => LedgerKind::FollowUp,
        }
    }
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum CliAuthorKind {
    Agent,
    Human,
}

impl From<CliAuthorKind> for AuthorKind {
    fn from(k: CliAuthorKind) -> Self {
        match k {
            CliAuthorKind::Agent => AuthorKind::Agent,
            CliAuthorKind::Human => AuthorKind::Human,
        }
    }
}

pub fn run(cfg: &Config, cmd: LedgerCmd) -> Result<()> {
    match cmd {
        LedgerCmd::Append(args) => append(cfg, args),
        LedgerCmd::Approve(args) => approve(cfg, args),
        LedgerCmd::Reject(args) => reject(cfg, args),
        LedgerCmd::Withdraw(args) => withdraw(cfg, args),
        LedgerCmd::Supersede(args) => supersede(cfg, args),
        LedgerCmd::Rebind(args) => rebind(cfg, args),
    }
}

fn approve(cfg: &Config, args: ApproveArgs) -> Result<()> {
    let engine = open_engine(cfg)?;
    let situation = Situation {
        description: format!("ledger.approve {}", args.entry_id),
        qualifiers: json!({ "entry_id": &args.entry_id }),
    };
    if let Decision::Deny {
        matched_policy,
        reason,
    } = engine
        .policy
        .evaluate(&situation, actions::LEDGER_APPROVE, &args.approver)?
    {
        anyhow::bail!("policy denied: {} (matched {})", reason, matched_policy);
    }
    let result = if let Some(ref ratify) = engine.ratify {
        ratify.approve_entry(
            &engine.repo,
            &engine.ref_name,
            &args.entry_id,
            &args.approver,
            &args.approver_kind,
            args.message.as_deref(),
            &cfg.agent_id,
        )
    } else {
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        ledger_store.approve_entry(
            &engine.ref_name,
            &args.entry_id,
            &args.approver,
            &args.approver_kind,
            args.message.as_deref(),
            &cfg.agent_id,
        )
    };

    match result {
        Ok(outcome) => {
            let status = if outcome.already_approved {
                "already-approved"
            } else {
                "approved"
            };
            let event = AuditEvent::new(
                event_types::LEDGER_APPROVE,
                &args.approver,
                &args.approver_kind,
                status,
            )
            .with_subject(&outcome.entry.entry_id)
            .with_secondary(&outcome.entry.symbol_id)
            .with_matched_policy(outcome.entry.matched_policy.clone())
            .with_payload(json!({ "tags": outcome.entry.tags }));
            emit_audit(engine.audit.as_ref(), event);

            println!(
                "{}",
                serde_json::to_string_pretty(&json!({
                    "status": status,
                    "entry_id": outcome.entry.entry_id,
                    "symbol_id": outcome.entry.symbol_id,
                    "tags": outcome.entry.tags,
                }))?
            );
            Ok(())
        }
        Err(e) => {
            let event = AuditEvent::new(
                event_types::LEDGER_APPROVE,
                &args.approver,
                &args.approver_kind,
                "error",
            )
            .with_subject(&args.entry_id)
            .with_reason(e.to_string());
            emit_audit(engine.audit.as_ref(), event);
            Err(e.into())
        }
    }
}

fn reject(cfg: &Config, args: RejectArgs) -> Result<()> {
    let engine = open_engine(cfg)?;
    let situation = Situation {
        description: format!("ledger.reject {}", args.entry_id),
        qualifiers: json!({ "entry_id": &args.entry_id }),
    };
    if let Decision::Deny {
        matched_policy,
        reason,
    } = engine
        .policy
        .evaluate(&situation, actions::LEDGER_REJECT, &args.reviewer)?
    {
        anyhow::bail!("policy denied: {} (matched {})", reason, matched_policy);
    }
    let result = if let Some(ref ratify) = engine.ratify {
        ratify.reject_entry(
            &engine.repo,
            &engine.ref_name,
            &args.entry_id,
            &args.reviewer,
            &args.reviewer_kind,
            &args.reason,
            &cfg.agent_id,
        )
    } else {
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        ledger_store.reject_entry(
            &engine.ref_name,
            &args.entry_id,
            &args.reviewer,
            &args.reviewer_kind,
            &args.reason,
            &cfg.agent_id,
        )
    };
    match result {
        Ok(outcome) => {
            let status = if outcome.already_resolved {
                "already-rejected"
            } else {
                "rejected"
            };
            let event = AuditEvent::new(
                event_types::LEDGER_REJECT,
                &args.reviewer,
                &args.reviewer_kind,
                status,
            )
            .with_subject(&outcome.entry.entry_id)
            .with_secondary(&outcome.entry.symbol_id)
            .with_matched_policy(outcome.entry.matched_policy.clone())
            .with_reason(&args.reason)
            .with_payload(json!({ "tags": outcome.entry.tags }));
            emit_audit(engine.audit.as_ref(), event);

            println!(
                "{}",
                serde_json::to_string_pretty(&json!({
                    "status": status,
                    "entry_id": outcome.entry.entry_id,
                    "symbol_id": outcome.entry.symbol_id,
                    "tags": outcome.entry.tags,
                }))?
            );
            Ok(())
        }
        Err(e) => {
            let event = AuditEvent::new(
                event_types::LEDGER_REJECT,
                &args.reviewer,
                &args.reviewer_kind,
                "error",
            )
            .with_subject(&args.entry_id)
            .with_reason(e.to_string());
            emit_audit(engine.audit.as_ref(), event);
            Err(e.into())
        }
    }
}

fn withdraw(cfg: &Config, args: WithdrawArgs) -> Result<()> {
    let engine = open_engine(cfg)?;
    let situation = Situation {
        description: format!("ledger.withdraw {}", args.entry_id),
        qualifiers: json!({ "entry_id": &args.entry_id }),
    };
    if let Decision::Deny {
        matched_policy,
        reason,
    } = engine
        .policy
        .evaluate(&situation, actions::LEDGER_WITHDRAW, &args.author_id)?
    {
        anyhow::bail!("policy denied: {} (matched {})", reason, matched_policy);
    }
    let result = if let Some(ref ratify) = engine.ratify {
        ratify.withdraw_entry(
            &engine.repo,
            &engine.ref_name,
            &args.entry_id,
            &args.author_id,
            &cfg.agent_id,
        )
    } else {
        let ledger_store = AsgLedgerStore::from_engine(&engine);
        ledger_store.withdraw_entry(
            &engine.ref_name,
            &args.entry_id,
            &args.author_id,
            &cfg.agent_id,
        )
    };
    match result {
        Ok(outcome) => {
            let status = if outcome.already_resolved {
                "already-withdrawn"
            } else {
                "withdrawn"
            };
            let event = AuditEvent::new(
                event_types::LEDGER_WITHDRAW,
                &args.author_id,
                "agent",
                status,
            )
            .with_subject(&outcome.entry.entry_id)
            .with_secondary(&outcome.entry.symbol_id)
            .with_payload(json!({ "tags": outcome.entry.tags }));
            emit_audit(engine.audit.as_ref(), event);

            println!(
                "{}",
                serde_json::to_string_pretty(&json!({
                    "status": status,
                    "entry_id": outcome.entry.entry_id,
                    "symbol_id": outcome.entry.symbol_id,
                    "tags": outcome.entry.tags,
                }))?
            );
            Ok(())
        }
        Err(e) => {
            let event = AuditEvent::new(
                event_types::LEDGER_WITHDRAW,
                &args.author_id,
                "agent",
                "error",
            )
            .with_subject(&args.entry_id)
            .with_reason(e.to_string());
            emit_audit(engine.audit.as_ref(), event);
            Err(e.into())
        }
    }
}

fn supersede(cfg: &Config, args: SupersedeArgs) -> Result<()> {
    let engine = open_engine(cfg)?;
    let index_store = AsgIndexStore::from_engine(&engine);
    let symbol = index_store
        .get_symbol_by_qname(&engine.ref_name, &args.qname)?
        .ok_or_else(|| anyhow::anyhow!("symbol not found: {}", args.qname))?;

    let author_kind_str: AuthorKind = args.author_kind.into();
    let author_kind_label = match author_kind_str {
        AuthorKind::Agent => "agent",
        AuthorKind::Human => "human",
    };
    let author = Author {
        kind: author_kind_str,
        id: args.author_id.clone(),
    };
    let situation = Situation {
        description: format!("ledger.supersede for {}", args.qname),
        qualifiers: json!({
            "qname": &args.qname,
            "symbol_id": &symbol.symbol_id,
            "file": &symbol.file,
            "language": &symbol.language,
        }),
    };
    if let Decision::Deny {
        matched_policy,
        reason,
    } = engine
        .policy
        .evaluate(&situation, actions::LEDGER_SUPERSEDE, &args.author_id)?
    {
        anyhow::bail!("policy denied: {} (matched {})", reason, matched_policy);
    }

    let mut entry = LedgerEntry::new(&symbol.symbol_id, args.kind.into(), args.summary, author);
    if let Some(body_path) = args.body {
        entry.body = Some(std::fs::read_to_string(body_path)?);
    }
    entry.supersedes = args.supersedes.clone();
    entry.tags.push("supersedes".to_string());

    let ledger_store = AsgLedgerStore::from_engine(&engine);
    match ledger_store.append_entry(&engine.ref_name, &entry, &cfg.agent_id) {
        Ok(()) => {
            let event = AuditEvent::new(
                event_types::LEDGER_SUPERSEDE,
                &args.author_id,
                author_kind_label,
                "success",
            )
            .with_subject(&entry.entry_id)
            .with_secondary(&entry.symbol_id)
            .with_payload(json!({
                "supersedes": entry.supersedes,
                "qname": args.qname,
            }));
            emit_audit(engine.audit.as_ref(), event);

            println!(
                "{}",
                serde_json::to_string_pretty(&json!({
                    "status": "superseded",
                    "entry_id": entry.entry_id,
                    "symbol_id": entry.symbol_id,
                    "supersedes": entry.supersedes,
                }))?
            );
            Ok(())
        }
        Err(e) => {
            let event = AuditEvent::new(
                event_types::LEDGER_SUPERSEDE,
                &args.author_id,
                author_kind_label,
                "error",
            )
            .with_secondary(&symbol.symbol_id)
            .with_reason(e.to_string());
            emit_audit(engine.audit.as_ref(), event);
            Err(e.into())
        }
    }
}

fn append(cfg: &Config, args: AppendArgs) -> Result<()> {
    let engine = open_engine(cfg)?;

    let index_store = AsgIndexStore::from_engine(&engine);
    let symbol = index_store
        .get_symbol_by_qname(&engine.ref_name, &args.qname)?
        .ok_or_else(|| anyhow::anyhow!("symbol not found: {}", args.qname))?;

    let ledger_kind: LedgerKind = args.kind.into();
    let author_kind_str: AuthorKind = args.author_kind.into();
    let author_kind_label = match author_kind_str {
        AuthorKind::Agent => "agent",
        AuthorKind::Human => "human",
    };
    let action = actions::ledger_append_action(ledger_kind.as_str());
    let situation = Situation {
        description: format!("ledger.append for {}", args.qname),
        qualifiers: json!({
            "qname": &args.qname,
            "kind": ledger_kind.as_str(),
            "symbol_id": &symbol.symbol_id,
            "file": &symbol.file,
            "language": &symbol.language,
        }),
    };
    let decision = engine
        .policy
        .evaluate(&situation, &action, &args.author_id)?;

    if let Decision::Deny {
        matched_policy,
        reason,
    } = &decision
    {
        // Emit a denied audit event even though no entry is written.
        let event = AuditEvent::new(
            event_types::LEDGER_APPEND,
            &args.author_id,
            author_kind_label,
            "denied",
        )
        .with_secondary(&symbol.symbol_id)
        .with_matched_policy(Some(matched_policy.clone()))
        .with_reason(reason.clone())
        .with_payload(json!({ "qname": &args.qname, "kind": ledger_kind.as_str() }));
        emit_audit(engine.audit.as_ref(), event);

        let err = json!({
            "status": "denied",
            "action": action,
            "matched_policy": matched_policy,
            "reason": reason,
        });
        println!("{}", serde_json::to_string_pretty(&err)?);
        return Err(anyhow::anyhow!("policy denied: {}", reason));
    }

    let author = Author {
        kind: author_kind_str,
        id: args.author_id.clone(),
    };
    let mut entry = LedgerEntry::new(&symbol.symbol_id, ledger_kind, args.summary, author);
    if let Some(body_path) = args.body {
        let text = std::fs::read_to_string(&body_path)?;
        entry.body = Some(text);
    }
    entry.matched_policy = decision.matched_policy();
    // Plan C t-002: validate role against the canonical RoleTag set;
    // emit a stderr warning on unknown so unknown tags don't break old
    // data but the user notices the typo.
    if let Some(ref r) = args.role {
        if agentstatedeveloper_core::RoleTag::from_str(r).is_none() {
            let valid: Vec<&str> = agentstatedeveloper_core::RoleTag::all()
                .iter()
                .map(|t| t.as_str())
                .collect();
            eprintln!(
                "asd: warning: role={:?} is not a canonical RoleTag. Valid: {}",
                r,
                valid.join(", ")
            );
        }
    }
    entry.role = args.role;
    entry.command = args.command;

    if let Decision::RequireApproval {
        approvers, reason, ..
    } = &decision
    {
        entry.tags.push("awaiting-approval".to_string());
        for a in approvers {
            entry.tags.push(format!("approver:{}", a));
        }
        if let Some(r) = reason {
            if entry.body.is_none() {
                entry.body = Some(format!("Approval reason: {}", r));
            }
        }
    }

    // t-001: inject CTX plan/task provenance from env vars.
    for tag in ctx_provenance_tags() {
        if !entry.tags.contains(&tag) {
            entry.tags.push(tag);
        }
    }

    let ledger_store = AsgLedgerStore::from_engine(&engine);
    ledger_store.append_entry(&engine.ref_name, &entry, &cfg.agent_id)?;

    let status = match &decision {
        Decision::Allow { .. } => "allowed",
        Decision::RequireApproval { .. } => "awaiting-approval",
        Decision::Deny { .. } => "denied",
        Decision::NoPolicyMatch => "no-policy-match",
    };
    let event = AuditEvent::new(
        event_types::LEDGER_APPEND,
        &args.author_id,
        author_kind_label,
        status,
    )
    .with_subject(&entry.entry_id)
    .with_secondary(&entry.symbol_id)
    .with_matched_policy(entry.matched_policy.clone())
    .with_payload(json!({
        "qname": &args.qname,
        "kind": ledger_kind.as_str(),
        "tags": &entry.tags,
    }));
    emit_audit(engine.audit.as_ref(), event);

    println!(
        "{}",
        serde_json::to_string_pretty(&json!({
            "entry_id": entry.entry_id,
            "matched_policy": entry.matched_policy,
            "status": status,
        }))?
    );
    Ok(())
}

fn rebind(cfg: &Config, args: RebindArgs) -> Result<()> {
    let engine = open_engine(cfg)?;

    let requested: Vec<(String, String)> = match (&args.map, args.from, args.to) {
        (Some(path), _, _) => {
            let text = std::fs::read_to_string(path)
                .map_err(|e| anyhow::anyhow!("read {}: {e}", path.display()))?;
            let map: serde_json::Map<String, serde_json::Value> = serde_json::from_str(&text)
                .map_err(|e| anyhow::anyhow!("{}: {e}", path.display()))?;
            map.into_iter()
                .map(|(from, to)| match to {
                    serde_json::Value::String(to) => Ok((from, to)),
                    _ => Err(anyhow::anyhow!(
                        "{}: the target for {from} must be a qualified name",
                        path.display()
                    )),
                })
                .collect::<Result<_>>()?
        }
        (None, Some(from), Some(to)) => vec![(from, to)],
        _ => anyhow::bail!("pass --from and --to, or --map"),
    };
    if requested.is_empty() {
        anyhow::bail!("no rebinds listed");
    }

    // Resolve and check every rebind before writing any of them.
    let index_store = AsgIndexStore::from_engine(&engine);
    let ledger_store = AsgLedgerStore::from_engine(&engine);
    let mut resolved = Vec::with_capacity(requested.len());
    let mut problems = Vec::new();
    for (from, to) in &requested {
        let situation = Situation::new("rebind symbol")
            .with_qualifier("from_symbol_id", from)
            .with_qualifier("to_qname", to);
        if let Decision::Deny {
            matched_policy,
            reason,
        } = engine
            .policy
            .evaluate(&situation, actions::LEDGER_REBIND, &args.agent_id)?
        {
            problems.push(format!(
                "{from}: policy denied by {matched_policy}: {reason}"
            ));
            continue;
        }
        let from_id = if from.starts_with("sym_") {
            if ledger_store
                .list_entries_with_superseded(&engine.ref_name, from)?
                .is_empty()
            {
                problems.push(format!("{from}: no ledger entries are filed under it"));
                continue;
            }
            from.clone()
        } else {
            match index_store.get_symbol_by_qname(&engine.ref_name, from)? {
                Some(symbol) => symbol.symbol_id,
                None => {
                    problems.push(format!(
                        "{from}: not in the index — for an orphaned symbol, pass its symbol_id"
                    ));
                    continue;
                }
            }
        };
        match index_store.get_symbol_by_qname(&engine.ref_name, to)? {
            Some(symbol) => resolved.push((from_id, symbol)),
            None => problems.push(format!("{to}: not in the index — run `asd index` first")),
        }
    }
    if !problems.is_empty() {
        anyhow::bail!("nothing rebound:\n  {}", problems.join("\n  "));
    }

    let outcomes = agentstatedeveloper_core::rebind_ledger(
        &engine.repo,
        engine.fts.as_ref(),
        &engine.ref_name,
        &resolved,
        &args.agent_id,
    )?;

    for (outcome, (from, _)) in outcomes.iter().zip(&requested) {
        let event = AuditEvent::new(event_types::LEDGER_REBIND, &args.agent_id, "agent", "allow")
            .with_subject(outcome.from_symbol_id.clone())
            .with_secondary(outcome.to_symbol_id.clone())
            .with_payload(json!({
                "from": from,
                "from_symbol_id": outcome.from_symbol_id,
                "to_symbol_id": outcome.to_symbol_id,
                "to_qname": outcome.to_qname,
                "entries_moved": outcome.entries_moved,
            }));
        emit_audit(engine.audit.as_ref(), event);
    }

    let output = match outcomes.as_slice() {
        [one] if args.map.is_none() => json!({
            "status": "rebound",
            "from_symbol_id": one.from_symbol_id,
            "to_symbol_id": one.to_symbol_id,
            "to_qname": one.to_qname,
            "entries_moved": one.entries_moved,
        }),
        all => json!({
            "status": "rebound",
            "rebinds": all,
            "entries_moved": all.iter().map(|o| o.entries_moved).sum::<usize>(),
        }),
    };
    println!("{}", serde_json::to_string_pretty(&output)?);
    Ok(())
}

// ---------------------------------------------------------------------------
// t-001: CTX plan/task provenance from env vars
// ---------------------------------------------------------------------------

/// Read CTXONE_PLAN and CTXONE_TASK env vars and return them as ledger tags.
/// Call this before every ledger append to attach workflow provenance.
pub fn ctx_provenance_tags() -> Vec<String> {
    let mut tags = Vec::new();
    if let Ok(plan) = std::env::var("CTXONE_PLAN") {
        if !plan.is_empty() {
            tags.push(format!("ctx:plan:{}", plan));
        }
    }
    if let Ok(task) = std::env::var("CTXONE_TASK") {
        if !task.is_empty() {
            tags.push(format!("ctx:task:{}", task));
        }
    }
    tags
}