impyard 0.1.1

Rent the intelligence, own the governance — a control plane for imps: software colleagues whose every action passes through a gateway you control (default-deny egress, injected credentials, budgets, approval gates, audit).
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
//! Actions — the box proposes a consequential action by POSTing an envelope to
//! the gateway's action host (`actions.impyard.internal`). The gateway attributes
//! it to the imp (identity token on the CONNECT, un-spoofable), checks the
//! admin's action grants + the trust ladder, and either executes it now (auto)
//! or files a durable gate. Executors run trusted-side and hold the real
//! credentials the box never sees. See docs/supervisor-spec.md.

pub mod gate;
pub mod smtp;
pub mod trust;

use crate::action::gate::Gate;
use crate::action::trust::TrustRule;
use crate::gateway::proxy::Body;
use crate::imp::journal;
use crate::paths;
use crate::util::now_rfc3339;
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::{Response, StatusCode};
use serde::Deserialize;
use serde_json::{json, Value};
use std::fs::OpenOptions;
use std::io::Write;
use std::sync::atomic::{AtomicU64, Ordering};

/// The sentinel host the box POSTs action envelopes to. It never leaves the
/// gateway: all box HTTPS is proxied, so this arrives as CONNECT + a
/// TLS-terminated POST the gateway handles internally instead of forwarding.
pub const ACTION_HOST: &str = "actions.impyard.internal";

// ── the envelope + admin policy ──────────────────────────────────────────────

#[derive(Debug, Deserialize)]
pub struct Envelope {
    pub intent: String,
    #[serde(default)]
    pub payload: Value,
    #[serde(default)]
    pub rationale: String,
    #[serde(default)]
    pub run_id: String,
    #[serde(default)]
    pub task_id: String,
}

fn org_scope() -> String {
    "org".to_string()
}
fn gate_default() -> String {
    "gate".to_string()
}

/// An admin-declared action an imp may propose (compiled from `[[action]]`).
#[derive(Debug, Clone, Deserialize)]
pub struct ActionGrant {
    #[serde(default = "org_scope")]
    pub scope: String,
    pub name: String,
    pub executor: String,
    /// Default trust level (T0 = "gate"); the trust ladder can override per payload.
    #[serde(default = "gate_default")]
    pub trust: String,
    /// When true, resolving a gate for this action files a continuation task so
    /// the imp can react to the outcome (§3.5). Default: just close the task.
    #[serde(default)]
    pub wake_on_resolve: bool,
}

#[derive(Debug, Clone, Default, Deserialize)]
pub struct ActionPolicy {
    #[serde(default)]
    pub actions: Vec<ActionGrant>,
    #[serde(default)]
    pub trust: Vec<TrustRule>,
}

pub fn load_action_policy() -> ActionPolicy {
    crate::config::snapshot()
        .map(|c| c.actions.clone())
        .unwrap_or_default()
}

fn grant_for<'a>(policy: &'a ActionPolicy, imp: &str, intent: &str) -> Option<&'a ActionGrant> {
    policy
        .actions
        .iter()
        .find(|a| crate::gateway::scope::applies(&a.scope, imp) && a.name == intent)
}

/// Is a channel-send payload targeting a channel an admin marked trusted?
/// (The trust store is channel-id keyed and platform-agnostic.)
fn channel_payload_trusted(payload: &Value) -> bool {
    payload
        .get("channel_id")
        .and_then(|v| v.as_str())
        .map(crate::channel::discord::channel_trusted)
        .unwrap_or(false)
}

// ── the gateway's action decision ────────────────────────────────────────────

fn reply(status: StatusCode, v: Value) -> Response<Body> {
    let mut resp = Response::new(
        Full::new(Bytes::from(v.to_string()))
            .map_err(|n| match n {})
            .boxed(),
    );
    *resp.status_mut() = status;
    resp.headers_mut().insert(
        hyper::header::CONTENT_TYPE,
        "application/json".parse().unwrap(),
    );
    resp
}

/// Route a request to the action host. `imp` is resolved from the identity
/// token. POST /submit proposes an action; GET /gates and /journal are the
/// imp's read-only view of its own state (the box's cross-run awareness).
pub async fn handle_action(
    imp: &str,
    trusted_run_id: &str,
    method: &str,
    path: &str,
    body: &[u8],
) -> Response<Body> {
    match (method, path) {
        ("POST", "/submit") => submit(imp, trusted_run_id, body).await,
        ("GET", "/gates") => {
            let gates: Vec<Value> = crate::action::gate::for_imp(imp)
                .iter()
                .map(|g| g.summary())
                .collect();
            reply(StatusCode::OK, json!({ "gates": gates }))
        }
        ("GET", "/journal") => reply(StatusCode::OK, json!({ "events": journal::tail(imp, 30) })),
        ("GET", "/memory") => {
            let memories = crate::imp::memory::visible_to_current_actor(imp, trusted_run_id);
            let user_settings = crate::imp::memory::current_user_settings(imp, trusted_run_id);
            journal::append(
                imp,
                trusted_run_id,
                "memory-read",
                json!({ "note_ids": memories.iter().map(|n| n.id.as_str()).collect::<Vec<_>>() }),
            );
            reply(
                StatusCode::OK,
                json!({ "memories": memories, "user_settings": user_settings }),
            )
        }
        _ => reply(
            StatusCode::NOT_FOUND,
            json!({ "status": "error", "error": "unknown action endpoint" }),
        ),
    }
}

/// Handle one action envelope: attribute, authorize, and either execute now or
/// file a gate.
async fn submit(imp: &str, trusted_run_id: &str, body: &[u8]) -> Response<Body> {
    let env: Envelope = match serde_json::from_slice(body) {
        Ok(e) => e,
        Err(e) => {
            return reply(
                StatusCode::BAD_REQUEST,
                json!({ "status": "error", "error": format!("bad envelope: {e}") }),
            )
        }
    };
    let run_id = if trusted_run_id.is_empty() {
        env.run_id.clone()
    } else {
        trusted_run_id.to_string()
    };
    let policy = load_action_policy();
    let Some(grant) = grant_for(&policy, imp, &env.intent) else {
        journal::append(
            imp,
            &run_id,
            "action-refused",
            json!({ "intent": env.intent, "reason": "no action grant in scope" }),
        );
        audit(imp, &env.intent, "refused", None, None);
        return reply(
            StatusCode::FORBIDDEN,
            json!({ "status": "denied", "reason": format!("no action grant for \"{}\"", env.intent) }),
        );
    };
    let grant = grant.clone();
    if grant.executor == "note" && trusted_run_id.is_empty() {
        journal::append(
            imp,
            &run_id,
            "action-refused",
            json!({ "intent": env.intent, "reason": "run-scoped action has no trusted run context" }),
        );
        audit(imp, &env.intent, "refused", None, None);
        return reply(
            StatusCode::FORBIDDEN,
            json!({ "status": "denied", "reason": "run-scoped action has no trusted run context" }),
        );
    }

    journal::append(
        imp,
        &run_id,
        "action-proposed",
        json!({ "intent": env.intent, "rationale": env.rationale, "run_id": run_id }),
    );

    let (executed, denied) = gate::history(imp, &env.intent);
    let level = if grant.executor == "note" {
        let context = crate::imp::memory::load_run_context(&run_id);
        match crate::imp::memory::action_trust(imp, &env.intent, &env.payload, &context) {
            Ok(level) => level.to_string(),
            Err(reason) => {
                journal::append(
                    imp,
                    &run_id,
                    "action-refused",
                    json!({ "intent": env.intent, "reason": reason }),
                );
                audit(imp, &env.intent, "refused", None, None);
                return reply(
                    StatusCode::FORBIDDEN,
                    json!({ "status": "denied", "reason": reason }),
                );
            }
        }
    } else if grant.executor == "identity" {
        // Identity is imp-wide — always hard-gated (D10).
        "gate".to_string()
    } else if (grant.executor == "discord"
        || grant.executor == "slack"
        || grant.executor == "purpose")
        && channel_payload_trusted(&env.payload)
    {
        // Replies AND channel-purpose refinements flow without a gate in a trusted
        // channel — its participants are authorized to set the purpose (they could
        // `/purpose set` directly). Untrusted channels still gate for review.
        "auto".to_string()
    } else {
        trust::evaluate(
            imp,
            &env.intent,
            &env.payload,
            &grant.trust,
            &policy.trust,
            executed,
            denied,
        )
    };
    if level == "auto" {
        match run_executor(&grant.executor, imp, &env.intent, &env.payload, &run_id).await {
            Ok(result) => {
                journal::append(
                    imp,
                    &run_id,
                    "executed",
                    json!({ "intent": env.intent, "auto": true, "result": result }),
                );
                audit(imp, &env.intent, "auto-executed", None, Some(&result));
                reply(
                    StatusCode::OK,
                    json!({ "status": "done", "result": result }),
                )
            }
            Err(e) => {
                journal::append(
                    imp,
                    &run_id,
                    "failed",
                    json!({ "intent": env.intent, "auto": true, "error": e }),
                );
                audit(imp, &env.intent, "failed", None, None);
                reply(StatusCode::OK, json!({ "status": "error", "error": e }))
            }
        }
    } else {
        let g = Gate {
            id: gate::new_id(),
            imp: imp.to_string(),
            intent: env.intent.clone(),
            executor: grant.executor.clone(),
            payload: env.payload.clone(),
            rationale: env.rationale.clone(),
            run_id: run_id.clone(),
            task_id: env.task_id.clone(),
            state: "pending".into(),
            filed_at: gate::now(),
            decided_by: None,
            decided_at: None,
            decision_note: None,
            executed_at: None,
            result: None,
            error: None,
        };
        if let Err(e) = gate::save(&g) {
            return reply(
                StatusCode::INTERNAL_SERVER_ERROR,
                json!({ "status": "error", "error": format!("could not file gate: {e}") }),
            );
        }
        journal::append(
            imp,
            &run_id,
            "gate-filed",
            json!({ "gate_id": g.id, "intent": env.intent, "rationale": env.rationale }),
        );
        audit(imp, &env.intent, "gated", Some(&g.id), None);
        reply(
            StatusCode::ACCEPTED,
            json!({ "status": "pending", "gate_id": g.id, "message": "held for human approval" }),
        )
    }
}

// ── approval-side execution (shared with `impyard gates approve`) ─────────────

/// Execute an approved gate, idempotently. `pending`/`approved` → run; `executed`
/// is terminal (never re-runs); a crash between approve and execute resumes.
pub async fn execute_gate(id: &str, decided_by: &str, note: Option<&str>) -> Result<Gate, String> {
    let mut g = gate::load(id).ok_or_else(|| format!("no such gate {id}"))?;
    if g.state == "executed" {
        return Err(format!("gate {id} already executed"));
    }
    if g.state == "denied" {
        return Err(format!("gate {id} was denied"));
    }
    if g.state == "pending" {
        g.state = "approved".into();
        g.decided_by = Some(decided_by.to_string());
        g.decided_at = Some(now_rfc3339());
        g.decision_note = note.map(String::from);
        gate::save(&g).map_err(|e| e.to_string())?;
        journal::append(
            &g.imp,
            &g.run_id,
            "approved",
            json!({ "gate_id": g.id, "by": decided_by, "note": note }),
        );
    }
    g.state = "executing".into();
    gate::save(&g).map_err(|e| e.to_string())?;
    match run_executor(&g.executor, &g.imp, &g.intent, &g.payload, &g.run_id).await {
        Ok(result) => {
            g.state = "executed".into();
            g.executed_at = Some(now_rfc3339());
            g.result = Some(result.clone());
            gate::save(&g).map_err(|e| e.to_string())?;
            journal::append(
                &g.imp,
                &g.run_id,
                "executed",
                json!({ "gate_id": g.id, "intent": g.intent, "result": result }),
            );
            audit(&g.imp, &g.intent, "executed", Some(&g.id), Some(&result));
            resolve_followup(&g);
            Ok(g)
        }
        Err(e) => {
            g.state = "failed".into();
            g.error = Some(e.clone());
            gate::save(&g).map_err(|e| e.to_string())?;
            journal::append(
                &g.imp,
                &g.run_id,
                "failed",
                json!({ "gate_id": g.id, "intent": g.intent, "error": e }),
            );
            audit(&g.imp, &g.intent, "failed", Some(&g.id), None);
            Err(e)
        }
    }
}

pub fn deny_gate(id: &str, decided_by: &str, note: Option<&str>) -> Result<Gate, String> {
    let mut g = gate::load(id).ok_or_else(|| format!("no such gate {id}"))?;
    if g.is_terminal() {
        return Err(format!("gate {id} is already {}", g.state));
    }
    g.state = "denied".into();
    g.decided_by = Some(decided_by.to_string());
    g.decided_at = Some(now_rfc3339());
    g.decision_note = note.map(String::from);
    gate::save(&g).map_err(|e| e.to_string())?;
    journal::append(
        &g.imp,
        &g.run_id,
        "denied",
        json!({ "gate_id": g.id, "by": decided_by, "note": note }),
    );
    audit(&g.imp, &g.intent, "denied", Some(&g.id), None);
    resolve_followup(&g);
    Ok(g)
}

/// After a gate reaches a terminal state, close the loop for its originating
/// task: if all the task's gates are resolved, mark it done, and — when the
/// action opts in with `wake_on_resolve` — file a continuation task so a fresh
/// box can react to the outcome (§3.5: ephemeral boxes + async gates meet here).
fn resolve_followup(g: &Gate) {
    if g.task_id.is_empty() {
        return;
    }
    if let Some(mut task) = crate::work::queue::find(&g.task_id) {
        if task.state == "needs-review" && gate::pending_for_task(&task.id).is_empty() {
            let _ = crate::work::queue::set_state(&mut task, "done");
        }
    }

    let policy = load_action_policy();
    let wake = grant_for(&policy, &g.imp, &g.intent)
        .map(|a| a.wake_on_resolve)
        .unwrap_or(false);
    if !wake {
        return;
    }
    let short = g.imp.strip_prefix("org/").unwrap_or(&g.imp).to_string();
    let outcome = if g.state == "executed" {
        format!(
            "was approved and executed. Result: {}",
            g.result.clone().unwrap_or(json!(null))
        )
    } else {
        format!(
            "was denied{}",
            g.decision_note
                .as_deref()
                .map(|n| format!(" ({n})"))
                .unwrap_or_default()
        )
    };
    let prompt = format!(
        "A previous action you proposed — {} (gate {}) — {}. Decide whether any follow-up is needed; if not, you are done.",
        g.intent, g.id, outcome
    );
    let context = json!({ "resolved_gate": { "id": g.id, "intent": g.intent, "state": g.state, "result": g.result, "decided_by": g.decided_by, "note": g.decision_note } });
    let _ = crate::work::queue::create(
        &short,
        &prompt,
        "continuation",
        false,
        15.0,
        "append",
        context,
        None,
        None,
    );
    journal::append(
        &g.imp,
        &g.run_id,
        "continuation-filed",
        json!({ "gate_id": g.id, "intent": g.intent }),
    );
}

// ── executors (trusted-side; hold real credentials the box never sees) ───────

/// Dispatch to the executor that performs an intent. New capabilities register
/// here. Executors that egress route through the gateway as the privileged
/// subject (uniform judge/inject/meter/audit); local ones act directly.
pub async fn run_executor(
    executor: &str,
    imp: &str,
    intent: &str,
    payload: &Value,
    run_id: &str,
) -> Result<Value, String> {
    match executor {
        "message-user" => exec_message_user(imp, payload).await,
        "email" => exec_email(imp, payload).await,
        "git-pr" => exec_git_pr(imp, run_id, payload),
        "identity" => exec_identity(imp, payload),
        "purpose" => exec_purpose(payload),
        "discord" => exec_discord(imp, payload).await,
        "slack" => exec_slack(imp, payload).await,
        "task" => exec_file_task(imp, payload, run_id),
        "note" => crate::imp::memory::execute(imp, intent, payload, run_id),
        other => Err(format!("no executor \"{other}\" for intent \"{intent}\"")),
    }
}

/// Deliver a note from the imp to its lead: a Discord DM when a bot token +
/// lead id are configured, else the local inbox. The bot token stays in the
/// vault; the box never holds it.
/// `file_task` — the bridge across the memory/knowledge boundary: a tainted
/// run queues durable work instead of writing records. The filed task is
/// imp-only by construction (context: null — no channel, no participants),
/// so it runs clean with a writable knowledge mount. The prompt is the entire
/// crossing, and the participant scan polices it (docs/knowledge-boundary.md).
fn exec_file_task(imp: &str, payload: &Value, run_id: &str) -> Result<Value, String> {
    if run_id.is_empty() {
        return Err("file-task needs a trusted run context".into());
    }
    let prompt = payload
        .get("prompt")
        .and_then(|v| v.as_str())
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .ok_or("file-task needs a non-empty \"prompt\"")?;
    let ceiling = payload
        .get("ceiling_min")
        .and_then(|v| v.as_f64())
        .unwrap_or(30.0)
        .clamp(1.0, 240.0);

    let context = crate::imp::memory::load_run_context(run_id);
    if let Err(reason) = crate::imp::boundary::check_task_prompt(&context, prompt) {
        journal::append(
            imp,
            run_id,
            "boundary-denied",
            json!({ "intent": "file-task", "reason": reason }),
        );
        return Err(reason);
    }

    let task = crate::work::queue::create(
        crate::paths::short_imp(imp),
        prompt,
        "imp",
        true, // imp-initiated: budget-gated at dispatch like other proactive work
        ceiling,
        "append",
        Value::Null,
        None,
        None,
    )
    .map_err(|e| e.to_string())?;
    journal::append(
        imp,
        run_id,
        "task-filed",
        json!({ "task_id": task.id, "prompt": prompt }),
    );
    eprintln!("file-task [{imp}] → {} ({} min)", task.id, ceiling);
    Ok(json!({ "task_id": task.id, "state": "waiting" }))
}

async fn exec_message_user(imp: &str, payload: &Value) -> Result<Value, String> {
    let text = payload
        .get("text")
        .and_then(|v| v.as_str())
        .ok_or("message-user needs a \"text\" field")?;

    if let Some(cred) = crate::credential::vault::get_credential("discord") {
        let token = cred.get("token").and_then(|v| v.as_str());
        let owner = cred
            .get("owner_id")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty());
        if let (Some(token), Some(owner)) = (token, owner) {
            match crate::channel::discord::open_dm(token, owner).await {
                Ok(dm) => match crate::channel::discord::post_message(token, &dm, text).await {
                    Ok(_) => {
                        eprintln!("message-user [{imp}] → lead DM");
                        return Ok(json!({ "delivered": "discord-dm" }));
                    }
                    Err(e) => {
                        eprintln!("message-user: DM post failed ({e}); trying other channels")
                    }
                },
                Err(e) => eprintln!("message-user: open DM failed ({e}); trying other channels"),
            }
        }
    }

    if let Some(cred) = crate::credential::vault::get_credential(&slack_credential_name(imp)) {
        let token = cred.get("bot_token").and_then(|v| v.as_str());
        let owner = cred
            .get("owner_id")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty());
        if let (Some(token), Some(owner)) = (token, owner) {
            match crate::channel::slack::open_dm(token, owner).await {
                Ok(dm) => match crate::channel::slack::post_message(token, &dm, text, None).await {
                    Ok(_) => {
                        eprintln!("message-user [{imp}] → lead Slack DM");
                        return Ok(json!({ "delivered": "slack-dm" }));
                    }
                    Err(e) => eprintln!("message-user: Slack DM post failed ({e}); using inbox"),
                },
                Err(e) => eprintln!("message-user: Slack open DM failed ({e}); using inbox"),
            }
        }
    }

    let path = paths::messages_log();
    if let Some(dir) = path.parent() {
        let _ = std::fs::create_dir_all(dir);
    }
    if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(&path) {
        let _ = writeln!(
            f,
            "{}",
            json!({ "ts": now_rfc3339(), "imp": imp, "text": text })
        );
    }
    eprintln!("message-user [{imp}]: {text}");
    Ok(json!({ "delivered": "inbox" }))
}

/// Post a message to a Discord channel (the imp's reply). Trusted-side; the
/// bot token comes from the vault, never the box.
async fn exec_discord(imp: &str, payload: &Value) -> Result<Value, String> {
    let channel = payload
        .get("channel_id")
        .and_then(|v| v.as_str())
        .ok_or("discord-send needs a \"channel_id\"")?;
    let text = payload
        .get("text")
        .and_then(|v| v.as_str())
        .filter(|s| !s.trim().is_empty())
        .ok_or("discord-send needs non-empty \"text\"")?;
    let cred = crate::credential::vault::get_credential("discord")
        .ok_or("no discord credential — run: impyard server vault connect discord")?;
    let token = cred
        .get("token")
        .and_then(|v| v.as_str())
        .ok_or("discord credential has no token")?;
    let id = crate::channel::discord::post_message(token, channel, text).await?;
    eprintln!("discord [{imp}] → channel {channel}");
    Ok(json!({ "sent": true, "channel_id": channel, "message_id": id }))
}

/// The imp's Slack credential: its `[channels] slack` binding from live
/// config, falling back to a credential literally named "slack".
fn slack_credential_name(imp: &str) -> String {
    let short = crate::paths::short_imp(imp).to_string();
    crate::config::snapshot()
        .ok()
        .and_then(|c| {
            c.listeners
                .iter()
                .find(|(w, platform, _)| *w == short && platform == "slack")
                .map(|(_, _, credential)| credential.clone())
        })
        .unwrap_or_else(|| "slack".to_string())
}

async fn exec_slack(imp: &str, payload: &Value) -> Result<Value, String> {
    let channel = payload
        .get("channel_id")
        .and_then(|v| v.as_str())
        .ok_or("slack-send needs a \"channel_id\"")?;
    let text = payload
        .get("text")
        .and_then(|v| v.as_str())
        .filter(|s| !s.trim().is_empty())
        .ok_or("slack-send needs non-empty \"text\"")?;
    let thread_ts = payload
        .get("thread_ts")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty());
    let name = slack_credential_name(imp);
    let cred = crate::credential::vault::get_credential(&name).ok_or_else(|| {
        format!("no \"{name}\" credential — run: impyard server vault connect slack")
    })?;
    let token = cred
        .get("bot_token")
        .and_then(|v| v.as_str())
        .ok_or("slack credential has no bot_token")?;
    let ts = crate::channel::slack::post_message(token, channel, text, thread_ts).await?;
    eprintln!("slack [{imp}] → channel {channel}");
    Ok(json!({ "sent": true, "channel_id": channel, "message_ts": ts }))
}

/// Send an email. If an SMTP credential is configured in the vault
/// (`impyard connect smtp`), deliver for real over TLS; otherwise fall back to a
/// local sink so the gate→approve→execute→audit path still works offline. Either
/// way the box never holds the credential — this runs trusted-side, post-gate.
async fn exec_email(imp: &str, payload: &Value) -> Result<Value, String> {
    let to: Vec<String> = payload
        .get("to")
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|x| x.as_str().map(String::from))
                .collect()
        })
        .filter(|v: &Vec<String>| !v.is_empty())
        .ok_or("email needs a non-empty \"to\" array")?;
    let subject = payload
        .get("subject")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let body = payload.get("body").and_then(|v| v.as_str()).unwrap_or("");

    if let Some(cfg) = smtp_config() {
        let status = crate::action::smtp::send(&cfg, &to, subject, body)
            .await
            .map_err(|e| format!("smtp send failed: {e}"))?;
        eprintln!("email [{imp}] → {to:?} via {}: {subject}", cfg.host);
        return Ok(
            json!({ "delivered": "smtp", "provider": cfg.host, "to": to, "status": status }),
        );
    }

    // No SMTP configured: fail loudly so an email is never silently dropped. The
    // local sink (a file, no real send) is opt-in for offline testing only.
    if std::env::var("IMPYARD_EMAIL_SINK").is_err() {
        return Err("email not sent: no SMTP configured — run `impyard server vault connect smtp` (e.g. your Mailgun SMTP creds)".into());
    }
    let dir = paths::outbox_dir();
    let _ = std::fs::create_dir_all(&dir);
    let file = dir.join(format!(
        "{}-{}.json",
        now_rfc3339().replace(':', "-"),
        imp.replace('/', "_")
    ));
    let rendered = json!({ "from": imp, "to": to, "subject": subject, "body": body });
    std::fs::write(
        &file,
        format!(
            "{}\n",
            serde_json::to_string_pretty(&rendered).unwrap_or_default()
        ),
    )
    .map_err(|e| e.to_string())?;
    eprintln!(
        "email [{imp}] → {to:?}: {subject} (IMPYARD_EMAIL_SINK — wrote local sink, NOT sent)"
    );
    Ok(json!({ "delivered": "local-sink", "to": to, "file": file.display().to_string() }))
}

/// SMTP settings from the vault (`~/.impyard/vault/smtp.json`), if present.
fn smtp_config() -> Option<crate::action::smtp::SmtpConfig> {
    let c = crate::credential::vault::get_credential("smtp")?;
    Some(crate::action::smtp::SmtpConfig {
        host: c.get("host")?.as_str()?.to_string(),
        port: c.get("port").and_then(|v| v.as_u64()).unwrap_or(465) as u16,
        user: c.get("user")?.as_str()?.to_string(),
        pass: c.get("pass")?.as_str()?.to_string(),
        from: c.get("from")?.as_str()?.to_string(),
    })
}

/// Land a code task's worktree as a pushed branch (and a PR where possible). The
/// box edited files in runs/<run_id>/worktree; here — only after approval — we
/// commit, push to the repo's origin, and open a PR. git push is direct (the
/// gateway can't govern git's wire protocol); the box never touches any of it.
fn exec_git_pr(imp: &str, run_id: &str, payload: &Value) -> Result<Value, String> {
    if run_id.is_empty() {
        return Err("code-change has no run_id — cannot find the worktree".into());
    }
    let wt = paths::run_dir(run_id).join("worktree");
    if !wt.exists() {
        return Err(format!("no worktree at {}", wt.display()));
    }
    let wt = wt.display().to_string();
    let message = payload
        .get("message")
        .and_then(|v| v.as_str())
        .unwrap_or("changes proposed by imp");
    let title = payload
        .get("title")
        .and_then(|v| v.as_str())
        .unwrap_or(message);
    let body = payload.get("body").and_then(|v| v.as_str()).unwrap_or("");

    git(&["-C", &wt, "add", "-A"])?;
    // Nothing staged → the proposal was empty; surface that rather than a git error.
    let clean = std::process::Command::new("git")
        .args(["-C", &wt, "diff", "--cached", "--quiet"])
        .status()
        .map(|s| s.success())
        .unwrap_or(false);
    if clean {
        return Err("no changes in the worktree to commit".into());
    }
    let author = format!("user.name=impyard imp {imp}");
    git(&[
        "-C",
        &wt,
        "-c",
        "user.email=imp@impyard.local",
        "-c",
        &author,
        "commit",
        "-m",
        message,
    ])?;
    let branch = git(&["-C", &wt, "rev-parse", "--abbrev-ref", "HEAD"])?;
    let commit = git(&["-C", &wt, "rev-parse", "--short", "HEAD"])?;
    git(&["-C", &wt, "push", "-u", "origin", &branch])?;

    // Open a PR if the GitHub CLI is available and authenticated; otherwise the
    // branch is pushed and the PR is opened out of band.
    let pr = match std::process::Command::new("gh")
        .args([
            "pr", "create", "--head", &branch, "--title", title, "--body", body,
        ])
        .current_dir(&wt)
        .output()
    {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
        _ => "branch pushed; open the PR from it".to_string(),
    };
    eprintln!("git-pr [{imp}] pushed {branch} ({commit})");
    Ok(json!({ "branch": branch, "commit": commit, "pushed": true, "pr": pr }))
}

/// Overwrite an imp's identity, only after an admin approved the exact text
/// (D10). Trusted-side; the box never writes here (its repo mount is read-only).
fn exec_identity(imp: &str, payload: &Value) -> Result<Value, String> {
    let content = payload
        .get("identity")
        .or_else(|| payload.get("charter"))
        .and_then(|v| v.as_str())
        .filter(|s| !s.trim().is_empty())
        .ok_or("identity-edit needs a non-empty \"identity\" field")?;
    let short = imp.strip_prefix("org/").unwrap_or(imp);
    let path = crate::run::boxed::identity_path(short);
    let dir = path.parent().ok_or("bad identity path")?;
    if !dir.exists() {
        return Err(format!(
            "no imp directory {} — is \"{short}\" a real imp?",
            dir.display()
        ));
    }
    write_atomic(&path, content)?;
    eprintln!("identity [{imp}] updated ({} bytes)", content.trim().len());
    Ok(json!({ "written": path.display().to_string(), "bytes": content.trim().len() }))
}

/// Overwrite a channel's purpose (channels/<id>/purpose.md), post-approval (D10).
fn exec_purpose(payload: &Value) -> Result<Value, String> {
    let channel = payload
        .get("channel_id")
        .and_then(|v| v.as_str())
        .ok_or("purpose-edit needs a \"channel_id\"")?;
    let content = payload
        .get("purpose")
        .and_then(|v| v.as_str())
        .filter(|s| !s.trim().is_empty())
        .ok_or("purpose-edit needs a non-empty \"purpose\" field")?;
    let path = crate::channel::discord::purpose_path(channel);
    let _ = std::fs::create_dir_all(path.parent().unwrap());
    write_atomic(&path, content)?;
    eprintln!(
        "purpose [{channel}] updated ({} bytes)",
        content.trim().len()
    );
    Ok(json!({ "written": path.display().to_string(), "channel_id": channel }))
}

fn write_atomic(path: &std::path::Path, content: &str) -> Result<(), String> {
    let tmp = path.with_extension("md.tmp");
    std::fs::write(&tmp, format!("{}\n", content.trim())).map_err(|e| e.to_string())?;
    std::fs::rename(&tmp, path).map_err(|e| e.to_string())?;
    Ok(())
}

fn git(args: &[&str]) -> Result<String, String> {
    let out = std::process::Command::new("git")
        .args(args)
        .output()
        .map_err(|e| e.to_string())?;
    if !out.status.success() {
        return Err(format!(
            "git {}: {}",
            args.join(" "),
            String::from_utf8_lossy(&out.stderr).trim()
        ));
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// A current-vs-proposed unified diff of a file (for `gates show` on an
/// identity/purpose gate — the reviewer sees exactly what would change).
pub fn identity_diff(imp: &str, proposed: &str) -> Option<String> {
    let short = imp.strip_prefix("org/").unwrap_or(imp);
    file_diff(&crate::run::boxed::identity_path(short), proposed)
}

pub fn purpose_diff(channel_id: &str, proposed: &str) -> Option<String> {
    file_diff(&crate::channel::discord::purpose_path(channel_id), proposed)
}

fn file_diff(current: &std::path::Path, proposed: &str) -> Option<String> {
    let current_arg = if current.exists() {
        current.to_path_buf()
    } else {
        std::path::PathBuf::from("/dev/null")
    };
    let tmp = std::env::temp_dir().join(format!("impyard-charter-{}.md", std::process::id()));
    std::fs::write(&tmp, format!("{}\n", proposed.trim())).ok()?;
    let out = std::process::Command::new("git")
        .args(["diff", "--no-index", "--"])
        .arg(&current_arg)
        .arg(&tmp)
        .output()
        .ok()?;
    let _ = std::fs::remove_file(&tmp);
    let diff = String::from_utf8_lossy(&out.stdout).to_string();
    if diff.trim().is_empty() {
        None
    } else {
        Some(diff)
    }
}

/// The diff the box produced in a run's worktree (for `gates show` on a code
/// gate — the human reviews the actual change, rendered live, not stored).
pub fn worktree_diff(run_id: &str) -> Option<String> {
    let wt = paths::run_dir(run_id).join("worktree");
    if !wt.exists() {
        return None;
    }
    let wt = wt.display().to_string();
    // Stage nothing; show working-tree changes against HEAD, including new files.
    let _ = std::process::Command::new("git")
        .args(["-C", &wt, "add", "-A", "-N"])
        .status();
    git(&["-C", &wt, "diff", "HEAD"]).ok()
}

// ── audit ────────────────────────────────────────────────────────────────────

/// Append an action decision to the shared audit log, alongside egress decisions.
fn audit(
    imp: &str,
    intent: &str,
    disposition: &str,
    gate_id: Option<&str>,
    result: Option<&Value>,
) {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let rec = json!({
        "decision_id": format!("act-{n:x}"),
        "ts": now_rfc3339(),
        "kind": "action",
        "imp": imp,
        "intent": intent,
        "disposition": disposition,
        "gate_id": gate_id,
        "result": result,
    });
    let path = paths::decisions_log();
    if let Some(dir) = path.parent() {
        let _ = std::fs::create_dir_all(dir);
    }
    if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(&path) {
        let _ = writeln!(f, "{rec}");
    }
}