openadapt-kernel 0.1.0__py3-none-any.whl
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.
- openadapt_kernel/__init__.py +147 -0
- openadapt_kernel/aci.py +82 -0
- openadapt_kernel/cli.py +215 -0
- openadapt_kernel/copilot.py +338 -0
- openadapt_kernel/extension_bridge.py +134 -0
- openadapt_kernel/fsm.py +198 -0
- openadapt_kernel/interceptor.py +262 -0
- openadapt_kernel/ledger.py +379 -0
- openadapt_kernel/macro.py +354 -0
- openadapt_kernel/mcp_server.py +224 -0
- openadapt_kernel/oracles.py +317 -0
- openadapt_kernel/probe.py +100 -0
- openadapt_kernel/registry.py +145 -0
- openadapt_kernel/runner.py +292 -0
- openadapt_kernel-0.1.0.dist-info/METADATA +52 -0
- openadapt_kernel-0.1.0.dist-info/RECORD +19 -0
- openadapt_kernel-0.1.0.dist-info/WHEEL +4 -0
- openadapt_kernel-0.1.0.dist-info/entry_points.txt +2 -0
- openadapt_kernel-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
"""Shadow-to-Autopilot induction, 4-mutant offline qualification, Micro-Handoff, and Ed25519 receipts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
from dataclasses import asdict, dataclass, field
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Tuple
|
|
11
|
+
from urllib.parse import urlparse
|
|
12
|
+
|
|
13
|
+
from cryptography.hazmat.primitives import serialization
|
|
14
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
|
|
15
|
+
|
|
16
|
+
from openadapt_kernel.ledger import ObligationLedger
|
|
17
|
+
|
|
18
|
+
AutonomyStage = Literal["SHADOW", "DRAFT_TO_COMMIT", "VERIFIED_AUTOPILOT"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _utc_now() -> str:
|
|
22
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class ShadowTrace:
|
|
27
|
+
"""One passive observation of a live human workflow completion (zero actuation)."""
|
|
28
|
+
|
|
29
|
+
trace_id: str
|
|
30
|
+
portal_origin: str
|
|
31
|
+
source_dossier: Dict[str, str]
|
|
32
|
+
submitted_fields: Dict[str, str]
|
|
33
|
+
readback_url: str
|
|
34
|
+
readback_text: str
|
|
35
|
+
confirmation_ref: Optional[str] = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class PortalPack:
|
|
40
|
+
"""Zero-PII structural pack shared across tenants on the same portal."""
|
|
41
|
+
|
|
42
|
+
pack_id: str
|
|
43
|
+
portal_origin: str
|
|
44
|
+
variable_fields: List[str]
|
|
45
|
+
static_defaults: Dict[str, str]
|
|
46
|
+
provenance_map: Dict[str, str] # target_field -> source_dossier_key
|
|
47
|
+
readback_url_pattern: str
|
|
48
|
+
stage: AutonomyStage = "SHADOW"
|
|
49
|
+
shadow_passes: int = 0
|
|
50
|
+
edge_branches: Dict[str, Dict[str, str]] = field(default_factory=dict)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class MutantQualificationReport:
|
|
55
|
+
qualified: bool
|
|
56
|
+
pre_write_refuted: bool
|
|
57
|
+
toast_only_refuted: bool
|
|
58
|
+
field_perturbation_refuted: bool
|
|
59
|
+
theme_jitter_verified: bool
|
|
60
|
+
reasons: List[str] = field(default_factory=list)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass
|
|
64
|
+
class MicroHandoffRequest:
|
|
65
|
+
step_id: str
|
|
66
|
+
prompt: str
|
|
67
|
+
staged_count: int
|
|
68
|
+
total_steps: int
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class ShadowObserver:
|
|
72
|
+
"""Induces zero-PII PortalPacks from passive human runs with no staging DB."""
|
|
73
|
+
|
|
74
|
+
@staticmethod
|
|
75
|
+
def induce_portal_pack(pack_id: str, traces: Sequence[ShadowTrace]) -> PortalPack:
|
|
76
|
+
if not traces:
|
|
77
|
+
raise ValueError("At least one ShadowTrace is required to induce a PortalPack")
|
|
78
|
+
|
|
79
|
+
origin = traces[0].portal_origin
|
|
80
|
+
all_fields = sorted({k for t in traces for k in t.submitted_fields})
|
|
81
|
+
static_defaults: Dict[str, str] = {}
|
|
82
|
+
variable_fields: List[str] = []
|
|
83
|
+
provenance_map: Dict[str, str] = {}
|
|
84
|
+
|
|
85
|
+
for fname in all_fields:
|
|
86
|
+
vals = [t.submitted_fields.get(fname, "") for t in traces]
|
|
87
|
+
if len(traces) >= 2 and len(set(vals)) == 1:
|
|
88
|
+
static_defaults[fname] = vals[0]
|
|
89
|
+
else:
|
|
90
|
+
variable_fields.append(fname)
|
|
91
|
+
|
|
92
|
+
# Infer SSA provenance when target field matches a source dossier key across runs
|
|
93
|
+
candidate_sources: Optional[set[str]] = None
|
|
94
|
+
for t in traces:
|
|
95
|
+
val = t.submitted_fields.get(fname, "").strip().lower()
|
|
96
|
+
if not val:
|
|
97
|
+
continue
|
|
98
|
+
matching_keys = {
|
|
99
|
+
sk for sk, sv in t.source_dossier.items() if str(sv).strip().lower() == val
|
|
100
|
+
}
|
|
101
|
+
if candidate_sources is None:
|
|
102
|
+
candidate_sources = matching_keys
|
|
103
|
+
else:
|
|
104
|
+
candidate_sources &= matching_keys
|
|
105
|
+
if candidate_sources:
|
|
106
|
+
provenance_map[fname] = sorted(candidate_sources)[0]
|
|
107
|
+
|
|
108
|
+
readback_url = traces[-1].readback_url.split("?")[0]
|
|
109
|
+
return PortalPack(
|
|
110
|
+
pack_id=pack_id,
|
|
111
|
+
portal_origin=origin,
|
|
112
|
+
variable_fields=variable_fields,
|
|
113
|
+
static_defaults=static_defaults,
|
|
114
|
+
provenance_map=provenance_map,
|
|
115
|
+
readback_url_pattern=readback_url,
|
|
116
|
+
stage="SHADOW",
|
|
117
|
+
shadow_passes=len(traces),
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def qualify_verifier_offline(
|
|
122
|
+
*,
|
|
123
|
+
expected_fields: Dict[str, str],
|
|
124
|
+
pre_write_text: str,
|
|
125
|
+
post_write_text: str,
|
|
126
|
+
verifier_fn: Callable[[Dict[str, str], str], bool],
|
|
127
|
+
) -> MutantQualificationReport:
|
|
128
|
+
"""Run the 4-mutant offline 'Plant-and-Catch' qualification suite (zero live writes).
|
|
129
|
+
|
|
130
|
+
Mutant 1 (Pre-Write Frame): must REFUTE.
|
|
131
|
+
Mutant 2 (Toast-Only Splice): pre-write text + fake 'Saved successfully!' toast -> must REFUTE.
|
|
132
|
+
Mutant 3 (Single-Field Perturbation): corrupt one expected field in post-write text -> must REFUTE.
|
|
133
|
+
Mutant 4 (Theme / Whitespace / Codec Jitter): nuisance wrapper/whitespace change -> must VERIFY.
|
|
134
|
+
"""
|
|
135
|
+
if not isinstance(pre_write_text, str) or not pre_write_text.strip():
|
|
136
|
+
raise ValueError("pre_write_text must be a non-empty captured pre-write DOM snapshot")
|
|
137
|
+
if not isinstance(post_write_text, str) or not post_write_text.strip():
|
|
138
|
+
raise ValueError("post_write_text must be a non-empty captured post-write DOM snapshot")
|
|
139
|
+
reasons: List[str] = []
|
|
140
|
+
|
|
141
|
+
pre_write_refuted = not verifier_fn(expected_fields, pre_write_text)
|
|
142
|
+
if not pre_write_refuted:
|
|
143
|
+
reasons.append("pre_write_frame_falsely_verified")
|
|
144
|
+
|
|
145
|
+
toast_text = f"{pre_write_text}\n[Banner] Saved successfully! Changes recorded."
|
|
146
|
+
toast_only_refuted = not verifier_fn(expected_fields, toast_text)
|
|
147
|
+
if not toast_only_refuted:
|
|
148
|
+
reasons.append("toast_only_splice_falsely_verified")
|
|
149
|
+
|
|
150
|
+
perturbed_text = post_write_text
|
|
151
|
+
mutated_any = False
|
|
152
|
+
for val in expected_fields.values():
|
|
153
|
+
if val and val in perturbed_text:
|
|
154
|
+
replacement = f"MUTATED_{hashlib.sha256(val.encode('utf-8')).hexdigest()[:8]}"
|
|
155
|
+
perturbed_text = perturbed_text.replace(val, replacement, 1)
|
|
156
|
+
mutated_any = True
|
|
157
|
+
break
|
|
158
|
+
if not mutated_any:
|
|
159
|
+
perturbed_text = ""
|
|
160
|
+
field_perturbation_refuted = not verifier_fn(expected_fields, perturbed_text)
|
|
161
|
+
if not field_perturbation_refuted:
|
|
162
|
+
reasons.append("single_field_perturbation_falsely_verified")
|
|
163
|
+
|
|
164
|
+
jitter_text = f" [theme:dark-v2]\n{post_write_text.replace(' ', ' ')}\n[footer:build-99] "
|
|
165
|
+
theme_jitter_verified = bool(verifier_fn(expected_fields, jitter_text))
|
|
166
|
+
if not theme_jitter_verified:
|
|
167
|
+
reasons.append("theme_codec_jitter_falsely_refuted")
|
|
168
|
+
|
|
169
|
+
qualified = (
|
|
170
|
+
pre_write_refuted
|
|
171
|
+
and toast_only_refuted
|
|
172
|
+
and field_perturbation_refuted
|
|
173
|
+
and theme_jitter_verified
|
|
174
|
+
)
|
|
175
|
+
return MutantQualificationReport(
|
|
176
|
+
qualified=qualified,
|
|
177
|
+
pre_write_refuted=pre_write_refuted,
|
|
178
|
+
toast_only_refuted=toast_only_refuted,
|
|
179
|
+
field_perturbation_refuted=field_perturbation_refuted,
|
|
180
|
+
theme_jitter_verified=theme_jitter_verified,
|
|
181
|
+
reasons=reasons,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class MicroHandoffSession:
|
|
186
|
+
"""Suspends execution at a single blocked control and assimilates the human's 1-click fix."""
|
|
187
|
+
|
|
188
|
+
def __init__(self, pack: PortalPack, steps: Sequence[Dict[str, Any]]) -> None:
|
|
189
|
+
self.pack = pack
|
|
190
|
+
self.steps = list(steps)
|
|
191
|
+
self.cursor = 0
|
|
192
|
+
self.completed_steps: List[str] = []
|
|
193
|
+
self.pending_handoff: Optional[MicroHandoffRequest] = None
|
|
194
|
+
|
|
195
|
+
def run_until_blocked(
|
|
196
|
+
self, executor: Callable[[Dict[str, Any]], bool]
|
|
197
|
+
) -> Tuple[Literal["COMPLETED", "AWAITING_MICRO_HANDOFF"], Optional[MicroHandoffRequest]]:
|
|
198
|
+
while self.cursor < len(self.steps):
|
|
199
|
+
step = self.steps[self.cursor]
|
|
200
|
+
branch_key = str(step.get("branch_key") or "")
|
|
201
|
+
if branch_key and branch_key in self.pack.edge_branches:
|
|
202
|
+
step = {**step, **self.pack.edge_branches[branch_key]}
|
|
203
|
+
self.steps[self.cursor] = step
|
|
204
|
+
if executor(step):
|
|
205
|
+
self.completed_steps.append(str(step.get("step_id", self.cursor)))
|
|
206
|
+
self.cursor += 1
|
|
207
|
+
else:
|
|
208
|
+
req = MicroHandoffRequest(
|
|
209
|
+
step_id=str(step.get("step_id", self.cursor)),
|
|
210
|
+
prompt=str(step.get("prompt") or f"Resolve control for step {self.cursor}"),
|
|
211
|
+
staged_count=self.cursor,
|
|
212
|
+
total_steps=len(self.steps),
|
|
213
|
+
)
|
|
214
|
+
self.pending_handoff = req
|
|
215
|
+
return "AWAITING_MICRO_HANDOFF", req
|
|
216
|
+
self.pending_handoff = None
|
|
217
|
+
return "COMPLETED", None
|
|
218
|
+
|
|
219
|
+
def resolve_micro_handoff(self, resolution: Dict[str, str]) -> None:
|
|
220
|
+
"""Record the operator's 1-click fix, update the PortalPack, and advance past the step."""
|
|
221
|
+
if self.pending_handoff is None:
|
|
222
|
+
raise RuntimeError("No pending micro-handoff to resolve")
|
|
223
|
+
step = self.steps[self.cursor]
|
|
224
|
+
branch_key = str(step.get("branch_key") or step.get("step_id") or self.cursor)
|
|
225
|
+
self.pack.edge_branches[branch_key] = dict(resolution)
|
|
226
|
+
self.steps[self.cursor] = {**step, **resolution}
|
|
227
|
+
self.completed_steps.append(self.pending_handoff.step_id)
|
|
228
|
+
self.cursor += 1
|
|
229
|
+
self.pending_handoff = None
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def generate_ephemeral_ed25519_keypair() -> Tuple[bytes, bytes]:
|
|
233
|
+
priv = Ed25519PrivateKey.generate()
|
|
234
|
+
priv_pem = priv.private_bytes(
|
|
235
|
+
encoding=serialization.Encoding.PEM,
|
|
236
|
+
format=serialization.PrivateFormat.PKCS8,
|
|
237
|
+
encryption_algorithm=serialization.NoEncryption(),
|
|
238
|
+
)
|
|
239
|
+
pub_pem = priv.public_key().public_bytes(
|
|
240
|
+
encoding=serialization.Encoding.PEM,
|
|
241
|
+
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
|
242
|
+
)
|
|
243
|
+
return priv_pem, pub_pem
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
TERMINAL_RECEIPT_OUTCOMES = frozenset(
|
|
247
|
+
{"VERIFIED", "HALTED", "FAILED", "PREPARE_REQUIRED", "ESCALATED", "READY_FOR_HUMAN_COMMIT"}
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _origin_host_only(value: str) -> str:
|
|
252
|
+
raw = str(value or "").strip()
|
|
253
|
+
if not raw:
|
|
254
|
+
return ""
|
|
255
|
+
parsed = urlparse(raw)
|
|
256
|
+
if parsed.hostname:
|
|
257
|
+
return parsed.hostname.lower()
|
|
258
|
+
if parsed.scheme:
|
|
259
|
+
return parsed.scheme.lower()
|
|
260
|
+
return "local" if raw.startswith("/") else raw
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _sha256_hex(val: str) -> str:
|
|
264
|
+
return hashlib.sha256(str(val).encode("utf-8")).hexdigest()
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def mint_receipt(
|
|
268
|
+
ledger: ObligationLedger,
|
|
269
|
+
workflow_name: str,
|
|
270
|
+
private_key_pem: bytes,
|
|
271
|
+
*,
|
|
272
|
+
allow_escalation_receipt: bool = False,
|
|
273
|
+
include_plaintext_values: bool = False,
|
|
274
|
+
outcome_override: Optional[str] = None,
|
|
275
|
+
) -> Dict[str, Any]:
|
|
276
|
+
"""Mint an Ed25519-signed openadapt.kernel.receipt/v1 artifact (zero-PHI redacted by default)."""
|
|
277
|
+
outcome = outcome_override or ledger.status
|
|
278
|
+
if outcome not in TERMINAL_RECEIPT_OUTCOMES and not allow_escalation_receipt:
|
|
279
|
+
raise ValueError(f"Cannot mint receipt for non-terminal outcome {outcome!r}")
|
|
280
|
+
|
|
281
|
+
obligations_payload: Dict[str, Any] = {}
|
|
282
|
+
for oid, ob in ledger.obligations.items():
|
|
283
|
+
if ob.readback_proof is None:
|
|
284
|
+
proof_obj: Optional[Dict[str, Any]] = None
|
|
285
|
+
elif include_plaintext_values:
|
|
286
|
+
proof_obj = asdict(ob.readback_proof)
|
|
287
|
+
else:
|
|
288
|
+
proof_obj = {
|
|
289
|
+
"channel": ob.readback_proof.channel,
|
|
290
|
+
"origin_host": _origin_host_only(ob.readback_proof.url_or_locator),
|
|
291
|
+
"cited_value_sha256": [_sha256_hex(s) for s in ob.readback_proof.cited_substrings],
|
|
292
|
+
"external_ref_sha256": (
|
|
293
|
+
_sha256_hex(ob.readback_proof.external_ref) if ob.readback_proof.external_ref else None
|
|
294
|
+
),
|
|
295
|
+
"observed_at_utc": ob.readback_proof.observed_at_utc,
|
|
296
|
+
}
|
|
297
|
+
target_sys = ob.target_system if include_plaintext_values else _origin_host_only(ob.target_system)
|
|
298
|
+
obligations_payload[oid] = {
|
|
299
|
+
"state": ob.state,
|
|
300
|
+
"target_system": target_sys,
|
|
301
|
+
"proof": proof_obj,
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
payload = {
|
|
305
|
+
"schema": "openadapt.kernel.receipt/v1",
|
|
306
|
+
"episode_id": ledger.episode_id,
|
|
307
|
+
"workflow_name": workflow_name,
|
|
308
|
+
"outcome": outcome,
|
|
309
|
+
"redacted": not include_plaintext_values,
|
|
310
|
+
"escalation_reason": ledger.escalation_reason,
|
|
311
|
+
"issued_at_utc": _utc_now(),
|
|
312
|
+
"obligations": obligations_payload,
|
|
313
|
+
}
|
|
314
|
+
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
|
315
|
+
digest = hashlib.sha256(canonical).hexdigest()
|
|
316
|
+
priv = serialization.load_pem_private_key(private_key_pem, password=None)
|
|
317
|
+
assert isinstance(priv, Ed25519PrivateKey)
|
|
318
|
+
sig = priv.sign(canonical)
|
|
319
|
+
return {
|
|
320
|
+
"payload": payload,
|
|
321
|
+
"sha256": digest,
|
|
322
|
+
"signature_b64": base64.b64encode(sig).decode("ascii"),
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def verify_receipt(receipt: Dict[str, Any], public_key_pem: bytes) -> bool:
|
|
327
|
+
"""Verify Ed25519 signature and SHA-256 digest offline."""
|
|
328
|
+
try:
|
|
329
|
+
payload = receipt["payload"]
|
|
330
|
+
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
|
331
|
+
if hashlib.sha256(canonical).hexdigest() != receipt["sha256"]:
|
|
332
|
+
return False
|
|
333
|
+
pub = serialization.load_pem_public_key(public_key_pem)
|
|
334
|
+
assert isinstance(pub, Ed25519PublicKey)
|
|
335
|
+
pub.verify(base64.b64decode(receipt["signature_b64"]), canonical)
|
|
336
|
+
return True
|
|
337
|
+
except Exception:
|
|
338
|
+
return False
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""Bridge between Chrome MV3 extension_evidence.jsonl logs and openadapt-kernel.
|
|
2
|
+
|
|
3
|
+
Ingests passive human recordings emitted by the OpenAdapt Co-Pilot extension
|
|
4
|
+
(DOM input/click events, redacted network_save POST/PUT/PATCH/DELETE events,
|
|
5
|
+
and frame_focus transitions) to induce zero-PII PortalPacks and drive
|
|
6
|
+
Shadow -> Draft-to-Commit -> Verified Autopilot workflows.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Dict, List, Optional, Sequence
|
|
15
|
+
|
|
16
|
+
from openadapt_kernel.copilot import PortalPack, ShadowObserver, ShadowTrace
|
|
17
|
+
from openadapt_kernel.interceptor import CommitInterceptor, NetworkEvent, is_search_or_filter_field
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class ExtensionSessionSummary:
|
|
22
|
+
portal_origin: str
|
|
23
|
+
submitted_fields: Dict[str, str]
|
|
24
|
+
mutating_requests: List[NetworkEvent]
|
|
25
|
+
readback_url: str
|
|
26
|
+
readback_text: str
|
|
27
|
+
secret_fields_skipped: int = 0
|
|
28
|
+
pre_write_text: str = ""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def parse_extension_evidence_jsonl(path: Path) -> ExtensionSessionSummary:
|
|
32
|
+
"""Parse one extension_evidence.jsonl recording into fields and wire saves."""
|
|
33
|
+
origin = ""
|
|
34
|
+
submitted_fields: Dict[str, str] = {}
|
|
35
|
+
mutating_requests: List[NetworkEvent] = []
|
|
36
|
+
readback_url = ""
|
|
37
|
+
readback_text = ""
|
|
38
|
+
pre_write_text = ""
|
|
39
|
+
secret_skipped = 0
|
|
40
|
+
|
|
41
|
+
for raw_line in path.read_text(encoding="utf-8").splitlines():
|
|
42
|
+
line = raw_line.strip()
|
|
43
|
+
if not line:
|
|
44
|
+
continue
|
|
45
|
+
ev: Dict[str, Any] = json.loads(line)
|
|
46
|
+
kind = str(ev.get("kind") or ev.get("type") or "").lower()
|
|
47
|
+
frame_origin = str(ev.get("frame_origin") or ev.get("origin") or "")
|
|
48
|
+
if frame_origin and not origin:
|
|
49
|
+
origin = frame_origin
|
|
50
|
+
|
|
51
|
+
if kind == "network_save":
|
|
52
|
+
method = str(ev.get("method") or "POST").upper()
|
|
53
|
+
url = str(ev.get("url") or "")
|
|
54
|
+
status = ev.get("status")
|
|
55
|
+
mutating_requests.append(
|
|
56
|
+
NetworkEvent(
|
|
57
|
+
method=method,
|
|
58
|
+
url=url,
|
|
59
|
+
status=int(status) if status is not None else None,
|
|
60
|
+
resource_type=str(ev.get("resource_type") or "fetch"),
|
|
61
|
+
post_data_preview=str(ev.get("body_preview") or "")[:200],
|
|
62
|
+
)
|
|
63
|
+
)
|
|
64
|
+
if url:
|
|
65
|
+
readback_url = url
|
|
66
|
+
elif kind in ("input", "change", "field_edit", "select"):
|
|
67
|
+
fname = str(ev.get("field") or ev.get("name") or ev.get("testid") or ev.get("target") or "").strip()
|
|
68
|
+
val = str(ev.get("value") or "")
|
|
69
|
+
if val == "<secret>":
|
|
70
|
+
secret_skipped += 1
|
|
71
|
+
continue
|
|
72
|
+
if not fname:
|
|
73
|
+
continue
|
|
74
|
+
if is_search_or_filter_field(
|
|
75
|
+
fname,
|
|
76
|
+
input_type=str(ev.get("input_type") or ""),
|
|
77
|
+
aria_role=str(ev.get("role") or ""),
|
|
78
|
+
label=str(ev.get("label") or ""),
|
|
79
|
+
):
|
|
80
|
+
continue
|
|
81
|
+
submitted_fields[fname] = val
|
|
82
|
+
elif kind in ("pre_write", "pre_commit", "pre_write_snapshot"):
|
|
83
|
+
if ev.get("text"):
|
|
84
|
+
pre_write_text = str(ev["text"])
|
|
85
|
+
elif kind in ("readback", "confirmation", "page_summary"):
|
|
86
|
+
if ev.get("url"):
|
|
87
|
+
readback_url = str(ev["url"])
|
|
88
|
+
if ev.get("text"):
|
|
89
|
+
readback_text = str(ev["text"])
|
|
90
|
+
|
|
91
|
+
return ExtensionSessionSummary(
|
|
92
|
+
portal_origin=origin or "unknown",
|
|
93
|
+
submitted_fields=submitted_fields,
|
|
94
|
+
mutating_requests=mutating_requests,
|
|
95
|
+
readback_url=readback_url,
|
|
96
|
+
readback_text=readback_text,
|
|
97
|
+
secret_fields_skipped=secret_skipped,
|
|
98
|
+
pre_write_text=pre_write_text,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def induce_pack_from_extension_recordings(
|
|
103
|
+
pack_id: str,
|
|
104
|
+
sessions: Sequence[tuple[Path, Dict[str, str], Optional[str]]],
|
|
105
|
+
) -> PortalPack:
|
|
106
|
+
"""Induce a zero-PII PortalPack from (evidence_jsonl_path, source_dossier, ref) tuples."""
|
|
107
|
+
traces: List[ShadowTrace] = []
|
|
108
|
+
for idx, (jsonl_path, dossier, ref) in enumerate(sessions, start=1):
|
|
109
|
+
summary = parse_extension_evidence_jsonl(jsonl_path)
|
|
110
|
+
traces.append(
|
|
111
|
+
ShadowTrace(
|
|
112
|
+
trace_id=f"ext-{idx}",
|
|
113
|
+
portal_origin=summary.portal_origin,
|
|
114
|
+
source_dossier=dossier,
|
|
115
|
+
submitted_fields=summary.submitted_fields,
|
|
116
|
+
readback_url=summary.readback_url,
|
|
117
|
+
readback_text=summary.readback_text,
|
|
118
|
+
confirmation_ref=ref,
|
|
119
|
+
)
|
|
120
|
+
)
|
|
121
|
+
return ShadowObserver.induce_portal_pack(pack_id, traces)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def replay_evidence_into_interceptor(
|
|
125
|
+
summary: ExtensionSessionSummary,
|
|
126
|
+
interceptor: CommitInterceptor,
|
|
127
|
+
) -> bool:
|
|
128
|
+
"""Feed parsed extension evidence into CommitInterceptor and return True if a commit occurred."""
|
|
129
|
+
interceptor.begin_step()
|
|
130
|
+
for fname, val in summary.submitted_fields.items():
|
|
131
|
+
interceptor.mark_field_edited(fname, val)
|
|
132
|
+
for req in summary.mutating_requests:
|
|
133
|
+
interceptor.record_network_event(req)
|
|
134
|
+
return interceptor.classify_step().is_commit
|
openadapt_kernel/fsm.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Formal UI State Machine (PortalFSM) compiler and pre-execution safety model checker.
|
|
2
|
+
|
|
3
|
+
Compiles passive shadow traces into a typed finite-state machine over portal states
|
|
4
|
+
and wire-verified transitions, then statically verifies three safety properties
|
|
5
|
+
before any click is executed:
|
|
6
|
+
1. No Double-Commit: no reachable path may traverse a mutating commit edge twice
|
|
7
|
+
for the same obligation without an explicit idempotency key.
|
|
8
|
+
2. Consent Dominance: every path reaching a consent-gated commit edge must carry
|
|
9
|
+
a verified capability token for that scope.
|
|
10
|
+
3. Subject Isolation: every opaque literal bound on a commit edge must originate
|
|
11
|
+
from the active episode's subject_key (blocking cross-patient/tenant leaks).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import Dict, List, Optional, Sequence, Set, Tuple
|
|
18
|
+
|
|
19
|
+
from openadapt_kernel.copilot import ShadowTrace
|
|
20
|
+
from openadapt_kernel.ledger import ObligationLedger
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class FSMState:
|
|
25
|
+
state_id: str
|
|
26
|
+
origin: str
|
|
27
|
+
url_pattern: str
|
|
28
|
+
dom_invariants: Tuple[str, ...] = ()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class FSMTransition:
|
|
33
|
+
transition_id: str
|
|
34
|
+
from_state: str
|
|
35
|
+
to_state: str
|
|
36
|
+
action_label: str
|
|
37
|
+
http_method: str = "GET"
|
|
38
|
+
is_commit: bool = False
|
|
39
|
+
idempotency_key: Optional[str] = None
|
|
40
|
+
required_consent_scope: Optional[str] = None
|
|
41
|
+
bound_fields: Tuple[str, ...] = ()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class SafetyViolation:
|
|
46
|
+
property_name: str
|
|
47
|
+
detail: str
|
|
48
|
+
path: List[str] = field(default_factory=list)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class SafetyProof:
|
|
53
|
+
safe: bool
|
|
54
|
+
checked_properties: List[str]
|
|
55
|
+
violations: List[SafetyViolation] = field(default_factory=list)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class PortalFSM:
|
|
60
|
+
fsm_id: str
|
|
61
|
+
initial_state: str
|
|
62
|
+
states: Dict[str, FSMState] = field(default_factory=dict)
|
|
63
|
+
transitions: List[FSMTransition] = field(default_factory=list)
|
|
64
|
+
|
|
65
|
+
def add_state(self, state: FSMState) -> None:
|
|
66
|
+
self.states[state.state_id] = state
|
|
67
|
+
|
|
68
|
+
def add_transition(self, tr: FSMTransition) -> None:
|
|
69
|
+
self.transitions.append(tr)
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def compile_from_traces(
|
|
73
|
+
cls,
|
|
74
|
+
fsm_id: str,
|
|
75
|
+
traces: Sequence[ShadowTrace],
|
|
76
|
+
*,
|
|
77
|
+
required_consent_scope: Optional[str] = None,
|
|
78
|
+
idempotency_key: Optional[str] = None,
|
|
79
|
+
) -> "PortalFSM":
|
|
80
|
+
"""Induce a typed 3-state (ENTRY -> STAGED -> VERIFIED_COMMIT) FSM from shadow traces."""
|
|
81
|
+
if not traces:
|
|
82
|
+
raise ValueError("compile_from_traces requires at least one ShadowTrace")
|
|
83
|
+
origin = traces[0].portal_origin
|
|
84
|
+
readback = traces[0].readback_url
|
|
85
|
+
fields = tuple(sorted({k for t in traces for k in t.submitted_fields.keys()}))
|
|
86
|
+
|
|
87
|
+
fsm = cls(fsm_id=fsm_id, initial_state="ENTRY")
|
|
88
|
+
fsm.add_state(FSMState("ENTRY", origin, origin, ("form_mounted",)))
|
|
89
|
+
fsm.add_state(FSMState("STAGED", origin, origin, ("fields_staged", "zero_dirty_mismatch")))
|
|
90
|
+
fsm.add_state(FSMState("VERIFIED_COMMIT", origin, readback, ("independent_readback_verified",)))
|
|
91
|
+
fsm.add_transition(
|
|
92
|
+
FSMTransition(
|
|
93
|
+
transition_id="stage_form",
|
|
94
|
+
from_state="ENTRY",
|
|
95
|
+
to_state="STAGED",
|
|
96
|
+
action_label="stage_form",
|
|
97
|
+
http_method="NONE",
|
|
98
|
+
is_commit=False,
|
|
99
|
+
bound_fields=fields,
|
|
100
|
+
)
|
|
101
|
+
)
|
|
102
|
+
fsm.add_transition(
|
|
103
|
+
FSMTransition(
|
|
104
|
+
transition_id="commit_and_readback",
|
|
105
|
+
from_state="STAGED",
|
|
106
|
+
to_state="VERIFIED_COMMIT",
|
|
107
|
+
action_label="submit",
|
|
108
|
+
http_method="POST",
|
|
109
|
+
is_commit=True,
|
|
110
|
+
idempotency_key=idempotency_key,
|
|
111
|
+
required_consent_scope=required_consent_scope,
|
|
112
|
+
bound_fields=fields,
|
|
113
|
+
)
|
|
114
|
+
)
|
|
115
|
+
return fsm
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def verify_fsm_safety(
|
|
119
|
+
fsm: PortalFSM,
|
|
120
|
+
*,
|
|
121
|
+
ledger: Optional[ObligationLedger] = None,
|
|
122
|
+
planned_bindings: Optional[Dict[str, str]] = None,
|
|
123
|
+
opaque_fields: Optional[Sequence[str]] = None,
|
|
124
|
+
active_subject_key: Optional[str] = None,
|
|
125
|
+
literal_subjects: Optional[Dict[str, str]] = None,
|
|
126
|
+
max_depth: int = 12,
|
|
127
|
+
) -> SafetyProof:
|
|
128
|
+
"""Statically verify No Double-Commit, Consent Dominance, and Subject Isolation."""
|
|
129
|
+
violations: List[SafetyViolation] = []
|
|
130
|
+
checked = ["no_double_commit", "consent_dominance", "subject_isolation"]
|
|
131
|
+
|
|
132
|
+
adj: Dict[str, List[FSMTransition]] = {}
|
|
133
|
+
for tr in fsm.transitions:
|
|
134
|
+
adj.setdefault(tr.from_state, []).append(tr)
|
|
135
|
+
|
|
136
|
+
# Bounded DFS over all reachable paths up to max_depth to detect double-commit cycles
|
|
137
|
+
stack: List[Tuple[str, List[str], Set[str]]] = [(fsm.initial_state, [], set())]
|
|
138
|
+
while stack:
|
|
139
|
+
state_id, path, committed_without_key = stack.pop()
|
|
140
|
+
if len(path) >= max_depth:
|
|
141
|
+
continue
|
|
142
|
+
for tr in adj.get(state_id, []):
|
|
143
|
+
next_path = [*path, tr.transition_id]
|
|
144
|
+
next_committed = set(committed_without_key)
|
|
145
|
+
if tr.is_commit:
|
|
146
|
+
if tr.transition_id in committed_without_key and not tr.idempotency_key:
|
|
147
|
+
violations.append(
|
|
148
|
+
SafetyViolation(
|
|
149
|
+
property_name="no_double_commit",
|
|
150
|
+
detail=f"Commit edge {tr.transition_id!r} reachable twice without idempotency_key",
|
|
151
|
+
path=next_path,
|
|
152
|
+
)
|
|
153
|
+
)
|
|
154
|
+
continue
|
|
155
|
+
if not tr.idempotency_key:
|
|
156
|
+
next_committed.add(tr.transition_id)
|
|
157
|
+
if tr.required_consent_scope:
|
|
158
|
+
if ledger is None or not ledger.has_consent(tr.required_consent_scope):
|
|
159
|
+
violations.append(
|
|
160
|
+
SafetyViolation(
|
|
161
|
+
property_name="consent_dominance",
|
|
162
|
+
detail=(
|
|
163
|
+
f"Commit edge {tr.transition_id!r} requires consent scope "
|
|
164
|
+
f"{tr.required_consent_scope!r}"
|
|
165
|
+
),
|
|
166
|
+
path=next_path,
|
|
167
|
+
)
|
|
168
|
+
)
|
|
169
|
+
# Avoid infinite non-commit self-loops while still exploring commit re-entries
|
|
170
|
+
if next_path.count(tr.transition_id) <= 2:
|
|
171
|
+
stack.append((tr.to_state, next_path, next_committed))
|
|
172
|
+
|
|
173
|
+
# Property 3: Subject isolation + SSA provenance check on planned commit bindings
|
|
174
|
+
if planned_bindings and opaque_fields:
|
|
175
|
+
if ledger is not None:
|
|
176
|
+
for pv in ledger.verify_ssa_provenance(planned_bindings, opaque_fields):
|
|
177
|
+
violations.append(
|
|
178
|
+
SafetyViolation(
|
|
179
|
+
property_name="subject_isolation",
|
|
180
|
+
detail=f"Field {pv.field_name!r} failed SSA provenance: {pv.reason}",
|
|
181
|
+
)
|
|
182
|
+
)
|
|
183
|
+
if active_subject_key and literal_subjects:
|
|
184
|
+
for fname in opaque_fields:
|
|
185
|
+
if fname in planned_bindings:
|
|
186
|
+
owner = literal_subjects.get(fname)
|
|
187
|
+
if owner is not None and owner != active_subject_key:
|
|
188
|
+
violations.append(
|
|
189
|
+
SafetyViolation(
|
|
190
|
+
property_name="subject_isolation",
|
|
191
|
+
detail=(
|
|
192
|
+
f"Cross-subject taint on {fname!r}: belongs to {owner!r}, "
|
|
193
|
+
f"active subject is {active_subject_key!r}"
|
|
194
|
+
),
|
|
195
|
+
)
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
return SafetyProof(safe=not violations, checked_properties=checked, violations=violations)
|