Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

.jg Workflow Syntax Reference

Complete syntax specification for Juglans .jg workflow files.

File Structure

A .jg file consists of three sections in order:

1. Metadata      — imports, schedule, visibility
2. Node definitions  — [id]: tool(params) or [id]: "literal"
3. Edge definitions  — [a] -> [b], conditionals, switch

All sections are optional. Comments begin with # and extend to end of line.


Metadata

A .jg file can declare resource imports at the top. Each line follows key: value format. Only the fields below are accepted — any other top-level key produces a parse error.

FieldTypeDescription
promptsstring listPrompt file glob patterns (loaded as .jgx)
toolsstring listTool definition file patterns (.json schemas)
pythonstring listPython module imports (loaded by the Python worker)
flowsobject mapSubworkflow imports: { alias: "path.jg" } — see Flow Imports
libslist or mapLibrary imports (function-only files) — see Lib Imports

Package-level fields like slug / name / version / description / author / entry / exit / schedule / is_public belong in the .jgflow manifest (used by the package registry), not in .jg workflow files. Entry nodes are inferred automatically from the graph topology (in-degree 0 nodes).

Metadata Examples

Minimal — no metadata at all:

[start]: notify(status="hello")

With imports:

prompts: ["./prompts/*.jgx"]

[start]: notify(status="begin")
[done]: notify(status="end")
[start] -> [done]

Multiple terminal nodes:

[start]: notify(status="begin")
[success]: notify(status="ok")
[failure]: notify(status="fail")

[start] -> [success]
[start] on error -> [failure]

Resource Imports

prompts: ["./prompts/*.jgx", "./shared/*.jgx"]

[step]: notify(status="imported")

Flow Imports

flows: {
  auth: "./auth.jg"
  trading: "./trading.jg"
}

[start]: notify(status="routing")
[done]: notify(status="complete")

[start] -> [done]

Lib Imports

Map form (explicit namespace):

libs: { db: "./libs/sqlite.jg" }

[step1]: db.read(table="users")

List form (auto namespace from filename stem):

libs: ["./libs/utils.jg"]

[step1]: utils.helper(x="test")

Python Module Imports

python: ["pandas", "sklearn.ensemble", "./utils.py"]

[load]: notify(status="python ready")

Node Definitions

Basic Syntax

[node_id]: tool_name(param1=value1, param2=value2)

Node IDs use letters, digits, and underscores. They must be wrapped in [...].

Tool Call Node

[greet]: notify(status="Hello, world!")

With multiple parameters:

[ask]: chat(
  agent="assistant",
  message="What is Rust?",
  format="json"
)

Variable References in Parameters

[a]: chat(message=input.question)
[b]: notify(status=output)
[c]: data = results
[a] -> [b] -> [c]

String Literal Node

[greeting]: "Hello, World!"

JSON Literal Node

[config]: {
  "model": "gpt-4o-mini",
  "temperature": 0.7
}

Assignment Syntax

Assignment syntax sets context variables directly:

[init]: count = 0, name = "Alice"

Multiple assignments separated by commas:

[setup]: status = "ready", retries = 3, items = []

Note: a node can hold multiple assignments or a single tool call, not both. To do both, split into two nodes.

Yield Node

yield <expr> emits a value to the caller without terminating the workflow. Streaming UIs use this to surface intermediate results while later steps keep running:

[progress]: yield "stage 1 complete"
[work2]:    fetch(url=input.url)
[progress2]: yield "stage 2 complete"

Yielded values arrive as SSE events on the web path and as callback invocations on embedded paths.

Decorators

A @fn(args) annotation placed immediately before a node attaches metadata that a decorator macro expands at compile time. Decorators stack — the topmost is applied first:

@get("/api/hello")
[hello]: response(body="hi")

@post("/api/chat")
@auth(required=true)
[chat_endpoint]: chat(message=input.text)

The two most common decorator families today:

FamilyUsed byExample
HTTP routingserve() / the web server@get("/path"), @post("/path")
Tool schema attachmentCustom builtins & adapters@tool("search", ...)

Decorators that aren’t recognized by any expansion simply pass through — they’re preserved as node-level metadata for later tooling.


Edge Definitions

Unconditional Edge

[a]: notify(status="first")
[b]: notify(status="second")

[a] -> [b]

Chain Edge

[a]: notify(status="1")
[b]: notify(status="2")
[c]: notify(status="3")

[a] -> [b] -> [c]

Conditional Edge

[check]: score = 85
[pass]: notify(status="passed")
[fail]: notify(status="failed")

[check] if score >= 60 -> [pass]
[check] if score < 60 -> [fail]

Supported comparison operators: ==, !=, >, <, >=, <=.

Boolean condition:

[gate]: ready = true
[go]: notify(status="go")
[wait]: notify(status="wait")

[gate] if ready -> [go]
[gate] if !ready -> [wait]

Default Path (Unconditional Fallback)

When no conditional edge matches, an unconditional edge serves as the default:

[router]: notify(status="routing")
[path_a]: notify(status="a")
[path_b]: notify(status="b")
[default_path]: notify(status="default")

[router] if x == "a" -> [path_a]
[router] if x == "b" -> [path_b]
[router] -> [default_path]

Error Handling Edge

[risky]: notify(status="try something risky")
[ok]: notify(status="success")
[err]: notify(status="error occurred")

[risky] -> [ok]
[risky] on error -> [err]

The error variable is set in the error handler node with two fields: node (the failing node ID) and message (the error text).

{"node": "risky", "message": "connection refused"}

Switch Routing

Execute exactly one matching branch:

[classify]: intent = "question"
[answer]: notify(status="answering")
[execute]: notify(status="executing")
[fallback]: notify(status="fallback")

[classify] -> switch intent {
    "question": [answer]
    "task": [execute]
    default: [fallback]
}

Switch with numeric cases:

[score]: level = 2
[low]: notify(status="low")
[mid]: notify(status="mid")
[high]: notify(status="high")

[score] -> switch level {
    1: [low]
    2: [mid]
    default: [high]
}

switch vs if edges:

Featureif edgesswitch
Multiple branches can fireYesNo (exactly one)
SyntaxMultiple linesSingle block
DefaultUnconditional edgedefault: keyword

ok: / err: cases — In addition to default:, switch accepts two special cases that work with the error edge system:

[parse]:       fetch(url=input.url)
[continue]:    notify(status="ok")
[retry_once]:  notify(status="retrying")
[fallback]:    notify(status="fallback")

[parse] -> switch {
    ok:           [continue]      # took the happy path
    err:          [retry_once]    # any on-error propagation
    err "timeout": [fallback]      # typed error (matches on error.kind / error.code)
}

Use ok: / err: when the branch decision is “did this node succeed?” rather than “what value did it produce?”. err "<type>": narrows to a specific error kind; other error types still fall through to plain err:.

Cross-Workflow Edges (with flows)

flows: {
  auth: "./auth.jg"
}

[start]: notify(status="begin")
[done]: notify(status="end")

[start] if need_auth -> [auth.start]
[auth.done] -> [done]
[start] -> [done]

Namespaced node references use [alias.node_id] format.

@/ Path Alias for Imports

When [paths].base is set in juglans.toml (e.g. base = "."), @/ resolves to {project_root}/{base}/ in any flows: or libs: import path:

# juglans.toml
[paths]
base = "."
# any workflow under the project root
flows: { auth: "@/shared/auth.jg" }
libs:  ["@/shared/helpers.jg"]

[start]: notify(status="ready")

This keeps imports stable regardless of how deeply nested the importing file is.


Function Definitions

Functions are reusable parameterized blocks. They are NOT added to the main DAG.

Single-Step Function

[greet(name)]: notify(status="Hello " + name)

[step1]: greet(name="world")

Multi-Step Function (Block Body)

[pipeline(msg)]: {
  notify(status="start: " + msg)
  notify(status="end: " + msg)
}

[run]: pipeline(msg="test")

Steps run sequentially; the function returns whatever is bound to output after the final step (either by an explicit output = ... assignment or as the result of the last task call). For conditional value selection, route between functions at the DAG level using if edges or switch. To bubble an error out of a function early, use return err { kind: "...", message: "..." }:

[validate(price)]: {
  assert price > 0
  output = "ok: " + str(price)
}

[reject(price)]: {
  return err { kind: "validation", message: "price must be positive" }
}

[run]: validate(price=10)

Multiple Parameters

[deploy(env, tag)]: {
  notify(status="deploying " + tag + " to " + env)
  notify(status="done deploying " + tag)
}

[staging]: deploy(env="staging", tag="v1.0")
[prod]: deploy(env="production", tag="v1.0")

[staging] -> [prod]

Function with assign_call

[check_health(url)]: {
  result = fetch_url(url=url)
  notify(status="checked " + url)
}

[step]: check_health(url="https://example.com")

Function with assert

[validate(x)]: {
  assert x != ""
  notify(status="valid: " + x)
}

[step]: validate(x="hello")

Loop Constructs

foreach

Iterate over a collection:

[init]: results = []

[loop]: foreach(item in input.items) {
  [handle]: notify(status=item)
  [save]: results = append(results, output)
  [handle] -> [save]
}

[done]: notify(status="finished")

[init] -> [loop] -> [done]

foreach parallel

Run iterations concurrently:

[batch]: foreach parallel(item in input.urls) {
  [fetch]: fetch_url(url=item)
}

while

Condition-based loop:

[init]: count = 0

[loop]: while(count < 5) {
  [inc]: count = count + 1
  [log]: notify(status="count=" + count)
  [inc] -> [log]
}

[done]: notify(status="loop done")

[init] -> [loop] -> [done]

Nested Loop Body

Loop bodies contain their own node definitions and edge definitions:

[start]: total = 0

[process]: foreach(item in input.data) {
  [step_a]: notify(status="processing " + item.id)
  [step_b]: total = total + 1
  [step_a] -> [step_b]
}

[end]: notify(status="total: " + total)

[start] -> [process] -> [end]

Struct Definitions

Structs define typed data containers with fields and optional defaults:

[User]: {
  name: str
  email: str
  age: int = 0
  role: str = "user"
}

[req]: new User(name="Alice", email="[email protected]")

Field Syntax

field_name: type_hint [= default_value]

Supported types: str, int, float, bool, list[T], dict[K, V], T? (optional). Class names are also valid types.

Instantiation

[u]: new User(name="Alice", email="[email protected]", age=30)

Fields with defaults can be omitted — they use their default value.


impl Blocks

impl blocks group methods and associated functions for a struct, similar to Rust:

[Counter]: {
  value: int = 0
  step: int = 1
}

impl Counter {
  [get(self)]: output = self.value
  [describe(self)]: output = "Counter(" + str(self.value) + ")"
  [defaults()]: output = "Counter defaults: value=0, step=1"
}

[c]: new Counter(value=10)
[val]: c.get()
[c] -> [val]

Instance Methods

Methods with self as the first parameter operate on an instance:

[c2]: new Counter(value=5, step=2)
[desc]: c2.describe()
[c2] -> [desc]

Inside a method body, self.field_name accesses instance fields.

Associated Functions

Methods without self are associated functions (static methods), called via Type.function():

[info]: Counter.defaults()

Standalone Method Syntax

Methods can also be defined outside impl blocks (backward-compatible):

[User]: {
  name: str
  email: str
}

[User.validate(self)]: valid = self.name != ""

[u]: new User(name="Alice", email="[email protected]")
[v]: u.validate()
[u] -> [v]

This is equivalent to defining validate inside impl User { ... }.


Trait Definitions

Traits define behavior contracts (interfaces) without inheritance:

trait Displayable {
  [format(self)]:
  [label(self)]: output = "[display] " + str(self.format())
}

[User]: {
  name: str
  email: str
}

impl Displayable for User {
  [format(self)]: output = self.name + " <" + self.email + ">"
}

[u]: new User(name="Alice", email="[email protected]")
[show]: u.format()
[u] -> [show]
  • Methods ending with : followed by a newline are required — implementing types must provide them.
  • Methods with a body are default implementations — inherited if not overridden.

impl Trait for Type

The compiler validates that all required methods are provided. Default methods (like label above) are automatically inherited.

Trait in Libraries

Traits and impl blocks can be defined in library files and imported via libs:. Trait names are namespace-prefixed like functions:

trait Renderable {
  [render(self)]:
}

[MyType]: {
  value: str = "hello"
}

impl Renderable for MyType {
  [render(self)]: output = self.value
}

[m]: new MyType(value="world")
[r]: m.render()
[m] -> [r]

Validator Diagnostics

juglans check reports diagnostics with stable codes. Errors fail the check; warnings are only shown with --all.

CodeSeverityMessage
W001WarningNo entry node specified; using first node as entry point
W002WarningNode <id> is not reachable from entry node
W003WarningNo terminal nodes found (all nodes have outgoing edges)
W004WarningUnknown tool <name>
W005Warningchat() should have agent or system_prompt parameter
W006–W014WarningVarious edge / parameter / on-tool / on-error refinements
W022WarningReserved variable name used as node id
E001ErrorEntry node <id> does not exist
E002ErrorCycle detected involving node <id>. Workflows must be acyclic (DAG).
E004ErrorWorkflow contains no nodes
E007Errorchat() requires message parameter
E008Errorp() requires slug or file parameter
E009Errormemory_search() requires query parameter
E010Errorhistory() requires chat_id parameter
E011–E021ErrorOther required-parameter / unknown-node-reference / type-validation errors

The full set lives in src/core/validator.rs (add_error / add_warning calls). Errors fail juglans check; warnings only show with --all.

Note: a top-level agents: declaration at the workflow level is silently parsed and discarded — agents are defined as inline JSON map nodes ([my_agent]: { "model": "...", ... }) and referenced by node id, not via a top-level list.


Comments

Line comments start with #:

# This is a comment

# First node
[start]: notify(status="hello")

# Another comment
[end]: notify(status="bye")

[start] -> [end]  # inline comments are also allowed

Variable System

VariableDescriptionExample
inputCLI/API input datainput.message, input.items
outputPrevious node outputoutput, output.field
Context varsWorkflow context (via assignment syntax)count, results
replyAgent reply metadatareply.output, reply.status
errorError info (in error handlers)error.node, error.message

Variables use dot notation for nested access: output.data.items[0].name.


Complete Example

prompts: ["./prompts/*.jgx"]

# Agent definitions
[classifier]: {
  "model": "gpt-4o-mini",
  "temperature": 0.0,
  "system_prompt": "Classify user intent as question, task, or chat. Return JSON."
}

[expert]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a knowledgeable expert."
}

[assistant]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a friendly assistant."
}

# Classify user intent
[classify]: chat(agent=classifier, message=input.query, format="json")

# Handler branches
[handle_question]: chat(agent=expert, message=input.query)
[handle_task]: chat(agent=expert, message=input.query)
[handle_chat]: chat(agent=assistant, message=input.query)

# Final output
[done]: notify(status="processed")

# Routing logic
[classifier] -> [classify]
[expert] -> [handle_question]
[assistant] -> [handle_chat]

[classify] -> switch output.intent {
    "question": [handle_question]
    "task": [handle_task]
    default: [handle_chat]
}

[handle_question] -> [done]
[handle_task] -> [done]
[handle_chat] -> [done]