greentic-deployer-dev 1.1.27411998332

Greentic deployer runtime for plan construction and deployment-pack dispatch
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
//! `gtc op secrets {list,put,get,rotate}` (`A3`).
//!
//! Operates on the env's bound `Secrets` env-pack. The actual backend
//! dispatch (AWS Secrets Manager, Azure Key Vault, dev-store, Vault, etc.)
//! lives in `greentic-secrets-lib`; the env-pack registry (A9) is what binds
//! a `PackDescriptor` to a concrete backend at runtime. A3 ships the
//! command surface, enforces the env-must-have-secrets-pack precondition,
//! and reports the resolved kind in every envelope.
//!
//! `put` is live for the `greentic.secrets.dev-store` kind (the default
//! binding `op env init` creates): it writes the value into the env's local
//! dev store at the same path the runtime reader (greentic-start
//! `SecretsClient::open(<env_dir>)`) resolves, so a put is immediately
//! visible to served revisions. All other kinds — and get/rotate against any
//! live backend — return `NotYetImplemented` and point at the gating PR
//! (A9 — env-pack registry + handler dispatch).
//! `list` returns the *namespace* keys the env owns (always `secret://<env>/...`)
//! — no actual material is fetched.

use std::path::{Path, PathBuf};

use chrono::Utc;
use greentic_deploy_spec::{CapabilitySlot, EnvId, EnvPackBinding, SecretRef};
use greentic_secrets_lib::{DevStore, SecretFormat, SecretsStore};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::environment::{EnvFlock, EnvironmentStore, LocalFsStore};

use super::{
    AuditCtx, AuditGens, OpError, OpFlags, OpOutcome, audit_and_record, resolve_idempotency_key,
};

const NOUN: &str = "secrets";

/// `PackDescriptor::path()` of the local dev-store secrets backend — the
/// default binding `op env init` creates and the only kind `put` dispatches
/// to in Phase A. Shared with `env apply` (PR-2), which pre-checks the bound
/// backend at validation time so a non-dev-store env fails before any
/// mutation instead of mid-run.
pub(super) const DEV_STORE_KIND_PATH: &str = "greentic.secrets.dev-store";

/// Same override the runtime reader honors (`greentic-start
/// `dev_store_path::override_path`): when set, both writer and reader use
/// this path instead of the env-dir defaults below.
pub(super) const DEV_SECRETS_PATH_ENV: &str = "GREENTIC_DEV_SECRETS_PATH";

/// Dev-store candidates relative to the env dir. MUST mirror greentic-start's
/// `dev_store_path.rs` (`STORE_RELATIVE` / `STORE_STATE_RELATIVE`) — the
/// runtime's `SecretsClient::open(<env_dir>)` resolves the same chain, so a
/// put here is what a served revision reads back.
pub(super) const DEV_STORE_RELATIVE: &str = ".greentic/dev/.dev.secrets.env";
const DEV_STORE_STATE_RELATIVE: &str = ".greentic/state/dev/.dev.secrets.env";

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretsListPayload {
    pub environment_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretsPutPayload {
    pub environment_id: String,
    /// Path relative to the env's secret namespace. The full SecretRef is
    /// rendered as `secret://<env>/<path>`.
    pub path: String,
    /// The value is intentionally typed as a plain JSON string so payload
    /// transport stays uniform; the live backend handler (A9) is what reads
    /// this and converts to the backend-native shape.
    pub value: String,
    /// Caller-supplied A8 §2 idempotency key. Optional on the CLI
    /// surface; when absent, the verb mints one per invocation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretsGetPayload {
    pub environment_id: String,
    pub path: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecretsRotatePayload {
    pub environment_id: String,
    pub path: String,
}

/// `op secrets list`. Returns the env's secret-ref namespace plus the kind
/// of the bound secrets env-pack. Phase A does not yet enumerate live
/// backend-side keys (no handler dispatch); the operator gets the namespace
/// plus backend identity, which is what wizards need to know to write into
/// the right place.
pub fn list(
    store: &LocalFsStore,
    flags: &OpFlags,
    payload: Option<SecretsListPayload>,
) -> Result<OpOutcome, OpError> {
    if flags.schema_only {
        return Ok(OpOutcome::new(NOUN, "list", list_schema()));
    }
    let payload = resolve_payload::<SecretsListPayload>(flags, payload)?;
    let env_id = parse_env_id(&payload.environment_id)?;
    let env = store.load(&env_id)?;
    let secrets = require_secrets_pack(&env, &env_id)?;
    // Walk every SecretRef known in the env so the operator can audit what
    // the env *expects* to be present. This is purely structural — the
    // backend itself may have more or fewer keys.
    let mut known_refs: Vec<String> = env
        .credentials_ref
        .as_ref()
        .map(|c| c.as_str().to_string())
        .into_iter()
        .collect();
    if let Some(bs) = env
        .bundles
        .iter()
        .map(|b| b.authorization_ref.to_string_lossy().into_owned())
        .next()
    {
        // authorization_ref is a path, not a secret://, but include it for
        // visibility into where bundle auth resolves.
        known_refs.push(format!("auth://{bs}"));
    }
    Ok(OpOutcome::new(
        NOUN,
        "list",
        json!({
            "environment_id": env_id.as_str(),
            "secrets_kind": secrets.kind.to_string(),
            "namespace": format!("secret://{}/", env_id.as_str()),
            "known_refs": known_refs,
            "snapshot_at": Utc::now(),
            "note": "Phase A: namespace + known-refs only; live backend enumeration lands in A9.",
        }),
    ))
}

pub fn put(
    store: &LocalFsStore,
    flags: &OpFlags,
    payload: Option<SecretsPutPayload>,
) -> Result<OpOutcome, OpError> {
    if flags.schema_only {
        return Ok(OpOutcome::new(NOUN, "put", put_schema()));
    }
    let payload = resolve_payload::<SecretsPutPayload>(flags, payload)?;
    let env_id = parse_env_id(&payload.environment_id)?;
    let idempotency_key = resolve_idempotency_key(payload.idempotency_key.clone())?;
    let ctx = AuditCtx {
        env_id: env_id.clone(),
        noun: NOUN,
        verb: "put",
        target: json!({"path": payload.path}),
        idempotency_key: Some(idempotency_key.as_str().to_string()),
    };
    audit_and_record(store, ctx, |_committed| {
        let env = store.load(&env_id)?;
        let secrets = require_secrets_pack(&env, &env_id)?;
        let rel_path = payload.path.trim_start_matches('/');
        // Build the resolved SecretRef so we can validate the env-scoping.
        let secret_uri = format!("secret://{}/{rel_path}", env_id.as_str());
        SecretRef::try_new(secret_uri.clone())
            .map_err(|e| OpError::InvalidArgument(format!("secret path: {e}")))?;
        // Make sure the value is non-empty — writing empty strings to a real
        // backend is almost always a bug.
        if payload.value.is_empty() {
            return Err(OpError::InvalidArgument(
                "value must not be empty".to_string(),
            ));
        }
        if secrets.kind.path() != DEV_STORE_KIND_PATH {
            return Err(OpError::NotYetImplemented(
                "secrets backend dispatch beyond the dev-store lands in A9 (env-pack registry)"
                    .to_string(),
            ));
        }
        validate_dev_store_secret_path(rel_path)?;
        let store_uri = format!("secrets://{}/{rel_path}", env_id.as_str());
        let dev_path = resolve_dev_store_path(
            &store.env_dir(&env_id)?,
            std::env::var_os(DEV_SECRETS_PATH_ENV).map(PathBuf::from),
        );
        dev_store_put(&dev_path, &store_uri, &payload.value)?;
        Ok((
            OpOutcome::new(
                NOUN,
                "put",
                json!({
                    "environment_id": env_id.as_str(),
                    "secret_ref": secret_uri,
                    "store_uri": store_uri,
                    "secrets_kind": secrets.kind.to_string(),
                    "store_path": dev_path.display().to_string(),
                    "written": true,
                }),
            ),
            AuditGens::NONE,
        ))
    })
}

pub fn get(
    store: &LocalFsStore,
    flags: &OpFlags,
    payload: Option<SecretsGetPayload>,
) -> Result<OpOutcome, OpError> {
    if flags.schema_only {
        return Ok(OpOutcome::new(NOUN, "get", get_schema()));
    }
    let payload = resolve_payload::<SecretsGetPayload>(flags, payload)?;
    let env_id = parse_env_id(&payload.environment_id)?;
    let env = store.load(&env_id)?;
    let _secrets = require_secrets_pack(&env, &env_id)?;
    SecretRef::try_new(format!(
        "secret://{}/{}",
        env_id.as_str(),
        payload.path.trim_start_matches('/')
    ))
    .map_err(|e| OpError::InvalidArgument(format!("secret path: {e}")))?;
    Err(OpError::NotYetImplemented(
        "secrets backend dispatch lands in A9 (env-pack registry); A3 wires the surface only"
            .to_string(),
    ))
}

pub fn rotate(
    store: &LocalFsStore,
    flags: &OpFlags,
    payload: Option<SecretsRotatePayload>,
) -> Result<OpOutcome, OpError> {
    if flags.schema_only {
        return Ok(OpOutcome::new(NOUN, "rotate", rotate_schema()));
    }
    let payload = resolve_payload::<SecretsRotatePayload>(flags, payload)?;
    let env_id = parse_env_id(&payload.environment_id)?;
    let ctx = AuditCtx {
        env_id: env_id.clone(),
        noun: NOUN,
        verb: "rotate",
        target: json!({"path": payload.path}),
        idempotency_key: None,
    };
    audit_and_record(store, ctx, |_committed| {
        let env = store.load(&env_id)?;
        let _secrets = require_secrets_pack(&env, &env_id)?;
        SecretRef::try_new(format!(
            "secret://{}/{}",
            env_id.as_str(),
            payload.path.trim_start_matches('/')
        ))
        .map_err(|e| OpError::InvalidArgument(format!("secret path: {e}")))?;
        Err(OpError::NotYetImplemented(
            "secret rotation depends on backend-specific rotate hooks; lands in A9".to_string(),
        ))
    })
}

// --- internals -----------------------------------------------------------

/// Where the env's dev store lives, mirroring the runtime reader's chain
/// (greentic-start `dev_store_path`): explicit override env var, else the
/// first *existing* default candidate under the env dir, else the primary
/// default (created on first write).
pub(super) fn resolve_dev_store_path(env_dir: &Path, override_path: Option<PathBuf>) -> PathBuf {
    if let Some(path) = override_path {
        return path;
    }
    let primary = env_dir.join(DEV_STORE_RELATIVE);
    if primary.exists() {
        return primary;
    }
    let fallback = env_dir.join(DEV_STORE_STATE_RELATIVE);
    if fallback.exists() {
        return fallback;
    }
    primary
}

/// Validate that `rel_path` (leading `/` already trimmed) is a writable
/// dev-store secret path: exactly `<tenant>/<team>/<pack>/<name>` with
/// store-canonical team and name segments.
///
/// The dev store's native key shape is the runtime's `secrets://` (plural)
/// URI: `secrets://<env>/<tenant>/<team>/<pack>/<name>`; the backend handler
/// converts the logical `secret://` ref 1:1. `DevStore::put` itself rejects
/// any other depth, so enforce the shape upfront with a teachable error
/// instead of surfacing the backend's "uri is missing category" — exactly
/// four non-empty segments.
///
/// Shared between `put` (pre-write) and `env apply`'s pre-mutation manifest
/// validation (PR-2) so the two surfaces cannot drift.
pub(super) fn validate_dev_store_secret_path(rel_path: &str) -> Result<(), OpError> {
    let shape_err = || {
        OpError::InvalidArgument(format!(
            "dev-store secret path must be `<tenant>/<team>/<pack>/<name>` \
             (e.g. `default/_/messaging-telegram/telegram_bot_token`); \
             got `{rel_path}`"
        ))
    };
    let segs: Vec<&str> = rel_path.split('/').collect();
    let [_tenant, team, _pack, name] = segs[..] else {
        return Err(shape_err());
    };
    if segs.iter().any(|s| s.is_empty()) {
        return Err(shape_err());
    }
    // The runtime reader canonicalizes the team segment before lookup
    // (greentic-start `secrets_manager::canonical_team` maps `default`/
    // empty — trimmed, case-insensitive — to `_`), so a literal
    // `default` team would be written under a key no lookup ever uses.
    // Same policy as the name segment: reject instead of silently
    // transforming.
    if !is_canonical_team(team) {
        return Err(OpError::InvalidArgument(format!(
            "team segment `{team}` is not store-canonical: the runtime \
             reads the default team as `_` — pass `_` (or a real team \
             name without surrounding whitespace)"
        )));
    }
    // The runtime reader canonicalizes the name segment before lookup
    // (greentic-start `secret_name::canonical_secret_name`), so a
    // non-canonical name would be written but never found. Reject
    // instead of silently transforming — producer and consumer must
    // share one derivation, and we share it by only accepting
    // already-canonical input.
    if !is_canonical_secret_name(name) {
        return Err(OpError::InvalidArgument(format!(
            "secret name `{name}` is not store-canonical: use lowercase \
             a-z, 0-9 and single `_` separators (no leading/trailing `_`)"
        )));
    }
    Ok(())
}

/// A segment is writable iff the runtime reader's canonicalization maps it to
/// itself — anything else is written under a key no lookup will ever use.
/// Both checks call the deployer-local copies of the reader's functions
/// (`runtime_secrets::{canonical_team,canonical_secret_name}`, faithful
/// mirrors of greentic-start's) so the predicate can't drift from the
/// transformation it guards.
fn is_canonical_team(team: &str) -> bool {
    crate::runtime_secrets::canonical_team(Some(team)) == team
}

fn is_canonical_secret_name(name: &str) -> bool {
    crate::runtime_secrets::canonical_secret_name(name) == name
}

/// Write one value into the dev store from this sync context.
///
/// `DevStore::put` is async; same constraint as
/// `runtime_secrets::block_on_async_resolution` — the caller may sit on a
/// current-thread runtime (where `block_in_place` panics) or no runtime at
/// all, so hop to a dedicated OS thread that owns its own current-thread
/// runtime.
///
/// The backend is load-snapshot-at-open / persist-full-snapshot-on-write
/// (its internal flock covers each step, NOT the open→put window), so two
/// concurrent writers silently lose the slower one's update. Serialize the
/// whole cycle with a blocking sidecar flock (`<store>.lock`) held from
/// before `DevStore::with_path` (the snapshot load) until after `put` (the
/// persist). The sidecar — not the store file itself — because the
/// backend's own flock on the store file would deadlock against ours.
/// This serializes `op secrets put` writers; other tools writing the same
/// store (`greentic-secrets apply`, the runtime's QA persist) don't take
/// this lock — closing that belongs in the backend (A9 follow-up).
///
/// Failures map to `OpError::Io` keyed on the store path — the dev store is
/// a local file, and adding a dedicated `OpError` variant would break
/// Map a deploy-spec `SecretRef` (scheme `secret://`) to the dev-store's
/// native URI (scheme `secrets://`, plural). The two schemes are deliberately
/// distinct contracts — deploy-spec refs vs runtime-store keys — and the
/// mapping is just a scheme rename today. Centralizing it here keeps every
/// caller doing the same translation and gives one grep target if the
/// mapping ever grows beyond a rename. See the `secrets://` vs `secret://`
/// trap noted in workspace memory.
pub(super) fn secret_ref_to_store_uri(secret_ref: &SecretRef) -> String {
    secret_ref.as_str().replacen("secret://", "secrets://", 1)
}

/// downstream exhaustive matches (greentic-operator's HTTP status mapping).
/// Error messages carry the backend's text only — never secret material.
pub(super) fn dev_store_put(path: &Path, uri: &str, value: &str) -> Result<(), OpError> {
    let io_err = |message: String| OpError::Io {
        path: path.to_path_buf(),
        source: std::io::Error::other(message),
    };
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|source| OpError::Io {
            path: parent.to_path_buf(),
            source,
        })?;
    }
    let _write_lock = EnvFlock::acquire(&dev_store_lock_path(path))
        .map_err(|source| OpError::Store(source.into()))?;
    let store = DevStore::with_path(path.to_path_buf())
        .map_err(|e| io_err(format!("open dev store: {e}")))?;
    std::thread::scope(|scope| {
        scope
            .spawn(|| {
                tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .map_err(|e| io_err(format!("build runtime: {e}")))?
                    .block_on(store.put(uri, SecretFormat::Text, value.as_bytes()))
                    .map_err(|e| io_err(format!("dev store write: {e}")))
            })
            .join()
            .expect("dev-store write thread panicked")
    })
}

/// Sidecar lock path for a dev store file: the full path with `.lock`
/// appended (`.dev.secrets.env` → `.dev.secrets.env.lock`). Appending to the
/// whole path (not just the file name) keeps the directory component intact
/// without the extract-fallback-reassemble dance.
fn dev_store_lock_path(store_path: &Path) -> PathBuf {
    let mut lock = store_path.as_os_str().to_os_string();
    lock.push(".lock");
    PathBuf::from(lock)
}

fn resolve_payload<T: serde::de::DeserializeOwned>(
    flags: &OpFlags,
    payload: Option<T>,
) -> Result<T, OpError> {
    if let Some(p) = payload {
        return Ok(p);
    }
    if let Some(path) = &flags.answers {
        return super::load_answers::<T>(path);
    }
    Err(OpError::InvalidArgument(
        "no payload provided: pass --answers <path> or supply the payload directly".to_string(),
    ))
}

fn parse_env_id(raw: &str) -> Result<EnvId, OpError> {
    EnvId::try_from(raw).map_err(|e| OpError::InvalidArgument(format!("environment_id: {e}")))
}

/// The env-must-have-secrets-pack precondition every secrets verb enforces.
/// Shared with `env apply`'s validation (PR-2).
pub(super) fn require_secrets_pack<'a>(
    env: &'a greentic_deploy_spec::Environment,
    env_id: &EnvId,
) -> Result<&'a EnvPackBinding, OpError> {
    env.pack_for_slot(CapabilitySlot::Secrets).ok_or_else(|| {
        OpError::Conflict(format!(
            "env `{env_id}` has no secrets env-pack bound; bind one with `op env-packs add` first"
        ))
    })
}

fn list_schema() -> Value {
    json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "title": "SecretsListPayload",
        "type": "object",
        "required": ["environment_id"],
        "additionalProperties": false,
        "properties": {"environment_id": {"type": "string"}}
    })
}

fn put_schema() -> Value {
    json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "title": "SecretsPutPayload",
        "type": "object",
        "required": ["environment_id", "path", "value"],
        "additionalProperties": false,
        "properties": {
            "environment_id": {"type": "string"},
            "path": {"type": "string", "description": "Relative path under secret://<env>/. For the dev-store backend: <tenant>/<team>/<pack>/<name> (e.g. default/_/messaging-telegram/telegram_bot_token). Use `_` for the default team — a literal `default` team is rejected (the runtime reads the default team as `_`)."},
            "value": {"type": "string"},
            "idempotency_key": {"type": ["string", "null"], "description": "Caller-supplied idempotency key; minted per invocation when absent."}
        }
    })
}

fn get_schema() -> Value {
    json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "title": "SecretsGetPayload",
        "type": "object",
        "required": ["environment_id", "path"],
        "additionalProperties": false,
        "properties": {
            "environment_id": {"type": "string"},
            "path": {"type": "string"}
        }
    })
}

fn rotate_schema() -> Value {
    json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "title": "SecretsRotatePayload",
        "type": "object",
        "required": ["environment_id", "path"],
        "additionalProperties": false,
        "properties": {
            "environment_id": {"type": "string"},
            "path": {"type": "string"}
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::tests_common::{make_binding, make_env};
    use tempfile::tempdir;

    fn env_with_secrets() -> greentic_deploy_spec::Environment {
        env_with_secrets_kind("greentic.secrets.dev-store@1.0.0")
    }

    #[test]
    fn list_reports_namespace_and_kind() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        let outcome = list(
            &store,
            &OpFlags::default(),
            Some(SecretsListPayload {
                environment_id: "local".to_string(),
            }),
        )
        .unwrap();
        assert_eq!(
            outcome.result.get("secrets_kind").and_then(|v| v.as_str()),
            Some("greentic.secrets.dev-store@1.0.0")
        );
        assert_eq!(
            outcome.result.get("namespace").and_then(|v| v.as_str()),
            Some("secret://local/")
        );
    }

    #[test]
    fn list_rejects_env_without_secrets_pack() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&make_env("local")).unwrap();
        let err = list(
            &store,
            &OpFlags::default(),
            Some(SecretsListPayload {
                environment_id: "local".to_string(),
            }),
        )
        .unwrap_err();
        assert!(matches!(err, OpError::Conflict(_)), "got {err:?}");
    }

    fn env_with_secrets_kind(kind: &str) -> greentic_deploy_spec::Environment {
        let mut env = make_env("local");
        env.packs.push(make_binding(CapabilitySlot::Secrets, kind));
        env
    }

    fn read_back(store_path: &str, uri: &str) -> Vec<u8> {
        crate::cli::tests_common::dev_store_read(Path::new(store_path), uri)
    }

    #[test]
    fn put_non_dev_store_backend_returns_not_yet_implemented() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store
            .save(&env_with_secrets_kind("greentic.secrets.aws-sm@1.0.0"))
            .unwrap();
        let err = put(
            &store,
            &OpFlags::default(),
            Some(SecretsPutPayload {
                environment_id: "local".to_string(),
                path: "credentials/aws".to_string(),
                value: "secret-material".to_string(),
                idempotency_key: None,
            }),
        )
        .unwrap_err();
        assert!(matches!(err, OpError::NotYetImplemented(_)), "got {err:?}");
    }

    #[test]
    fn put_writes_through_to_env_dev_store() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        let outcome = put(
            &store,
            &OpFlags::default(),
            Some(SecretsPutPayload {
                environment_id: "local".to_string(),
                path: "default/_/messaging-telegram/telegram_bot_token".to_string(),
                value: "tok-dummy-123".to_string(),
                idempotency_key: None,
            }),
        )
        .unwrap();
        let result = &outcome.result;
        assert_eq!(
            result.get("store_uri").and_then(|v| v.as_str()),
            Some("secrets://local/default/_/messaging-telegram/telegram_bot_token")
        );
        assert_eq!(result.get("written").and_then(|v| v.as_bool()), Some(true));
        // The outcome must never echo the value.
        let envelope = serde_json::to_string(&outcome).unwrap();
        assert!(!envelope.contains("tok-dummy-123"));
        let store_path = result
            .get("store_path")
            .and_then(|v| v.as_str())
            .expect("store_path in outcome");
        let bytes = read_back(
            store_path,
            "secrets://local/default/_/messaging-telegram/telegram_bot_token",
        );
        assert_eq!(bytes, b"tok-dummy-123".to_vec());
    }

    #[test]
    fn put_rejects_default_team_segment() {
        // The runtime reads the default team as `_`; a literal `default`
        // segment would be written but never looked up.
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        for team in ["default", "Default", "DEFAULT"] {
            let err = put(
                &store,
                &OpFlags::default(),
                Some(SecretsPutPayload {
                    environment_id: "local".to_string(),
                    path: format!("acme/{team}/messaging-telegram/telegram_bot_token"),
                    value: "tok-dummy".to_string(),
                    idempotency_key: None,
                }),
            )
            .unwrap_err();
            assert!(
                matches!(&err, OpError::InvalidArgument(msg) if msg.contains('_')),
                "team `{team}` got {err:?}"
            );
        }
    }

    #[test]
    fn concurrent_puts_do_not_lose_writes() {
        // The dev backend is load-snapshot / persist-full-snapshot; without
        // the sidecar flock spanning open→put, concurrent writers lose
        // updates silently (each persists a snapshot missing the other's
        // key). With the lock, every key must survive.
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        let names: Vec<String> = (0..8).map(|i| format!("concurrent_key_{i}")).collect();
        let store = &store;
        std::thread::scope(|scope| {
            for name in &names {
                scope.spawn(move || {
                    let outcome = put(
                        store,
                        &OpFlags::default(),
                        Some(SecretsPutPayload {
                            environment_id: "local".to_string(),
                            path: format!("default/_/demo-pack/{name}"),
                            value: format!("value-{name}"),
                            idempotency_key: None,
                        }),
                    )
                    .unwrap();
                    assert_eq!(
                        outcome.result.get("written").and_then(|v| v.as_bool()),
                        Some(true)
                    );
                });
            }
        });
        let store_path = dir
            .path()
            .join("local")
            .join(DEV_STORE_RELATIVE)
            .display()
            .to_string();
        for name in &names {
            let bytes = read_back(
                &store_path,
                &format!("secrets://local/default/_/demo-pack/{name}"),
            );
            assert_eq!(bytes, format!("value-{name}").into_bytes());
        }
    }

    #[test]
    fn dev_store_lock_path_is_sidecar() {
        assert_eq!(
            dev_store_lock_path(Path::new("/x/.greentic/dev/.dev.secrets.env")),
            Path::new("/x/.greentic/dev/.dev.secrets.env.lock")
        );
        assert_eq!(
            dev_store_lock_path(Path::new("state/dev-store.dat")),
            Path::new("state/dev-store.dat.lock")
        );
    }

    #[test]
    fn put_rejects_non_canonical_name_segment() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        let err = put(
            &store,
            &OpFlags::default(),
            Some(SecretsPutPayload {
                environment_id: "local".to_string(),
                path: "default/_/messaging-telegram/TELEGRAM-BOT-TOKEN".to_string(),
                value: "tok-dummy".to_string(),
                idempotency_key: None,
            }),
        )
        .unwrap_err();
        assert!(matches!(err, OpError::InvalidArgument(_)), "got {err:?}");
    }

    #[test]
    fn put_rejects_wrong_depth_path() {
        // `DevStore::put` only accepts the 5-segment `secrets://` shape; the
        // verb rejects other depths upfront with a teachable message.
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        for path in ["credentials/aws", "default/_/pack/extra/name", "a//b/c"] {
            let err = put(
                &store,
                &OpFlags::default(),
                Some(SecretsPutPayload {
                    environment_id: "local".to_string(),
                    path: path.to_string(),
                    value: "v".to_string(),
                    idempotency_key: None,
                }),
            )
            .unwrap_err();
            assert!(
                matches!(&err, OpError::InvalidArgument(msg) if msg.contains("<tenant>/<team>/<pack>/<name>")),
                "path `{path}` got {err:?}"
            );
        }
    }

    #[test]
    fn resolve_dev_store_path_override_wins() {
        let dir = tempdir().unwrap();
        let override_path = dir.path().join("custom.dat");
        assert_eq!(
            resolve_dev_store_path(dir.path(), Some(override_path.clone())),
            override_path
        );
    }

    #[test]
    fn resolve_dev_store_path_prefers_existing_candidate() {
        let dir = tempdir().unwrap();
        let fallback = dir.path().join(DEV_STORE_STATE_RELATIVE);
        std::fs::create_dir_all(fallback.parent().unwrap()).unwrap();
        std::fs::write(&fallback, b"").unwrap();
        assert_eq!(resolve_dev_store_path(dir.path(), None), fallback);
        // Once the primary exists it wins over the state fallback.
        let primary = dir.path().join(DEV_STORE_RELATIVE);
        std::fs::create_dir_all(primary.parent().unwrap()).unwrap();
        std::fs::write(&primary, b"").unwrap();
        assert_eq!(resolve_dev_store_path(dir.path(), None), primary);
    }

    #[test]
    fn resolve_dev_store_path_defaults_to_primary() {
        let dir = tempdir().unwrap();
        assert_eq!(
            resolve_dev_store_path(dir.path(), None),
            dir.path().join(DEV_STORE_RELATIVE)
        );
    }

    #[test]
    fn canonical_name_fixed_points() {
        assert!(is_canonical_secret_name("telegram_bot_token"));
        assert!(is_canonical_secret_name("a1"));
        assert!(!is_canonical_secret_name(""));
        assert!(!is_canonical_secret_name("TELEGRAM_BOT_TOKEN"));
        assert!(!is_canonical_secret_name("bot-token"));
        assert!(!is_canonical_secret_name("_leading"));
        assert!(!is_canonical_secret_name("trailing_"));
        assert!(!is_canonical_secret_name("double__underscore"));
    }

    #[test]
    fn put_rejects_empty_value() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        let err = put(
            &store,
            &OpFlags::default(),
            Some(SecretsPutPayload {
                environment_id: "local".to_string(),
                path: "x".to_string(),
                value: "".to_string(),
                idempotency_key: None,
            }),
        )
        .unwrap_err();
        assert!(matches!(err, OpError::InvalidArgument(_)), "got {err:?}");
    }

    #[test]
    fn get_yields_not_yet_implemented_after_path_validation() {
        let dir = tempdir().unwrap();
        let store = LocalFsStore::new(dir.path());
        store.save(&env_with_secrets()).unwrap();
        let err = get(
            &store,
            &OpFlags::default(),
            Some(SecretsGetPayload {
                environment_id: "local".to_string(),
                path: "credentials/aws".to_string(),
            }),
        )
        .unwrap_err();
        assert!(matches!(err, OpError::NotYetImplemented(_)), "got {err:?}");
    }
}