3 Commits

Author SHA1 Message Date
e736a27b59 Feat v0.9.8 conditional routing SDK primitive
All checks were successful
CI/CD / detect-changes (pull_request) Successful in 4s
CI/CD / test-frontend (pull_request) Has been skipped
CI/CD / e2e-smoke (pull_request) Has been skipped
CI/CD / test-runners (pull_request) Has been skipped
CI/CD / test-go-pg (pull_request) Successful in 2m55s
CI/CD / test-sqlite (pull_request) Successful in 3m17s
CI/CD / build-and-deploy (pull_request) Successful in 1m5s
Promote workflow branch-rule evaluation to a generic Starlark
routing.evaluate(rules, data) module available to all extensions.
10 operators, first-match-wins, no permission gate. 8 new tests.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 19:17:03 +00:00
01f2ac5bb7 Chore roadmap v013x additions
All checks were successful
CI/CD / detect-changes (pull_request) Successful in 3s
CI/CD / test-frontend (pull_request) Has been skipped
CI/CD / test-runners (pull_request) Has been skipped
CI/CD / e2e-smoke (pull_request) Has been skipped
CI/CD / test-go-pg (pull_request) Successful in 2m49s
CI/CD / test-sqlite (pull_request) Successful in 3m4s
CI/CD / build-and-deploy (pull_request) Successful in 46s
Slot three new versions into v0.13.x series:
- v0.13.0 Custom Public Root Surface (unblocks everything)
- v0.13.6 Package Registry Extension (after file-share)
- v0.13.10 armature.run Deployment (dogfood gate)

Existing versions renumbered accordingly (v0.13.0-8 → v0.13.1-9,
quality gate → v0.13.11). Design decisions log updated.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 18:25:45 +00:00
e4bec9c18c Feat v0.9.7 workflow starlark write ops
All checks were successful
CI/CD / detect-changes (pull_request) Successful in 3s
CI/CD / test-frontend (pull_request) Has been skipped
CI/CD / test-runners (pull_request) Has been skipped
CI/CD / e2e-smoke (pull_request) Has been skipped
CI/CD / test-go-pg (pull_request) Successful in 2m44s
CI/CD / test-sqlite (pull_request) Successful in 3m4s
CI/CD / build-and-deploy (pull_request) Successful in 1m23s
Add workflow.start(), workflow.advance(), workflow.cancel(), and
workflow.submit_signoff() to the Starlark workflow module. Extract
WorkflowEngine interface in sandbox package to break the circular
import between workflow and sandbox packages.

- WorkflowEngine interface (Start/Advance/Cancel/SubmitSignoff)
- instanceToDict/signoffToDict/dictToJSON shared helpers
- Runner.SetWorkflowEngine setter + main.go wiring
- 6 new unit tests with mock engine

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 18:20:03 +00:00
10 changed files with 912 additions and 63 deletions

View File

@@ -2,6 +2,58 @@
All notable changes to Armature are documented here.
## v0.9.8 — Conditional Routing → SDK Primitive
Promotes the workflow branch-rule engine to a generic Starlark SDK
module available to all extensions — no permission required.
**New Starlark module: `routing`**
- `routing.evaluate(rules, data)` — evaluates an ordered list of
condition rules against a data dict; returns the first matching
rule's `target` string, or `None` if no rule matches
- 10 operators: `exists`, `not_exists`, `eq`, `neq`, `gt`, `lt`,
`gte`, `lte`, `in`, `contains`
- First-match-wins semantics
- Domain-agnostic: uses `target` (not `target_stage`) so any
extension can use it for feature flags, content routing, approval
logic, etc.
- Always available — pure computation, no I/O, no permission gate
**Tests:** 8 new unit tests covering all operators, type coercion,
first-match-wins, empty/missing/bad input
## v0.9.7 — Full Read/Write Workflow Starlark Module
Extensions with `workflow.access` permission can now start, advance,
cancel, and signoff workflow instances directly from Starlark scripts.
**WorkflowEngine interface**
- Defined in `sandbox` package to break the `workflow ↔ sandbox` circular
import (follows `NotificationSender` / `ConnectionResolver` pattern)
- 4 methods: `Start`, `Advance`, `Cancel`, `SubmitSignoff`
- `workflow.Engine` satisfies the interface implicitly — zero changes to
the engine package
**New Starlark builtins**
- `workflow.start(workflow_id, data={})` → instance dict
- `workflow.advance(instance_id, data={})` → instance dict
- `workflow.cancel(instance_id)` → None
- `workflow.submit_signoff(instance_id, decision, comment="")` → signoff dict
- All write ops require authenticated user context (`RunContext.UserID`)
- Graceful errors when engine or user context unavailable
**Refactors**
- `instanceToDict` helper extracted — shared by `get_instance`, `start`,
`advance`
- `signoffToDict` helper for signoff return values
- `dictToJSON` helper for Starlark dict → `json.RawMessage` conversion
**Tests:** 6 new unit tests (mock engine, happy path + error guards)
## v0.9.6 — Deprecate stage_type, Collapse stage_mode
Simplifies the workflow stage classification model by removing

View File

@@ -129,16 +129,21 @@ Manifest `form_template` accepted at package level. 16 new tests.
"review" mapped to "form" on input; review surface removed (~110 lines).
Migration 018. 4 package manifests updated.
**v0.9.7 — Full Read/Write Workflow Starlark Module**
**v0.9.7 — Full Read/Write Workflow Starlark Module** *(completed)*
Add `workflow.start()`, `workflow.advance()`, `workflow.cancel()`,
`workflow.submit_signoff()` to the Starlark module. Extract engine
interface to break circular import.
`WorkflowEngine` interface extracted in sandbox package to break
circular import. Four write builtins added: `workflow.start()`,
`workflow.advance()`, `workflow.cancel()`, `workflow.submit_signoff()`.
`instanceToDict` and `signoffToDict` helpers shared by read+write paths.
6 new tests.
**v0.9.8 — Conditional Routing → SDK Primitive**
**v0.9.8 — Conditional Routing → SDK Primitive** *(completed)*
Expose `routing.evaluate(rules, data)` as a Starlark SDK function.
Branch rules become a reusable decision engine for any extension.
`routing.evaluate(rules, data)` Starlark builtin — a generic decision
engine reusable by any extension. 10 operators (exists, not_exists, eq,
neq, gt, lt, gte, lte, in, contains), first-match-wins, returns target
string or None. Always available (pure computation, no permission).
8 new tests.
**v0.9.9 — Surface Access via Roles**
@@ -213,23 +218,28 @@ Design doc: `docs/DESIGN-chat-v012x.md`.
### v0.13.x — Reference Libraries + Extensions
Core libraries and remaining extensions. `llm-bridge` is the key
delivery — extends both notes and chat through composability primitives,
and introduces the **tool meta-tool** pattern: `sw.actions.list()` becomes
the LLM tool registry, so installing an extension = granting AI a new
capability. Zero configuration.
Custom public root surface unblocks everything — anonymous visitors,
landing pages, and the package registry. `llm-bridge` is the key
library delivery — extends both notes and chat through composability
primitives, and introduces the **tool meta-tool** pattern:
`sw.actions.list()` becomes the LLM tool registry, so installing an
extension = granting AI a new capability. Zero configuration.
`armature.run` deployment is the dogfood gate at the end of the series.
| Version | Title |
|---------|-------|
| v0.13.0 | `vector-store` Library |
| v0.13.1 | `llm-bridge` Core Library |
| v0.13.2 | `llm-bridge` → Chat: Multi-Persona Context + Tool Meta-Tool |
| v0.13.3 | `llm-bridge`Notes: AI Toolbar Actions |
| v0.13.4 | `file-share` Extension |
| v0.13.5 | `code-workspace` Extension |
| v0.13.6 | `image-gen` + `image-edit` Extensions |
| v0.13.7 | Tool Meta-Tool Hardening + Scoping |
| v0.13.8 | Integration Quality Gate |
| v0.13.0 | Custom Public Root Surface |
| v0.13.1 | `vector-store` Library |
| v0.13.2 | `llm-bridge` Core Library |
| v0.13.3 | `llm-bridge`Chat: Multi-Persona Context + Tool Meta-Tool |
| v0.13.4 | `llm-bridge` → Notes: AI Toolbar Actions |
| v0.13.5 | `file-share` Extension |
| v0.13.6 | Package Registry Extension |
| v0.13.7 | `code-workspace` Extension |
| v0.13.8 | `image-gen` + `image-edit` Extensions |
| v0.13.9 | Tool Meta-Tool Hardening + Scoping |
| v0.13.10 | `armature.run` Deployment |
| v0.13.11 | Integration Quality Gate |
---
@@ -351,6 +361,9 @@ These are candidates, not commitments. Each requires a design doc.
| Layered prompt architecture (6 layers) | Admin safety not overridable. Clear separation: platform → space → character → context → tools → user. |
| Personas in llm-bridge, not chat | Chat sees AI as just another participant_type. Persona identity is llm-bridge's concern. |
| llm-bridge after notes + chat (v0.13.x) | Proves the composability hooks work without being designed for a specific consumer. |
| Custom public root first in v0.13.x | Unblocks registry, landing page, and armature.run. Small kernel change, high leverage. |
| Package registry as reference extension | Proves public surfaces work. Needs files module for .pkg storage. Self-referential: Armature's registry runs on Armature. |
| armature.run as dogfood gate | If armature.run can't run on Armature, the platform isn't ready. Issues feed into quality gate fixes. |
| Sidecar connect-inward | No K8s RBAC, no service mesh, no DNS discovery. Works on any deployment target. |
| Sidecar HTTP/JSON, not gRPC | KISS. 4-endpoint contract. Every language has HTTP. |
| User sidecars in v0.14.5 | Prove instance contract first, extend to users with same mechanism. |

View File

@@ -1 +1 @@
0.9.6
0.9.8

View File

@@ -84,6 +84,24 @@ Returns `True` if the user has the permission, `False` otherwise (including
when the user is not found). Resolves the user's groups and merges granted
permissions — works for both kernel and extension-declared permissions.
### routing
Generic rule-based decision engine. Evaluates an ordered list of conditions
against a data dict, returning the first matching rule's target string.
```python
result = routing.evaluate([
{"field": "priority", "op": "eq", "value": "critical", "target": "escalation"},
{"field": "amount", "op": "gt", "value": 10000, "target": "manager_review"},
{"field": "region", "op": "in", "value": ["EU", "UK"], "target": "gdpr_flow"},
], stage_data)
# Returns "escalation", "manager_review", "gdpr_flow", or None
```
Each rule is a dict with `field`, `op`, `value`, and `target`. Operators:
`exists`, `not_exists`, `eq`, `neq`, `gt`, `lt`, `gte`, `lte`, `in`,
`contains`. First-match-wins; returns `None` if no rule matches.
## Permission-gated modules
These modules are only available if the package has the corresponding

View File

@@ -451,6 +451,7 @@ func main() {
// ── Workflow Engine (shared by public + protected routes) ──
wfEngine := workflow.NewEngine(stores, bus, starlarkRunner)
starlarkRunner.SetWorkflowEngine(wfEngine)
// ── Public Workflow Entry ─────
publicWfH := handlers.NewWorkflowPublicHandler(wfEngine, stores)

View File

@@ -0,0 +1,190 @@
package sandbox
// routing_module.go
//
// Starlark routing module — a generic rule-based decision engine.
// Always available (pure computation, no I/O).
//
// Starlark API:
// result = routing.evaluate(rules, data)
// # result → "target_string" or None
import (
"fmt"
"strings"
"go.starlark.net/starlark"
"go.starlark.net/starlarkstruct"
)
// BuildRoutingModule creates the "routing" Starlark module.
// No permission required — pure computation.
func BuildRoutingModule() *starlarkstruct.Module {
return MakeModule("routing", starlark.StringDict{
"evaluate": starlark.NewBuiltin("routing.evaluate", routingEvaluateBuiltin()),
})
}
// routingRule is the generic equivalent of workflow.Condition.
// Uses "target" instead of "target_stage" to be domain-agnostic.
type routingRule struct {
Field string
Op string
Value any
Target string
}
func routingEvaluateBuiltin() func(*starlark.Thread, *starlark.Builtin, starlark.Tuple, []starlark.Tuple) (starlark.Value, error) {
return func(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var rulesVal, dataVal starlark.Value
if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 2, &rulesVal, &dataVal); err != nil {
return nil, err
}
// Convert rules list → []routingRule
rulesList, ok := rulesVal.(*starlark.List)
if !ok {
return nil, fmt.Errorf("routing.evaluate: rules must be a list, got %s", rulesVal.Type())
}
rules := make([]routingRule, rulesList.Len())
for i := 0; i < rulesList.Len(); i++ {
ruleDict, ok := rulesList.Index(i).(*starlark.Dict)
if !ok {
return nil, fmt.Errorf("routing.evaluate: rules[%d] must be a dict, got %s", i, rulesList.Index(i).Type())
}
m := DictToMap(ruleDict)
field, _ := m["field"].(string)
op, _ := m["op"].(string)
target, _ := m["target"].(string)
if field == "" || op == "" || target == "" {
return nil, fmt.Errorf("routing.evaluate: rules[%d] must have field, op, and target", i)
}
rules[i] = routingRule{
Field: field,
Op: op,
Value: m["value"],
Target: target,
}
}
// Convert data dict → Go map
dataDict, ok := dataVal.(*starlark.Dict)
if !ok {
return nil, fmt.Errorf("routing.evaluate: data must be a dict, got %s", dataVal.Type())
}
data := DictToMap(dataDict)
// Evaluate rules — first match wins
for _, rule := range rules {
if evaluateRoutingCondition(rule, data) {
return starlark.String(rule.Target), nil
}
}
return starlark.None, nil
}
}
// ── Evaluation helpers (mirrored from workflow/routing.go) ─────────
//
// These are pure functions copied from the workflow package to avoid
// a sandbox → workflow import cycle. The workflow package continues
// using its own copy for ResolveNextStage.
// evaluateRoutingCondition checks if a single rule matches against data.
func evaluateRoutingCondition(rule routingRule, data map[string]any) bool {
val, exists := data[rule.Field]
switch rule.Op {
case "exists":
return exists
case "not_exists":
return !exists
}
if !exists {
return false
}
switch rule.Op {
case "eq":
return routingCompareEq(val, rule.Value)
case "neq":
return !routingCompareEq(val, rule.Value)
case "gt":
return routingCompareNum(val, rule.Value) > 0
case "lt":
return routingCompareNum(val, rule.Value) < 0
case "gte":
return routingCompareNum(val, rule.Value) >= 0
case "lte":
return routingCompareNum(val, rule.Value) <= 0
case "in":
return routingCompareIn(val, rule.Value)
case "contains":
return routingCompareContains(val, rule.Value)
default:
return false
}
}
func routingCompareEq(a, b any) bool {
return fmt.Sprintf("%v", a) == fmt.Sprintf("%v", b)
}
func routingCompareNum(a, b any) int {
af := routingToFloat(a)
bf := routingToFloat(b)
if af == nil || bf == nil {
return 0
}
switch {
case *af < *bf:
return -1
case *af > *bf:
return 1
default:
return 0
}
}
func routingToFloat(v any) *float64 {
switch n := v.(type) {
case float64:
return &n
case int:
f := float64(n)
return &f
case int64:
f := float64(n)
return &f
case string:
var f float64
if _, err := fmt.Sscanf(n, "%f", &f); err == nil {
return &f
}
}
return nil
}
func routingCompareIn(val, list any) bool {
arr, ok := list.([]any)
if !ok {
return false
}
vs := fmt.Sprintf("%v", val)
for _, item := range arr {
if fmt.Sprintf("%v", item) == vs {
return true
}
}
return false
}
func routingCompareContains(val, target any) bool {
s := fmt.Sprintf("%v", val)
t := fmt.Sprintf("%v", target)
return strings.Contains(s, t)
}

View File

@@ -0,0 +1,162 @@
package sandbox
import (
"testing"
"go.starlark.net/starlark"
)
func runRoutingScript(t *testing.T, script string) starlark.StringDict {
t.Helper()
mod := BuildRoutingModule()
predeclared := starlark.StringDict{"routing": mod}
globals, err := starlark.ExecFile(&starlark.Thread{Name: "test"}, "test.star", script, predeclared)
if err != nil {
t.Fatal(err)
}
return globals
}
func runRoutingScriptErr(t *testing.T, script string) error {
t.Helper()
mod := BuildRoutingModule()
predeclared := starlark.StringDict{"routing": mod}
_, err := starlark.ExecFile(&starlark.Thread{Name: "test"}, "test.star", script, predeclared)
return err
}
func TestRoutingEvaluate_SingleMatch(t *testing.T) {
globals := runRoutingScript(t, `
result = routing.evaluate([
{"field": "priority", "op": "eq", "value": "high", "target": "escalation"},
], {"priority": "high"})
`)
result := globals["result"]
if s, ok := result.(starlark.String); !ok || string(s) != "escalation" {
t.Fatalf("expected 'escalation', got %v", result)
}
}
func TestRoutingEvaluate_FirstMatchWins(t *testing.T) {
globals := runRoutingScript(t, `
result = routing.evaluate([
{"field": "amount", "op": "gt", "value": 100, "target": "big"},
{"field": "amount", "op": "gt", "value": 50, "target": "medium"},
], {"amount": 200})
`)
result := globals["result"]
if s, ok := result.(starlark.String); !ok || string(s) != "big" {
t.Fatalf("expected 'big', got %v", result)
}
}
func TestRoutingEvaluate_NoMatch(t *testing.T) {
globals := runRoutingScript(t, `
result = routing.evaluate([
{"field": "status", "op": "eq", "value": "done", "target": "finish"},
], {"status": "pending"})
`)
if globals["result"] != starlark.None {
t.Fatalf("expected None, got %v", globals["result"])
}
}
func TestRoutingEvaluate_EmptyRules(t *testing.T) {
globals := runRoutingScript(t, `
result = routing.evaluate([], {"x": 1})
`)
if globals["result"] != starlark.None {
t.Fatalf("expected None, got %v", globals["result"])
}
}
func TestRoutingEvaluate_AllOperators(t *testing.T) {
globals := runRoutingScript(t, `
# exists
r1 = routing.evaluate([{"field": "x", "op": "exists", "value": "", "target": "yes"}], {"x": 1})
# not_exists
r2 = routing.evaluate([{"field": "x", "op": "not_exists", "value": "", "target": "yes"}], {"y": 1})
# eq
r3 = routing.evaluate([{"field": "s", "op": "eq", "value": "abc", "target": "yes"}], {"s": "abc"})
# neq
r4 = routing.evaluate([{"field": "s", "op": "neq", "value": "abc", "target": "yes"}], {"s": "xyz"})
# gt
r5 = routing.evaluate([{"field": "n", "op": "gt", "value": 10, "target": "yes"}], {"n": 20})
# lt
r6 = routing.evaluate([{"field": "n", "op": "lt", "value": 10, "target": "yes"}], {"n": 5})
# gte
r7 = routing.evaluate([{"field": "n", "op": "gte", "value": 10, "target": "yes"}], {"n": 10})
# lte
r8 = routing.evaluate([{"field": "n", "op": "lte", "value": 10, "target": "yes"}], {"n": 10})
# in
r9 = routing.evaluate([{"field": "s", "op": "in", "value": ["a", "b", "c"], "target": "yes"}], {"s": "b"})
# contains
r10 = routing.evaluate([{"field": "s", "op": "contains", "value": "ell", "target": "yes"}], {"s": "hello"})
`)
for _, name := range []string{"r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10"} {
v := globals[name]
if s, ok := v.(starlark.String); !ok || string(s) != "yes" {
t.Errorf("%s: expected 'yes', got %v", name, v)
}
}
}
func TestRoutingEvaluate_TypeCoercion(t *testing.T) {
globals := runRoutingScript(t, `
# Numeric string vs int
r1 = routing.evaluate([
{"field": "n", "op": "gt", "value": 10, "target": "yes"},
], {"n": "20"})
# Int equality via string normalization
r2 = routing.evaluate([
{"field": "n", "op": "eq", "value": 42, "target": "yes"},
], {"n": 42})
`)
for _, name := range []string{"r1", "r2"} {
v := globals[name]
if s, ok := v.(starlark.String); !ok || string(s) != "yes" {
t.Errorf("%s: expected 'yes', got %v", name, v)
}
}
}
func TestRoutingEvaluate_BadInput(t *testing.T) {
// rules must be a list
err1 := runRoutingScriptErr(t, `routing.evaluate("bad", {})`)
if err1 == nil {
t.Fatal("expected error for non-list rules")
}
// data must be a dict
err2 := runRoutingScriptErr(t, `routing.evaluate([], "bad")`)
if err2 == nil {
t.Fatal("expected error for non-dict data")
}
// rule missing required fields
err3 := runRoutingScriptErr(t, `routing.evaluate([{"field": "x"}], {})`)
if err3 == nil {
t.Fatal("expected error for incomplete rule")
}
}
func TestRoutingEvaluate_MissingFields(t *testing.T) {
globals := runRoutingScript(t, `
# Field not in data — eq should not match
r1 = routing.evaluate([
{"field": "absent", "op": "eq", "value": "x", "target": "bad"},
], {"other": "y"})
# not_exists matches when field is absent
r2 = routing.evaluate([
{"field": "absent", "op": "not_exists", "value": "", "target": "good"},
], {"other": "y"})
`)
if globals["r1"] != starlark.None {
t.Fatalf("r1: expected None for missing field, got %v", globals["r1"])
}
if s, ok := globals["r2"].(starlark.String); !ok || string(s) != "good" {
t.Fatalf("r2: expected 'good', got %v", globals["r2"])
}
}

View File

@@ -82,6 +82,7 @@ type Runner struct {
workspaceRoot string // empty = workspace module unavailable
workspaceQuota int // MB, 0 = unlimited
capabilities map[string]bool // detected environment capabilities
wfEngine WorkflowEngine // nil = workflow write ops unavailable
}
// NewRunner creates a runner with the given sandbox and dependencies.
@@ -139,6 +140,12 @@ func (r *Runner) SetCapabilities(caps map[string]bool) {
r.capabilities = caps
}
// SetWorkflowEngine attaches the workflow engine for write operations
// (start/advance/cancel/submit_signoff) in the workflow Starlark module.
func (r *Runner) SetWorkflowEngine(e WorkflowEngine) {
r.wfEngine = e
}
// SetAllowPrivateIPs disables the SSRF check that blocks connections to
// private/loopback IPs. For self-hosted environments where extensions
// reach internal services. Controlled by EXT_ALLOW_PRIVATE_IPS env var.
@@ -396,7 +403,7 @@ func (r *Runner) buildModulesWithLibCtx(ctx context.Context, packageID string, m
filesLevel = 2
case models.ExtPermWorkflowAccess:
modules["workflow"] = BuildWorkflowModule(ctx, r.stores)
modules["workflow"] = BuildWorkflowModule(ctx, r.stores, r.wfEngine, rc)
case models.ExtPermConnectionsRead:
if r.connResolver != nil && rc != nil && rc.UserID != "" {
@@ -460,6 +467,9 @@ func (r *Runner) buildModulesWithLibCtx(ctx context.Context, packageID string, m
// Always available — read-only team role queries
modules["teams"] = BuildTeamsModule(ctx, r.stores)
// Always available — pure-computation routing decision engine
modules["routing"] = BuildRoutingModule()
// Allows any starlark package to load declared library dependencies.
if lc != nil {
modules["lib"] = BuildLibModule(ctx, r, packageID, rc, lc)

View File

@@ -8,10 +8,11 @@ package sandbox
// Starlark API:
// wf = workflow.get_definition(workflow_id) # returns dict
// inst = workflow.get_instance(instance_id) # returns dict
// instances = workflow.list_instances(workflow_id) # list instances
// inst = workflow.start(workflow_id, data={}) # start new instance
// inst = workflow.advance(instance_id, data={}) # advance to next stage
// workflow.cancel(instance_id) # cancel instance
// instances = workflow.list_instances(workflow_id) # list instances
// signoff = workflow.submit_signoff(instance_id, decision, comment="") # submit signoff
import (
"context"
@@ -21,21 +22,37 @@ import (
"go.starlark.net/starlark"
"go.starlark.net/starlarkstruct"
"armature/models"
"armature/store"
)
// WorkflowEngine is the subset of the workflow engine needed by Starlark
// write operations. Defined here (not in the workflow package) to avoid
// circular imports — workflow imports sandbox for the Runner.
type WorkflowEngine interface {
Start(ctx context.Context, workflowID string, initialData json.RawMessage, userID string) (*models.WorkflowInstance, error)
Advance(ctx context.Context, instanceID string, stageData json.RawMessage, userID string) (*models.WorkflowInstance, error)
Cancel(ctx context.Context, instanceID string, userID string) error
SubmitSignoff(ctx context.Context, instanceID, userID, decision, comment string) (*models.WorkflowSignoff, error)
}
// BuildWorkflowModule creates the "workflow" Starlark module for a package.
// Requires the workflow.access permission.
//
// Mutating operations (start/advance/cancel) are available via HTTP API;
// Starlark builtins for them will be added when the engine interface is
// extracted to a shared package to avoid circular imports.
func BuildWorkflowModule(ctx context.Context, stores store.Stores) *starlarkstruct.Module {
return MakeModule("workflow", starlark.StringDict{
// Read operations use stores directly. Write operations delegate to the
// WorkflowEngine interface (engine may be nil if not wired — write builtins
// return an error in that case).
func BuildWorkflowModule(ctx context.Context, stores store.Stores, engine WorkflowEngine, rc *RunContext) *starlarkstruct.Module {
members := starlark.StringDict{
"get_definition": starlark.NewBuiltin("workflow.get_definition", workflowGetDef(ctx, stores)),
"get_instance": starlark.NewBuiltin("workflow.get_instance", workflowGetInstance(ctx, stores)),
"list_instances": starlark.NewBuiltin("workflow.list_instances", workflowListInstances(ctx, stores)),
})
"start": starlark.NewBuiltin("workflow.start", workflowStart(ctx, engine, rc)),
"advance": starlark.NewBuiltin("workflow.advance", workflowAdvance(ctx, engine, rc)),
"cancel": starlark.NewBuiltin("workflow.cancel", workflowCancel(ctx, engine, rc)),
"submit_signoff": starlark.NewBuiltin("workflow.submit_signoff", workflowSubmitSignoff(ctx, engine, rc)),
}
return MakeModule("workflow", members)
}
func workflowGetDef(ctx context.Context, stores store.Stores) func(*starlark.Thread, *starlark.Builtin, starlark.Tuple, []starlark.Tuple) (starlark.Value, error) {
@@ -98,7 +115,12 @@ func workflowGetInstance(ctx context.Context, stores store.Stores) func(*starlar
if err != nil {
return starlark.None, fmt.Errorf("workflow.get_instance: %w", err)
}
return instanceToDict(inst), nil
}
}
// instanceToDict converts a WorkflowInstance to a Starlark dict.
func instanceToDict(inst *models.WorkflowInstance) *starlark.Dict {
d := starlark.NewDict(8)
d.SetKey(starlark.String("id"), starlark.String(inst.ID))
d.SetKey(starlark.String("workflow_id"), starlark.String(inst.WorkflowID))
@@ -122,9 +144,20 @@ func workflowGetInstance(ctx context.Context, stores store.Stores) func(*starlar
if inst.EntryToken != nil {
d.SetKey(starlark.String("entry_token"), starlark.String(*inst.EntryToken))
}
return d, nil
return d
}
// signoffToDict converts a WorkflowSignoff to a Starlark dict.
func signoffToDict(s *models.WorkflowSignoff) *starlark.Dict {
d := starlark.NewDict(7)
d.SetKey(starlark.String("id"), starlark.String(s.ID))
d.SetKey(starlark.String("instance_id"), starlark.String(s.InstanceID))
d.SetKey(starlark.String("stage"), starlark.String(s.Stage))
d.SetKey(starlark.String("user_id"), starlark.String(s.UserID))
d.SetKey(starlark.String("decision"), starlark.String(s.Decision))
d.SetKey(starlark.String("comment"), starlark.String(s.Comment))
d.SetKey(starlark.String("created_at"), starlark.String(s.CreatedAt.Format("2006-01-02T15:04:05Z07:00")))
return d
}
func workflowListInstances(ctx context.Context, stores store.Stores) func(*starlark.Thread, *starlark.Builtin, starlark.Tuple, []starlark.Tuple) (starlark.Value, error) {
@@ -155,5 +188,113 @@ func workflowListInstances(ctx context.Context, stores store.Stores) func(*starl
}
}
// workflowRoute routes the workflow to a named stage.
// Starlark: workflow.route(instance_id, target_stage, reason)
// ── Instance Write API ──────────────
// workflowWriteGuard checks that the engine and user context are available.
func workflowWriteGuard(engine WorkflowEngine, rc *RunContext) error {
if engine == nil {
return fmt.Errorf("workflow engine not available")
}
if rc == nil || rc.UserID == "" {
return fmt.Errorf("workflow write operations require an authenticated user context")
}
return nil
}
// dictToJSON converts a Starlark dict to json.RawMessage.
func dictToJSON(d *starlark.Dict) (json.RawMessage, error) {
m := DictToMap(d)
b, err := json.Marshal(m)
if err != nil {
return nil, err
}
return json.RawMessage(b), nil
}
func workflowStart(ctx context.Context, engine WorkflowEngine, rc *RunContext) func(*starlark.Thread, *starlark.Builtin, starlark.Tuple, []starlark.Tuple) (starlark.Value, error) {
return func(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var workflowID string
data := starlark.NewDict(0)
if err := starlark.UnpackArgs("workflow.start", args, kwargs,
"workflow_id", &workflowID,
"data?", &data,
); err != nil {
return nil, err
}
if err := workflowWriteGuard(engine, rc); err != nil {
return nil, fmt.Errorf("workflow.start: %w", err)
}
dataJSON, err := dictToJSON(data)
if err != nil {
return nil, fmt.Errorf("workflow.start: marshal data: %w", err)
}
inst, err := engine.Start(ctx, workflowID, dataJSON, rc.UserID)
if err != nil {
return nil, fmt.Errorf("workflow.start: %w", err)
}
return instanceToDict(inst), nil
}
}
func workflowAdvance(ctx context.Context, engine WorkflowEngine, rc *RunContext) func(*starlark.Thread, *starlark.Builtin, starlark.Tuple, []starlark.Tuple) (starlark.Value, error) {
return func(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var instanceID string
data := starlark.NewDict(0)
if err := starlark.UnpackArgs("workflow.advance", args, kwargs,
"instance_id", &instanceID,
"data?", &data,
); err != nil {
return nil, err
}
if err := workflowWriteGuard(engine, rc); err != nil {
return nil, fmt.Errorf("workflow.advance: %w", err)
}
dataJSON, err := dictToJSON(data)
if err != nil {
return nil, fmt.Errorf("workflow.advance: marshal data: %w", err)
}
inst, err := engine.Advance(ctx, instanceID, dataJSON, rc.UserID)
if err != nil {
return nil, fmt.Errorf("workflow.advance: %w", err)
}
return instanceToDict(inst), nil
}
}
func workflowCancel(ctx context.Context, engine WorkflowEngine, rc *RunContext) func(*starlark.Thread, *starlark.Builtin, starlark.Tuple, []starlark.Tuple) (starlark.Value, error) {
return func(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var instanceID string
if err := starlark.UnpackPositionalArgs("workflow.cancel", args, kwargs, 1, &instanceID); err != nil {
return nil, err
}
if err := workflowWriteGuard(engine, rc); err != nil {
return nil, fmt.Errorf("workflow.cancel: %w", err)
}
if err := engine.Cancel(ctx, instanceID, rc.UserID); err != nil {
return nil, fmt.Errorf("workflow.cancel: %w", err)
}
return starlark.None, nil
}
}
func workflowSubmitSignoff(ctx context.Context, engine WorkflowEngine, rc *RunContext) func(*starlark.Thread, *starlark.Builtin, starlark.Tuple, []starlark.Tuple) (starlark.Value, error) {
return func(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
var instanceID, decision string
comment := ""
if err := starlark.UnpackArgs("workflow.submit_signoff", args, kwargs,
"instance_id", &instanceID,
"decision", &decision,
"comment?", &comment,
); err != nil {
return nil, err
}
if err := workflowWriteGuard(engine, rc); err != nil {
return nil, fmt.Errorf("workflow.submit_signoff: %w", err)
}
signoff, err := engine.SubmitSignoff(ctx, instanceID, rc.UserID, decision, comment)
if err != nil {
return nil, fmt.Errorf("workflow.submit_signoff: %w", err)
}
return signoffToDict(signoff), nil
}
}

View File

@@ -0,0 +1,262 @@
package sandbox
import (
"context"
"encoding/json"
"testing"
"time"
"go.starlark.net/starlark"
"armature/models"
"armature/store"
)
// ── Mock Engine ──────────────────────
type mockWorkflowEngine struct {
startResult *models.WorkflowInstance
advanceResult *models.WorkflowInstance
signoffResult *models.WorkflowSignoff
lastMethod string
lastWorkflowID string
lastInstanceID string
lastUserID string
lastData json.RawMessage
lastDecision string
lastComment string
}
func (m *mockWorkflowEngine) Start(_ context.Context, workflowID string, data json.RawMessage, userID string) (*models.WorkflowInstance, error) {
m.lastMethod = "Start"
m.lastWorkflowID = workflowID
m.lastData = data
m.lastUserID = userID
return m.startResult, nil
}
func (m *mockWorkflowEngine) Advance(_ context.Context, instanceID string, data json.RawMessage, userID string) (*models.WorkflowInstance, error) {
m.lastMethod = "Advance"
m.lastInstanceID = instanceID
m.lastData = data
m.lastUserID = userID
return m.advanceResult, nil
}
func (m *mockWorkflowEngine) Cancel(_ context.Context, instanceID string, userID string) error {
m.lastMethod = "Cancel"
m.lastInstanceID = instanceID
m.lastUserID = userID
return nil
}
func (m *mockWorkflowEngine) SubmitSignoff(_ context.Context, instanceID, userID, decision, comment string) (*models.WorkflowSignoff, error) {
m.lastMethod = "SubmitSignoff"
m.lastInstanceID = instanceID
m.lastUserID = userID
m.lastDecision = decision
m.lastComment = comment
return m.signoffResult, nil
}
// ── Helpers ──────────────────────────
func testInstance() *models.WorkflowInstance {
return &models.WorkflowInstance{
ID: "inst-1",
WorkflowID: "wf-1",
WorkflowVersion: 2,
CurrentStage: "review",
Status: "active",
StartedBy: "user-1",
StageData: json.RawMessage(`{"key":"val"}`),
}
}
func testSignoff() *models.WorkflowSignoff {
return &models.WorkflowSignoff{
ID: "sig-1",
InstanceID: "inst-1",
Stage: "review",
UserID: "user-1",
Decision: "approve",
Comment: "LGTM",
CreatedAt: time.Date(2026, 4, 3, 12, 0, 0, 0, time.UTC),
}
}
func runWorkflowScript(t *testing.T, engine WorkflowEngine, rc *RunContext, script string) (starlark.StringDict, error) {
t.Helper()
mod := BuildWorkflowModule(context.Background(), store.Stores{}, engine, rc)
predeclared := starlark.StringDict{"workflow": mod}
globals, err := starlark.ExecFile(&starlark.Thread{Name: "test"}, "test.star", script, predeclared)
return globals, err
}
// ── Tests ────────────────────────────
func TestWorkflowStart(t *testing.T) {
mock := &mockWorkflowEngine{startResult: testInstance()}
rc := &RunContext{UserID: "user-1"}
globals, err := runWorkflowScript(t, mock, rc, `
result = workflow.start("wf-1", data={"key": "val"})
`)
if err != nil {
t.Fatal(err)
}
if mock.lastMethod != "Start" {
t.Fatalf("expected Start, got %s", mock.lastMethod)
}
if mock.lastWorkflowID != "wf-1" {
t.Fatalf("expected wf-1, got %s", mock.lastWorkflowID)
}
if mock.lastUserID != "user-1" {
t.Fatalf("expected user-1, got %s", mock.lastUserID)
}
// Verify data was marshaled
var d map[string]interface{}
if err := json.Unmarshal(mock.lastData, &d); err != nil {
t.Fatal(err)
}
if d["key"] != "val" {
t.Fatalf("expected data key=val, got %v", d)
}
// Verify returned dict
result := globals["result"].(*starlark.Dict)
id, _, _ := result.Get(starlark.String("id"))
if id.(starlark.String).GoString() != "inst-1" {
t.Fatalf("expected id=inst-1, got %v", id)
}
status, _, _ := result.Get(starlark.String("status"))
if status.(starlark.String).GoString() != "active" {
t.Fatalf("expected status=active, got %v", status)
}
}
func TestWorkflowAdvance(t *testing.T) {
inst := testInstance()
inst.CurrentStage = "complete"
mock := &mockWorkflowEngine{advanceResult: inst}
rc := &RunContext{UserID: "user-1"}
globals, err := runWorkflowScript(t, mock, rc, `
result = workflow.advance("inst-1", data={"step": 2})
`)
if err != nil {
t.Fatal(err)
}
if mock.lastMethod != "Advance" {
t.Fatalf("expected Advance, got %s", mock.lastMethod)
}
if mock.lastInstanceID != "inst-1" {
t.Fatalf("expected inst-1, got %s", mock.lastInstanceID)
}
result := globals["result"].(*starlark.Dict)
stage, _, _ := result.Get(starlark.String("current_stage"))
if stage.(starlark.String).GoString() != "complete" {
t.Fatalf("expected current_stage=complete, got %v", stage)
}
}
func TestWorkflowCancel(t *testing.T) {
mock := &mockWorkflowEngine{}
rc := &RunContext{UserID: "user-1"}
globals, err := runWorkflowScript(t, mock, rc, `
result = workflow.cancel("inst-1")
`)
if err != nil {
t.Fatal(err)
}
if mock.lastMethod != "Cancel" {
t.Fatalf("expected Cancel, got %s", mock.lastMethod)
}
if mock.lastInstanceID != "inst-1" {
t.Fatalf("expected inst-1, got %s", mock.lastInstanceID)
}
if mock.lastUserID != "user-1" {
t.Fatalf("expected user-1, got %s", mock.lastUserID)
}
if globals["result"] != starlark.None {
t.Fatalf("expected None, got %v", globals["result"])
}
}
func TestWorkflowSubmitSignoff(t *testing.T) {
mock := &mockWorkflowEngine{signoffResult: testSignoff()}
rc := &RunContext{UserID: "user-1"}
globals, err := runWorkflowScript(t, mock, rc, `
result = workflow.submit_signoff("inst-1", "approve", comment="LGTM")
`)
if err != nil {
t.Fatal(err)
}
if mock.lastMethod != "SubmitSignoff" {
t.Fatalf("expected SubmitSignoff, got %s", mock.lastMethod)
}
if mock.lastDecision != "approve" {
t.Fatalf("expected approve, got %s", mock.lastDecision)
}
if mock.lastComment != "LGTM" {
t.Fatalf("expected LGTM, got %s", mock.lastComment)
}
result := globals["result"].(*starlark.Dict)
decision, _, _ := result.Get(starlark.String("decision"))
if decision.(starlark.String).GoString() != "approve" {
t.Fatalf("expected decision=approve, got %v", decision)
}
comment, _, _ := result.Get(starlark.String("comment"))
if comment.(starlark.String).GoString() != "LGTM" {
t.Fatalf("expected comment=LGTM, got %v", comment)
}
}
func TestWorkflowWrite_NoUser(t *testing.T) {
mock := &mockWorkflowEngine{startResult: testInstance()}
_, err := runWorkflowScript(t, mock, nil, `
result = workflow.start("wf-1")
`)
if err == nil {
t.Fatal("expected error for nil RunContext")
}
if got := err.Error(); !contains(got, "authenticated user context") {
t.Fatalf("unexpected error: %s", got)
}
}
func TestWorkflowWrite_NoEngine(t *testing.T) {
rc := &RunContext{UserID: "user-1"}
_, err := runWorkflowScript(t, nil, rc, `
result = workflow.start("wf-1")
`)
if err == nil {
t.Fatal("expected error for nil engine")
}
if got := err.Error(); !contains(got, "engine not available") {
t.Fatalf("unexpected error: %s", got)
}
}
// contains is a test helper — strings.Contains without importing strings.
func contains(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}