ragleap-flows 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,43 @@
1
+ # Environment
2
+ .env
3
+ *.env.local
4
+
5
+ # Python
6
+ __pycache__/
7
+ *.py[cod]
8
+ *.egg-info/
9
+ venv/
10
+ .venv/
11
+
12
+ # Node
13
+ node_modules/
14
+
15
+ # Docker
16
+ docker-compose.override.yml
17
+
18
+ # IDE
19
+ .vscode/
20
+ .idea/
21
+
22
+ # OS
23
+ .DS_Store
24
+ Thumbs.db
25
+
26
+ # Logs
27
+ *.log
28
+ .env
29
+
30
+ # Package build artifacts
31
+ dist/
32
+ build/
33
+
34
+ # RagLeap command
35
+ .ragleap-ollama
36
+ backups/
37
+
38
+ # Folder grants are the owner's private choices
39
+ grants/*
40
+ !grants/README.txt
41
+
42
+ # Maven build output
43
+ java/ragleap-observability/target/
@@ -0,0 +1,23 @@
1
+ # Changelog
2
+
3
+ All notable changes to `ragleap-flows` are documented here. Format loosely follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
+
6
+ ## [0.1.0] - 2026-11-23
7
+
8
+ First release. The PR block replaces 2026-11-20 with the UTC date of that day.
9
+
10
+ ### Added
11
+
12
+ - `from_json` / `from_dict`: a strict loader for flow files (plain JSON data, no code). Unknown keys, wrong types,
13
+ duplicate keys, NaN, unknown targets, cycles, unreachable steps, paths that read a step that does not always run
14
+ before them and oversize files are refused with `FlowError`.
15
+ - Steps: `tool`, `approval`, `branch`. Paths (`$input.x`, `$step.field.0`), operators `eq ne lt le gt ge in exists
16
+ truthy`, `all` and `any`.
17
+ - `FlowRunner.run(scope, input)` and `FlowRunner.resume(scope, run_id, decisions)`: every run belongs to a
18
+ `ragleap_security.Scope`; a wrong scope, an unknown run and a damaged state give the same `ResumeError("unknown run")`;
19
+ 128-bit run ids; an atomic claim on resume; `store_for(tenant)` for one store per tenant; `rate_limiter`; `audit` with
20
+ no text, fail closed; a taint rule for `outbound` steps after `external` steps or an untrusted input.
21
+ - `dispatch=` as an alternative to `tools=`, so tool calls can go through a per-tenant dispatcher.
22
+ - Hard limits: 100 steps, 256 KiB flow, 64 KiB input, 64 KiB step output, 1 MiB state, 300 s deadline.
23
+ - `scripts/mutation_check.py` (68 mutations, all killed on Python 3.10 and 3.12).
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.5
2
+ Name: ragleap-flows
3
+ Version: 0.1.0
4
+ Summary: Multi-tenant flows as plain JSON data: tool steps, approval checkpoints and branches, run under a tenant Scope with durable pause and resume, hard limits and an audit trail without text. Built on ragleap-agents state stores and ragleap-security. Not n8n, no code in flow files, no eval. Not independently audited.
5
+ Project-URL: Homepage, https://github.com/ragleap/ragleap-core
6
+ Project-URL: Repository, https://github.com/ragleap/ragleap-core
7
+ Project-URL: Issues, https://github.com/ragleap/ragleap-core/issues
8
+ Author: RagLeap
9
+ License-Expression: MIT
10
+ Keywords: agents,approval,flows,human-in-the-loop,llm,multi-tenant,self-hosted,workflow
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: ragleap-agents>=0.5.1
21
+ Requires-Dist: ragleap-security>=0.2.0
22
+ Requires-Dist: ragleap-tools>=0.5.1
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest>=8.0.0; extra == 'test'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # ragleap-flows
28
+
29
+ Multi-tenant flows as plain JSON data: **tool steps**, **approval checkpoints** and **branches**. Every run belongs
30
+ to a `ragleap_security.Scope`; a paused run survives a restart and is resumed later, only by the tenant that owns it.
31
+
32
+ Alpha (0.1.0). MIT. Python 3.10+. Not independently audited.
33
+
34
+ pip install ragleap-flows
35
+
36
+ This is not n8n and not a workflow engine with connectors. A flow file holds no code: no `eval`, no scripts, no
37
+ string interpolation. It is a small, auditable core for "do these tool calls, ask a human here, branch there".
38
+
39
+ ## A flow
40
+
41
+ {
42
+ "version": 1,
43
+ "steps": [
44
+ {"id": "look", "type": "tool", "tool": "lookup_order", "arguments": {"order": "$input.order"}, "next": "check"},
45
+ {"id": "check", "type": "branch",
46
+ "cases": [{"when": {"path": "$look.amount", "op": "gt", "value": 100}, "goto": "ask"}], "else": "pay"},
47
+ {"id": "ask", "type": "approval", "prompt": "Approve this refund?", "show": {"amount": "$look.amount"}, "next": "pay"},
48
+ {"id": "pay", "type": "tool", "tool": "refund", "outbound": true, "arguments": {"order": "$input.order"}}
49
+ ],
50
+ "output": {"refunded": "$pay.ok"}
51
+ }
52
+
53
+ Step types: `tool` (`tool`, `arguments`, `next`, `outbound`, `external`), `approval` (`prompt`, `show`, `next`),
54
+ `branch` (`cases` of `when` and `goto`, then `else`). A missing `next` ends the run.
55
+
56
+ Values move between steps with paths: `$input.x` and `$step_id.field.0`. A string that is exactly a path is replaced by
57
+ the value it points at (dict keys by name, list items by position). There is no interpolation and no attribute access;
58
+ `"$$x"` is the literal text `$x`. Operators: `eq ne lt le gt ge in exists truthy`, combined with `all` and `any`. A
59
+ number never equals a `True`, and a missing value satisfies no comparison (not even `ne`).
60
+
61
+ ## Run it
62
+
63
+ import ragleap_flows as rf
64
+ from ragleap_security import Scope
65
+
66
+ flow = rf.from_json(open("refund.json").read()) # checked once, strictly
67
+ runner = rf.FlowRunner(flow, toolkit, store=my_store) # toolkit: a ragleap_tools Toolkit
68
+ tenant = Scope("acme") # the host authenticates; the library never does
69
+
70
+ result = runner.run(tenant, {"order": "A-17"})
71
+ if result.status == "awaiting_approval":
72
+ result = runner.resume(tenant, result.run_id, {result.pending["step"]: True})
73
+
74
+ `status` is one of `done`, `awaiting_approval`, `rejected`, `failed`, `stopped`. Use `dispatch=` instead of `tools=`
75
+ to route tool calls yourself, for example through a governed, per-tenant dispatcher: `dispatch(scope, name, arguments)`
76
+ must return a `ToolResult`. Any `ragleap_agents` state store works (`InMemoryStateStore`, `SQLiteStateStore`).
77
+
78
+ ## Multi-tenant rules
79
+
80
+ 1. Every call takes exactly a `Scope`. There is no unscoped run; single-tenant use is one fixed scope.
81
+ 2. A run records its scope key. `resume` continues it only for exactly that scope (every part). A wrong scope, an
82
+ unknown run id and a damaged stored state all give the same `ResumeError("unknown run")`, and ownership is checked
83
+ before any decision is read, so nobody learns that another tenant's run exists.
84
+ 3. Run ids are 128-bit random tokens.
85
+ 4. `store_for(tenant)` gives each tenant its own store. One shared store is safe because of the checks above, but
86
+ anyone with access to the store file sees every tenant.
87
+ 5. Audit events (an `AuditLog`) hold the scope, ids, step ids, tool names and sizes, never input, arguments or
88
+ results. If a record cannot be written, the error is raised and nothing continues.
89
+ 6. A `rate_limiter` (anything with `check(scope)`) is checked before a run starts or resumes.
90
+ 7. Taint, as in ragleap-agents: after a step marked `"external": true`, or for a run started with `tainted=True`, every
91
+ later `"outbound": true` tool step pauses for approval first (`pending["forced"]` is true), each time.
92
+
93
+ ## Hard limits
94
+
95
+ 100 steps per flow, 256 KiB flow file, 64 KiB input, 64 KiB per step output, 1 MiB saved state, 300 s deadline per
96
+ `run` or `resume` call (checked between steps), no cycles, every step reachable, a path may only read a step that
97
+ always runs before it. Each limit is refused or stopped with a named reason, never silently cut.
98
+
99
+ ## What this does not defend
100
+
101
+ - It does not authenticate anybody. Pass only a `Scope` your application has established.
102
+ - A tool that reads another tenant's data by itself is not stopped. Tools must be written tenant-safe, or called through
103
+ a per-tenant dispatcher.
104
+ - Approval is only as good as who is allowed to call `resume`. The library does not check who the approver is.
105
+ - Taint only works if your flow marks `external` and `outbound` steps honestly. An unmarked step is trusted.
106
+ - The deadline is checked between steps; a single slow tool call is not interrupted.
107
+ - A run that crashes while `running` stays `running`; 0.1.0 does not recover it automatically.
108
+ - One shared store file shows every tenant to whoever can read it; the state is not encrypted.
109
+ - Not tested on Windows or macOS, network file systems, or several processes sharing one store beyond the atomic claim.
110
+ - No independent security review.
111
+
112
+ ## Tests
113
+
114
+ 153 tests; `scripts/mutation_check.py` breaks 68 protections one at a time and requires a test to fail. All 68 are caught.
115
+ One more candidate was dropped as an equivalent mutant (the `$$` check in `parse_path` is also enforced by the segment
116
+ rule).
@@ -0,0 +1,90 @@
1
+ # ragleap-flows
2
+
3
+ Multi-tenant flows as plain JSON data: **tool steps**, **approval checkpoints** and **branches**. Every run belongs
4
+ to a `ragleap_security.Scope`; a paused run survives a restart and is resumed later, only by the tenant that owns it.
5
+
6
+ Alpha (0.1.0). MIT. Python 3.10+. Not independently audited.
7
+
8
+ pip install ragleap-flows
9
+
10
+ This is not n8n and not a workflow engine with connectors. A flow file holds no code: no `eval`, no scripts, no
11
+ string interpolation. It is a small, auditable core for "do these tool calls, ask a human here, branch there".
12
+
13
+ ## A flow
14
+
15
+ {
16
+ "version": 1,
17
+ "steps": [
18
+ {"id": "look", "type": "tool", "tool": "lookup_order", "arguments": {"order": "$input.order"}, "next": "check"},
19
+ {"id": "check", "type": "branch",
20
+ "cases": [{"when": {"path": "$look.amount", "op": "gt", "value": 100}, "goto": "ask"}], "else": "pay"},
21
+ {"id": "ask", "type": "approval", "prompt": "Approve this refund?", "show": {"amount": "$look.amount"}, "next": "pay"},
22
+ {"id": "pay", "type": "tool", "tool": "refund", "outbound": true, "arguments": {"order": "$input.order"}}
23
+ ],
24
+ "output": {"refunded": "$pay.ok"}
25
+ }
26
+
27
+ Step types: `tool` (`tool`, `arguments`, `next`, `outbound`, `external`), `approval` (`prompt`, `show`, `next`),
28
+ `branch` (`cases` of `when` and `goto`, then `else`). A missing `next` ends the run.
29
+
30
+ Values move between steps with paths: `$input.x` and `$step_id.field.0`. A string that is exactly a path is replaced by
31
+ the value it points at (dict keys by name, list items by position). There is no interpolation and no attribute access;
32
+ `"$$x"` is the literal text `$x`. Operators: `eq ne lt le gt ge in exists truthy`, combined with `all` and `any`. A
33
+ number never equals a `True`, and a missing value satisfies no comparison (not even `ne`).
34
+
35
+ ## Run it
36
+
37
+ import ragleap_flows as rf
38
+ from ragleap_security import Scope
39
+
40
+ flow = rf.from_json(open("refund.json").read()) # checked once, strictly
41
+ runner = rf.FlowRunner(flow, toolkit, store=my_store) # toolkit: a ragleap_tools Toolkit
42
+ tenant = Scope("acme") # the host authenticates; the library never does
43
+
44
+ result = runner.run(tenant, {"order": "A-17"})
45
+ if result.status == "awaiting_approval":
46
+ result = runner.resume(tenant, result.run_id, {result.pending["step"]: True})
47
+
48
+ `status` is one of `done`, `awaiting_approval`, `rejected`, `failed`, `stopped`. Use `dispatch=` instead of `tools=`
49
+ to route tool calls yourself, for example through a governed, per-tenant dispatcher: `dispatch(scope, name, arguments)`
50
+ must return a `ToolResult`. Any `ragleap_agents` state store works (`InMemoryStateStore`, `SQLiteStateStore`).
51
+
52
+ ## Multi-tenant rules
53
+
54
+ 1. Every call takes exactly a `Scope`. There is no unscoped run; single-tenant use is one fixed scope.
55
+ 2. A run records its scope key. `resume` continues it only for exactly that scope (every part). A wrong scope, an
56
+ unknown run id and a damaged stored state all give the same `ResumeError("unknown run")`, and ownership is checked
57
+ before any decision is read, so nobody learns that another tenant's run exists.
58
+ 3. Run ids are 128-bit random tokens.
59
+ 4. `store_for(tenant)` gives each tenant its own store. One shared store is safe because of the checks above, but
60
+ anyone with access to the store file sees every tenant.
61
+ 5. Audit events (an `AuditLog`) hold the scope, ids, step ids, tool names and sizes, never input, arguments or
62
+ results. If a record cannot be written, the error is raised and nothing continues.
63
+ 6. A `rate_limiter` (anything with `check(scope)`) is checked before a run starts or resumes.
64
+ 7. Taint, as in ragleap-agents: after a step marked `"external": true`, or for a run started with `tainted=True`, every
65
+ later `"outbound": true` tool step pauses for approval first (`pending["forced"]` is true), each time.
66
+
67
+ ## Hard limits
68
+
69
+ 100 steps per flow, 256 KiB flow file, 64 KiB input, 64 KiB per step output, 1 MiB saved state, 300 s deadline per
70
+ `run` or `resume` call (checked between steps), no cycles, every step reachable, a path may only read a step that
71
+ always runs before it. Each limit is refused or stopped with a named reason, never silently cut.
72
+
73
+ ## What this does not defend
74
+
75
+ - It does not authenticate anybody. Pass only a `Scope` your application has established.
76
+ - A tool that reads another tenant's data by itself is not stopped. Tools must be written tenant-safe, or called through
77
+ a per-tenant dispatcher.
78
+ - Approval is only as good as who is allowed to call `resume`. The library does not check who the approver is.
79
+ - Taint only works if your flow marks `external` and `outbound` steps honestly. An unmarked step is trusted.
80
+ - The deadline is checked between steps; a single slow tool call is not interrupted.
81
+ - A run that crashes while `running` stays `running`; 0.1.0 does not recover it automatically.
82
+ - One shared store file shows every tenant to whoever can read it; the state is not encrypted.
83
+ - Not tested on Windows or macOS, network file systems, or several processes sharing one store beyond the atomic claim.
84
+ - No independent security review.
85
+
86
+ ## Tests
87
+
88
+ 153 tests; `scripts/mutation_check.py` breaks 68 protections one at a time and requires a test to fail. All 68 are caught.
89
+ One more candidate was dropped as an equivalent mutant (the `$$` check in `parse_path` is also enforced by the segment
90
+ rule).
@@ -0,0 +1,26 @@
1
+ # ragleap-flows 0.1.0: design notes
2
+
3
+ Design proposal: issue #794 (API surface) and its multi-tenant design comment. These notes record where the code
4
+ differs from that comment, and why, so the issue is not silently rewritten.
5
+
6
+ ## Differences from the #794 comment
7
+
8
+ - `run(scope, input)` and `resume(scope, run_id, decisions)` take the scope as the FIRST, required argument. There is
9
+ no unscoped run and no `require_scope` switch.
10
+ - Tool steps run through `tools=` (a `ragleap_tools.Toolkit`) or `dispatch=` (any `dispatch(scope, name, arguments)`
11
+ returning a ToolResult). `GovernedToolkit.call` has exactly that shape, but it is unreleased in ragleap-tools 0.5.1,
12
+ so flows 0.1.0 does not depend on it.
13
+ - Taint is runtime, not static: a tool step may be marked `external` (its result is untrusted) or `outbound`. An
14
+ outbound step reached while tainted pauses for approval (forced), each time.
15
+ - A path may only read a step that always runs before it. This is stricter than "an earlier step" and is checked when
16
+ the flow loads.
17
+ - Flow output: an optional `output` template. A path in it to a step that did not run gives `output=None` and stop
18
+ reason `output_unavailable` (the run still counts as `done`; its side effects already happened).
19
+ - Saved state reuses the ragleap-agents `StateStore` protocol and statuses, so `SQLiteStateStore` and its atomic
20
+ `save_if_status` claim are shared, not copied.
21
+
22
+ ## Not in 0.1.0
23
+
24
+ `AgentStep` (0.2.0), parallel branches, `WebhookStep` (belongs in ragleap-integrations), automatic recovery of a run
25
+ that crashed while `running`, a per-tenant run count (the StateStore has no list or count), post-quantum or other
26
+ signing of flow files.
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ragleap-flows"
7
+ version = "0.1.0"
8
+ description = "Multi-tenant flows as plain JSON data: tool steps, approval checkpoints and branches, run under a tenant Scope with durable pause and resume, hard limits and an audit trail without text. Built on ragleap-agents state stores and ragleap-security. Not n8n, no code in flow files, no eval. Not independently audited."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ { name = "RagLeap" }
14
+ ]
15
+ keywords = ["workflow", "flows", "approval", "human-in-the-loop", "multi-tenant", "llm", "agents", "self-hosted"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Topic :: Software Development :: Libraries :: Python Modules",
25
+ ]
26
+
27
+ dependencies = [
28
+ "ragleap-agents>=0.5.1",
29
+ "ragleap-security>=0.2.0",
30
+ "ragleap-tools>=0.5.1",
31
+ ]
32
+
33
+ [project.optional-dependencies]
34
+ test = ["pytest>=8.0.0"]
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/ragleap/ragleap-core"
38
+ Repository = "https://github.com/ragleap/ragleap-core"
39
+ Issues = "https://github.com/ragleap/ragleap-core/issues"
40
+
41
+ [tool.hatch.build.targets.wheel]
42
+ packages = ["src/ragleap_flows"]
@@ -0,0 +1,144 @@
1
+ """Breaks one protection at a time in a temporary copy of the package and requires a test to fail.
2
+
3
+ python scripts/mutation_check.py [--results FILE]
4
+
5
+ Killed = a test failed (the protection is tested). SURVIVED = nothing failed: a missing test. Every anchor must
6
+ match exactly once, so a refactor that moves code makes this script fail loudly instead of passing quietly.
7
+ Resumable: finished mutations are read back from the results file and skipped.
8
+ """
9
+ import argparse
10
+ import os
11
+ import shutil
12
+ import subprocess
13
+ import sys
14
+ import tempfile
15
+
16
+ R, F = "src/ragleap_flows/runner.py", "src/ragleap_flows/flow.py"
17
+
18
+ MUTATIONS = [
19
+ # --- runner: ownership and scope
20
+ ("owns-always-true", R, 'return isinstance(stored, str) and hmac.compare_digest(stored.encode("utf-8"), scope.key.encode("utf-8"))', "return True"),
21
+ ("owns-prefix-only", R, "hmac.compare_digest(stored.encode(\"utf-8\"), scope.key.encode(\"utf-8\"))", "stored.startswith(scope.key)"),
22
+ ("owns-check-removed", R, "if not isinstance(state, dict) or not self._owns(state, scope):", "if not isinstance(state, dict):"),
23
+ ("flow-digest-check-removed", R, 'if state.get("flow") != self.flow.digest:', "if False:"),
24
+ ("version-check-before-owner", R, 'raise ResumeError("this run belongs to a different version of the flow")', 'raise ResumeError("unknown run")'),
25
+ ("pending-step-not-validated", R, "if step_id not in self.flow.steps:", "if False:"),
26
+ ("resume-status-check-removed", R, 'if state.get("status") != "awaiting_approval" or not pending:', "if not pending:"),
27
+ ("extra-decisions-allowed", R, "if set(decisions) != {step_id}:", "if False:"),
28
+ ("decision-type-unchecked", R, "if not isinstance(approved, bool):", "if False:"),
29
+ ("claim-ignored", R, 'if not claim(state["run_id"], state, "awaiting_approval"):', "if False:"),
30
+ ("rejection-ignored", R, "if not approved:", "if False:"),
31
+ ("approval-not-recorded", R, 'state["approved"].append(step_id)', "pass"),
32
+ ("run-id-short", R, "secrets.token_urlsafe(16)", "secrets.token_urlsafe(4)"),
33
+ ("run-scope-not-saved", R, '"scope": scope.key,', '"scope": "tenant=nobody",'),
34
+ ("scope-not-required", R, "scope = _require_scope(scope)\n if not isinstance(tainted, bool):", "if not isinstance(tainted, bool):"),
35
+ ("store-for-unchecked", R, 'if not callable(getattr(store, "load", None)) or not callable(getattr(store, "save", None)):', "if False:"),
36
+ ("store-for-ignores-tenant", R, "store = self._store_for(scope.tenant)", "store = self._store_for('shared')"),
37
+ # --- runner: taint and approval
38
+ ("taint-rule-off", R, 'if step.get("outbound") and state["tainted"] and sid not in state["approved"]:', "if False:"),
39
+ ("taint-ignores-input-flag", R, '"tainted": tainted,', '"tainted": False,'),
40
+ ("external-step-does-not-taint", R, 'if step.get("external"):', "if False:"),
41
+ ("forced-approval-reused-for-all", R, 'if step.get("outbound") and state["tainted"] and sid not in state["approved"]:', 'if step.get("outbound") and state["tainted"] and not state["approved"]:'),
42
+ ("approval-step-skipped", R, 'if sid not in state["approved"]:\n try:\n show', "if False:\n try:\n show"),
43
+ # --- runner: limits and failure handling
44
+ ("deadline-ignored", R, "if deadline is not None and self._clock() > deadline:", "if False:"),
45
+ ("output-cap-off", R, "if size > MAX_OUTPUT_BYTES:", "if size > MAX_OUTPUT_BYTES * 1000:"),
46
+ ("output-not-json-allowed", R, 'ok, err = False, "output_not_json"', "pass"),
47
+ ("state-cap-off", R, "if _json_size(state) > MAX_STATE_BYTES:", "if _json_size(state) > MAX_STATE_BYTES * 1000:"),
48
+ ("input-cap-off", R, "if _json_size(data) > MAX_INPUT_BYTES:", "if _json_size(data) > MAX_INPUT_BYTES * 1000:"),
49
+ ("rate-limit-ignored", R, "if not decision.allowed:", "if False:"),
50
+ ("tool-failure-continues", R, 'return self._finish(state, store, "failed", "tool_failed:" + sid)', 'state["current"] = step.get("next"); continue'),
51
+ ("success-check-loose", R, "if res.success is not True:", "if not res.success:"),
52
+ ("invalid-result-accepted", R, 'if not hasattr(res, "success") or not hasattr(res, "result"):', "if False:"),
53
+ ("tool-exception-detail-leaks", R, '"tool raised " + type(e).__name__', "str(e)"),
54
+ ("missing-value-continues", R, 'return self._finish(state, store, "failed", "missing_value")\n ok, value', 'pass\n ok, value'),
55
+ ("branch-takes-last-match", R, "nxt = case[\"goto\"]\n break", "nxt = case[\"goto\"]"),
56
+ ("output-missing-raises", R, 'state["final"], state["stop_reason"] = None, "output_unavailable"\n self._audit', 'raise Missing()\n self._audit'),
57
+ ("audit-scope-dropped", R, 'Scope.parse(state["scope"]))', "None)"),
58
+ ("audit-errors-swallowed", R, 'self.audit.append(event, {"run_id": state["run_id"], **data}, Scope.parse(state["scope"]))', 'try:\n self.audit.append(event, {"run_id": state["run_id"], **data}, Scope.parse(state["scope"]))\n except Exception:\n pass'),
59
+ ("audit-leaks-input", R, 'self._audit(state, "flow.start", tainted=tainted, input_bytes=_json_size(data))', 'self._audit(state, "flow.start", tainted=tainted, input=data)'),
60
+ ("config-both-tools-and-dispatch", R, 'if tools is not None and dispatch is not None:', "if False:"),
61
+ ("config-unknown-tool-allowed", R, 'if s["type"] == "tool" and s["tool"] not in tools:', "if False:"),
62
+ # --- flow: validation
63
+ ("cycle-allowed", F, "if state.get(t) == 1:", "if False:"),
64
+ ("unreachable-allowed", F, "if set(state) != ids:", "if False:"),
65
+ ("read-before-run-union", F, "res = set.intersection(*sets) if sets else set()", "res = set.union(*sets) if sets else set()"),
66
+ ("dup-ids-allowed", F, 's["id"] in steps or s["id"] in _RESERVED', 's["id"] in _RESERVED'),
67
+ ("input-id-allowed", F, 's["id"] in steps or s["id"] in _RESERVED', 's["id"] in steps'),
68
+ ("unknown-keys-allowed", F, "if k not in required and k not in optional:", "if False:"),
69
+ ("dup-json-keys-allowed", F, "if k in out:", "if False:"),
70
+ ("nan-in-json-allowed", F, 'raise _fail("NaN and Infinity are not allowed in a flow file")', "return 0"),
71
+ ("version-bool-accepted", F, 'if not _is_int(d["version"]) or d["version"] != 1:', 'if d["version"] != 1:'),
72
+ ("step-cap-off", F, "if not isinstance(raw, list) or not 1 <= len(raw) <= MAX_STEPS:", "if not isinstance(raw, list) or not 1 <= len(raw):"),
73
+ ("file-size-cap-off", F, "if len(canonical(d).encode(\"ascii\")) > MAX_FLOW_BYTES:", "if False:"),
74
+ ("text-size-cap-off", F, 'if len(text.encode("utf-8")) > MAX_FLOW_BYTES:', "if False:"),
75
+ ("prompt-cap-off", F, "1 <= len(s[\"prompt\"]) <= MAX_PROMPT_CHARS", "1 <= len(s[\"prompt\"])"),
76
+ ("nested-value-cap-off", F, "if depth > MAX_DEPTH:\n raise _fail(\"a value is nested too deeply\")", "if False:\n raise _fail(\"a value is nested too deeply\")"),
77
+ ("in-needs-list-off", F, 'if c["op"] == "in" and not isinstance(c["value"], list):', "if False:"),
78
+ ("novalue-op-with-value", F, 'if "value" in c:\n raise _fail("this operator takes no value")', 'if False:\n raise _fail("this operator takes no value")'),
79
+ # --- flow: paths and conditions
80
+ # dropped as equivalent: parse_path's startswith('$$') clause is also enforced by the segment regex ($ is not allowed)
81
+ ("literal-dollar-not-unescaped", F, "return template[1:]", "return template"),
82
+ ("list-leading-zero-allowed", F, "(len(seg) > 1 and seg[0] == \"0\") or ", ""),
83
+ ("list-out-of-range-allowed", F, "or int(seg) >= len(cur):", ":"),
84
+ ("missing-key-returns-none", F, "if seg not in cur:\n raise Missing()\n cur = cur[seg]", "cur = cur.get(seg)"),
85
+ ("missing-satisfies-condition", F, " except Missing:\n return False\n if op ==", " except Missing:\n return True\n if op =="),
86
+ ("bool-equals-int", F, "if isinstance(a, bool) or isinstance(b, bool):\n return isinstance(a, bool) and isinstance(b, bool) and a == b", "if False:\n pass"),
87
+ ("bool-compares-as-number", F, "if isinstance(v, bool) or isinstance(ref, bool):\n return False", "if False:\n return False"),
88
+ ("string-vs-number-compares", F, "if not (both_num or both_str):", "if False:"),
89
+ ("all-becomes-any", F, 'return all(eval_cond(x, values) for x in c["all"])', 'return any(eval_cond(x, values) for x in c["all"])'),
90
+ ("any-becomes-all", F, 'return any(eval_cond(x, values) for x in c["any"])', 'return all(eval_cond(x, values) for x in c["any"])'),
91
+ ("gt-becomes-ge", F, '"gt": v > ref', '"gt": v >= ref'),
92
+ ("lt-becomes-le", F, '"lt": v < ref', '"lt": v <= ref'),
93
+ ]
94
+
95
+
96
+ def run_tests(pkg_dir):
97
+ env = dict(os.environ, PYTHONPATH=os.path.join(pkg_dir, "src"))
98
+ p = subprocess.run([sys.executable, "-m", "pytest", "-x", "-q", "-p", "no:cacheprovider", "tests"], cwd=pkg_dir,
99
+ env=env, capture_output=True, text=True, timeout=600)
100
+ return p.returncode, p.stdout[-300:]
101
+
102
+
103
+ def main():
104
+ ap = argparse.ArgumentParser()
105
+ ap.add_argument("--results", default=os.path.join(tempfile.gettempdir(), "flows_mutations.tsv"))
106
+ args = ap.parse_args()
107
+ here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
108
+ done = {}
109
+ if os.path.exists(args.results):
110
+ for line in open(args.results):
111
+ name, _, verdict = line.rstrip("\n").partition("\t")
112
+ done[name] = verdict
113
+ names = [m[0] for m in MUTATIONS]
114
+ assert len(set(names)) == len(names), "duplicate mutation names"
115
+ with tempfile.TemporaryDirectory() as tmp:
116
+ work = os.path.join(tmp, "pkg")
117
+ shutil.copytree(here, work, ignore=shutil.ignore_patterns("__pycache__", ".pytest_cache", "*.egg-info"))
118
+ rc, out = run_tests(work)
119
+ assert rc == 0, "baseline fails: " + out
120
+ for name, rel, old, new in MUTATIONS:
121
+ if name in done:
122
+ continue
123
+ path = os.path.join(work, rel)
124
+ src = open(path).read()
125
+ if src.count(old) != 1:
126
+ print("ANCHOR %s: %r matches %d times" % (name, old[:50], src.count(old)))
127
+ open(args.results, "a").write("%s\tANCHOR\n" % name)
128
+ continue
129
+ open(path, "w").write(src.replace(old, new))
130
+ try:
131
+ rc, _ = run_tests(work)
132
+ finally:
133
+ open(path, "w").write(src)
134
+ verdict = "killed" if rc != 0 else "SURVIVED"
135
+ print("%-36s %s" % (name, verdict))
136
+ open(args.results, "a").write("%s\t%s\n" % (name, verdict))
137
+ verdicts = [l.rstrip("\n").split("\t")[1] for l in open(args.results)]
138
+ print("killed %d of %d; survived %d; anchor problems %d" % (verdicts.count("killed"), len(MUTATIONS),
139
+ verdicts.count("SURVIVED"), verdicts.count("ANCHOR")))
140
+ return 0 if verdicts.count("killed") == len(MUTATIONS) else 1
141
+
142
+
143
+ if __name__ == "__main__":
144
+ sys.exit(main())
@@ -0,0 +1,18 @@
1
+ """ragleap_flows - multi-tenant flows as plain JSON data: tool steps, approval checkpoints and branches.
2
+
3
+ Every run belongs to a ragleap_security Scope. See runner.py for the isolation rules and flow.py for the file
4
+ format and the hard limits. Not independently audited.
5
+ """
6
+
7
+ from ragleap_agents import ResumeError
8
+
9
+ from ragleap_flows.flow import (DEADLINE_SECONDS, MAX_FLOW_BYTES, MAX_INPUT_BYTES, MAX_OUTPUT_BYTES, MAX_STATE_BYTES,
10
+ MAX_STEPS, Flow, FlowError, from_dict, from_json)
11
+ from ragleap_flows.runner import FlowResult, FlowRunner
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ __all__ = [
16
+ "DEADLINE_SECONDS", "Flow", "FlowError", "FlowResult", "FlowRunner", "MAX_FLOW_BYTES", "MAX_INPUT_BYTES",
17
+ "MAX_OUTPUT_BYTES", "MAX_STATE_BYTES", "MAX_STEPS", "ResumeError", "__version__", "from_dict", "from_json",
18
+ ]