plotroom 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.
Files changed (150) hide show
  1. plotroom/__init__.py +0 -0
  2. plotroom/__main__.py +8 -0
  3. plotroom/_secret_file.py +8 -0
  4. plotroom/adapters/__init__.py +0 -0
  5. plotroom/adapters/claude_desktop.py +219 -0
  6. plotroom/adapters/embedding_http.py +175 -0
  7. plotroom/adapters/github/__init__.py +337 -0
  8. plotroom/adapters/github/app_credential.py +209 -0
  9. plotroom/adapters/github/ci.py +738 -0
  10. plotroom/adapters/github/commit_statuses.py +63 -0
  11. plotroom/adapters/github/deployments.py +213 -0
  12. plotroom/adapters/github/details.py +867 -0
  13. plotroom/adapters/github/issue_details.py +368 -0
  14. plotroom/adapters/github/junit.py +210 -0
  15. plotroom/adapters/github/junit_xml.py +162 -0
  16. plotroom/adapters/github/kodus_review.py +347 -0
  17. plotroom/adapters/github/pr_details.py +192 -0
  18. plotroom/adapters/github/pull_comparison.py +108 -0
  19. plotroom/adapters/github/read.py +530 -0
  20. plotroom/adapters/github/ticket_tree.py +336 -0
  21. plotroom/adapters/mcp/__init__.py +5 -0
  22. plotroom/adapters/mcp/proxy.py +722 -0
  23. plotroom/adapters/mcp/server.py +931 -0
  24. plotroom/adapters/openrouter.py +151 -0
  25. plotroom/adapters/store_sqlite/__init__.py +6 -0
  26. plotroom/adapters/store_sqlite/actions_sql.py +148 -0
  27. plotroom/adapters/store_sqlite/asks_sql.py +153 -0
  28. plotroom/adapters/store_sqlite/backfill_sql.py +138 -0
  29. plotroom/adapters/store_sqlite/budgets_sql.py +102 -0
  30. plotroom/adapters/store_sqlite/checklists_sql.py +77 -0
  31. plotroom/adapters/store_sqlite/claims_sql.py +54 -0
  32. plotroom/adapters/store_sqlite/embedding_sql.py +275 -0
  33. plotroom/adapters/store_sqlite/github_sql.py +331 -0
  34. plotroom/adapters/store_sqlite/goals_sql.py +57 -0
  35. plotroom/adapters/store_sqlite/human_queue_sql.py +60 -0
  36. plotroom/adapters/store_sqlite/items_sql.py +129 -0
  37. plotroom/adapters/store_sqlite/lanes_sql.py +85 -0
  38. plotroom/adapters/store_sqlite/ledger_sql.py +506 -0
  39. plotroom/adapters/store_sqlite/migrate.py +194 -0
  40. plotroom/adapters/store_sqlite/migrations/env.py +36 -0
  41. plotroom/adapters/store_sqlite/migrations/script.py.mako +19 -0
  42. plotroom/adapters/store_sqlite/migrations/versions/0001_project_meta.py +23 -0
  43. plotroom/adapters/store_sqlite/migrations/versions/0002_event_log.py +40 -0
  44. plotroom/adapters/store_sqlite/migrations/versions/0003_next_items.py +49 -0
  45. plotroom/adapters/store_sqlite/migrations/versions/0004_actions.py +28 -0
  46. plotroom/adapters/store_sqlite/migrations/versions/0005_lanes.py +36 -0
  47. plotroom/adapters/store_sqlite/migrations/versions/0006_work_items.py +22 -0
  48. plotroom/adapters/store_sqlite/migrations/versions/0007_item_changes.py +33 -0
  49. plotroom/adapters/store_sqlite/migrations/versions/0008_claude_turn_aliases.py +30 -0
  50. plotroom/adapters/store_sqlite/migrations/versions/0009_github_projection.py +38 -0
  51. plotroom/adapters/store_sqlite/migrations/versions/0010_github_pull_freshness.py +37 -0
  52. plotroom/adapters/store_sqlite/migrations/versions/0011_github_resources.py +27 -0
  53. plotroom/adapters/store_sqlite/migrations/versions/0012_local_triggers_outbox.py +80 -0
  54. plotroom/adapters/store_sqlite/migrations/versions/0013_lane_claims.py +22 -0
  55. plotroom/adapters/store_sqlite/migrations/versions/0015_recurring_triggers.py +45 -0
  56. plotroom/adapters/store_sqlite/migrations/versions/0016_merge_controller.py +28 -0
  57. plotroom/adapters/store_sqlite/migrations/versions/0017_lane_checklists.py +36 -0
  58. plotroom/adapters/store_sqlite/migrations/versions/0018_guardrails.py +33 -0
  59. plotroom/adapters/store_sqlite/migrations/versions/0019_clerk_import_metadata.py +16 -0
  60. plotroom/adapters/store_sqlite/migrations/versions/0020_search.py +30 -0
  61. plotroom/adapters/store_sqlite/migrations/versions/0021_human_queue.py +46 -0
  62. plotroom/adapters/store_sqlite/migrations/versions/0022_search_records.py +77 -0
  63. plotroom/adapters/store_sqlite/migrations/versions/0023_operator_goals.py +25 -0
  64. plotroom/adapters/store_sqlite/migrations/versions/0024_embedding_rejections.py +36 -0
  65. plotroom/adapters/store_sqlite/outbox_sql.py +78 -0
  66. plotroom/adapters/store_sqlite/routes_sql.py +26 -0
  67. plotroom/adapters/store_sqlite/search_sql.py +116 -0
  68. plotroom/adapters/store_sqlite/store.py +623 -0
  69. plotroom/adapters/store_sqlite/triggers_sql.py +111 -0
  70. plotroom/adapters/store_sqlite/work_items_sql.py +36 -0
  71. plotroom/adapters/switchboard.py +152 -0
  72. plotroom/adapters/usage_fixture.py +11 -0
  73. plotroom/adapters/work_items_bmad.py +256 -0
  74. plotroom/adapters/work_items_github_issues.py +323 -0
  75. plotroom/app/__init__.py +0 -0
  76. plotroom/app/bridge.py +162 -0
  77. plotroom/app/clerk_import.py +349 -0
  78. plotroom/app/cli.py +290 -0
  79. plotroom/app/clock.py +12 -0
  80. plotroom/app/config.py +984 -0
  81. plotroom/app/daemon_start.py +453 -0
  82. plotroom/app/lock.py +77 -0
  83. plotroom/app/logging.py +93 -0
  84. plotroom/app/portfile.py +218 -0
  85. plotroom/app/runtime.py +518 -0
  86. plotroom/app/serve.py +671 -0
  87. plotroom/app/session_intake.py +51 -0
  88. plotroom/app/sqlite_floor.py +35 -0
  89. plotroom/app/tokens.py +265 -0
  90. plotroom/core/__init__.py +0 -0
  91. plotroom/core/actions.py +67 -0
  92. plotroom/core/ask_checks.py +124 -0
  93. plotroom/core/asks.py +123 -0
  94. plotroom/core/branch_updates.py +207 -0
  95. plotroom/core/bridge.py +112 -0
  96. plotroom/core/briefs.py +83 -0
  97. plotroom/core/budgets.py +182 -0
  98. plotroom/core/catalog.py +464 -0
  99. plotroom/core/checklists.py +151 -0
  100. plotroom/core/claims.py +296 -0
  101. plotroom/core/clerk_import.py +379 -0
  102. plotroom/core/commands.py +85 -0
  103. plotroom/core/deploy_window.py +21 -0
  104. plotroom/core/envelope.py +20 -0
  105. plotroom/core/events.py +227 -0
  106. plotroom/core/github.py +306 -0
  107. plotroom/core/github_projection.py +310 -0
  108. plotroom/core/goal_language.py +374 -0
  109. plotroom/core/goal_projection.py +146 -0
  110. plotroom/core/human_queue.py +119 -0
  111. plotroom/core/intake.py +106 -0
  112. plotroom/core/kodus_review.py +53 -0
  113. plotroom/core/lanes.py +281 -0
  114. plotroom/core/ledger.py +808 -0
  115. plotroom/core/merge_controller.py +344 -0
  116. plotroom/core/merge_flakes.py +422 -0
  117. plotroom/core/merge_gate.py +724 -0
  118. plotroom/core/merge_lane.py +70 -0
  119. plotroom/core/merge_overlap.py +76 -0
  120. plotroom/core/next_items.py +60 -0
  121. plotroom/core/operator_goals.py +103 -0
  122. plotroom/core/outbox.py +70 -0
  123. plotroom/core/pull_overlaps.py +152 -0
  124. plotroom/core/reports.py +62 -0
  125. plotroom/core/roles.py +100 -0
  126. plotroom/core/routing.py +55 -0
  127. plotroom/core/run_reports.py +53 -0
  128. plotroom/core/search.py +266 -0
  129. plotroom/core/search_sources.py +94 -0
  130. plotroom/core/snapshot.py +204 -0
  131. plotroom/core/trigger_actions.py +89 -0
  132. plotroom/core/triggers.py +550 -0
  133. plotroom/core/unit_of_work.py +541 -0
  134. plotroom/core/watchers.py +35 -0
  135. plotroom/core/work_items.py +23 -0
  136. plotroom/core/writer.py +164 -0
  137. plotroom/ports/__init__.py +6 -0
  138. plotroom/ports/clock.py +12 -0
  139. plotroom/ports/github_write.py +72 -0
  140. plotroom/ports/search.py +197 -0
  141. plotroom/ports/session_reader.py +23 -0
  142. plotroom/ports/store.py +323 -0
  143. plotroom/ports/usage_meter.py +35 -0
  144. plotroom/ports/work_items.py +22 -0
  145. plotroom/py.typed +0 -0
  146. plotroom-0.1.0.dist-info/METADATA +230 -0
  147. plotroom-0.1.0.dist-info/RECORD +150 -0
  148. plotroom-0.1.0.dist-info/WHEEL +4 -0
  149. plotroom-0.1.0.dist-info/entry_points.txt +2 -0
  150. plotroom-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,146 @@
1
+ """Read-only facts that the goal evaluator can use from one project snapshot."""
2
+
3
+ from collections import defaultdict
4
+ from collections.abc import Iterable, Mapping
5
+ from dataclasses import dataclass
6
+ from typing import TypeGuard
7
+
8
+ from plotroom.core.github_projection import (
9
+ ISSUE_PAGINATION_VERIFIED,
10
+ ISSUE_RELATION_RETRY,
11
+ GitHubRecord,
12
+ GitHubResource,
13
+ )
14
+ from plotroom.core.lanes import Lane
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class GoalIssue:
19
+ number: int
20
+ title: str
21
+ state: str
22
+ milestone: int | None
23
+ labels: frozenset[str]
24
+ assignees: frozenset[str]
25
+ # None means relationship evidence is unavailable. A foreign reference remains
26
+ # in the tuple so the evaluator can distinguish it from a known empty list.
27
+ blockers: tuple[int | str, ...] | None
28
+ lanes: frozenset[str]
29
+ decisions: frozenset[str]
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class GoalFacts:
34
+ repository: str
35
+ issues: Mapping[int, GoalIssue]
36
+ human_login: str | None
37
+ as_of: str | None = None
38
+ unresolved_lanes: frozenset[str] = frozenset()
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class StoredGoal:
43
+ name: str
44
+ text: str
45
+ updated_at: str
46
+ uses_blockers: bool = False
47
+ uses_lanes: bool = False
48
+ uses_decisions: bool = False
49
+
50
+
51
+ def verified_issue_projection(resource: GitHubResource | None) -> TypeGuard[GitHubResource]:
52
+ """Only the verified page walk can establish complete goal evidence."""
53
+ return (
54
+ resource is not None
55
+ and resource.complete
56
+ and resource.attributes.get(ISSUE_PAGINATION_VERIFIED) is True
57
+ )
58
+
59
+
60
+ def issue_number(repository: str, ref: str) -> int | None:
61
+ """Resolve numeric or GitHub-qualified refs against this project only."""
62
+ owner, separator, number = ref.rpartition("#")
63
+ if separator and owner and owner.casefold() != repository.casefold():
64
+ return None
65
+ if not number.isascii() or not number.isdecimal() or len(number) > 19:
66
+ return None
67
+ result = int(number)
68
+ return result if 0 < result <= 2**63 - 1 else None
69
+
70
+
71
+ def _links(repository: str, entries: Iterable[tuple[str, Iterable[str]]]) -> dict[int, set[str]]:
72
+ result: dict[int, set[str]] = defaultdict(set)
73
+ for identifier, refs in entries:
74
+ for ref in refs:
75
+ if (number := issue_number(repository, ref)) is not None:
76
+ result[number].add(identifier)
77
+ return result
78
+
79
+
80
+ def project_goal_facts(
81
+ repository: str,
82
+ human_login: str | None,
83
+ issues: GitHubResource,
84
+ tree: GitHubResource | None,
85
+ lanes: Iterable[Lane],
86
+ decisions: Iterable[tuple[str, Iterable[str]]],
87
+ ) -> GoalFacts:
88
+ """Join the existing issue, relationship, lane and decision projections."""
89
+ assignees: dict[int, frozenset[str]] = {
90
+ record.fields["number"]: frozenset(login.casefold() for login in record.fields["assignees"])
91
+ for record in issues.records
92
+ if record.kind == "issue_assignees"
93
+ }
94
+ metadata: dict[int, GitHubRecord] = {}
95
+ if tree is not None and tree.attributes.get(ISSUE_PAGINATION_VERIFIED) is True:
96
+ retry = set(tree.attributes.get(ISSUE_RELATION_RETRY, []))
97
+ metadata = {
98
+ record.fields["number"]: record
99
+ for record in tree.records
100
+ if record.kind == "issue_metadata"
101
+ and record.fields["number"] not in retry
102
+ and (tree.complete or record.details.get(ISSUE_PAGINATION_VERIFIED) is True)
103
+ }
104
+ lane_refs: list[tuple[str, list[str]]] = []
105
+ unresolved_lanes: set[str] = set()
106
+ for lane in lanes:
107
+ if lane.state == "archived":
108
+ continue
109
+ confirmed: list[str] = []
110
+ for ref in lane.work_items:
111
+ if "#" not in ref:
112
+ unresolved_lanes.add(lane.id)
113
+ else:
114
+ confirmed.append(ref)
115
+ lane_refs.append((lane.id, confirmed))
116
+ lane_links = _links(repository, lane_refs)
117
+ decision_links = _links(repository, decisions)
118
+ projected: dict[int, GoalIssue] = {}
119
+ for record in issues.records:
120
+ if record.details.get("resource") != "issue":
121
+ continue
122
+ number: int = record.fields["number"]
123
+ details = record.details
124
+ relation = metadata.get(number)
125
+ blockers: tuple[int | str, ...] | None = None
126
+ updated_at = details.get("updated_at")
127
+ if updated_at and relation is not None and relation.details.get("updated_at") == updated_at:
128
+ blockers = tuple(relation.fields["blocked_by"])
129
+ projected[number] = GoalIssue(
130
+ number=number,
131
+ title=details["title"],
132
+ state=record.fields["state"],
133
+ milestone=details["milestone"],
134
+ labels=frozenset(details["labels"]),
135
+ assignees=assignees.get(number, frozenset()),
136
+ blockers=blockers,
137
+ lanes=frozenset(lane_links.get(number, ())),
138
+ decisions=frozenset(decision_links.get(number, ())),
139
+ )
140
+ return GoalFacts(
141
+ repository,
142
+ projected,
143
+ human_login.casefold() if human_login else None,
144
+ issues.as_of or None,
145
+ frozenset(unresolved_lanes),
146
+ )
@@ -0,0 +1,119 @@
1
+ """Human decisions and their verbatim evidence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from dataclasses import asdict, dataclass
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from plotroom.core.asks import settle_asks
10
+ from plotroom.core.commands import CommandError
11
+ from plotroom.core.events import FieldSpec, format_time
12
+ from plotroom.core.github_projection import projected_comment
13
+
14
+ if TYPE_CHECKING:
15
+ from plotroom.core.ask_checks import Ask
16
+ from plotroom.core.unit_of_work import UnitOfWork
17
+
18
+ DECISION_FIELDS = (
19
+ FieldSpec("who", "str"),
20
+ FieldSpec("exact_words", "str"),
21
+ FieldSpec("where_ref", "object"),
22
+ FieldSpec("governs", "array"),
23
+ FieldSpec("settles", "array"),
24
+ )
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Decision:
29
+ decision_id: str
30
+ who: str
31
+ exact_words: str
32
+ where_ref: dict[str, Any]
33
+ governs: list[str]
34
+ settles: list[str]
35
+ created_at: str
36
+
37
+ def render(self) -> dict[str, Any]:
38
+ return asdict(self)
39
+
40
+
41
+ def _text(value: Any, name: str) -> str:
42
+ if not isinstance(value, str) or not value.strip():
43
+ raise CommandError("invalid", f"{name} must be a non-empty string")
44
+ try:
45
+ value.encode("utf-8")
46
+ except UnicodeEncodeError:
47
+ raise CommandError("invalid", f"{name} must be valid UTF-8 text") from None
48
+ return value
49
+
50
+
51
+ async def _verify_evidence(
52
+ uow: UnitOfWork,
53
+ who: str,
54
+ exact_words: str,
55
+ where_ref: dict[str, Any],
56
+ repository: str | None,
57
+ human_login: str | None,
58
+ ) -> None:
59
+ kind = where_ref.get("kind")
60
+ if kind == "chat":
61
+ if set(where_ref) != {"kind", "ref"}:
62
+ raise CommandError("invalid", "chat citations require only kind and ref")
63
+ _text(where_ref["ref"], "where_ref.ref")
64
+ if human_login is not None and who.casefold() != human_login.casefold():
65
+ raise CommandError("forbidden", "who does not match the configured human_login")
66
+ return
67
+ if kind != "github_comment" or set(where_ref) != {"kind", "repository", "issue", "comment_id"}:
68
+ raise CommandError(
69
+ "invalid", "GitHub comment citations require kind, repository, issue and comment_id"
70
+ )
71
+ issue, comment_id = where_ref["issue"], where_ref["comment_id"]
72
+ if (
73
+ type(issue) is not int
74
+ or not 0 < issue < 2**63
75
+ or type(comment_id) is not int
76
+ or not 0 < comment_id < 2**63
77
+ ):
78
+ raise CommandError("invalid", "issue and comment_id must be positive GitHub numbers")
79
+ if repository is None or where_ref["repository"] != repository:
80
+ raise CommandError("invalid", "the citation must name the configured GitHub repository")
81
+ if human_login is None or who.casefold() != human_login.casefold():
82
+ raise CommandError("forbidden", "who must match the configured human_login")
83
+ comment = await projected_comment(uow, repository, issue, comment_id)
84
+ author = comment.fields.get("author")
85
+ if not isinstance(author, str) or author.casefold() != human_login.casefold():
86
+ raise CommandError("forbidden", "the projected comment author does not match human_login")
87
+ if exact_words not in comment.body:
88
+ raise CommandError("invalid", "exact_words do not appear verbatim in the cited comment")
89
+
90
+
91
+ async def decide(
92
+ uow: UnitOfWork, args: dict[str, Any], *, repository: str | None, human_login: str | None
93
+ ) -> dict[str, Any]:
94
+ who = _text(args["who"], "who")
95
+ exact_words = _text(args["exact_words"], "exact_words")
96
+ where_ref = args["where_ref"]
97
+ governs = [_text(ticket, "governs entry") for ticket in args["governs"]]
98
+ settles = [_text(ask_id, "settles entry") for ask_id in args["settles"]]
99
+ await _verify_evidence(uow, who, exact_words, where_ref, repository, human_login)
100
+ linked_asks: list[Ask] = []
101
+ for ask_id in dict.fromkeys(settles):
102
+ ask = await uow.find_ask(ask_id)
103
+ if ask is None:
104
+ raise CommandError("not_found", f"ask {ask_id!r} was not found")
105
+ if ask.settled_by is not None:
106
+ raise CommandError("conflict", f"ask {ask_id!r} has already been settled")
107
+ linked_asks.append(ask)
108
+ decision = Decision(
109
+ f"dec_{uuid.uuid7()}",
110
+ who,
111
+ exact_words,
112
+ where_ref,
113
+ governs,
114
+ settles,
115
+ format_time(uow.now()),
116
+ )
117
+ await uow.insert_decision(decision)
118
+ await settle_asks(uow, linked_asks, decision.decision_id)
119
+ return {"decision_id": decision.decision_id}
@@ -0,0 +1,106 @@
1
+ """Record inbound events and the actionable items they produce."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from plotroom.core.events import AppendResult, FieldSpec, LedgerError, NewEvent
10
+ from plotroom.core.lanes import infer_lane
11
+
12
+ if TYPE_CHECKING:
13
+ from plotroom.core.unit_of_work import UnitOfWork
14
+ from plotroom.ports.session_reader import SessionEvent
15
+
16
+ INBOUND_MESSAGE = "inbound_message"
17
+ TURN_REPORT = "claude.turn_report"
18
+ SESSION_MESSAGE = "claude.session_message"
19
+ SESSION_FIELD = FieldSpec("session_id", "str")
20
+ TURN_FIELDS = (
21
+ SESSION_FIELD,
22
+ FieldSpec("report_digest", "str"),
23
+ FieldSpec("turn_index", "int", required=False),
24
+ )
25
+ CLAUDE_APPENDERS = frozenset({"system", "orchestrator", "clerk", "worker"})
26
+
27
+
28
+ async def append_inbound(uow: UnitOfWork, event: NewEvent) -> AppendResult:
29
+ result = await uow.append(event)
30
+ if result.created:
31
+ await uow.raise_item(
32
+ INBOUND_MESSAGE,
33
+ result.event.id,
34
+ "orchestrator",
35
+ {
36
+ "kind": event.kind,
37
+ "lane_id": event.lane_id,
38
+ "fields": event.fields,
39
+ "body": event.body,
40
+ },
41
+ )
42
+ return result
43
+
44
+
45
+ async def record_claude(
46
+ uow: UnitOfWork,
47
+ report: SessionEvent,
48
+ *,
49
+ lane: str | None = None,
50
+ session_worker: str | None = None,
51
+ ) -> AppendResult:
52
+ role, _, caller = uow.role.partition(":")
53
+ if role not in CLAUDE_APPENDERS or report.kind not in (TURN_REPORT, SESSION_MESSAGE):
54
+ raise LedgerError("forbidden", "ingest accepts only Claude reports and session messages")
55
+ if not report.session_id.strip():
56
+ raise LedgerError("invalid", "session_id must be nonempty")
57
+ try:
58
+ body_bytes = report.body.encode("utf-8")
59
+ except UnicodeError:
60
+ raise LedgerError("invalid", "Claude report text must be valid UTF-8") from None
61
+ if role == "worker":
62
+ if session_worker is not None and session_worker != caller:
63
+ raise LedgerError("forbidden", "the Claude session is bound to another worker")
64
+ lane = await infer_lane(uow, worker=caller)
65
+ if lane is None:
66
+ raise LedgerError("forbidden", "a worker must have a current lane")
67
+ elif lane is None and session_worker is not None:
68
+ lane = await infer_lane(uow, worker=session_worker)
69
+ elif lane is not None and await uow.find_lane(lane) is None:
70
+ raise LedgerError("not_found", "lane not found")
71
+
72
+ fields: dict[str, Any] = {"session_id": report.session_id}
73
+ if report.kind == SESSION_MESSAGE:
74
+ if not report.upstream_id or report.turn_index is not None:
75
+ raise LedgerError("invalid", "a session message needs upstream_id and no turn_index")
76
+ if role == "worker":
77
+ fields["worker"] = caller
78
+ uid = json.dumps([report.session_id, report.upstream_id], separators=(",", ":"))
79
+ result = await append_inbound(
80
+ uow, NewEvent("claude", SESSION_MESSAGE, uid, fields, report.body, lane)
81
+ )
82
+ if role == "worker" and result.event.lane_id != lane:
83
+ raise LedgerError("forbidden", "the message is already recorded on another lane")
84
+ return result
85
+ if report.upstream_id is not None:
86
+ raise LedgerError("invalid", "a turn report derives its upstream_id from the report")
87
+ digest = hashlib.sha256(body_bytes).hexdigest()
88
+ aliases = [f"digest:{digest}"]
89
+ fields["report_digest"] = digest
90
+ if report.turn_index is not None:
91
+ if type(report.turn_index) is not int or report.turn_index < 1:
92
+ raise LedgerError("invalid", "turn_index must be a positive integer")
93
+ fields["turn_index"] = report.turn_index
94
+ aliases.insert(0, f"index:{report.turn_index}")
95
+ existing = await uow.find_claude_turn(report.session_id, tuple(aliases))
96
+ if existing is not None:
97
+ result = AppendResult(existing, False)
98
+ else:
99
+ uid = json.dumps([report.session_id, aliases[0]], separators=(",", ":"))
100
+ result = await append_inbound(
101
+ uow, NewEvent("claude", TURN_REPORT, uid, fields, report.body, lane)
102
+ )
103
+ if role == "worker" and result.event.lane_id != lane:
104
+ raise LedgerError("forbidden", "the turn is already recorded on another lane")
105
+ await uow.bind_claude_turn(report.session_id, tuple(aliases), result.event.id)
106
+ return result
@@ -0,0 +1,53 @@
1
+ """Configured trust for Kodus review evidence."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from plotroom.core.github_projection import GitHubResource, checks_for_head
6
+
7
+ KODUS_CHECK_FINGERPRINT = "kodus_check_fingerprint"
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class OpeningHeadAttestation:
12
+ repository: str
13
+ pull_number: int
14
+ pull_id: int
15
+ created_at: str
16
+ head_sha: str
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class KodusReviewPolicy:
21
+ app_id: int
22
+ app_slug: str
23
+ check_name: str
24
+ opening_heads: tuple[OpeningHeadAttestation, ...] = ()
25
+
26
+ def opening_head(self, repository: str, pull_number: int) -> OpeningHeadAttestation | None:
27
+ matches = [
28
+ entry
29
+ for entry in self.opening_heads
30
+ if (entry.repository, entry.pull_number) == (repository, pull_number)
31
+ ]
32
+ return matches[0] if len(matches) == 1 else None
33
+
34
+
35
+ def trusted_current_check(
36
+ policy: KodusReviewPolicy,
37
+ checks: GitHubResource,
38
+ head_sha: str,
39
+ check_id: int,
40
+ fingerprint: str,
41
+ conclusion: str,
42
+ ) -> bool:
43
+ """The independent check read and ordinary checks must agree on the current attempt."""
44
+ latest = checks_for_head(checks, head_sha)
45
+ return latest is not None and any(
46
+ check.fields.get("id") == check_id
47
+ and check.fields.get("name") == policy.check_name
48
+ and check.fields.get("status") == "completed"
49
+ and check.fields.get("conclusion") == conclusion
50
+ and check.details.get("app_id") == policy.app_id
51
+ and check.details.get(KODUS_CHECK_FINGERPRINT) == fingerprint
52
+ for check in latest
53
+ )