-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathaetherra_script_service.py
More file actions
1937 lines (1821 loc) · 80.1 KB
/
Copy pathaetherra_script_service.py
File metadata and controls
1937 lines (1821 loc) · 80.1 KB
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
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2025 Aetherra Labs and Contributors
"""
Aetherra Script Service
=======================
(c) Aetherra Labs. Proprietary Aether Script interpreter scaffolding.
Lightweight .aether interpreter for goals, assignments, and memory ops.
This minimal implementation is designed to satisfy current tests and can be
extended to support full EBNF from the specification. Optional signing
verification can be enabled via environment flags for protection.
"""
# Standard library imports
import importlib
import hashlib
import json
import logging
import os
import re
import uuid
from datetime import datetime
from importlib import metadata as importlib_metadata
from pathlib import Path
from typing import Any
# Optional runtime imports kept inside functions to avoid heavy deps on import
try: # Prefer absolute package path
# Aetherra imports
from Aetherra.aetherra_core.memory.aetherra_memory_engine import (
AetherraMemoryEngine,
)
except Exception: # Fallback for variations in path
AetherraMemoryEngine = None # type: ignore
logger = logging.getLogger(__name__)
SIGNATURE_MARKER = "# @signature:"
def _hash_value(value: Any) -> str | None:
if value is None:
return None
raw = str(value)
if not raw:
return None
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def _guardian_capability_checker(requester: str, capability: str) -> bool:
if requester == "aether_script:runtime" and capability in {"script:run"}:
return True
from Aetherra.security.capabilities import has_capability
return has_capability(requester, capability)
def _guardian_preflight_script_execution(
*,
requester: str,
filename: str,
script_content: str,
metadata: dict[str, Any],
):
from Aetherra.guardian import IntentDeclaration, evaluate_intent
approval_id = os.getenv("AETHERRA_GUARDIAN_APPROVAL_ID", "").strip() or None
return evaluate_intent(
IntentDeclaration(
requester=requester,
subsystem="aether_script",
action="script.execute",
target=f"aether_script:{_hash_value(filename)}",
purpose="Execute an Aether Script through the bounded lightweight runtime",
capabilities=("script:run",),
expected_outcome="script parsed and executed with bounded workflow semantics",
reversible=False,
rollback_plan=None,
evidence=("aether_script.execute:request",),
metadata={
**metadata,
"filename_hash": _hash_value(filename),
"script_hash": _hash_value(script_content),
"script_length": len(script_content or ""),
},
),
approval_id=approval_id,
capability_checker=_guardian_capability_checker,
)
class AetherScriptService:
"""Minimal .aether interpreter with async interface."""
def __init__(self, service_registry=None):
self.service_registry = service_registry
self.interpreter_ready = False
self.running = False
self.memory_engine = None
self._last_ctx = {}
self._trace = []
async def initialize(self):
"""Initialize the Aether Script service (no-op for now)."""
# Try to attach to the memory system
try:
if self.service_registry is not None:
mem = self.service_registry.get_service("memory_system")
if mem is not None:
self.memory_engine = mem
if self.memory_engine is None and AetherraMemoryEngine is not None:
# Local memory engine as a fallback
self.memory_engine = AetherraMemoryEngine()
except Exception:
# Keep service usable even if memory system is unavailable
self.memory_engine = None
self.interpreter_ready = True
return True
async def start(self):
self.running = True
return True
async def stop(self):
self.running = False
return True
async def execute_script_file(
self, script_path: str, context: dict | None = None
) -> dict[str, Any]:
text = Path(script_path).read_text(encoding="utf-8")
return await self.execute_script_content(
text, filename=script_path, context=context
)
async def execute_script_content(
self,
script_content: str,
filename: str = "<string>",
context: dict | None = None,
) -> dict[str, Any]:
try:
context = context or {}
guardian_metadata = self._build_guardian_execution_metadata(
script_content,
filename,
)
requester = (
str(context.get("_requester") or "").strip()
or os.getenv("AETHERRA_PRINCIPAL", "").strip()
or "aether_script:runtime"
)
decision = _guardian_preflight_script_execution(
requester=requester,
filename=filename,
script_content=script_content,
metadata=guardian_metadata,
)
if not decision.allowed:
return {
"success": False,
"error": "guardian_denied",
"reason": decision.reason,
"audit_id": decision.audit_id,
"file": filename,
}
# Optional strict signature verification
self._maybe_verify_signature(script_content, filename)
# Prefer block-aware execution for v1.1 features
# Seed a requester principal for capability checks
seeded_context = dict(context)
try:
seeded_context.setdefault("_requester", f"script:{Path(filename).name}")
except Exception:
seeded_context.setdefault("_requester", "aether_script")
results = await self._execute_script_with_blocks(
script_content, seeded_context
)
payload: dict[str, Any] = {"results": results}
# Expose policy and requires for tooling/UX
if isinstance(self._last_ctx, dict):
if "_policy" in self._last_ctx:
payload["policy"] = dict(self._last_ctx.get("_policy", {}))
if "_requires" in self._last_ctx:
payload["requires"] = list(self._last_ctx.get("_requires", []))
if self._last_ctx.get("_transactions"):
payload["transactions"] = list(
self._last_ctx.get("_transactions", [])
)
if "_rollback_tokens" in self._last_ctx:
payload["rollback_tokens"] = list(
self._last_ctx.get("_rollback_tokens", [])
)
if "_rollback_registry" in self._last_ctx:
payload["rollback_registry"] = dict(
self._last_ctx.get("_rollback_registry", {})
)
if "_types" in self._last_ctx:
payload["types"] = dict(self._last_ctx.get("_types", {}))
if "_warnings" in self._last_ctx:
payload["warnings"] = list(self._last_ctx.get("_warnings", []))
if "_verified_capabilities" in self._last_ctx:
payload["verified_capabilities"] = list(
self._last_ctx.get("_verified_capabilities", [])
)
# Optionally expose trace if requested
if os.getenv("AETHERRA_TRACE", "0") == "1":
payload["trace"] = list(self._trace)
# Persist audit trail metadata (model/seed/cost/tokens/prompts sanitized)
import contextlib
with contextlib.suppress(Exception):
self._audit_run(script_content, payload, context, filename)
return {"success": True, "result": payload}
except Exception as e:
logger.error(f"[AETHER] Execute failed: {e}")
return {"success": False, "error": str(e), "file": filename}
async def _execute_script_with_blocks(
self, script_content: str, context: dict[str, Any]
) -> list[dict[str, Any]]:
"""Block-aware execution supporting if/elif/else, loops, workflow, meta, on_error.
Indentation defines blocks. We normalize by subtracting the minimum indent
from all non-empty, non-comment lines to allow scripts indented in tests.
"""
ctx: dict[str, Any] = dict(context or {})
results: list[dict[str, Any]] = []
self._trace = []
raw_lines = script_content.splitlines()
# Build line records with indent counts
line_recs = []
indents = []
for ln, raw in enumerate(raw_lines, start=1):
stripped = raw.strip()
if not stripped or stripped.startswith("#"):
continue
indent = len(raw) - len(raw.lstrip(" "))
line_recs.append({"line_num": ln, "indent": indent, "text": stripped})
indents.append(indent)
if not line_recs:
self._last_ctx = ctx
return results
base = min(indents)
for rec in line_recs:
rec["indent"] = max(0, rec["indent"] - base)
# Normalize physical indentation widths into logical levels to support
# nested blocks regardless of absolute space counts (e.g. 4 or 8 spaces).
# Each distinct indent value becomes an incrementing level.
unique_indents = sorted({rec["indent"] for rec in line_recs})
indent_level_map = {val: i for i, val in enumerate(unique_indents)}
for rec in line_recs:
rec["indent"] = indent_level_map[rec["indent"]]
# Recursive block processor
async def process_block(start_idx: int, parent_indent: int) -> int:
idx = start_idx
# Transaction state for this block scope
txn_active = False
txn_ops: list[dict[str, Any]] = []
txn_name = None
while idx < len(line_recs):
rec = line_recs[idx]
if rec["indent"] < parent_indent:
break
if rec["indent"] > parent_indent:
# Shouldn't happen: stray deeper indent without header
idx += 1
continue
text = rec["text"]
line_num = rec["line_num"]
# Transactions (kept compatible with legacy syntax)
if re.match(r"^begin\s+transaction(\s+\w+)?\s*$", text, re.IGNORECASE):
if txn_active:
raise ValueError("nested transactions not supported")
txn_active = True
m = re.match(
r"^begin\s+transaction(?:\s+(\w+))?\s*$", text, re.IGNORECASE
)
txn_name = m.group(1) if m else None
self._trace.append(
{"type": "txn_begin", "name": txn_name, "line": line_num}
)
results.append(
{
"type": "transaction_begin",
"name": txn_name,
"line": line_num,
}
)
idx += 1
continue
if re.match(r"^commit\s+transaction\s*$", text, re.IGNORECASE):
if not txn_active:
raise ValueError("commit without active transaction")
summary = {
"type": "transaction_commit",
"name": txn_name,
"ops": len(txn_ops),
"line": line_num,
}
results.append(summary)
self._trace.append(
{
"type": "txn_commit",
"name": txn_name,
"ops": len(txn_ops),
"line": line_num,
}
)
ctx.setdefault("_transactions", []).append(
{"name": txn_name, "ops": list(txn_ops)}
)
txn_active = False
txn_ops = []
txn_name = None
idx += 1
continue
if re.match(r"^rollback\s+transaction\s*$", text, re.IGNORECASE):
if not txn_active:
raise ValueError("rollback without active transaction")
results.append(
{
"type": "transaction_rollback",
"name": txn_name,
"ops": len(txn_ops),
"line": line_num,
}
)
self._trace.append(
{
"type": "txn_rollback",
"name": txn_name,
"ops": len(txn_ops),
"line": line_num,
}
)
txn_active = False
txn_ops = []
txn_name = None
idx += 1
continue
# Conditional: if/elif/else chain
if re.match(r"^if\s+.+$", text, re.IGNORECASE):
# Collect branches at this indent
branches = [] # list of (kind, expr or None, block_start, block_end)
# IF branch
if_block_start = idx + 1
# Find block end for IF by scanning until indent <= current and not elif/else of same group
j = if_block_start
while j < len(line_recs) and line_recs[j]["indent"] > parent_indent:
j += 1
branches.append(("if", text[2:].strip(), if_block_start, j))
k = j
# Collect elif/else that follow
while (
k < len(line_recs) and line_recs[k]["indent"] == parent_indent
):
t = line_recs[k]["text"]
if re.match(r"^elif\s+.+$", t, re.IGNORECASE):
bstart = k + 1
m = bstart
while (
m < len(line_recs)
and line_recs[m]["indent"] > parent_indent
):
m += 1
branches.append(("elif", t[4:].strip(), bstart, m))
k = m
continue
if re.match(r"^else\s*$", t, re.IGNORECASE):
bstart = k + 1
m = bstart
while (
m < len(line_recs)
and line_recs[m]["indent"] > parent_indent
):
m += 1
branches.append(("else", None, bstart, m))
k = m
continue
break
# Evaluate branches
chosen = None
for kind, expr, bstart, bend in branches:
ok = False
if kind == "else":
ok = True
else:
try:
ok = bool(self._eval_expression(expr, ctx))
except Exception:
ok = False
if ok:
chosen = (kind, bstart, bend)
break
results.append(
{
"type": "conditional",
"line": line_num,
"branches": [b[0] for b in branches],
"taken": chosen[0] if chosen else None,
}
)
# Execute chosen block
if chosen:
_, bstart, bend = chosen
await process_block(bstart, parent_indent + 1)
# Advance index to end of chain
idx = k
continue
# For loop: for var in expr
m_for = re.match(
r"^for\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\s+(.+)$", text, re.IGNORECASE
)
if m_for:
var = m_for.group(1)
expr = m_for.group(2).strip()
# Locate block
block_start = idx + 1
j = block_start
while j < len(line_recs) and line_recs[j]["indent"] > parent_indent:
j += 1
seq = self._eval_expression(expr, ctx)
iterations = 0
if isinstance(seq, (list, tuple)):
for item in seq:
ctx[var] = item
await process_block(block_start, parent_indent + 1)
iterations += 1
results.append(
{
"type": "for_loop",
"line": line_num,
"var": var,
"iterations": iterations,
}
)
idx = j
continue
# While loop: while condition
m_while = re.match(r"^while\s+(.+)$", text, re.IGNORECASE)
if m_while:
cond_expr = m_while.group(1).strip()
block_start = idx + 1
j = block_start
while j < len(line_recs) and line_recs[j]["indent"] > parent_indent:
j += 1
iterations = 0
max_iter = 1000
while iterations < max_iter and bool(
self._eval_expression(cond_expr, ctx)
):
await process_block(block_start, parent_indent + 1)
iterations += 1
results.append(
{
"type": "while_loop",
"line": line_num,
"iterations": iterations,
}
)
idx = j
continue
# Workflow block
if re.match(r"^workflow\s*$", text, re.IGNORECASE):
block_start = idx + 1
j = block_start
while j < len(line_recs) and line_recs[j]["indent"] > parent_indent:
j += 1
# Parse inner lines
steps = []
props = {}
k2 = block_start
while k2 < j:
inner = line_recs[k2]["text"]
if inner.startswith("- "):
step_line = inner[2:].strip()
# Parse name and optional (args)
head_m = re.match(
r"^([A-Za-z_][A-Za-z0-9_]*)(?:\(([^)]*)\))?(.*)$",
step_line,
)
if head_m:
name = head_m.group(1)
args_raw = (head_m.group(2) or "").strip()
rest = (head_m.group(3) or "").strip()
# Defaults
alias = None
retry = None
timeout_raw_val = None
requires_raw = None
# Extract tokens in any order
am = re.search(
r"\bas\s+([A-Za-z_][A-Za-z0-9_]*)\b", rest
)
if am:
alias = am.group(1)
rm = re.search(r"\bretry=(\d+)\b", rest)
if rm:
retry = rm.group(1)
tm = re.search(
r"\btimeout=(\"([^\"]+)\"|\d+(?:\.\d+)?(?:ms|s|m|h))\b",
rest,
)
if tm:
timeout_raw_val = (
tm.group(2)
if tm.group(2) is not None
else tm.group(1)
)
elif "timeout=" in rest:
# Fallback parsing for timeout value until whitespace
tail = rest.split("timeout=", 1)[1].lstrip()
if tail.startswith('"'):
m_end = re.search(r'"([^"]*)"', tail)
if m_end:
timeout_raw_val = m_end.group(1)
else:
mv = re.match(r"^([^\s]+)", tail)
if mv:
timeout_raw_val = mv.group(1)
qm = re.search(r"\brequires=\[(.*?)\]", rest)
if qm:
requires_raw = qm.group(1)
# Parse positional and keyword args
pos_args: list[Any] = []
kw_args: dict[str, Any] = {}
if args_raw:
for part in args_raw.split(","):
p = part.strip()
if not p:
continue
if "=" in p:
k, v = p.split("=", 1)
kw_args[k.strip()] = self._eval_expression(
v.strip(), ctx
)
else:
pos_args.append(
self._eval_expression(p, ctx)
)
# Requires list
requires: list[str] = []
if requires_raw:
for tok in requires_raw.split(","):
t = tok.strip().strip('"').strip("'")
if t:
requires.append(t)
step_obj: dict[str, Any] = {"name": name}
if pos_args:
step_obj["args"] = pos_args
if kw_args:
step_obj["kwargs"] = kw_args
if alias:
step_obj["as"] = alias
if retry:
step_obj["retry"] = int(retry)
if timeout_raw_val:
raw_timeout = timeout_raw_val.strip('"')
step_obj["timeout"] = raw_timeout
step_obj["timeout_secs"] = self._normalize_duration(
raw_timeout
)
if requires:
step_obj["requires"] = requires
steps.append(step_obj)
else:
# property assignment inside workflow
am = re.match(
r"^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)$", inner
)
if am:
key = am.group(1)
val = self._eval_expression(am.group(2), ctx)
props[key] = val
k2 += 1
# Inherit workflow-level requires into each step if provided as a property list
wf_requires = props.get("requires")
if isinstance(wf_requires, list):
for step in steps:
existing = step.get("requires", [])
if not isinstance(existing, list):
existing = []
merged: list[str] = []
for cap in list(wf_requires) + list(existing):
if cap not in merged:
merged.append(cap)
if merged:
step["requires"] = merged
# Active execution of workflow steps with retry + timeout semantics
executed_steps = []
for step in steps:
exec_result = await self._execute_workflow_step(step, ctx)
executed_steps.append(exec_result)
# Bind alias if provided and step succeeded
if (
step.get("as")
and exec_result.get("success")
and "result" in exec_result
):
ctx[step["as"]] = exec_result["result"]
results.append(
{
"type": "workflow",
"line": line_num,
"steps": executed_steps,
"properties": props,
}
)
idx = j
continue
# Parallel block
if re.match(r"^parallel\s*$", text, re.IGNORECASE):
block_start = idx + 1
j = block_start
while j < len(line_recs) and line_recs[j]["indent"] > parent_indent:
j += 1
pre_count = len(results)
await process_block(block_start, parent_indent + 1)
# Collect only assignments created within this parallel block
assigned_vars = [
r.get("variable")
for r in results[pre_count:]
if r.get("type") == "assignment"
]
results.append(
{
"type": "parallel",
"line": line_num,
"tasks": assigned_vars,
"count": len(assigned_vars),
}
)
idx = j
continue
# Await statement: await a, b, c
m_await = re.match(r"^await\s+(.+)$", text, re.IGNORECASE)
if m_await:
vars_raw = m_await.group(1)
var_names = [v.strip() for v in vars_raw.split(",") if v.strip()]
missing = [v for v in var_names if v not in ctx]
results.append(
{
"type": "await",
"line": line_num,
"vars": var_names,
"missing": missing,
}
)
idx += 1
continue
# Transaction block
if re.match(r"^transaction\s*$", text, re.IGNORECASE):
block_start = idx + 1
j = block_start
while j < len(line_recs) and line_recs[j]["indent"] > parent_indent:
j += 1
# Snapshot context prior to executing transaction body (exclude internal keys)
pre_ctx_snapshot = {
k: v for k, v in ctx.items() if not str(k).startswith("_")
}
pre_count = len(results)
await process_block(block_start, parent_indent + 1)
ops = [r for r in results[pre_count:] if isinstance(r, dict)]
changed_vars: set[str] = set()
simulated_error = False
for r in results[pre_count:]:
if isinstance(r, dict):
if r.get("type") in ("assignment", "typed_assignment"):
var = r.get("variable")
if isinstance(var, str):
changed_vars.add(var)
if r.get("type") == "simulate_error":
simulated_error = True
restore: dict[str, Any] = {}
delete: list[str] = []
for var in changed_vars:
if var in pre_ctx_snapshot:
restore[var] = pre_ctx_snapshot[var]
else:
delete.append(var)
tx_record = {
"type": "transaction",
"line": line_num,
"ops": len(ops),
"ops_count": len(
ops
), # Also expose as ops_count for Option 3 tests
"rollback_token": str(uuid.uuid4()),
"rollback_plan": {"restore": restore, "delete": delete},
"rollback_simulated": bool(simulated_error),
}
results.append(tx_record)
# Store in context for payload exposure
tx_list = ctx.setdefault("_transactions", [])
tx_list.append(tx_record)
# Also collect rollback tokens for convenience
rb = ctx.setdefault("_rollback_tokens", [])
rb.append(tx_record["rollback_token"])
# Registry of rollback plans keyed by token
ctx.setdefault("_rollback_registry", {})[
tx_record["rollback_token"]
] = tx_record["rollback_plan"]
idx = j
continue
# Policy block (indented form)
if re.match(r"^policy\s*$", text, re.IGNORECASE):
block_start = idx + 1
j = block_start
policy_kv = {}
while j < len(line_recs) and line_recs[j]["indent"] > parent_indent:
inner = line_recs[j]["text"]
am = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)$", inner)
if am:
key = am.group(1)
val = self._eval_expression(am.group(2), ctx)
policy_kv[key] = val
j += 1
# Duration normalization: add <key>_secs for keys ending with timeout/duration
for pk, pv in list(policy_kv.items()):
lpk = pk.lower()
if lpk.endswith("timeout") or lpk.endswith("duration"):
secs = None
if isinstance(pv, int | float):
secs = float(pv)
elif isinstance(pv, str):
secs = self._normalize_duration(pv)
if secs is not None:
policy_kv[f"{pk}_secs"] = secs
ctx.setdefault("_policy", {}).update(policy_kv)
results.append({"type": "policy", **policy_kv})
idx = j
continue
# Require block (indented form)
if re.match(r"^require\s*$", text, re.IGNORECASE):
block_start = idx + 1
j = block_start
plugins_list: list[str] = []
capabilities_list: list[str] = []
mode = None
while j < len(line_recs) and line_recs[j]["indent"] > parent_indent:
inner = line_recs[j]["text"]
# Check for plugins = [...] syntax
mplugins_eq = re.match(r"^plugins\s*=\s*(\[.*\])\s*$", inner)
if mplugins_eq:
raw = mplugins_eq.group(1)[1:-1].strip()
if raw:
for tok in raw.split(","):
plugins_list.append(
tok.strip().strip('"').strip("'")
)
j += 1
continue
# Check for capabilities = [...] syntax
mcap_eq = re.match(r"^capabilities\s*=\s*(\[.*\])\s*$", inner)
if mcap_eq:
raw = mcap_eq.group(1)[1:-1].strip()
if raw:
for tok in raw.split(","):
capabilities_list.append(
tok.strip().strip('"').strip("'")
)
j += 1
continue
if re.match(r"^plugins:\s*$", inner):
mode = "plugins"
j += 1
continue
if re.match(r"^capabilities:\s*(\[.*\])?\s*$", inner):
mode = "capabilities"
mcap = re.match(r"^capabilities:\s*(\[.*\])?\s*$", inner)
if mcap and mcap.group(1):
# inline list form capabilities: ["a","b"]
raw = mcap.group(1)[1:-1].strip()
if raw:
for tok in raw.split(","):
capabilities_list.append(
tok.strip().strip('"').strip("'")
)
j += 1
continue
if inner.startswith("-") and mode == "plugins":
pm = re.match(r"^-\s+\"(.+?)\"\s*$", inner)
if pm:
plugins_list.append(pm.group(1))
else:
# allow unquoted dash items
pm2 = re.match(r"^-\s+(.+)$", inner)
if pm2:
plugins_list.append(pm2.group(1).strip())
j += 1
continue
if mode == "capabilities" and inner.startswith("-"):
cm = re.match(r"^-\s+\"(.+?)\"\s*$", inner)
if cm:
capabilities_list.append(cm.group(1))
else:
cm2 = re.match(r"^-\s+(.+)$", inner)
if cm2:
capabilities_list.append(cm2.group(1).strip())
j += 1
continue
# key=value inside require block (ignore unknown)
j += 1
ctx.setdefault("_requires", []).append(
{
"type": "require_block",
"plugins": list(plugins_list),
"capabilities": list(capabilities_list),
}
)
# Soft warnings for missing plugins (best-effort using installed_plugins if available)
try:
plugin_mgr = ctx.get("plugins")
installed = (
getattr(plugin_mgr, "installed_plugins", {})
if plugin_mgr
else {}
)
missing = []
for p in plugins_list:
base = re.split(r"[><=]", p)[0].strip()
if base and base not in installed:
missing.append(p)
if missing:
ctx.setdefault("_warnings", []).append(
"missing_plugins:" + ",".join(missing)
)
except Exception as exc: # noqa: BLE001
import logging
logging.getLogger(__name__).debug(
"Require block plugin scan failed: %s", exc
)
# Capability verification against security policy (if available)
if capabilities_list:
missing_caps: list[str] = []
verified_caps: list[str] = []
requester = ctx.get("_capability_requester") or ctx.get(
"_requester", "aether_script"
)
try:
from Aetherra.security.capabilities import (
has_capability, # type: ignore
)
except Exception:
# Import failed: treat all capabilities as unverified
ctx.setdefault("_warnings", []).append(
"capabilities_unverified:" + ",".join(capabilities_list)
)
else:
for cap in capabilities_list:
try:
if has_capability(str(requester), str(cap)):
verified_caps.append(cap)
else:
missing_caps.append(cap)
except Exception:
missing_caps.append(cap)
if verified_caps:
ctx.setdefault("_verified_capabilities", []).extend(
verified_caps
)
if missing_caps:
ctx.setdefault("_warnings", []).append(
"missing_capabilities:" + ",".join(missing_caps)
)
if (
os.getenv("AETHERRA_REQUIRE_CAPABILITIES", "0")
== "1"
):
# Strict mode: propagate failure (do NOT swallow inside try)
raise ValueError(
"Missing required capabilities: "
+ ",".join(missing_caps)
)
results.append(
{
"type": "require",
"line": line_num,
"plugins": list(plugins_list),
"capabilities": list(capabilities_list),
}
)
idx = j
continue
# Plugin contract block
if re.match(r"^plugin_contract\s*$", text, re.IGNORECASE):
block_start = idx + 1
j = block_start
contract = {}
while j < len(line_recs) and line_recs[j]["indent"] > parent_indent:
inner = line_recs[j]["text"]
am = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)$", inner)
if am:
key = am.group(1)
val = self._eval_expression(am.group(2), ctx)
contract[key] = val
j += 1
results.append({"type": "plugin_contract", **contract})
idx = j
continue
# Meta block
if re.match(r"^meta\s*$", text, re.IGNORECASE):
block_start = idx + 1
j = block_start
meta = {}
while j < len(line_recs) and line_recs[j]["indent"] > parent_indent:
inner = line_recs[j]["text"]
am = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)$", inner)
if am:
key = am.group(1)
val = self._eval_expression(am.group(2), ctx)
meta[key] = val
j += 1
results.append({"type": "meta", **meta})
idx = j
continue
# on_error block
if re.match(r"^on_error\s*$", text, re.IGNORECASE):
block_start = idx + 1
j = block_start
handlers = []
while j < len(line_recs) and line_recs[j]["indent"] > parent_indent:
inner = line_recs[j]["text"]
if inner.startswith("- "):
wm = re.match(r"^-\s+when\s+(.+)$", inner)
if wm:
when = wm.group(1).strip()
else:
j += 1
continue
# next line(s) should be indented more with 'do '
j += 1
if (
j < len(line_recs)
and line_recs[j]["indent"] > parent_indent
):
dm = re.match(r"^do\s+(.+)$", line_recs[j]["text"])
action = dm.group(1).strip() if dm else ""
handlers.append({"when": when, "do": action})
else:
handlers.append({"when": when, "do": ""})
continue
j += 1
results.append({"type": "on_error", "handlers": handlers})
idx = j
continue
# Fallback: single statement execution
stmt_result = await self._execute_statement(text, ctx, line_num)
if stmt_result is not None:
results.append(stmt_result)
self._trace.append(
{"line": line_num, "statement": text, "result": stmt_result}
)
if txn_active and isinstance(stmt_result, dict):
txn_ops.append(
{
"line": line_num,
"op": stmt_result.get("type"),
"idempotent": bool(
stmt_result.get("idempotent", False)
),
}
)
idx += 1
return idx
await process_block(0, 0)
self._last_ctx = ctx
return results
def _eval_expression(self, expr: str, context: dict) -> Any:
"""Simple expression evaluator for literals, variables, comparisons, booleans, lists, and addition.
Note: Intentionally limited for safety and test needs.
"""
s = str(expr).strip()