app-kit 0.0.2

Application and durable workflow composition for ai-kit
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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
//! Durable applications over caller-owned storage and configured agents.
//!
//! Start with [`AppConfig`] and [`App::open`], create a [`Workspace`], then select
//! a [`workflow::Workflow`]. The [local example](#local-workflow) runs with
//! caller-created embedded Lance StateStore and no Agent value or external service.
//!
//! [`workflow`] contains definitions, execution controls, state operations,
//! graph inspection, immutable checkpoints, and the five concrete App behavior
//! seams. [`AgentSpec`] transfers an already-built Agent; App never constructs
//! providers, tools or lower storage from declarations. Exact associated lower
//! Workspace, Conversation and StateTransaction types remain attached.
//!
//! Call [`App::shutdown`] while the captured Tokio runtime and lower runtimes
//! are alive and driven. Run handles observe accepted work; [`workflow::Execution`]
//! owns lazy advancement. Dropping an execution can revoke uncommitted work,
//! while observation loss cannot revoke an admitted native commit.
//!
//! Public supporting types live under [`workflow`]. The state serialization
//! registry stores only field/tag codecs; it is not a runtime behavior registry.

//!
//! # Choose a workflow
//!
//! - Application builders: the [local workflow](#local-workflow),
//!   [explicit execution and retained history](workflow), then
//!   [durable reopen and migration prerequisites](App::open).
//! - Custom implementers: [configure concrete behavior](AppConfig#configure-behavior)
//!   with the five workflow traits. Their examples run locally; lower
//!   [`agents_kit::AgentBackend`] and [`storage_kit::StateStoreBackend`]
//!   implementations remain direct, statically selected values.
//! - Agent-backed workflows: transfer already-built values through [`AgentSpec`].
//!   App owns eventual consuming Agent shutdown, without rebuilding credentials,
//!   tools, Providers or persistence from declarations.
//!
//! # Local workflow
//!
//! ```
//! use agents_kit::Agent;
//! use app_kit::{App, AppConfig, Shutdown, WorkspaceConfig};
//! use app_kit::workflow::{ExecutionOptions, RunStatus, WorkflowDefinition};
//! use storage_kit::{StateStore, state::config::{LanceStateStoreConfig, StateStoreConfig}};
//! # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
//! # runtime.block_on(async {
//! let store = StateStore::connect(StateStoreConfig::lance(LanceStateStoreConfig::memory())).await?;
//! let definition = WorkflowDefinition::parse(r#"{
//!     "schema":"app-kit.workflow/v2", "id":"counter", "revision":"r1",
//!     "state":{"count":0}, "required":["count"],
//!     "reducers":{"count":"reject_concurrent"}, "entry":"increment",
//!     "nodes":[{"id":"increment","step":{"kind":"state","mutations":[
//!         {"kind":"increment","target":"count","value":{"kind":"literal","value":1}}
//!     ]}}], "routes":{}
//! }"#)?;
//! let mut app = App::open(AppConfig::<_, Agent>::new(store, Vec::new(), vec![definition])).await?;
//! let outcome = async {
//!     let workspace = app.create_workspace(WorkspaceConfig {
//!         name: Some("local counter".into()), root: std::env::current_dir()?,
//!     }).await?;
//!     let workflow = workspace.workflow("counter".parse()?).await?;
//!     let run = workflow.start(ExecutionOptions::default()).await?;
//!     Ok::<_, Box<dyn std::error::Error>>(run.wait().await?)
//! }.await;
//! let cleanup = app.shutdown(Shutdown::CancelAndDrain {
//!     timeout: std::time::Duration::from_secs(5),
//! }).await;
//! if let Err(error) = &cleanup { eprintln!("App shutdown: {error}"); }
//! let snapshot = outcome?; // Preserve the operation error after attempting shutdown.
//! cleanup?;
//! assert!(matches!(snapshot.status, RunStatus::Succeeded));
//! assert_eq!(snapshot.state.values()["count"], 1);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! # })?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::fmt;
use std::num::NonZeroUsize;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;

use agents_kit::AgentBackend;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use storage_kit::StateStoreBackend;
use uuid::{Uuid, Variant, Version};

use crate::workflow::{
    ActionBackend, ChildExecutor, ConditionBackend, InlineExecutor, JsonState, LifecycleHooks,
    NoActions, NoConditions, NoHooks, StateTyping, Workflow, WorkflowDefinition, WorkflowId,
};

mod app;
mod storage;
mod workspace;

/// Opaque workflow definitions and runtime handles.
pub mod workflow;

/// An open application generation.
///
/// Owns one durable application generation, its transferred agents and accepted work.
///
/// Supply a concrete [`storage_kit::StateStoreBackend`] through [`AppConfig`].
/// Each [`AgentSpec`] preserves its concrete [`agents_kit::AgentBackend`] and its
/// associated Workspace/Conversation types. An empty agent inventory can execute
/// state-only workflows; the `Agent` type in the [local example](crate#local-workflow)
/// constructs no Agent value.
///
/// Keep the Tokio runtime and any caller-owned lower runtimes alive and driven
/// through [`Self::shutdown`]. Root drop revokes admission and requests supervised
/// best-effort cleanup; it cannot substitute for awaited shutdown. Workspace and
/// run observers do not keep admission alive after the App is revoked.
///
/// See [the local workflow](crate#local-workflow).
pub struct App<
    CS: StateStoreBackend,
    A: AgentBackend,
    X: ActionBackend = NoActions,
    C: ConditionBackend = NoConditions,
    T: StateTyping = JsonState,
    H: LifecycleHooks = NoHooks,
    E: ChildExecutor = InlineExecutor,
> {
    runtime: Arc<app::AppRuntime<CS, A, X, C, T, H, E>>,
}

/// Complete application configuration.
///
/// App does not offer a separate built-in storage construction path:
///
/// ```compile_fail
/// let _ = app_kit::AppState::<storage_kit::StateStore>::Ephemeral;
/// ```
///
/// Owns caller-built storage, a homogeneous agent inventory, and workflow definitions.
///
/// The consuming `with_*` methods change their concrete App behavior parameter.
/// They do not erase backends or alter already admitted runs. Heterogeneous agent
/// inventories use a caller-owned exhaustive hierarchy. Dropping configuration
/// before open does not perform asynchronous Agent shutdown.
///
/// # Configure behavior
///
/// Start with ready storage, ready Agents, and parsed definitions. Apply the
/// consuming configuration methods before [`App::open`]; they retain exact
/// implementation types, including associated lower children and transaction
/// ownership. None registers a runtime callback or erases a backend.
///
/// | Behavior | Complete implementation example | Attach before open |
/// | --- | --- | --- |
/// | Produce lazy action events and writes | [`workflow::ActionBackend`] | [`Self::with_actions`] |
/// | Evaluate declared routing predicates | [`workflow::ConditionBackend`] | [`Self::with_conditions`] |
/// | Construct and validate application state | [`workflow::StateTyping`] | [`Self::with_state_typing`] |
/// | Observe authoritative lifecycle events | [`workflow::LifecycleHooks`] | [`Self::with_hooks`] |
/// | Drive concrete local child futures | [`workflow::ChildExecutor`] | [`Self::with_child_executor`] |
///
/// The linked examples exercise each concrete behavior directly. Attach it before
/// opening App. Action and condition declarations must match the workflow's
/// exact logical keys and revisions. A custom child executor must return every
/// admitted completion exactly once; it never creates child identities. App's
/// built-in `NoActions`, `NoConditions`, `JsonState`, `NoHooks` and `InlineExecutor`
/// are suitable defaults only where their actual behavior satisfies the workflow.
///
/// Lower composition is independent: `A::Workspace` fixes its Conversation,
/// while `CS::Transaction` fixes consuming commit/rollback. For heterogeneous
/// Agent inventories implement matching caller-owned exhaustive hierarchies;
/// do not substitute public trait objects or independent child parameters.
///
/// See [the local workflow](crate#local-workflow).
pub struct AppConfig<
    CS: StateStoreBackend,
    A: AgentBackend,
    X: ActionBackend = NoActions,
    C: ConditionBackend = NoConditions,
    T: StateTyping = JsonState,
    H: LifecycleHooks = NoHooks,
    E: ChildExecutor = InlineExecutor,
> {
    state: CS,
    agents: Vec<AgentSpec<A>>,
    workflows: Vec<WorkflowDefinition>,
    actions: Vec<X>,
    conditions: Vec<C>,
    typing: T,
    hooks: H,
    executor: E,
}

/// Declares one configured lower agent.
///
/// The key and revision are caller-owned logical binding metadata, validated by
/// [`App::open`]. Keep the same revision only while the configuration is compatible.
/// App never derives compatibility from the opaque lower Agent identity. A
/// successful open takes responsibility for consuming Agent shutdown.
///
/// The [caller-owned Agent recipe](https://github.com/jecsand838/ai-kit/blob/main/app-kit/tests/workflow_mock_composition.rs)
/// executes a real App with private, direct-trait Agent and StateStore mocks.
/// Its `caller_agent_struct_materializes_and_executes_without_supplied_backends`
/// test asserts the prompt, workflow result and consuming Agent shutdown. Run it
/// with `cargo test --locked -p app-kit --test workflow_mock_composition`.
/// This is an integration-tested recipe, not an imported doctest fixture; it
/// demonstrates process-local composition rather than native durability.
pub struct AgentSpec<A: AgentBackend> {
    key: String,
    revision: String,
    agent: Arc<A>,
}

/// Selects application shutdown behavior.
///
/// Drain timeouts limit observation only. Once admission is sealed, a timed-out
/// or dropped shutdown observer does not cancel the finalizer or reopen App.
/// Keep all owning runtimes driven until shutdown completes.
pub enum Shutdown {
    /// Rejects shutdown while accepted work remains.
    RejectActive,
    /// Seals admission and drains accepted work.
    Drain {
        /// Bounds this caller's observation of finalization.
        timeout: Duration,
    },
    /// Seals admission, cancels accepted work, and drains it.
    CancelAndDrain {
        /// Bounds this caller's observation of finalization.
        timeout: Duration,
    },
}

/// An application workspace handle.
///
/// A typed projection into the owning App generation. Dropping it does not delete
/// or close lower workspaces. Replacement uses a complete configuration and a
/// revision fence; successful deletion revokes this projection. Retained terminal
/// history can still be opened through its workflow after workspace deletion.
///
/// # Workspace lifecycle
///
/// Replacement and deletion use the latest observed revision as their fence.
/// This example uses real process-local storage without configuring Agents or workflows.
///
/// ```
/// use agents_kit::Agent;
/// use app_kit::{App, AppConfig, Shutdown, WorkspaceConfig};
/// use storage_kit::{StateStore, state::config::{LanceStateStoreConfig, StateStoreConfig}};
/// use std::{num::NonZeroUsize, time::Duration};
/// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
/// # runtime.block_on(async {
/// let store = StateStore::connect(
///     StateStoreConfig::lance(LanceStateStoreConfig::memory()),
/// ).await?;
/// let mut app = App::open(AppConfig::<_, Agent>::new(store, Vec::new(), Vec::new())).await?;
/// let outcome = async {
///     let root = std::env::current_dir()?;
///     let mut workspace = app.create_workspace(WorkspaceConfig {
///         name: Some("draft".into()), root: root.clone(),
///     }).await?;
///     let before = workspace.snapshot().await?;
///     let reopened = app.workspace(workspace.id().clone()).await?;
///     assert_eq!(reopened.snapshot().await?.revision, before.revision);
///     let updated = workspace.replace(before.revision, WorkspaceConfig {
///         name: Some("reviewed".into()), root,
///     }).await?;
///     assert!(updated.revision > before.revision);
///     assert_eq!(updated.config.name.as_deref(), Some("reviewed"));
///     workspace.delete(updated.revision).await?;
///     assert!(app.list_workspaces(None, NonZeroUsize::new(10).unwrap()).await?.is_empty());
///     Ok::<(), Box<dyn std::error::Error>>(())
/// }.await;
/// let cleanup = app.shutdown(Shutdown::CancelAndDrain {
///     timeout: Duration::from_secs(5),
/// }).await;
/// if let Err(error) = &cleanup { eprintln!("App shutdown: {error}"); }
/// outcome?;
/// cleanup?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct Workspace<
    CS: StateStoreBackend,
    A: AgentBackend,
    X: ActionBackend = NoActions,
    C: ConditionBackend = NoConditions,
    T: StateTyping = JsonState,
    H: LifecycleHooks = NoHooks,
    E: ChildExecutor = InlineExecutor,
> {
    runtime: workspace::WorkspaceRuntime<CS, A, X, C, T, H, E>,
}

/// A validated application workspace identity.
///
/// Parsing and deserialization require `appws_` followed by a canonical lowercase,
/// hyphenated UUIDv4. Identity equality does not establish lower-agent compatibility.
///
/// # Example
///
/// ```
/// use app_kit::WorkspaceId;
/// let id: WorkspaceId = "appws_8a7c251e-b5b8-4d9e-8f0b-123456789abc".parse()?;
/// assert_eq!(id.to_string(), "appws_8a7c251e-b5b8-4d9e-8f0b-123456789abc");
/// assert!("appws_not-a-uuid".parse::<WorkspaceId>().is_err());
/// # Ok::<(), app_kit::AppError>(())
/// ```
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WorkspaceId(String);

/// Complete caller-authored workspace configuration.
///
/// The root is an absolute, lexical UTF-8 path, 1–4,096 bytes without control
/// characters. Validation does not create directories or resolve symlinks. A present
/// name is trimmed and must be nonempty, control-free, and at most 256 UTF-8 bytes.
///
/// # Example
///
/// ```
/// use app_kit::WorkspaceConfig;
/// let config = WorkspaceConfig { name: Some("review".into()), root: std::env::current_dir()? };
/// assert!(config.root.is_absolute());
/// # Ok::<(), std::io::Error>(())
/// ```
pub struct WorkspaceConfig {
    /// Optionally names the lower workspace.
    pub name: Option<String>,
    /// Selects the absolute workspace root.
    pub root: PathBuf,
}

/// The current caller-visible workspace truth.
///
/// See [the workspace lifecycle](Workspace).
#[non_exhaustive]
pub struct WorkspaceSnapshot {
    /// Identifies the workspace.
    pub id: WorkspaceId,
    /// Fences complete replacement.
    pub revision: u64,
    /// Contains the committed configuration.
    pub config: WorkspaceConfig,
}

/// A safe caller-visible application error.
///
/// Operational messages are bounded and redact lower payloads and identities.
/// Errors supplied by explicitly registered codecs or lifecycle hooks retain
/// caller context at that opt-in boundary. Match variants (with a fallback for
/// this non-exhaustive enum), rather than parsing Display text. An error from an
/// observer does not by itself prove an accepted native operation rolled back.
#[non_exhaustive]
#[derive(Debug)]
pub enum AppError {
    /// Caller-authored input is invalid.
    InvalidInput(String),
    /// Exact scoped evidence proves a resource absent.
    NotFound(String),
    /// A durable fact, fence, or transition conflicts.
    Conflict(String),
    /// Finite capacity or an exclusive owner prevents progress.
    Busy(String),
    /// Revocation or terminal invalidation rejects new work.
    Closed(String),
    /// An application-owned deadline elapsed.
    Timeout(String),
    /// Caller behavior, a lower public operation, or a private durable record failed.
    Integration(String),
}

enum IdentitySyntax {
    Named(&'static str),
    Uuid {
        name: &'static str,
        prefix: &'static str,
    },
}

impl<
    CS: StateStoreBackend,
    A: AgentBackend,
    X: ActionBackend,
    C: ConditionBackend,
    T: StateTyping,
    H: LifecycleHooks,
    E: ChildExecutor,
> App<CS, A, X, C, T, H, E>
{
    /// Opens or reconciles one application generation.
    ///
    /// Validates bindings and retained records, claims one durable generation, and
    /// reconstructs recovery ownership before returning. A successful newer opener
    /// fences handles from the previous generation. Configuration is consumed.
    ///
    /// # Durable reopen and deployment
    ///
    /// Reopen with a fresh handle to the same caller-owned StateStore, the same
    /// compatible workflow definitions, and freshly constructed or reopened lower
    /// integrations. Never reuse a consumed Agent or infer a new logical identity
    /// from its display representation. The state-only example below needs no Agent
    /// value and demonstrates that shutdown retains history until explicit deletion.
    ///
    /// Existing App v6 records require a **cold, one-way v6-to-v7 migration**.
    /// Stop older clients, settle all their owners and take a whole-store physical
    /// backup before opening with this version. Opening performs the supported
    /// migration before claiming the new generation. Mixed-version operation,
    /// in-place downgrade, reset and corruption repair are not supported. Restore
    /// the physical backup for a rollback deployment; do not open migrated data
    /// with an older client. Unsupported epochs and corrupt current records fail
    /// rather than falling back to another decoder.
    ///
    /// After Agent ownership transfer, ordinary failure awaits consuming Agent cleanup
    /// and preserves the primary failure. Cancelling this open future during transfer
    /// does not promise graceful cleanup: reopen the durable lower products and App to
    /// reconcile their retained facts.
    ///
    /// # Errors
    ///
    /// Returns [`AppError::InvalidInput`] for invalid or conflicting construction
    /// metadata, [`AppError::Conflict`] for incompatible retained revisions or lost
    /// ownership, and [`AppError::Integration`] for unsupported durable versions,
    /// invalid retained records, or lower failures. Recovery can also report capacity,
    /// closure, or deadline errors; no live App is returned on failure.
    ///
    /// # Example
    ///
    /// ```
    /// use agents_kit::Agent;
    /// use app_kit::{App, AppConfig, Shutdown, WorkspaceConfig};
    /// use app_kit::workflow::{ExecutionOptions, RunSelector, RunStatus, WorkflowDefinition};
    /// use storage_kit::StateStore;
    /// use storage_kit::state::config::{LanceStateStoreConfig, StateStoreConfig};
    /// use std::time::Duration;
    /// let directory = std::env::temp_dir().join(format!("ai-kit-app-doc-{}", uuid::Uuid::new_v4()));
    /// std::fs::create_dir(&directory)?;
    /// let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// let result = runtime.block_on(async {
    ///     let definition_source = r#"{
    ///         "schema":"app-kit.workflow/v2","id":"counter","revision":"r1",
    ///         "state":{"count":0},"required":["count"],"reducers":{"count":"reject_concurrent"},
    ///         "entry":"increment","nodes":[{"id":"increment","step":{"kind":"state",
    ///         "mutations":[{"kind":"increment","target":"count","value":{"kind":"literal","value":1}}]}}],
    ///         "routes":{}
    ///     }"#;
    ///     let config = StateStoreConfig::lance(LanceStateStoreConfig::directory(&directory));
    ///     let store = StateStore::connect(config.clone()).await?;
    ///     let mut app = App::open(AppConfig::<_, Agent>::new(store, Vec::new(), vec![WorkflowDefinition::parse(definition_source)?])).await?;
    ///     let first = async {
    ///         let workspace = app.create_workspace(WorkspaceConfig { name: None, root: directory.clone() }).await?;
    ///         let workflow = workspace.workflow("counter".parse()?).await?;
    ///         let run = workflow.start(ExecutionOptions::default()).await?;
    ///         let terminal = run.wait().await?;
    ///         assert!(matches!(terminal.status, RunStatus::Succeeded));
    ///         Ok::<_, app_kit::AppError>((workspace.id().clone(), run.id().clone()))
    ///     }.await;
    ///     let shutdown = app.shutdown(Shutdown::CancelAndDrain { timeout: Duration::from_secs(5) }).await;
    ///     if let Err(error) = &shutdown { eprintln!("App shutdown: {error}"); }
    ///     drop(app);
    ///     let (workspace_id, run_id) = first?;
    ///     shutdown?;
    ///
    ///     let fresh_store = StateStore::connect(config).await?;
    ///     let mut reopened = App::open(AppConfig::<_, Agent>::new(fresh_store, Vec::new(), vec![WorkflowDefinition::parse(definition_source)?])).await?;
    ///     let readback = async {
    ///         let workspace = reopened.workspace(workspace_id).await?;
    ///         let workflow = workspace.workflow("counter".parse()?).await?;
    ///         let mut run = workflow.open_run(RunSelector::Latest(run_id.clone())).await?;
    ///         let terminal = run.snapshot().await?;
    ///         assert!(matches!(terminal.status, RunStatus::Succeeded));
    ///         assert_eq!(terminal.state.values()["count"], 1);
    ///         run.delete(terminal.checkpoint).await?;
    ///         assert!(matches!(workflow.open_run(RunSelector::Latest(run_id)).await,
    ///             Err(app_kit::AppError::NotFound(_))));
    ///         Ok::<(), app_kit::AppError>(())
    ///     }.await;
    ///     let shutdown = reopened.shutdown(Shutdown::CancelAndDrain { timeout: Duration::from_secs(5) }).await;
    ///     if let Err(error) = &shutdown { eprintln!("App shutdown: {error}"); }
    ///     drop(reopened);
    ///     readback?;
    ///     shutdown?;
    ///     Ok::<(), Box<dyn std::error::Error>>(())
    /// });
    /// // A shutdown timeout bounds the waiter, not necessarily the owned finalizer.
    /// // Remove the directory only after both generations demonstrably settled.
    /// if result.is_ok() {
    ///     std::fs::remove_dir_all(&directory)?;
    /// } else {
    ///     eprintln!("Retain {} for cleanup reconciliation", directory.display());
    /// }
    /// result?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub async fn open(config: AppConfig<CS, A, X, C, T, H, E>) -> Result<Self, AppError> {
        Ok(Self {
            runtime: app::AppTrace::span(|| tracing::info_span!(target: "app_kit", "app.open"))
                .observe(std::pin::pin!(app::AppRuntime::open(config)))
                .await?,
        })
    }

    /// Creates and materializes one workspace.
    ///
    /// Materializes the complete configured Agent key/revision inventory before
    /// publishing the App workspace. Durable intent precedes each lower operation;
    /// unresolved partial progress remains recoverable rather than a visible success.
    ///
    /// # Errors
    ///
    /// Returns [`AppError::InvalidInput`] for invalid configuration, [`AppError::Busy`]
    /// when admission is full, or [`AppError::Closed`] after revocation. Conflicting
    /// materialization evidence, lower/storage failures, and bounded waits report
    /// `Conflict`, `Integration`, or `Timeout` respectively.
    ///
    /// See [the workspace lifecycle](Workspace).
    pub async fn create_workspace(
        &self,
        config: WorkspaceConfig,
    ) -> Result<Workspace<CS, A, X, C, T, H, E>, AppError> {
        Ok(Workspace {
            runtime: self.runtime.create_workspace(config).await?,
        })
    }

    /// Reopens one workspace by typed identity.
    ///
    /// A retained terminal head can establish a history-only scope after coordination
    /// is deleted. That handle permits retained-run lookup, not fresh admission.
    ///
    /// # Errors
    ///
    /// Returns [`AppError::NotFound`] when neither active coordination nor readable
    /// retained history exists in this scope. Revocation, incompatible lifecycle
    /// progress, and unreadable durable evidence report `Closed`, `Conflict`, or
    /// `Integration`.
    ///
    /// See [durable workspace reopen](App::open).
    pub async fn workspace(
        &self,
        id: WorkspaceId,
    ) -> Result<Workspace<CS, A, X, C, T, H, E>, AppError> {
        Ok(Workspace {
            runtime: self.runtime.workspace(id).await?,
        })
    }

    /// Lists workspaces in canonical identity order.
    ///
    /// The cursor is exclusive and pages contain active workspaces only. Limits are
    /// 1–1,000; larger requests are rejected rather than silently clamped.
    ///
    /// # Errors
    ///
    /// Returns [`AppError::InvalidInput`] for an excessive limit, [`AppError::NotFound`]
    /// for an unknown cursor, and `Closed` or `Integration` for revoked or unreadable
    /// application state.
    ///
    /// See [the workspace lifecycle](Workspace).
    pub async fn list_workspaces(
        &self,
        after: Option<WorkspaceId>,
        limit: NonZeroUsize,
    ) -> Result<Vec<WorkspaceSnapshot>, AppError> {
        self.runtime.list_workspaces(after, limit).await
    }

    /// Finalizes this application according to `policy`.
    ///
    /// `RejectActive` leaves admission open if work remains. Drain policies seal
    /// admission; `CancelAndDrain` also requests explicit cancellation. Successful
    /// completion joins App-owned work and consumes each transferred Agent once.
    /// The timeout bounds this observer, not the continuing finalizer. Cancelling the
    /// observer or timing out never reopens admission or detaches accepted cleanup.
    ///
    /// # Errors
    ///
    /// Returns [`AppError::Busy`] when `RejectActive` encounters accepted work,
    /// [`AppError::InvalidInput`] for an invalid timeout, or [`AppError::Timeout`] when
    /// observation expires. Durable conflicts and lower cleanup failures remain
    /// `Conflict` or `Integration`; cleanup does not erase an earlier failure.
    ///
    /// See [the local workflow and error cleanup](crate#local-workflow).
    pub async fn shutdown(&mut self, policy: Shutdown) -> Result<(), AppError> {
        self.runtime.shutdown(policy).await
    }
}

impl<CS: StateStoreBackend, A: AgentBackend> AppConfig<CS, A> {
    /// Constructs configuration from a caller-owned control-plane store and agents.
    ///
    /// The store is required even for process-local operation. App preserves its
    /// concrete transaction type and never constructs lower products. Ownership
    /// transfers to App when [`App::open`] is called.
    ///
    /// See [the local workflow](crate#local-workflow).
    #[must_use]
    pub fn new(state: CS, agents: Vec<AgentSpec<A>>, workflows: Vec<WorkflowDefinition>) -> Self {
        Self {
            state,
            agents,
            workflows,
            actions: Vec::new(),
            conditions: Vec::new(),
            typing: JsonState,
            hooks: NoHooks,
            executor: InlineExecutor,
        }
    }
}

impl<
    CS: StateStoreBackend,
    A: AgentBackend,
    X: ActionBackend,
    C: ConditionBackend,
    T: StateTyping,
    H: LifecycleHooks,
    E: ChildExecutor,
> AppConfig<CS, A, X, C, T, H, E>
{
    /// Replaces the complete caller-owned action inventory before opening App.
    ///
    /// Values retain their concrete type and need not implement `Clone`. App
    /// validates their stable declarations before accepting any workflow work.
    /// Replacing an inventory drops its previous values without invoking them.
    ///
    /// See [the complete action implementation](workflow::ActionBackend).
    #[must_use]
    pub fn with_actions<N: ActionBackend>(
        self,
        actions: Vec<N>,
    ) -> AppConfig<CS, A, N, C, T, H, E> {
        AppConfig {
            state: self.state,
            agents: self.agents,
            workflows: self.workflows,
            actions,
            conditions: self.conditions,
            typing: self.typing,
            hooks: self.hooks,
            executor: self.executor,
        }
    }

    /// Replaces the complete caller-owned condition inventory before opening App.
    ///
    /// App validates stable logical keys and revisions without evaluating the
    /// predicates. Replacing an inventory drops its previous values.
    ///
    /// See [the complete condition implementation](workflow::ConditionBackend).
    #[must_use]
    pub fn with_conditions<N: ConditionBackend>(
        self,
        conditions: Vec<N>,
    ) -> AppConfig<CS, A, X, N, T, H, E> {
        AppConfig {
            state: self.state,
            agents: self.agents,
            workflows: self.workflows,
            actions: self.actions,
            conditions,
            typing: self.typing,
            hooks: self.hooks,
            executor: self.executor,
        }
    }

    /// Replaces the caller-owned workflow typing policy before opening App.
    ///
    /// The policy remains concrete and need not implement `Clone`. Its data
    /// values are local to validation or execution and need not be `Send`.
    ///
    /// See [the complete state typing implementation](workflow::StateTyping).
    #[must_use]
    pub fn with_state_typing<N: StateTyping>(self, typing: N) -> AppConfig<CS, A, X, C, N, H, E> {
        AppConfig {
            state: self.state,
            agents: self.agents,
            workflows: self.workflows,
            actions: self.actions,
            conditions: self.conditions,
            typing,
            hooks: self.hooks,
            executor: self.executor,
        }
    }

    /// Replaces the caller-owned lifecycle observer before opening App.
    ///
    /// Replacement drops the prior observer without invoking it. The new
    /// observer retains its concrete type and need not implement `Clone`.
    ///
    /// See [the complete lifecycle hook implementation](workflow::LifecycleHooks).
    #[must_use]
    pub fn with_hooks<N: LifecycleHooks>(self, hooks: N) -> AppConfig<CS, A, X, C, T, N, E> {
        AppConfig {
            state: self.state,
            agents: self.agents,
            workflows: self.workflows,
            actions: self.actions,
            conditions: self.conditions,
            typing: self.typing,
            hooks,
            executor: self.executor,
        }
    }

    /// Replaces the caller-owned admitted child executor before opening App.
    ///
    /// The executor remains concrete. Its associated execution futures are
    /// created only for admitted child work and need not implement `Send`.
    ///
    /// See [the complete child executor workflow](workflow::ChildExecutor).
    #[must_use]
    pub fn with_child_executor<N: ChildExecutor>(
        self,
        executor: N,
    ) -> AppConfig<CS, A, X, C, T, H, N> {
        AppConfig {
            state: self.state,
            agents: self.agents,
            workflows: self.workflows,
            actions: self.actions,
            conditions: self.conditions,
            typing: self.typing,
            hooks: self.hooks,
            executor,
        }
    }
}

impl<A: AgentBackend> AgentSpec<A> {
    /// Constructs one configured lower-agent entry.
    ///
    /// The key and revision are caller-owned logical binding metadata, validated by
    /// [`App::open`]. Keep the same revision only while the configuration is compatible.
    /// App never derives compatibility from the opaque lower Agent identity. A
    /// successful open takes responsibility for consuming Agent shutdown.
    ///
    /// Construction is local and does not start a service. See [caller-owned Agent
    /// composition](AgentSpec) for an executable recipe using direct trait mocks.
    #[must_use]
    pub fn new(key: String, revision: String, agent: A) -> Self {
        Self {
            key,
            revision,
            agent: Arc::new(agent),
        }
    }
}

impl<
    CS: StateStoreBackend,
    A: AgentBackend,
    X: ActionBackend,
    C: ConditionBackend,
    T: StateTyping,
    H: LifecycleHooks,
    E: ChildExecutor,
> Drop for App<CS, A, X, C, T, H, E>
{
    fn drop(&mut self) {
        self.runtime.request_drop();
    }
}

impl<
    CS: StateStoreBackend,
    A: AgentBackend,
    X: ActionBackend,
    C: ConditionBackend,
    T: StateTyping,
    H: LifecycleHooks,
    E: ChildExecutor,
> Workspace<CS, A, X, C, T, H, E>
{
    /// Returns this workspace's stable identity.
    ///
    /// See [the workspace lifecycle](Workspace).
    pub fn id(&self) -> &WorkspaceId {
        self.runtime.id()
    }

    /// Loads the current workspace snapshot.
    ///
    /// # Errors
    ///
    /// Returns `Closed` after revocation or sealing, `NotFound` for absent coordination,
    /// `Conflict` during unresolved lifecycle progress, or `Integration` for unreadable
    /// committed evidence. A history-only workspace has no configuration snapshot.
    ///
    /// See [the workspace lifecycle](Workspace).
    pub async fn snapshot(&self) -> Result<WorkspaceSnapshot, AppError> {
        self.runtime.snapshot().await
    }

    /// Atomically replaces the complete workspace configuration.
    ///
    /// This is full replacement, including the name and root. Preflight checks all
    /// lower workspaces before fan-out. A partial lower failure retains the old App
    /// revision and durable reverse compensation; preflight never reserves a revision.
    ///
    /// # Errors
    ///
    /// Returns `Conflict` for a stale revision, a nonterminal run pinned to the current
    /// revision, or partial lower fan-out (even if compensation succeeds). Invalid
    /// configuration, capacity, revocation, storage/lower failures and bounded waits
    /// report `InvalidInput`, `Busy`, `Closed`, `Integration`, or `Timeout`.
    ///
    /// See [the workspace lifecycle](Workspace).
    pub async fn replace(
        &self,
        expected_revision: u64,
        config: WorkspaceConfig,
    ) -> Result<WorkspaceSnapshot, AppError> {
        self.runtime.replace(expected_revision, config).await
    }

    /// Opens a configured workflow in this workspace.
    ///
    /// Selects the current configured definition for new work. A deleted workspace
    /// may retain a history-only workflow when exact terminal evidence still exists.
    ///
    /// # Errors
    ///
    /// Returns `NotFound` for an unavailable definition or retained scope, `Closed`
    /// for revoked admission, or `Integration` for inconsistent durable evidence.
    ///
    /// See [the local workflow](crate#local-workflow).
    pub async fn workflow(
        &self,
        id: WorkflowId,
    ) -> Result<Workflow<CS, A, X, C, T, H, E>, AppError> {
        Ok(Workflow::from_runtime(self.runtime.workflow(id).await?))
    }

    /// Deletes this workspace after proving its revision fence.
    ///
    /// Seals new admission, requests cancellation, and deletes lower workspaces only
    /// after every run is terminal with no unresolved effect. Progress is durable and
    /// resumable; terminal run history is retained until explicit run deletion.
    ///
    /// # Errors
    ///
    /// Returns `Conflict` for a stale revision or incompatible deletion intent, `Busy`
    /// while unresolved work prevents deletion, and `Closed` for revoked ownership.
    /// Invalid fences, storage/lower failures, or expired observation return
    /// `InvalidInput`, `Integration`, or `Timeout`.
    ///
    /// See [the workspace lifecycle](Workspace).
    pub async fn delete(&mut self, expected_revision: u64) -> Result<(), AppError> {
        self.runtime.delete(expected_revision).await
    }
}

impl WorkspaceId {
    pub(crate) fn generate() -> Self {
        Self(format!("appws_{}", Uuid::new_v4().hyphenated()))
    }

    pub(crate) fn as_str(&self) -> &str {
        &self.0
    }
}

impl IdentitySyntax {
    fn parse(&self, value: &str) -> Result<String, AppError> {
        match self {
            Self::Named(name) => {
                let valid = !value.is_empty()
                    && value.len() <= 128
                    && value.bytes().enumerate().all(|(index, byte)| {
                        byte.is_ascii_lowercase()
                            || byte.is_ascii_digit()
                            || (index > 0 && matches!(byte, b'_' | b'-'))
                    });
                if valid {
                    Ok(value.to_owned())
                } else {
                    Err(AppError::InvalidInput(format!(
                        "{name} must match [a-z0-9][a-z0-9_-]{{0,127}}"
                    )))
                }
            }
            Self::Uuid { name, prefix } => {
                let Some(encoded) = value.strip_prefix(prefix) else {
                    return Err(AppError::InvalidInput(format!(
                        "{name} has an invalid prefix"
                    )));
                };
                let parsed = Uuid::parse_str(encoded)
                    .map_err(|_| AppError::InvalidInput(format!("{name} is not a UUIDv4")))?;
                if parsed.get_version() != Some(Version::Random)
                    || parsed.get_variant() != Variant::RFC4122
                    || parsed.hyphenated().to_string() != encoded
                {
                    return Err(AppError::InvalidInput(format!(
                        "{name} must contain a canonical lowercase UUIDv4"
                    )));
                }
                Ok(value.to_owned())
            }
        }
    }
}

impl fmt::Display for WorkspaceId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

impl FromStr for WorkspaceId {
    type Err = AppError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        IdentitySyntax::Uuid {
            name: "WorkspaceId",
            prefix: "appws_",
        }
        .parse(value)
        .map(Self)
    }
}

impl Serialize for WorkspaceId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for WorkspaceId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        String::deserialize(deserializer)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

impl fmt::Display for AppError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidInput(message) => write!(formatter, "invalid input: {message}"),
            Self::NotFound(message) => write!(formatter, "not found: {message}"),
            Self::Conflict(message) => write!(formatter, "conflict: {message}"),
            Self::Busy(message) => write!(formatter, "busy: {message}"),
            Self::Closed(message) => write!(formatter, "closed: {message}"),
            Self::Timeout(message) => write!(formatter, "timeout: {message}"),
            Self::Integration(message) => write!(formatter, "integration: {message}"),
        }
    }
}

impl std::error::Error for AppError {}