btai 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.
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.5
2
+ Name: btai
3
+ Version: 0.1.0
4
+ Summary: btai.work public workflow launcher (catalog cache + zip fetch)
5
+ Requires-Python: >=3.12
@@ -0,0 +1,10 @@
1
+ btai_cli/__init__.py,sha256=OFfNeN8hVt9RUEM2AbrSi6V6UJw41OtYzQDY2OeeKy8,76
2
+ btai_cli/cache.py,sha256=71082ndg0hyayrmXe2dfty68N53v1tMYyVWqdseGYPQ,3983
3
+ btai_cli/catalog.py,sha256=QLxKCX2FOGgDPH_SVzAgHOXYbhqTXE9n2KGw6CJgg-Q,1484
4
+ btai_cli/cli.py,sha256=YSk2GQ_Iikb7cHNpjj85hFHedQrpDKH1osdOerI8LA0,5595
5
+ btai_cli/feedback_cmd.py,sha256=2IY6D5H9frkzVIwZvyUtZmVc3f2jFcw8x_3jffFRRBM,3862
6
+ btai_cli/feedback_v2.py,sha256=SODTfvSoX3pqIT9p-uYH8ITjJHgR_X3N60bJpg2jTNY,3485
7
+ btai-0.1.0.dist-info/METADATA,sha256=OWDwa1wKHiSSQG60vPN-CoJ9qwUumVEYJyNFh_rRZSE,144
8
+ btai-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ btai-0.1.0.dist-info/entry_points.txt,sha256=FvksjNug2ojBn3_pvTmDn5W77PtHp6Xd_rBbIS9dkj4,43
10
+ btai-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ btai = btai_cli.cli:main
btai_cli/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Global btai.work CLI: cached catalog, zip download with sha256 verify."""
btai_cli/cache.py ADDED
@@ -0,0 +1,123 @@
1
+ """On-disk catalog and workflow zip cache."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from dataclasses import dataclass
9
+ from datetime import UTC, datetime, timedelta
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ CATALOG_URL = "https://api.btai.work/v1/workflows"
14
+ CATALOG_TTL = timedelta(hours=24)
15
+ DEFAULT_CACHE_ROOT = Path(os.environ.get("BTAI_CACHE_ROOT", Path.home() / ".cache" / "btai" / "launcher"))
16
+
17
+
18
+ @dataclass
19
+ class CatalogCache:
20
+ root: Path
21
+
22
+ @classmethod
23
+ def default(cls) -> CatalogCache:
24
+ return cls(DEFAULT_CACHE_ROOT)
25
+
26
+ def catalog_path(self) -> Path:
27
+ return self.root / "catalog.json"
28
+
29
+ def etag_path(self) -> Path:
30
+ return self.root / "etag.txt"
31
+
32
+ def fetched_at_path(self) -> Path:
33
+ return self.root / "fetched-at.txt"
34
+
35
+ def workflow_dir(self, workflow_id: str) -> Path:
36
+ return self.root / "workflows" / workflow_id
37
+
38
+ def workflow_meta_path(self, workflow_id: str) -> Path:
39
+ return self.workflow_dir(workflow_id) / "meta.json"
40
+
41
+ def workflow_zip_path(self, workflow_id: str) -> Path:
42
+ return self.workflow_dir(workflow_id) / "workflow.zip"
43
+
44
+ def ensure_dirs(self) -> None:
45
+ self.root.mkdir(parents=True, exist_ok=True)
46
+
47
+ def read_fetched_at(self) -> datetime | None:
48
+ path = self.fetched_at_path()
49
+ if not path.is_file():
50
+ return None
51
+ try:
52
+ return datetime.fromisoformat(path.read_text(encoding="utf-8").strip())
53
+ except ValueError:
54
+ return None
55
+
56
+ def catalog_fresh(self, now: datetime | None = None) -> bool:
57
+ ts = self.read_fetched_at()
58
+ if ts is None:
59
+ return False
60
+ now = now or datetime.now(UTC)
61
+ if ts.tzinfo is None:
62
+ ts = ts.replace(tzinfo=UTC)
63
+ return now - ts < CATALOG_TTL
64
+
65
+ def load_catalog(self) -> dict[str, Any] | None:
66
+ path = self.catalog_path()
67
+ if not path.is_file():
68
+ return None
69
+ try:
70
+ return json.loads(path.read_text(encoding="utf-8"))
71
+ except (OSError, json.JSONDecodeError):
72
+ return None
73
+
74
+ def save_catalog(self, body: dict[str, Any], *, etag: str | None = None) -> None:
75
+ self.ensure_dirs()
76
+ self.catalog_path().write_text(
77
+ json.dumps(body, ensure_ascii=False, indent=2) + "\n",
78
+ encoding="utf-8",
79
+ )
80
+ self.fetched_at_path().write_text(datetime.now(UTC).isoformat(), encoding="utf-8")
81
+ if etag:
82
+ self.etag_path().write_text(etag.strip(), encoding="utf-8")
83
+
84
+ def list_workflows(self) -> list[dict[str, Any]]:
85
+ cat = self.load_catalog()
86
+ if not cat:
87
+ return []
88
+ rows = cat.get("workflows")
89
+ return [r for r in rows if isinstance(r, dict)] if isinstance(rows, list) else []
90
+
91
+ def find_workflow(self, workflow_id: str) -> dict[str, Any] | None:
92
+ for row in self.list_workflows():
93
+ if row.get("id") == workflow_id:
94
+ return row
95
+ return None
96
+
97
+ def save_workflow_zip(
98
+ self,
99
+ workflow_id: str,
100
+ zip_bytes: bytes,
101
+ *,
102
+ generation: int,
103
+ sha256: str,
104
+ ) -> None:
105
+ d = self.workflow_dir(workflow_id)
106
+ d.mkdir(parents=True, exist_ok=True)
107
+ self.workflow_zip_path(workflow_id).write_bytes(zip_bytes)
108
+ meta = {
109
+ "workflow_id": workflow_id,
110
+ "generation": generation,
111
+ "sha256": sha256.lower(),
112
+ }
113
+ self.workflow_meta_path(workflow_id).write_text(
114
+ json.dumps(meta, ensure_ascii=False, indent=2) + "\n",
115
+ encoding="utf-8",
116
+ )
117
+
118
+ def verify_local_zip(self, workflow_id: str, expected_sha256: str) -> bool:
119
+ path = self.workflow_zip_path(workflow_id)
120
+ if not path.is_file():
121
+ return False
122
+ actual = hashlib.sha256(path.read_bytes()).hexdigest()
123
+ return actual.lower() == expected_sha256.lower()
btai_cli/catalog.py ADDED
@@ -0,0 +1,43 @@
1
+ """Fetch public workflow catalog over HTTPS."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import urllib.error
7
+ import urllib.request
8
+ from typing import Any
9
+
10
+ from btai_cli.cache import CATALOG_URL
11
+
12
+ UA = "btai-cli/0.1"
13
+
14
+
15
+ def fetch_catalog(*, if_none_match: str | None = None) -> tuple[int, dict[str, Any] | None, str | None]:
16
+ headers = {"User-Agent": UA, "Accept": "application/json"}
17
+ if if_none_match:
18
+ headers["If-None-Match"] = if_none_match
19
+ req = urllib.request.Request(CATALOG_URL, headers=headers)
20
+ try:
21
+ with urllib.request.urlopen(req, timeout=60) as resp:
22
+ etag = resp.headers.get("ETag")
23
+ if resp.status == 304:
24
+ return 304, None, etag
25
+ body = json.loads(resp.read().decode("utf-8"))
26
+ if not isinstance(body, dict):
27
+ return 0, None, etag
28
+ return resp.status, body, etag
29
+ except urllib.error.HTTPError as exc:
30
+ if exc.code == 304:
31
+ return 304, None, exc.headers.get("ETag")
32
+ raise
33
+ except (urllib.error.URLError, json.JSONDecodeError) as exc:
34
+ raise RuntimeError(f"catalog fetch failed: {exc}") from exc
35
+
36
+
37
+ def download_zip(url: str) -> bytes:
38
+ req = urllib.request.Request(url, headers={"User-Agent": UA})
39
+ try:
40
+ with urllib.request.urlopen(req, timeout=120) as resp:
41
+ return resp.read()
42
+ except urllib.error.URLError as exc:
43
+ raise RuntimeError(f"zip download failed: {exc}") from exc
btai_cli/cli.py ADDED
@@ -0,0 +1,156 @@
1
+ """Entry: btai list | find | refresh | fetch | feedback."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import sys
8
+ from typing import Sequence
9
+
10
+ from btai_cli.cache import CatalogCache
11
+ from btai_cli.catalog import download_zip, fetch_catalog
12
+ from btai_cli.feedback_cmd import cmd_feedback
13
+
14
+
15
+ def _tokenize(words: str) -> list[str]:
16
+ return [w.lower() for w in words.split() if w.strip()]
17
+
18
+
19
+ def _row_matches(row: dict, tokens: Sequence[str]) -> bool:
20
+ hay = " ".join(
21
+ str(row.get(k) or "") for k in ("id", "can", "cannot")
22
+ ).lower()
23
+ return all(t in hay for t in tokens)
24
+
25
+
26
+ def cmd_list(cache: CatalogCache, *, force_network: bool) -> int:
27
+ if force_network or not cache.catalog_fresh():
28
+ _do_refresh(cache, force=True)
29
+ rows = cache.list_workflows()
30
+ if not rows:
31
+ print("No catalog in cache. Run: btai refresh", file=sys.stderr)
32
+ return 1
33
+ for row in rows:
34
+ wid = row.get("id", "")
35
+ has_zip = "zip" in row and row.get("sha256")
36
+ gen = row.get("generation", "-")
37
+ print(f"{wid}\tgen={gen}\tzip={'yes' if has_zip else 'no'}")
38
+ return 0
39
+
40
+
41
+ def cmd_find(cache: CatalogCache, words: str, *, force_network: bool) -> int:
42
+ tokens = _tokenize(words)
43
+ if not tokens:
44
+ print("usage: btai find <words>", file=sys.stderr)
45
+ return 1
46
+ if force_network or not cache.catalog_fresh():
47
+ _do_refresh(cache, force=True)
48
+ matches = [r for r in cache.list_workflows() if _row_matches(r, tokens)]
49
+ if not matches:
50
+ print("No matching workflows.")
51
+ return 0
52
+ for row in matches:
53
+ print(f"{row.get('id')}\t{row.get('can', '')[:80]}")
54
+ return 0
55
+
56
+
57
+ def _do_refresh(cache: CatalogCache, *, force: bool) -> None:
58
+ etag = cache.etag_path().read_text(encoding="utf-8").strip() if cache.etag_path().is_file() else None
59
+ if not force and cache.catalog_fresh():
60
+ return
61
+ status, body, new_etag = fetch_catalog(if_none_match=etag)
62
+ if status == 304:
63
+ cache.fetched_at_path().write_text(
64
+ __import__("datetime").datetime.now(__import__("datetime").UTC).isoformat(),
65
+ encoding="utf-8",
66
+ )
67
+ return
68
+ if body is None:
69
+ raise RuntimeError("catalog fetch returned empty body")
70
+ cache.save_catalog(body, etag=new_etag)
71
+
72
+
73
+ def cmd_refresh(cache: CatalogCache) -> int:
74
+ try:
75
+ _do_refresh(cache, force=True)
76
+ except RuntimeError as exc:
77
+ print(str(exc), file=sys.stderr)
78
+ return 1
79
+ n = len(cache.list_workflows())
80
+ print(f"Catalog refreshed ({n} workflows).")
81
+ return 0
82
+
83
+
84
+ def cmd_fetch(cache: CatalogCache, workflow_id: str) -> int:
85
+ if not cache.catalog_fresh():
86
+ try:
87
+ _do_refresh(cache, force=False)
88
+ except RuntimeError as exc:
89
+ print(str(exc), file=sys.stderr)
90
+ return 1
91
+ row = cache.find_workflow(workflow_id)
92
+ if row is None:
93
+ try:
94
+ _do_refresh(cache, force=True)
95
+ except RuntimeError as exc:
96
+ print(str(exc), file=sys.stderr)
97
+ return 1
98
+ row = cache.find_workflow(workflow_id)
99
+ if row is None:
100
+ print(f"Unknown workflow id: {workflow_id}", file=sys.stderr)
101
+ return 1
102
+ zip_url = row.get("zip")
103
+ sha = row.get("sha256")
104
+ gen = row.get("generation", 1)
105
+ if not zip_url or not sha:
106
+ print(f"{workflow_id} has no public zip in catalog.", file=sys.stderr)
107
+ return 1
108
+ try:
109
+ data = download_zip(str(zip_url))
110
+ except RuntimeError as exc:
111
+ print(str(exc), file=sys.stderr)
112
+ return 1
113
+ actual = hashlib.sha256(data).hexdigest()
114
+ if actual.lower() != str(sha).lower():
115
+ print(f"sha256 mismatch for {workflow_id}", file=sys.stderr)
116
+ return 1
117
+ cache.save_workflow_zip(workflow_id, data, generation=int(gen), sha256=actual)
118
+ print(f"Stored {workflow_id} ({len(data)} bytes, gen={gen}, sha256 ok).")
119
+ return 0
120
+
121
+
122
+ def main(argv: list[str] | None = None) -> int:
123
+ parser = argparse.ArgumentParser(prog="btai", description="btai.work workflow catalog CLI")
124
+ sub = parser.add_subparsers(dest="cmd", required=True)
125
+ sub.add_parser("list", help="List cached catalog workflows")
126
+ f = sub.add_parser("find", help="Search id/can/cannot in cache")
127
+ f.add_argument("words", nargs="+", help="words to match")
128
+ sub.add_parser("refresh", help="Refresh catalog (ignore 24h TTL)")
129
+ fe = sub.add_parser("fetch", help="Download and verify one workflow zip")
130
+ fe.add_argument("workflow_id")
131
+ fb = sub.add_parser("feedback", help="Preview or send btai-feedback/2 to /v1/feedback")
132
+ fb.add_argument("--file", metavar="PATH", help="Read feedback JSON from file (default: stdin)")
133
+ fb.add_argument(
134
+ "--source",
135
+ choices=("internal", "user"),
136
+ default="user",
137
+ help="Feedback source (default: user; use internal only for house probes)",
138
+ )
139
+ fb.add_argument("--yes", action="store_true", help="POST after printing JSON (default: preview only)")
140
+ args = parser.parse_args(argv)
141
+ cache = CatalogCache.default()
142
+ if args.cmd == "list":
143
+ return cmd_list(cache, force_network=False)
144
+ if args.cmd == "find":
145
+ return cmd_find(cache, " ".join(args.words), force_network=False)
146
+ if args.cmd == "refresh":
147
+ return cmd_refresh(cache)
148
+ if args.cmd == "fetch":
149
+ return cmd_fetch(cache, args.workflow_id)
150
+ if args.cmd == "feedback":
151
+ return cmd_feedback(file_path=args.file, source=args.source, yes=args.yes)
152
+ return 1
153
+
154
+
155
+ if __name__ == "__main__":
156
+ raise SystemExit(main())
@@ -0,0 +1,121 @@
1
+ """`btai feedback`: preview or POST btai-feedback/2 to /v1/feedback."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ import urllib.error
9
+ import urllib.request
10
+ from typing import Any, Callable
11
+
12
+ from btai_cli.feedback_v2 import FEEDBACK_V2_FORMAT, validate_feedback_v2_document
13
+
14
+ DEFAULT_FEEDBACK_URL = "https://api.btai.work/v1/feedback"
15
+ UA = "btai-cli/0.1"
16
+
17
+
18
+ def feedback_url() -> str:
19
+ return os.environ.get("BTAI_FEEDBACK_URL", DEFAULT_FEEDBACK_URL).strip() or DEFAULT_FEEDBACK_URL
20
+
21
+
22
+ def load_feedback_json(*, file_path: str | None, stdin: Any) -> dict[str, Any]:
23
+ if file_path:
24
+ raw = open(file_path, encoding="utf-8").read()
25
+ else:
26
+ raw = stdin.read()
27
+ if not raw.strip():
28
+ raise ValueError("empty")
29
+ doc = json.loads(raw)
30
+ if not isinstance(doc, dict):
31
+ raise ValueError("root")
32
+ return doc
33
+
34
+
35
+ def post_feedback(
36
+ url: str,
37
+ payload: dict[str, Any],
38
+ *,
39
+ opener: Callable[..., Any] | None = None,
40
+ ) -> tuple[int, dict[str, Any] | None]:
41
+ data = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
42
+ req = urllib.request.Request(
43
+ url,
44
+ data=data,
45
+ method="POST",
46
+ headers={
47
+ "User-Agent": UA,
48
+ "Content-Type": "application/json",
49
+ "Accept": "application/json",
50
+ },
51
+ )
52
+ open_fn = opener or urllib.request.urlopen
53
+ try:
54
+ with open_fn(req, timeout=60) as resp:
55
+ body_raw = resp.read().decode("utf-8")
56
+ try:
57
+ body = json.loads(body_raw) if body_raw.strip() else None
58
+ except json.JSONDecodeError:
59
+ body = None
60
+ return int(resp.status), body if isinstance(body, dict) else None
61
+ except urllib.error.HTTPError as exc:
62
+ raw = exc.read().decode(errors="replace")
63
+ try:
64
+ body = json.loads(raw) if raw.strip() else None
65
+ except json.JSONDecodeError:
66
+ body = None
67
+ return int(exc.code), body if isinstance(body, dict) else None
68
+
69
+
70
+ def cmd_feedback(
71
+ *,
72
+ file_path: str | None,
73
+ source: str,
74
+ yes: bool,
75
+ stdin: Any | None = None,
76
+ opener: Callable[..., Any] | None = None,
77
+ ) -> int:
78
+ if source not in ("internal", "user"):
79
+ print("source must be internal or user", file=sys.stderr)
80
+ return 1
81
+ try:
82
+ doc = load_feedback_json(file_path=file_path, stdin=stdin or sys.stdin)
83
+ payload = validate_feedback_v2_document(doc, source=source)
84
+ except ValueError as exc:
85
+ key = str(exc)
86
+ if key == "pass":
87
+ print(
88
+ "Refusing to send feedback: outcome=pass (omit POST when all checks pass).",
89
+ file=sys.stderr,
90
+ )
91
+ return 2
92
+ if key in ("paths", "error_excerpt"):
93
+ print(
94
+ f"Refusing to send logic feedback locally: missing or invalid {key}.",
95
+ file=sys.stderr,
96
+ )
97
+ return 2
98
+ print(f"Invalid feedback JSON: {key}", file=sys.stderr)
99
+ return 1
100
+ except json.JSONDecodeError:
101
+ print("Invalid JSON input.", file=sys.stderr)
102
+ return 1
103
+ except OSError as exc:
104
+ print(f"Cannot read input: {exc}", file=sys.stderr)
105
+ return 1
106
+
107
+ line = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
108
+ print(line)
109
+ if not yes:
110
+ print("Preview only (use --yes to POST).", file=sys.stderr)
111
+ return 0
112
+
113
+ url = feedback_url()
114
+ status, body = post_feedback(url, payload, opener=opener)
115
+ if status == 202 and isinstance(body, dict) and body.get("accepted") is True:
116
+ print(f"Accepted HTTP {status}.", file=sys.stderr)
117
+ return 0
118
+ print(f"POST failed HTTP {status}.", file=sys.stderr)
119
+ if body:
120
+ print(json.dumps(body, ensure_ascii=False), file=sys.stderr)
121
+ return 1
@@ -0,0 +1,101 @@
1
+ """Pure btai-feedback/2 JSON builder (no network). CLI: `btai feedback`; future MCP tool: feedback."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from typing import Any
8
+
9
+ FEEDBACK_V2_FORMAT = "btai-feedback/2"
10
+ FEEDBACK_V2_MAX_BYTES = 12_288
11
+ _WORKFLOW_ID_RE = re.compile(r"^[a-z][a-z0-9_-]{1,63}$")
12
+ _CASE_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")
13
+ _SHA256_RE = re.compile(r"^[a-f0-9]{64}$")
14
+ _PATH_EXT = re.compile(r"\.(py|md|json|txt|csv|html|zip|ts|js)$", re.IGNORECASE)
15
+
16
+
17
+ def build_feedback_v2_payload(
18
+ *,
19
+ workflow_id: str,
20
+ generation: int,
21
+ sha256: str,
22
+ case_id: str,
23
+ kind: str,
24
+ source: str,
25
+ expected: str,
26
+ actual: str,
27
+ error_excerpt: str = "",
28
+ paths: list[str] | None = None,
29
+ ) -> dict[str, Any]:
30
+ if kind not in ("logic", "env"):
31
+ raise ValueError("kind")
32
+ if source not in ("internal", "user"):
33
+ raise ValueError("source")
34
+ if not _WORKFLOW_ID_RE.match(workflow_id):
35
+ raise ValueError("workflow_id")
36
+ if generation < 1 or not _SHA256_RE.match(sha256):
37
+ raise ValueError("generation or sha256")
38
+ if not _CASE_ID_RE.match(case_id):
39
+ raise ValueError("case_id")
40
+ if len(expected) < 1 or len(expected) > 400:
41
+ raise ValueError("expected")
42
+ if len(actual) < 1 or len(actual) > 400:
43
+ raise ValueError("actual")
44
+ if len(error_excerpt) > 1200:
45
+ raise ValueError("error_excerpt")
46
+ normalized_paths: list[str] = []
47
+ for raw in paths or []:
48
+ rel = str(raw).strip().lstrip("./")
49
+ if not rel or ".." in rel.split("/") or not _PATH_EXT.search(rel):
50
+ raise ValueError("paths")
51
+ normalized_paths.append(rel)
52
+ if len(normalized_paths) > 8:
53
+ raise ValueError("paths")
54
+ if kind == "logic":
55
+ if len(error_excerpt) < 1:
56
+ raise ValueError("error_excerpt")
57
+ if len(normalized_paths) < 1:
58
+ raise ValueError("paths")
59
+ doc = {
60
+ "format": FEEDBACK_V2_FORMAT,
61
+ "workflow_id": workflow_id,
62
+ "generation": generation,
63
+ "sha256": sha256,
64
+ "case_id": case_id,
65
+ "outcome": "warning",
66
+ "kind": kind,
67
+ "source": source,
68
+ "expected": expected,
69
+ "actual": actual,
70
+ "error_excerpt": error_excerpt,
71
+ "paths": normalized_paths,
72
+ }
73
+ raw = json.dumps(doc, ensure_ascii=False, separators=(",", ":"))
74
+ if len(raw.encode("utf-8")) > FEEDBACK_V2_MAX_BYTES:
75
+ raise ValueError("payload too large")
76
+ return doc
77
+
78
+
79
+ def validate_feedback_v2_document(doc: Any, *, source: str) -> dict[str, Any]:
80
+ """Validate a parsed JSON object for POST /v1/feedback (no network)."""
81
+ if not isinstance(doc, dict):
82
+ raise ValueError("root")
83
+ if doc.get("format") != FEEDBACK_V2_FORMAT:
84
+ raise ValueError("format")
85
+ outcome = str(doc.get("outcome", ""))
86
+ if outcome == "pass":
87
+ raise ValueError("pass")
88
+ if outcome != "warning":
89
+ raise ValueError("outcome")
90
+ return build_feedback_v2_payload(
91
+ workflow_id=str(doc.get("workflow_id", "")),
92
+ generation=int(doc.get("generation", 0)),
93
+ sha256=str(doc.get("sha256", "")),
94
+ case_id=str(doc.get("case_id", "")),
95
+ kind=str(doc.get("kind", "")),
96
+ source=source,
97
+ expected=str(doc.get("expected", "")),
98
+ actual=str(doc.get("actual", "")),
99
+ error_excerpt=str(doc.get("error_excerpt", "") or ""),
100
+ paths=list(doc.get("paths") or []),
101
+ )