multicast-codemode 1.0.0

Portable durable Code Mode runtime for multicast tools
Documentation
//! Model-facing contracts for the shared callable workflow API.
use crate::{DescribeOutput, SearchResult};

pub(crate) const OPERATIONS: &[(&str, &str, &str)] = &[
    (
        "define",
        "Create a portable immutable workflow without running it.",
        "define<I,O>(source: string | WorkflowSource<I,O>, schemas?: WorkflowSchemas, bindings?: Record<string,unknown>): Promise<WorkflowHandle<I,O>>",
    ),
    (
        "bundle",
        "Seal mutually recursive definitions; the fourth source argument contains peer handles.",
        "bundle(definitions: Record<string,WorkflowDefinition>): Promise<Record<string,WorkflowHandle>>",
    ),
    (
        "resolve",
        "Pin a publication's current immutable version, optionally checking a version.",
        "resolve<I=unknown,O=unknown>(name:string, version?:string): Promise<WorkflowHandle<I,O>>",
    ),
    (
        "inspect",
        "Read a handle's input, output, version, and generated TypeScript contract.",
        "inspect(handle:WorkflowHandle | WorkflowReference): Promise<WorkflowContract>",
    ),
    (
        "bind",
        "Bind explicit object input fields; callers cannot override them.",
        "bind<I,O>(handle:WorkflowHandle<I,O>, values:Partial<I>): Promise<WorkflowHandle<Partial<I>,O>>",
    ),
    (
        "pipe",
        "Compose sequential child calls; reject proven schema incompatibility and report unknown edges.",
        "pipe<I=unknown,O=unknown>(handles:WorkflowHandle<any,any>[]): Promise<WorkflowHandle<I,O>>",
    ),
    (
        "start",
        "Admit an owned child without waiting for its result.",
        "start<I,O>(handle:WorkflowHandle<I,O>, input:I): Promise<WorkflowRun<O>>",
    ),
    (
        "map",
        "Run ordered inputs in bounded parallel batches; failures cancel owned siblings.",
        "map<I,O>(handle:WorkflowHandle<I,O>, inputs:I[], concurrency?:number): Promise<O[]>",
    ),
    (
        "settle",
        "Wait for every run and return ordered success or failure outcomes.",
        "settle<O>(runs:WorkflowRun<O>[]): Promise<({status:'fulfilled',value:O}|{status:'rejected',reason:string})[]>",
    ),
    (
        "scope",
        "Join owned children and durably release temporary definitions on exit.",
        "scope<T>(body:(scoped:WorkflowAPI)=>Promise<T>): Promise<T>",
    ),
    (
        "publish",
        "Atomically publish a name and operation receipt; null requires an absent name.",
        "publish(handle:WorkflowHandle<any,any>, name:string, expectedVersion?:string|null): Promise<{name:string,version:string,handle:WorkflowReference}>",
    ),
    (
        "delete",
        "Remove only a matching publication name; pinned runs and history remain.",
        "delete(name:string, expectedVersion:string): Promise<boolean>",
    ),
    (
        "release",
        "Release this execution's temporary ownership; active children and publications retain their dependencies.",
        "release(handle:WorkflowHandle<any,any>): Promise<void>",
    ),
    (
        "hydrate",
        "Convert validated data references back to callable facades inside this store.",
        "hydrate<T=unknown>(value:unknown): T",
    ),
];

pub(crate) fn types() -> String {
    let methods = OPERATIONS
        .iter()
        .map(|(_, description, signature)| format!("  /** {description} */\n  {signature};"))
        .collect::<Vec<_>>()
        .join("\n");
    format!(
        r#"type WorkflowSchema = boolean | Record<string,unknown>;
type WorkflowSchemas = {{input?:WorkflowSchema,output?:WorkflowSchema}};
type WorkflowReference = {{__workflow_ref:{{store:string,version:string,member:string}}}};
type WorkflowRun<O=unknown> = {{readonly __workflow_run:{{store:string,id:string}},result():Promise<O>}};
type WorkflowHandle<I=unknown,O=unknown> = WorkflowReference & {{(input:I):Promise<O>;start(input:I):Promise<WorkflowRun<O>>;readonly compatibility?:('compatible'|'unknown')[]}};
type WorkflowSource<I,O> = (input:I,bindings:any,self:WorkflowHandle<I,O>,peers:Record<string,WorkflowHandle<any,any>>)=>Promise<O>;
type WorkflowDefinition = WorkflowSchemas & {{source:string,bindings?:Record<string,unknown>}};
type WorkflowContract = {{reference:WorkflowReference,input:WorkflowSchema,output:WorkflowSchema,types:string}};
interface WorkflowAPI {{
{methods}
}}
declare namespace codemode {{const workflows:WorkflowAPI;}}
// Handles confer no authority. Calls can durably pause for child approval; inspect child IDs before approving.
"#
    )
}
pub(crate) fn description(target: &str) -> Option<DescribeOutput> {
    if target == "codemode.workflows"
        || OPERATIONS
            .iter()
            .any(|(name, _, _)| target == format!("codemode.workflows.{name}"))
    {
        Some(DescribeOutput {path:target.into(),description:Some("Durable callable workflow composition with shared host budgets and explicit bindings".into()),requires_approval:false,types:types(),kind:"workflow-api".into()})
    } else {
        None
    }
}
pub(crate) fn matches(query: &str) -> Vec<SearchResult> {
    let tokens: Vec<_> = query.split_whitespace().map(str::to_lowercase).collect();
    if tokens.is_empty() {
        return Vec::new();
    }
    OPERATIONS
        .iter()
        .filter_map(|(name, description, _)| {
            let path = format!("codemode.workflows.{name}");
            let haystack = format!("{path} {description}").to_lowercase();
            if !tokens.iter().all(|token| haystack.contains(token)) {
                return None;
            }
            Some(SearchResult {
                path,
                connector: "codemode.workflows".into(),
                method: (*name).into(),
                description: Some((*description).into()),
                types: types(),
                requires_approval: false,
                kind: "workflow-api".into(),
                score: 100,
            })
        })
        .collect()
}