File size: 40,901 Bytes
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
 
fd11263
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
d26f22a
 
fd11263
 
 
 
 
 
 
 
d26f22a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd11263
d26f22a
 
 
 
 
 
 
 
fd11263
 
d26f22a
 
 
 
 
 
fd11263
d26f22a
 
 
 
 
 
 
 
 
 
 
fd11263
d26f22a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
 
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d26f22a
fd11263
 
 
d26f22a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Concrete agent execution adapters and the shared OpenCode projection."""

from __future__ import annotations

import json
import os
import re
import shutil
import subprocess
import time
import uuid
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable

from ...config import SkillEvaluationConfig
from ...datasets.models import EvaluationCase
from ...models import ExecutionEvidence, SkillBundle, TaskArtifact, TraceRef


def _expected_files(profile: SkillEvaluationConfig) -> list[str]:
    params = profile.params_for("execution", "expected_files_present") or {}
    return list(params.get("expected_files", []) or [])


def _export_info(export: dict[str, Any], *, expected_session_id: str | None = None) -> tuple[dict[str, Any], str]:
    """Validate the small, stable envelope emitted by ``opencode export``."""
    info = export.get("info")
    if not isinstance(info, dict):
        raise ValueError("OpenCode export must contain an info object")
    session_id = info.get("id")
    if not isinstance(session_id, str) or not session_id.strip():
        raise ValueError("OpenCode export info.id must be a non-empty session id")
    if expected_session_id is not None and expected_session_id != session_id:
        raise ValueError(
            f"--session-id {expected_session_id!r} does not match export session {session_id!r}"
        )
    return info, session_id


def project_opencode_export(
    export_path: str | Path,
    case: EvaluationCase,
    *,
    trace_project: str,
    task_workspace: str | Path | None = None,
    expected_session_id: str | None = None,
    run_id: str | None = None,
) -> TaskArtifact:
    """Project a persisted OpenCode export into the common ``TaskArtifact`` seam.

    This function deliberately does not call OpenCode or the evaluation backend.  It only
    translates the export transcript and explicitly supplied workspace into
    execution evidence; trace evaluators read the referenced session through
    the injected ``TraceStore``.
    """
    path = Path(export_path).resolve()
    if not path.is_file():
        raise FileNotFoundError(f"OpenCode export does not exist: {path}")
    try:
        export = json.loads(path.read_text(encoding="utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError) as exc:
        raise ValueError(f"invalid OpenCode export JSON: {path}") from exc
    if not isinstance(export, dict):
        raise ValueError("OpenCode export must contain an object")
    info, session_id = _export_info(export, expected_session_id=expected_session_id)
    # Some export wrappers include the originating case explicitly.  Validate
    # it when present, while accepting native OpenCode exports that have no
    # case field at all.
    exported_case_id = export.get("case_id", info.get("case_id"))
    if exported_case_id is not None and exported_case_id != case.case_id:
        raise ValueError(
            f"export case id {exported_case_id!r} does not match requested case {case.case_id!r}"
        )
    messages = export.get("messages")
    if not isinstance(messages, list) or not messages:
        raise ValueError("OpenCode export must contain a non-empty messages list")

    final_output = ""
    assistant_seen = False
    tool_calls: list[dict[str, Any]] = []
    prompt_tokens = completion_tokens = reasoning_tokens = total_tokens = 0
    finish_reasons: list[str] = []
    export_status = export.get("status", info.get("status"))
    if export_status:
        finish_reasons.append(str(export_status).lower())
    for message in messages:
        if not isinstance(message, dict):
            continue
        message_info = message.get("info") if isinstance(message.get("info"), dict) else {}
        role = message_info.get("role")
        if role == "assistant":
            assistant_seen = True
            tokens = message_info.get("tokens") if isinstance(message_info.get("tokens"), dict) else {}
            cache = tokens.get("cache") if isinstance(tokens.get("cache"), dict) else {}
            prompt_tokens += int(tokens.get("input") or 0) + int(cache.get("read") or 0) + int(cache.get("write") or 0)
            completion_tokens += int(tokens.get("output") or 0)
            reasoning_tokens += int(tokens.get("reasoning") or 0)
            total_tokens += int(tokens.get("total") or 0)
            finish = message_info.get("finish")
            if finish:
                finish_reasons.append(str(finish).lower())
        parts = message.get("parts") if isinstance(message.get("parts"), list) else []
        for part in parts:
            if not isinstance(part, dict):
                continue
            if role == "assistant" and part.get("type") == "text" and isinstance(part.get("text"), str):
                final_output = part["text"].strip() or final_output
            if part.get("type") in {"tool", "tool_use"}:
                state = part.get("state") if isinstance(part.get("state"), dict) else {}
                tool_call = {
                    "name": str(part.get("tool") or state.get("tool") or "unknown"),
                    "status": str(state.get("status", part.get("status", "unknown"))),
                }
                # Keep the structured payload when OpenCode includes it.  It
                # is execution evidence, not a trace fallback, and retaining
                # it makes export replay equivalent to a headless run.
                for key in ("input", "output", "result", "error"):
                    value = state.get(key, part.get(key))
                    if value is not None:
                        tool_call[key] = value
                tool_calls.append(tool_call)

    workspace = Path(task_workspace).resolve() if task_workspace is not None else None
    changed_files: list[str] = []
    refs: list[str] = [path.as_posix()]
    if workspace is not None:
        if not workspace.is_dir():
            raise FileNotFoundError(f"task workspace does not exist: {workspace}")
        output_root = workspace / "ai-output"
        if output_root.is_dir():
            files = sorted(item for item in output_root.rglob("*") if item.is_file())
            changed_files = [item.relative_to(workspace).as_posix() for item in files]
            refs.extend(item.as_posix() for item in files)

    failed = any(token in {"error", "failed", "aborted", "cancelled"} for token in finish_reasons)
    if not assistant_seen:
        failed = True
    status = "failed" if failed else "completed"
    run_id = run_id or f"export-{uuid.uuid4().hex[:12]}"
    output = {
        "final_output": final_output,
        "tool_calls": tool_calls,
        "validation": [],
        "changed_files": changed_files,
    }
    return TaskArtifact(
        run_id=run_id,
        case_id=case.case_id,
        status=status,
        output=output,
        artifact_refs=refs,
        metadata={
            "adapter": "opencode-export",
            "source_export": path.as_posix(),
            "session_id": session_id,
            "trace_project": trace_project,
            "task_workspace": workspace.as_posix() if workspace else None,
            "export_directory": info.get("directory"),
            "token_usage": {
                "prompt": prompt_tokens,
                "completion": completion_tokens,
                "reasoning": reasoning_tokens,
                "total": total_tokens or prompt_tokens + completion_tokens,
            },
            "completion_reasons": finish_reasons,
            "model": info.get("model"),
        },
        execution=ExecutionEvidence(
            final_output=final_output,
            tool_calls=tool_calls,
            changed_files=changed_files,
            task_workspace=workspace.as_posix() if workspace else None,
            returncode=0 if status == "completed" else 1,
        ),
        trace_ref=TraceRef(trace_project, session_id),
    )


@dataclass
class OpenCodeAdapter:
    """Run OpenCode in an isolated task workspace and project its JSONL output."""

    command: list[str]
    parser: Callable[[Path, EvaluationCase, SkillBundle], TaskArtifact] | None = None
    workdir: str | Path | None = None
    run_root: str | Path = "workspace/opencode-runs"
    env: dict[str, str] = field(default_factory=dict)
    model: str | None = None
    # OpenCode's --auto applies to the headless run client.  Keep it opt-in:
    # it approves permissions broadly and is unnecessary when the Skill is
    # staged inside the task workspace (the default path).
    auto_approve: bool = False
    timeout_seconds: float | None = 1800
    # Project used by the reconciler and TraceRef; independent of storage vendor.
    trace_project: str = "subject-opencode"
    server_host: str = "127.0.0.1"
    server_port: int = 4099
    server_url: str | None = None
    flush_wait_seconds: float = 5.0
    server_log_path: str | Path | None = None
    _server_process: subprocess.Popen | None = field(default=None, init=False, repr=False)
    _owns_server: bool = field(default=False, init=False, repr=False)

    @property
    def attach_url(self) -> str:
        return self.server_url or f"http://{self.server_host}:{self.server_port}"

    def _healthy(self) -> bool:
        try:
            with urllib.request.urlopen(f"{self.attach_url}/global/health", timeout=1) as response:
                return 200 <= response.status < 300
        except (OSError, urllib.error.URLError):
            return False

    def _abort_session(self, session_id: str | None, directory: Path | None = None) -> bool:
        """Stop a server-side session after the local client times out."""
        if not session_id:
            return False
        url = f"{self.attach_url}/session/{urllib.parse.quote(session_id, safe='')}"
        url += "/abort"
        if directory is not None:
            url += "?" + urllib.parse.urlencode({"directory": directory.as_posix()})
        request = urllib.request.Request(url, method="POST")
        try:
            with urllib.request.urlopen(request, timeout=5) as response:
                return 200 <= response.status < 300
        except (OSError, urllib.error.URLError):
            return False

    def start(self) -> None:
        """Reuse an external OpenCode server or start one owned by us."""
        if self._server_process is not None and self._server_process.poll() is None and self._owns_server:
            return
        if not self.server_url and self.server_port == 0:
            import socket
            with socket.socket() as sock:
                sock.bind((self.server_host, 0))
                self.server_port = sock.getsockname()[1]
        if self._healthy():
            if self._server_process is None:
                self._owns_server = False
            return
        log_path = Path(self.server_log_path) if self.server_log_path else Path(self.run_root) / "opencode-server.log"
        log_path.parent.mkdir(parents=True, exist_ok=True)
        stream = log_path.open("a", encoding="utf-8")
        process_env = os.environ.copy()
        process_env.update(self.env)
        command = [self.command[0], "serve", "--hostname", self.server_host,
                   "--port", str(self.server_port), "--print-logs"]
        self._server_process = subprocess.Popen(command, cwd=self.workdir, env=process_env,
                                                 stdout=stream, stderr=subprocess.STDOUT)
        self._owns_server = True
        stream.close()
        deadline = time.monotonic() + 30
        while time.monotonic() < deadline:
            if self._healthy():
                self._owns_server = True
                return
            if self._server_process.poll() is not None:
                break
            time.sleep(0.25)
        self.stop()
        raise RuntimeError(f"OpenCode server did not become ready at {self.attach_url}")

    def stop(self) -> None:
        """Stop only a server started by this adapter."""
        process = self._server_process
        self._server_process = None
        if process is None or not self._owns_server:
            self._owns_server = False
            return
        if process.poll() is None:
            process.terminate()
            try:
                process.wait(timeout=10)
            except subprocess.TimeoutExpired:
                process.kill()
                process.wait(timeout=5)
        self._owns_server = False

    def run(self, case: EvaluationCase, skill: SkillBundle, profile: SkillEvaluationConfig) -> TaskArtifact:
        started = time.monotonic()
        run_id = f"opencode-{uuid.uuid4().hex[:12]}"
        task_root = Path(self.run_root).resolve() / case.case_id / run_id
        task_root.mkdir(parents=True, exist_ok=False)
        fixture = self._copy_fixture(case, task_root)
        skill_entrypoint = self._copy_skill(skill, task_root)
        events = task_root / "opencode-events.jsonl"
        stderr_path = task_root / "opencode-stderr.log"
        prompt = self._prompt(case, skill, profile, task_root, fixture, skill_entrypoint)
        command = [part for part in self.command if part != "--auto"]
        if "--attach" not in command:
            command.extend(["--attach", self.attach_url])
        command.extend(["--format", "json"])
        if self.auto_approve:
            command.append("--auto")
        if self.model:
            command.extend(["--model", self.model])
        command.extend(["--dir", str(task_root), prompt])
        process_env = os.environ.copy()
        process_env.update(self.env)
        try:
            with events.open("w", encoding="utf-8") as stream, stderr_path.open("w", encoding="utf-8") as error_stream:
                completed = subprocess.run(command, cwd=self.workdir, env=process_env,
                                           stdout=stream, stderr=error_stream, check=False,
                                           timeout=self.timeout_seconds)
        except subprocess.TimeoutExpired:
            # The child may have emitted a substantial partial JSONL trace
            # before timing out.  Parse it once to recover the server session,
            # abort that session, then parse again after the tracing grace
            # period so the artifact is a stable final snapshot.
            initial = self._parse(events, case, skill, run_id, task_root, fixture)
            trace_ref = initial.trace_ref
            if isinstance(trace_ref, dict):
                trace_ref = TraceRef(str(trace_ref.get("project", self.trace_project)),
                                     str(trace_ref.get("session_id", "")))
            abort_requested = bool(trace_ref and trace_ref.session_id)
            abort_succeeded = self._abort_session(
                trace_ref.session_id if trace_ref else None, task_root
            )
            if self.flush_wait_seconds:
                time.sleep(max(0.0, self.flush_wait_seconds))
            artifact = self._parse(events, case, skill, run_id, task_root, fixture)
            trace_ref = artifact.trace_ref or trace_ref
            duration = time.monotonic() - started
            metadata = {**artifact.metadata, "adapter": "opencode", "command": command,
                        "model": self.model, "duration_seconds": duration,
                        "task_workspace": task_root.as_posix(),
                        "skill_workspace": skill_entrypoint.parent.as_posix(),
                        "skill_entrypoint": skill_entrypoint.as_posix(),
                        "auto_approve": self.auto_approve, "timed_out": True,
                        "abort_requested": abort_requested,
                        "abort_succeeded": abort_succeeded,
                        "returncode": None}
            artifact = TaskArtifact(**{**artifact.to_dict(), "status": "failed",
                "output": {**artifact.output, "error": f"OpenCode timed out after {self.timeout_seconds} seconds"},
                "artifact_refs": list(dict.fromkeys([*artifact.artifact_refs, stderr_path.as_posix()])),
                "metadata": metadata,
                "trace_ref": trace_ref,
                "execution": ExecutionEvidence(
                    final_output=str(artifact.output.get("final_output", "")),
                    tool_calls=list(artifact.output.get("tool_calls", [])),
                    validation=list(artifact.output.get("validation", [])),
                    changed_files=list(artifact.output.get("changed_files", [])),
                    duration_seconds=duration,
                    task_workspace=task_root.as_posix(),
                    returncode=None,
                )})
            return artifact
        time.sleep(max(0.0, self.flush_wait_seconds))
        artifact = self.parser(events, case, skill) if self.parser else self._parse(
            events, case, skill, run_id, task_root, fixture
        )
        metadata = {**artifact.metadata, "duration_seconds": time.monotonic() - started,
                    "returncode": completed.returncode, "task_workspace": task_root.as_posix(),
                    "command": command,
                    "skill_workspace": skill_entrypoint.parent.as_posix(),
                    "skill_entrypoint": skill_entrypoint.as_posix(),
                    "auto_approve": self.auto_approve}
        artifact = TaskArtifact(**{**artifact.to_dict(),
            "artifact_refs": list(dict.fromkeys([*artifact.artifact_refs, stderr_path.as_posix()])),
            "metadata": metadata})
        trace_ref = artifact.trace_ref
        if isinstance(trace_ref, dict):
            trace_ref = TraceRef(str(trace_ref.get("project", self.trace_project)), str(trace_ref.get("session_id", "")))
        artifact = TaskArtifact(**{**artifact.to_dict(), "execution": ExecutionEvidence(
            final_output=str(artifact.output.get("final_output", "")),
            tool_calls=list(artifact.output.get("tool_calls", [])),
            validation=list(artifact.output.get("validation", [])),
            changed_files=list(artifact.output.get("changed_files", [])),
            duration_seconds=float(metadata.get("duration_seconds", 0.0)),
            task_workspace=task_root.as_posix(),
            returncode=completed.returncode,
        ), "trace_ref": trace_ref})
        if completed.returncode != 0 and artifact.status == "completed":
            artifact = TaskArtifact(**{**artifact.to_dict(), "status": "failed"})
        # OpenCode can finish a tool turn while the final detached tracing
        # reconcile is still in flight.  Give the hook a short grace period
        # before trace evaluators query the session; this is separate from
        # the model execution timeout and does not delay ordinary runs much.
        if artifact.trace_ref is not None and self.flush_wait_seconds:
            time.sleep(max(0.0, self.flush_wait_seconds))
        return artifact

    def _copy_fixture(self, case: EvaluationCase, task_root: Path) -> Path | None:
        fixture = case.metadata.get("fixture")
        fixture_path = fixture.get("path") if isinstance(fixture, dict) else None
        if not fixture_path:
            return None
        source = Path(fixture_path)
        if not source.is_absolute():
            source = Path(self.workdir or Path.cwd()) / source
        if not source.is_file():
            raise FileNotFoundError(f"OpenCode fixture does not exist: {source}")
        target = task_root / "input" / source.name
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(source, target)
        return target

    @staticmethod
    def _copy_skill(skill: SkillBundle, task_root: Path) -> Path:
        """Copy the complete Skill bundle under the isolated task workspace.

        OpenCode prompts that point at the source checkout make the CLI request
        an external-directory permission.  A strict file-by-file copy keeps all
        relative references available while ensuring the agent only reads the
        run-local snapshot.  Symlinks are rejected instead of being followed.
        """
        source = Path(skill.root).resolve()
        if not source.is_dir():
            raise FileNotFoundError(f"Skill root does not exist: {source}")
        target = task_root / "input" / "skill"
        target.mkdir(parents=True, exist_ok=False)
        for source_path in source.rglob("*"):
            relative = source_path.relative_to(source)
            # Match SkillBundle hashing rules and avoid staging editor state,
            # caches, or bytecode that can never be part of the contract.
            if any(part.startswith(".") or part == "__pycache__" for part in relative.parts):
                continue
            if source_path.suffix == ".pyc" or relative.as_posix() == "skill.yaml":
                continue
            destination = target / relative
            if source_path.is_symlink():
                raise ValueError(f"Skill bundle contains unsupported symlink: {source_path}")
            if source_path.is_dir():
                destination.mkdir(parents=True, exist_ok=True)
            elif source_path.is_file():
                destination.parent.mkdir(parents=True, exist_ok=True)
                shutil.copy2(source_path, destination)
        entrypoint = target / "SKILL.md"
        if not entrypoint.is_file():
            raise FileNotFoundError(f"staged Skill entrypoint does not exist: {entrypoint}")
        return entrypoint

    @staticmethod
    def _prompt(case: EvaluationCase, skill: SkillBundle, profile: SkillEvaluationConfig,
                task_root: Path, fixture: Path | None,
                skill_entrypoint: Path | None = None) -> str:
        entrypoint = skill_entrypoint or Path(skill.entrypoint)
        expected_files = _expected_files(profile)
        file_contract = ""
        if expected_files:
            names = ", ".join(expected_files)
            file_contract = (
                f" The required output basenames are exactly: {names}. Create every one "
                "with these exact names; do not add a case ID, prefix, suffix, or directory."
            )
        telemetry_contract = ""
        if profile.instrumentation.protocol:
            telemetry_contract = (
                f" This run requires the Skill's explicit {profile.instrumentation.protocol} "
                "completion events: emit every event exactly where the Skill specifies, "
                "in order, and do not omit or batch checkpoints; missing telemetry is a failed evaluation."
            )
        return (f"Execute evaluation case {case.case_id} using the skill at {entrypoint}.\n"
                f"Task: {case.input}\nDesign specification: {fixture or 'provided in the task input'}\n"
                f"Use {task_root} as USER_PATH and write every generated artifact under "
                f"{task_root / 'ai-output'}.{file_contract} Follow the skill completion "
                "contract and complete the task without waiting for another message." + telemetry_contract)

    def _parse(self, events_path: Path, case: EvaluationCase, skill: SkillBundle,
               run_id: str, task_root: Path, fixture: Path | None) -> TaskArtifact:
        events: list[dict[str, Any]] = []
        parse_errors = 0
        for line in events_path.read_text(encoding="utf-8", errors="replace").splitlines():
            try:
                events.append(json.loads(line))
            except json.JSONDecodeError:
                parse_errors += 1
        session_id = next((str(event["sessionID"]) for event in events if event.get("sessionID")), None)
        final_output = ""
        tool_calls: list[dict[str, Any]] = []
        validation: list[dict[str, Any]] = []
        prompt_tokens = completion_tokens = reasoning_tokens = total_tokens = 0
        completion_reasons: list[str] = []
        for event in events:
            part = event.get("part") if isinstance(event.get("part"), dict) else {}
            if part.get("type") == "text" and isinstance(part.get("text"), str):
                final_output = part["text"].strip() or final_output
            if event.get("type") == "tool_use":
                state = part.get("state") if isinstance(part.get("state"), dict) else {}
                tool_calls.append({"name": str(part.get("tool", "unknown")),
                                   "status": state.get("status", "unknown")})
                command = (state.get("input") or {}).get("command") if isinstance(state.get("input"), dict) else None
                if command and self._runs_validator(str(command)):
                    # OpenCode versions place command metadata either inside
                    # the tool state or alongside it on the part.  Merge the
                    # two views while preserving the state status/input.
                    validator_state = dict(state)
                    if isinstance(part.get("metadata"), dict):
                        validator_state["metadata"] = {
                            **part["metadata"],
                            **(state.get("metadata") if isinstance(state.get("metadata"), dict) else {}),
                        }
                    if "output" not in validator_state and isinstance(part.get("output"), (str, dict)):
                        validator_state["output"] = part["output"]
                    validation.append({"command": str(command), "exit_code": self._validator_exit_code(validator_state),
                                       "status": state.get("status", "unknown")})
            if event.get("type") == "step_finish":
                reason = str(part.get("reason", "")).strip().lower()
                if reason:
                    completion_reasons.append(reason)
                tokens = part.get("tokens") if isinstance(part.get("tokens"), dict) else {}
                cache = tokens.get("cache") if isinstance(tokens.get("cache"), dict) else {}
                prompt_tokens += int(tokens.get("input") or 0) + int(cache.get("read") or 0) + int(cache.get("write") or 0)
                completion_tokens += int(tokens.get("output") or 0)
                reasoning_tokens += int(tokens.get("reasoning") or 0)
                total_tokens += int(tokens.get("total") or 0)
        output_root = task_root / "ai-output"
        files = sorted(path for path in output_root.rglob("*") if path.is_file()) if output_root.is_dir() else []
        changed_files = [path.relative_to(task_root).as_posix() for path in files]
        normal_finish = any(reason in {"stop", "end_turn", "completed", "success"}
                            for reason in completion_reasons)
        incomplete_tool_turn = (
            "tool-calls" in completion_reasons and not final_output and not files
        )
        return TaskArtifact(
            run_id=run_id, case_id=case.case_id,
            status=("completed" if events and parse_errors == 0 and not incomplete_tool_turn
                    and (final_output or files or normal_finish) else "failed"),
            output={"final_output": final_output, "tool_calls": tool_calls,
                    "validation": validation, "changed_files": changed_files},
            artifact_refs=[events_path.as_posix(), *((task_root / relative).as_posix() for relative in changed_files)],
            metadata={"fixture": case.metadata.get("fixture"),
                      "fixture_copy": fixture.as_posix() if fixture else None, "skill_id": skill.skill_id,
                      "skill_version": skill.version, "adapter": "opencode", "command": self.command,
                      "model": self.model, "session_id": session_id, "token_usage": {
                          "prompt": prompt_tokens, "completion": completion_tokens,
                          "reasoning": reasoning_tokens,
                          "total": total_tokens or prompt_tokens + completion_tokens,
                      }, "parse_errors": parse_errors,
                      "completion_reasons": completion_reasons,
                      "task_workspace": task_root.as_posix()},
            execution=ExecutionEvidence(
                final_output=final_output,
                tool_calls=tool_calls,
                validation=validation,
                changed_files=changed_files,
                task_workspace=task_root.as_posix(),
                returncode=0,
            ),
            trace_ref=TraceRef(self.trace_project, session_id) if session_id else None,
        )

    @staticmethod
    def _runs_validator(command: str) -> bool:
        return any(
            re.search(r"\bpython(?:\d+(?:\.\d+)*)?\s+\S*validat\S*", segment, re.I)
            or re.match(r"\s*\S*validat\S*", segment, re.I)
            for segment in re.split(r"&&|;|\|\|", command)
        )

    @staticmethod
    def _validator_exit_code(state: dict[str, Any]) -> int | None:
        """Extract a validator's process result without confusing tool status with exit status."""
        metadata = state.get("metadata") if isinstance(state.get("metadata"), dict) else {}
        for source in (metadata, state):
            for key in ("exit", "exit_code", "returncode", "return_code"):
                value = source.get(key)
                if isinstance(value, bool):
                    continue
                if isinstance(value, int):
                    return value
                if isinstance(value, str) and value.strip().lstrip("-").isdigit():
                    return int(value.strip())
        import re
        output = state.get("output", "")
        if isinstance(output, dict):
            output = json.dumps(output, ensure_ascii=False)
        if isinstance(output, str):
            for pattern in (r"\bEXIT\s*[:=]\s*(-?\d+)\b", r"\bexit_code\s*[:=]\s*(-?\d+)\b"):
                match = re.search(pattern, output, re.IGNORECASE)
                if match:
                    return int(match.group(1))
        return None


@dataclass
class OpenCodeExportAdapter:
    """Replay one user-provided ``opencode export`` without running an Agent."""

    export_json: str | Path
    trace_project: str
    task_workspace: str | Path | None = None
    session_id: str | None = None

    def start(self) -> None:
        """Offline export replay has no process lifecycle."""

    def stop(self) -> None:
        """Offline export replay has no process lifecycle."""

    def run(self, case: EvaluationCase, skill: SkillBundle, profile: SkillEvaluationConfig) -> TaskArtifact:
        return project_opencode_export(
            self.export_json,
            case,
            trace_project=self.trace_project,
            task_workspace=self.task_workspace,
            expected_session_id=self.session_id,
        )


@dataclass
class InteractiveOpenCodeAdapter(OpenCodeAdapter):
    """Run OpenCode's real TUI in a run-local workspace.

    The adapter creates the session through the already running OpenCode
    server, sends the initial case prompt asynchronously, and then hands the
    terminal to OpenCode.  After the user exits, the persisted session is
    exported and projected through the same ``TaskArtifact`` path as offline
    replay.
    """

    interactive_timeout: float | None = None

    def _create_session(self, directory: Path, title: str) -> str:
        query = urllib.parse.urlencode({"directory": directory.as_posix()})
        request = urllib.request.Request(
            f"{self.attach_url}/session?{query}",
            data=json.dumps({"title": title}).encode("utf-8"),
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        try:
            with urllib.request.urlopen(request, timeout=15) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError(f"OpenCode session creation failed: HTTP {response.status}")
                payload = json.loads(response.read().decode("utf-8"))
        except (OSError, urllib.error.URLError, json.JSONDecodeError) as exc:
            raise RuntimeError(f"could not create OpenCode session for {directory}") from exc
        session_id = payload.get("id") if isinstance(payload, dict) else None
        if not isinstance(session_id, str) or not session_id:
            raise RuntimeError("OpenCode session creation returned no id")
        return session_id

    def _send_prompt(self, session_id: str, prompt: str, directory: Path) -> None:
        query = urllib.parse.urlencode({"directory": directory.as_posix()})
        request_body: dict[str, Any] = {"parts": [{"type": "text", "text": prompt}]}
        # ``attach`` intentionally has no --model flag.  OpenCode's server
        # API accepts the model on PromptRequest, so pass the explicit CLI
        # selection there rather than appending an unsupported TUI option.
        if self.model:
            provider, separator, model_id = self.model.partition("/")
            if separator and provider and model_id:
                request_body["model"] = {"providerID": provider, "modelID": model_id}
        request = urllib.request.Request(
            f"{self.attach_url}/session/{urllib.parse.quote(session_id, safe='')}/prompt_async?{query}",
            data=json.dumps(request_body).encode("utf-8"),
            headers={"Content-Type": "application/json"},
            method="POST",
        )
        try:
            with urllib.request.urlopen(request, timeout=15) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError(f"OpenCode rejected initial prompt: HTTP {response.status}")
        except (OSError, urllib.error.URLError) as exc:
            raise RuntimeError(f"could not send initial prompt to OpenCode session {session_id}") from exc

    def _export_session(self, session_id: str, target: Path, process_env: dict[str, str], cwd: Path) -> Path:
        command = [self.command[0], "export", session_id]
        # OpenCode can exit before a large pipe-backed stdout flush completes.
        # A regular file avoids truncated-but-successful exports; validate it too.
        with target.open("w", encoding="utf-8") as stream:
            completed = subprocess.run(
                command, cwd=cwd, env=process_env, stdout=stream,
                stderr=subprocess.PIPE, text=True, check=False, timeout=120,
            )
        if completed.returncode != 0 or not target.stat().st_size:
            raise RuntimeError(
                f"OpenCode export failed for session {session_id} (exit {completed.returncode})"
            )
        document = json.loads(target.read_text(encoding="utf-8"))
        _export_info(document, expected_session_id=session_id)
        return target

    def run(self, case: EvaluationCase, skill: SkillBundle, profile: SkillEvaluationConfig) -> TaskArtifact:
        started = time.monotonic()
        run_id = f"interactive-{uuid.uuid4().hex[:12]}"
        task_root = Path(self.run_root).resolve() / case.case_id / run_id
        task_root.mkdir(parents=True, exist_ok=False)
        fixture = self._copy_fixture(case, task_root)
        skill_entrypoint = self._copy_skill(skill, task_root)
        process_env = os.environ.copy()
        process_env.update(self.env)
        prompt = self._prompt(case, skill, profile, task_root, fixture, skill_entrypoint)
        session_id = self._create_session(task_root, f"{case.case_id} interactive evaluation")
        self._send_prompt(session_id, prompt, task_root)
        command = [self.command[0], "attach", self.attach_url, "--session", session_id,
                   "--dir", task_root.as_posix()]
        # ``opencode attach`` does not expose the headless ``--auto`` flag;
        # permissions remain interactive in a real TTY.
        timed_out = False
        interrupted = False
        returncode: int | None = None
        try:
            completed = subprocess.run(
                command, cwd=self.workdir, env=process_env, check=False,
                timeout=self.interactive_timeout,
            )
            returncode = completed.returncode
        except subprocess.TimeoutExpired:
            timed_out = True
            self._abort_session(session_id, task_root)
        except KeyboardInterrupt:
            interrupted = True
            self._abort_session(session_id, task_root)

        raw_root = task_root / "raw"
        raw_root.mkdir(exist_ok=True)
        export_path = raw_root / "opencode-export.json"
        try:
            artifact = self._project_after_export(
                self._export_session(session_id, export_path, process_env, task_root),
                case, skill, run_id, task_root, fixture, self.trace_project,
                expected_session_id=session_id,
            )
            export_error = None
        except Exception as exc:
            # An interrupted or crashed TUI may leave no export.  Preserve the
            # explicitly created session and raw path as a failed TaskArtifact
            # so the backend still creates the experiment and exposes diagnostics.
            export_error = str(exc)
            artifact = TaskArtifact(
                run_id=run_id,
                case_id=case.case_id,
                status="failed",
                output={"final_output": "", "tool_calls": [], "validation": [],
                        "changed_files": [], "error": export_error},
                artifact_refs=[export_path.as_posix()] if export_path.is_file() else [],
                metadata={"adapter": "opencode-interactive", "session_id": session_id,
                          "trace_project": self.trace_project, "export_error": export_error},
                execution=ExecutionEvidence(task_workspace=task_root.as_posix(), returncode=returncode),
                trace_ref=TraceRef(self.trace_project, session_id),
            )
        status = (
            "completed"
            if returncode == 0 and not timed_out and not interrupted
            and export_error is None and artifact.status == "completed"
            else "failed"
        )
        duration = time.monotonic() - started
        metadata = {
            **artifact.metadata,
            "adapter": "opencode-interactive",
            "command": command,
            "model": self.model,
            "duration_seconds": duration,
            "task_workspace": task_root.as_posix(),
            "skill_workspace": skill_entrypoint.parent.as_posix(),
            "skill_entrypoint": skill_entrypoint.as_posix(),
            "interactive": True,
            "timed_out": timed_out,
            "interrupted": interrupted,
            "returncode": returncode,
            "export_error": export_error,
        }
        trace_ref = artifact.trace_ref
        if isinstance(trace_ref, dict):
            trace_ref = TraceRef(
                str(trace_ref.get("project", self.trace_project)),
                str(trace_ref.get("session_id", "")),
            )
        artifact = TaskArtifact(
            **{**artifact.to_dict(), "status": status,
               "artifact_refs": list(dict.fromkeys([*artifact.artifact_refs, export_path.as_posix()])),
               "metadata": metadata,
               "execution": ExecutionEvidence(
                   final_output=str(artifact.output.get("final_output", "")),
                   tool_calls=list(artifact.output.get("tool_calls", [])),
                   validation=list(artifact.output.get("validation", [])),
                   changed_files=list(artifact.output.get("changed_files", [])),
                   task_workspace=task_root.as_posix(),
                   returncode=returncode,
               ),
               "trace_ref": trace_ref})
        # The OpenCode process can exit before coding-harness-tracing has
        # reconciled and persisted the final spans.  Keep this grace period
        # immediately before EvaluationLoop queries the trace store; it is bounded
        # and opt-out for tests/advanced callers via ``flush_wait_seconds=0``.
        if self.flush_wait_seconds:
            time.sleep(max(0.0, self.flush_wait_seconds))
        return artifact

    @staticmethod
    def _project_after_export(export_path: Path, case: EvaluationCase, skill: SkillBundle,
                              run_id: str, task_root: Path, fixture: Path | None,
                              trace_project: str, expected_session_id: str | None = None) -> TaskArtifact:
        # The projection is intentionally shared with OpenCodeExportAdapter;
        # ``skill`` and ``fixture`` are accepted to keep this seam explicit
        # and leave room for future interactive-only audit metadata.
        del skill, fixture
        return project_opencode_export(
            export_path, case, trace_project=trace_project, task_workspace=task_root,
            expected_session_id=expected_session_id, run_id=run_id,
        )


__all__ = [
    "OpenCodeAdapter",
    "OpenCodeExportAdapter",
    "InteractiveOpenCodeAdapter",
]