codex_harness.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  1. #!/usr/bin/env python3
  2. """Small offline coordinator for the frozen multi-project UART refactor."""
  3. from __future__ import annotations
  4. import hashlib
  5. import json
  6. import os
  7. import re
  8. import shutil
  9. import subprocess
  10. import uuid
  11. from datetime import datetime, timezone
  12. from pathlib import Path, PurePosixPath
  13. from typing import Any, Iterable, Mapping, Sequence
  14. RUN_ID_RE = re.compile(r"^[0-9a-f]{32}$")
  15. COMMIT_RE = re.compile(r"^[0-9a-f]{8}$")
  16. FULL_COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")
  17. SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
  18. AGENT_TASK_REPORT_SCHEMA = "prod2u-native-agent-task-report-v1"
  19. AGENT_SELECTION_SOURCES = frozenset(
  20. {"explicit", "inherited", "automatic", "default", "not_exposed", "unknown"}
  21. )
  22. AGENT_TASK_STATUSES = frozenset({"completed", "blocked", "failed", "integration_conflict"})
  23. PROJECT_ID = "prod2u-door-temp"
  24. PROJECT_PATH = Path("projects/prod2u-door-temp/project.json")
  25. SOURCE_MANIFEST_PATH = Path("src/generated/td-source-manifest.json")
  26. PROTOCOL_PATH = Path("docs/prod2u-door-temp-protocol.zh-CN.md")
  27. REQUIREMENTS_PATH = Path("projects/prod2u-door-temp/requirements.zh-CN.md")
  28. VERIFICATION_TARGETS_PATH = Path("config/prod2u_p4_verification_targets_v1.json")
  29. PACKAGE_INFO_SCHEMA = "prod2u-p4-normal-v3-folder-package-info-v3"
  30. PACKAGE_MANIFEST_SCHEMA = "prod2u-simple-package-manifest-v2"
  31. RUNTIME_PROFILE = "prod2u-door-temp-115200-v1"
  32. PACKAGE_HASH_EXCLUSIONS = frozenset(
  33. {
  34. "package-info.json",
  35. "package_manifest.json",
  36. "evidence/package-selftest-result.json",
  37. }
  38. )
  39. PACKAGE_RECEIPT_PATHS = (
  40. "evidence/td-primary-receipt.json",
  41. "evidence/td-confirmation-receipt.json",
  42. "evidence/python-unit-receipt.json",
  43. "evidence/icarus-receipt.json",
  44. "evidence/verilator-receipt.json",
  45. "evidence/cocotb-receipt.json",
  46. "evidence/formal-receipt.json",
  47. )
  48. def _receipt_payload(
  49. *,
  50. name: str,
  51. run_id: str,
  52. commit: str,
  53. bitstream_sha256: str,
  54. project_config_sha256: str,
  55. td_source_manifest_sha256: str | None = None,
  56. ) -> dict[str, Any]:
  57. return {
  58. "schema": f"prod2u-p4-normal-v3-{name}-receipt-v1",
  59. "status": "not_run",
  60. "verification_run_id": run_id,
  61. "commit": commit,
  62. "bitstream_sha256": bitstream_sha256,
  63. "project_config_sha256": project_config_sha256,
  64. "td_source_manifest_sha256": td_source_manifest_sha256,
  65. "command": None,
  66. "tool_version": None,
  67. "placeholder": True,
  68. "authoritative": False,
  69. "authority_boundary": "Offline package placeholder. No COM, JTAG, programming, or board action.",
  70. }
  71. def _copy_bound_receipt(
  72. source: Path,
  73. destination: Path,
  74. *,
  75. run_id: str,
  76. commit: str,
  77. bitstream_sha256: str,
  78. project_config_sha256: str,
  79. td_source_manifest_sha256: str | None = None,
  80. receipt_role: str | None = None,
  81. preserve_bitstream_sha256: bool = False,
  82. require_bitstream_sha256: bool = False,
  83. ) -> dict[str, Any]:
  84. try:
  85. value = json.loads(Path(source).read_text(encoding="utf-8-sig"))
  86. except (OSError, UnicodeError, json.JSONDecodeError) as exc:
  87. raise ValueError(f"receipt is not readable JSON: {source}") from exc
  88. if not isinstance(value, dict):
  89. raise ValueError(f"receipt root must be an object: {source}")
  90. bindings = {
  91. "verification_run_id": run_id,
  92. "commit": commit,
  93. "project_config_sha256": project_config_sha256,
  94. }
  95. if td_source_manifest_sha256 is not None:
  96. bindings["td_source_manifest_sha256"] = td_source_manifest_sha256
  97. for field, expected in bindings.items():
  98. observed = value.get(field)
  99. if observed not in {None, "", expected}:
  100. raise ValueError(f"receipt binding mismatch for {field}: {source}")
  101. value[field] = expected
  102. if not preserve_bitstream_sha256:
  103. observed = value.get("bitstream_sha256")
  104. if observed not in {None, ""} and observed != bitstream_sha256:
  105. raise ValueError(f"receipt bitstream binding mismatch: {source}")
  106. if observed not in {None, ""}:
  107. value["bitstream_sha256"] = bitstream_sha256
  108. elif value.get("status") == "pass" and not SHA256_RE.fullmatch(str(value.get("bitstream_sha256", ""))):
  109. raise ValueError(f"confirmation receipt requires its own bitstream SHA256: {source}")
  110. value["commit_full"] = commit
  111. if receipt_role is not None:
  112. value["receipt_role"] = receipt_role
  113. # Authoritative receipts must have every binding field already present and
  114. # non-empty. Package processing may only verify and copy; it must not invent
  115. # command, tool_version, or other provenance fields and then promote the
  116. # receipt to authoritative.
  117. required_authoritative_fields = [
  118. "verification_run_id",
  119. "commit",
  120. "project_config_sha256",
  121. "command",
  122. "tool_version",
  123. "status",
  124. ]
  125. if td_source_manifest_sha256 is not None:
  126. required_authoritative_fields.append("td_source_manifest_sha256")
  127. missing = [field for field in required_authoritative_fields if not value.get(field)]
  128. if require_bitstream_sha256 and not SHA256_RE.fullmatch(str(value.get("bitstream_sha256", ""))):
  129. missing.append("bitstream_sha256")
  130. if preserve_bitstream_sha256 and not SHA256_RE.fullmatch(str(value.get("bitstream_sha256", ""))):
  131. missing.append("bitstream_sha256")
  132. was_pass = value.get("status") == "pass"
  133. if was_pass and not missing:
  134. value["authoritative"] = True
  135. value["placeholder"] = False
  136. else:
  137. if was_pass and missing:
  138. value["status"] = "blocked"
  139. value["authoritative"] = False
  140. value["placeholder"] = True
  141. value["source_receipt_sha256"] = sha256_file(source)
  142. _write_json(destination, value)
  143. return value
  144. def _package_file_hashes(package: Path) -> dict[str, str]:
  145. return {
  146. path.relative_to(package).as_posix(): sha256_file(path)
  147. for path in sorted(package.rglob("*"))
  148. if path.is_file()
  149. and path.relative_to(package).as_posix() not in PACKAGE_HASH_EXCLUSIONS
  150. }
  151. def _package_selftest_script() -> str:
  152. return """$ErrorActionPreference = 'Stop'
  153. $excluded = @(
  154. 'package-info.json',
  155. 'package_manifest.json',
  156. 'evidence/package-selftest-result.json'
  157. )
  158. function Require-File([string]$Relative) {
  159. $path = Join-Path $PSScriptRoot $Relative
  160. if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "missing file: $Relative" }
  161. return $path
  162. }
  163. function Read-Json([string]$Relative) {
  164. $path = Require-File $Relative
  165. try { return (Get-Content -LiteralPath $path -Raw | ConvertFrom-Json) }
  166. catch { throw "invalid JSON: $Relative" }
  167. }
  168. function Get-Value($Object, [string]$Name) {
  169. if ($null -eq $Object) { return $null }
  170. $property = $Object.PSObject.Properties[$Name]
  171. if ($null -eq $property) { return $null }
  172. return $property.Value
  173. }
  174. function Has-Value($Object, [string]$Name) {
  175. if ($null -eq $Object) { return $false }
  176. return $null -ne $Object.PSObject.Properties[$Name]
  177. }
  178. function Assert-Equal([string]$Name, $Actual, $Expected) {
  179. if ($Actual -ne $Expected) { throw "$Name mismatch" }
  180. }
  181. function Assert-HashMap([string]$Name, $Actual, $Expected) {
  182. $actualProperties = @($Actual.PSObject.Properties | Sort-Object Name)
  183. $expectedProperties = @($Expected.PSObject.Properties | Sort-Object Name)
  184. if ($actualProperties.Count -ne $expectedProperties.Count) { throw "$Name key count mismatch" }
  185. for ($index = 0; $index -lt $actualProperties.Count; $index++) {
  186. if ($actualProperties[$index].Name -ne $expectedProperties[$index].Name -or
  187. $actualProperties[$index].Value -ne $expectedProperties[$index].Value) {
  188. throw "$Name mismatch"
  189. }
  190. }
  191. }
  192. function Assert-Safety([string]$Name, $Object) {
  193. Assert-Equal "$Name.verification_scope" (Get-Value $Object 'verification_scope') 'offline'
  194. Assert-Equal "$Name.hardware_validation" (Get-Value $Object 'hardware_validation') 'not_run'
  195. Assert-Equal "$Name.board_validation" (Get-Value $Object 'board_validation') 'not_run'
  196. Assert-Equal "$Name.programming_validation" (Get-Value $Object 'programming_validation') 'not_run'
  197. Assert-Equal "$Name.COM" (Get-Value $Object 'COM') $false
  198. Assert-Equal "$Name.JTAG" (Get-Value $Object 'JTAG') $false
  199. }
  200. $info = Read-Json 'package-info.json'
  201. $manifest = Read-Json 'package_manifest.json'
  202. $sourceManifest = Read-Json 'source_manifest.json'
  203. $validation = Read-Json 'evidence/validation-summary.json'
  204. $selftestResult = Read-Json 'evidence/package-selftest-result.json'
  205. $projectHash = (Get-FileHash (Require-File 'project.json') -Algorithm SHA256).Hash.ToLowerInvariant()
  206. $bitstreamHash = (Get-FileHash (Require-File 'fw.bit') -Algorithm SHA256).Hash.ToLowerInvariant()
  207. $sourceManifestHash = (Get-FileHash (Require-File 'source_manifest.json') -Algorithm SHA256).Hash.ToLowerInvariant()
  208. $validationHash = (Get-FileHash (Require-File 'evidence/validation-summary.json') -Algorithm SHA256).Hash.ToLowerInvariant()
  209. $selftestHash = (Get-FileHash (Require-File 'evidence/package-selftest-result.json') -Algorithm SHA256).Hash.ToLowerInvariant()
  210. $runId = [string](Get-Value $info 'verification_run_id')
  211. $commit = [string](Get-Value $info 'commit')
  212. $commitFull = [string](Get-Value $info 'commit_full')
  213. $tdSourceManifestHash = [string](Get-Value $info 'td_source_manifest_sha256')
  214. if ($commitFull -notmatch '^[0-9a-f]{40}$') { throw 'invalid exact commit' }
  215. if ($runId -notmatch '^[0-9a-f]{32}$') { throw 'invalid exact run id' }
  216. if ($tdSourceManifestHash -notmatch '^[0-9a-f]{64}$') { throw 'invalid TD source manifest hash' }
  217. Assert-Equal 'package-info.schema' (Get-Value $info 'schema') 'prod2u-p4-normal-v3-folder-package-info-v3'
  218. Assert-Equal 'package-info.profile' (Get-Value $info 'profile') 'prod2u-door-temp-115200-v1'
  219. Assert-Equal 'package-info.project_id' (Get-Value $info 'project_id') 'prod2u-door-temp'
  220. Assert-Equal 'package-info.verification_run_id' (Get-Value $info 'verification_run_id') $runId
  221. Assert-Equal 'package-info.commit_full' (Get-Value $info 'commit_full') $commitFull
  222. Assert-Equal 'package-info.bitstream_sha256' (Get-Value $info 'bitstream_sha256') $bitstreamHash
  223. Assert-Equal 'package-info.project_sha256' (Get-Value $info 'project_sha256') $projectHash
  224. Assert-Equal 'package-info.project_config_sha256' (Get-Value $info 'project_config_sha256') $projectHash
  225. Assert-Equal 'package-info.source_manifest_sha256' (Get-Value $info 'source_manifest_sha256') $sourceManifestHash
  226. Assert-Equal 'package-info.td_source_manifest_sha256' (Get-Value $info 'td_source_manifest_sha256') $tdSourceManifestHash
  227. Assert-Equal 'package-info.validation_summary_sha256' (Get-Value $info 'validation_summary_sha256') $validationHash
  228. Assert-Equal 'package-info.package_selftest_result_sha256' (Get-Value $info 'package_selftest_result_sha256') $selftestHash
  229. Assert-Equal 'package-info.formal_trace_manifest_sha256' (Get-Value $info 'formal_trace_manifest_sha256') ((Get-FileHash (Require-File 'evidence/formal-trace-manifest.json') -Algorithm SHA256).Hash.ToLowerInvariant())
  230. Assert-Safety 'package-info' $info
  231. Assert-Equal 'package_manifest.schema' (Get-Value $manifest 'schema') 'prod2u-simple-package-manifest-v2'
  232. if (@('UNVERIFIED', 'VERIFIED_OFFLINE') -notcontains [string](Get-Value $manifest 'status')) {
  233. throw "unsupported package status: $((Get-Value $manifest 'status'))"
  234. }
  235. Assert-Equal 'package_manifest.run_id' (Get-Value $manifest 'run_id') $runId
  236. Assert-Equal 'package_manifest.commit_full' (Get-Value $manifest 'commit_full') $commitFull
  237. Assert-Equal 'package_manifest.bitstream_sha256' (Get-Value $manifest 'bitstream_sha256') $bitstreamHash
  238. Assert-Equal 'package_manifest.project_sha256' (Get-Value $manifest 'project_sha256') $projectHash
  239. Assert-Equal 'package_manifest.source_manifest_sha256' (Get-Value $manifest 'source_manifest_sha256') $sourceManifestHash
  240. Assert-Equal 'package_manifest.td_source_manifest_sha256' (Get-Value $manifest 'td_source_manifest_sha256') $tdSourceManifestHash
  241. Assert-Equal 'package_manifest.package_info_sha256' (Get-Value $manifest 'package_info_sha256') ((Get-FileHash (Require-File 'package-info.json') -Algorithm SHA256).Hash.ToLowerInvariant())
  242. Assert-Safety 'package_manifest' $manifest
  243. Assert-Equal 'source_manifest.project_id' (Get-Value $sourceManifest 'project_id') 'prod2u-door-temp'
  244. Assert-Equal 'source_manifest.project_sha256' (Get-Value $sourceManifest 'project_sha256') $projectHash
  245. Assert-Equal 'source_manifest.generated_source_manifest_sha256' (Get-Value $sourceManifest 'generated_source_manifest_sha256') $tdSourceManifestHash
  246. Assert-Equal 'project_config_sha256.txt' ((Get-Content (Require-File 'project_config_sha256.txt') -Raw).Trim()) $projectHash
  247. Assert-Equal 'bitstream_sha256.txt' ((Get-Content (Require-File 'bitstream_sha256.txt') -Raw).Trim()) $bitstreamHash
  248. Assert-Equal 'validation.verification_run_id' (Get-Value $validation 'verification_run_id') $runId
  249. Assert-Equal 'validation.commit' (Get-Value $validation 'commit') $commit
  250. Assert-Equal 'validation.commit_full' (Get-Value $validation 'commit_full') $commitFull
  251. Assert-Equal 'validation.bitstream_sha256' (Get-Value $validation 'bitstream_sha256') $bitstreamHash
  252. Assert-Equal 'validation.project_config_sha256' (Get-Value $validation 'project_config_sha256') $projectHash
  253. Assert-Equal 'validation.td_source_manifest_sha256' (Get-Value $validation 'td_source_manifest_sha256') $tdSourceManifestHash
  254. Assert-Safety 'validation' $validation
  255. Assert-Equal 'package-selftest-result.verification_run_id' (Get-Value $selftestResult 'verification_run_id') $runId
  256. Assert-Equal 'package-selftest-result.commit_full' (Get-Value $selftestResult 'commit_full') $commitFull
  257. Assert-Equal 'package-selftest-result.bitstream_sha256' (Get-Value $selftestResult 'bitstream_sha256') $bitstreamHash
  258. Assert-Equal 'package-selftest-result.project_config_sha256' (Get-Value $selftestResult 'project_config_sha256') $projectHash
  259. Assert-Equal 'package-selftest-result.td_source_manifest_sha256' (Get-Value $selftestResult 'td_source_manifest_sha256') $tdSourceManifestHash
  260. Assert-Equal 'package-selftest-result.returncode' (Get-Value $selftestResult 'returncode') 0
  261. if ((Has-Value $selftestResult 'package_info_sha256') -or
  262. (Has-Value $selftestResult 'package_selftest_result_sha256')) {
  263. throw 'package-selftest-result contains self-referential hashes'
  264. }
  265. $observedExclusions = @((Get-Value $info 'hash_exclusions') | ForEach-Object { [string]$_ } | Sort-Object)
  266. $expectedExclusions = @($excluded | Sort-Object)
  267. if (($observedExclusions -join '|') -ne ($expectedExclusions -join '|')) { throw 'package-info hash exclusions mismatch' }
  268. Assert-Equal 'package_manifest.hash_exclusions' (((Get-Value $manifest 'hash_exclusions') | ForEach-Object { [string]$_ } | Sort-Object) -join '|') ($expectedExclusions -join '|')
  269. Assert-Equal 'package-selftest-result.hash_exclusions' (((Get-Value $selftestResult 'hash_exclusions') | ForEach-Object { [string]$_ } | Sort-Object) -join '|') ($expectedExclusions -join '|')
  270. $actualFiles = [ordered]@{}
  271. Get-ChildItem -LiteralPath $PSScriptRoot -Recurse -File | ForEach-Object {
  272. $relative = $_.FullName.Substring($PSScriptRoot.Length + 1).Replace([char]92, [char]47)
  273. if ($excluded -notcontains $relative) {
  274. $actualFiles[$relative] = (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant()
  275. }
  276. }
  277. $actualFileMap = $actualFiles | ConvertTo-Json -Depth 100 | ConvertFrom-Json
  278. Assert-HashMap 'package-info.file_sha256' (Get-Value $info 'file_sha256') $actualFileMap
  279. Assert-HashMap 'package_manifest.file_sha256' (Get-Value $manifest 'file_sha256') $actualFileMap
  280. $selftestFileMap = Get-Value $selftestResult 'file_sha256'
  281. if ($null -eq $selftestFileMap) { $selftestFileMap = Get-Value $selftestResult 'package_file_sha256' }
  282. Assert-HashMap 'package-selftest-result.file_sha256' $selftestFileMap $actualFileMap
  283. $receiptFiles = @(Get-ChildItem -LiteralPath (Join-Path $PSScriptRoot 'evidence') -Filter '*-receipt.json' -File)
  284. if ($receiptFiles.Count -lt 7) { throw 'receipt set is incomplete' }
  285. $receiptHashes = [ordered]@{}
  286. foreach ($receiptFile in $receiptFiles) {
  287. $receiptRelative = 'evidence/' + $receiptFile.Name
  288. $receiptHashes[$receiptRelative] = (Get-FileHash -LiteralPath $receiptFile.FullName -Algorithm SHA256).Hash.ToLowerInvariant()
  289. $receipt = Read-Json $receiptRelative
  290. Assert-Equal "$($receiptFile.Name).verification_run_id" (Get-Value $receipt 'verification_run_id') $runId
  291. $receiptCommit = [string](Get-Value $receipt 'commit_full')
  292. if (-not $receiptCommit) { $receiptCommit = [string](Get-Value $receipt 'commit') }
  293. Assert-Equal "$($receiptFile.Name).commit" $receiptCommit $commitFull
  294. Assert-Equal "$($receiptFile.Name).project_config_sha256" (Get-Value $receipt 'project_config_sha256') $projectHash
  295. Assert-Equal "$($receiptFile.Name).td_source_manifest_sha256" (Get-Value $receipt 'td_source_manifest_sha256') $tdSourceManifestHash
  296. if (Has-Value $receipt 'verification_scope') { Assert-Safety $receiptFile.Name $receipt }
  297. }
  298. $receiptHashObject = $receiptHashes | ConvertTo-Json -Depth 100 | ConvertFrom-Json
  299. Assert-HashMap 'package-info.receipt_sha256' (Get-Value $info 'receipt_sha256') $receiptHashObject
  300. Assert-HashMap 'package-manifest.receipt_sha256' (Get-Value $manifest 'receipt_sha256') $receiptHashObject
  301. $formalReceipt = Read-Json 'evidence/formal-receipt.json'
  302. $traceManifest = Read-Json 'evidence/formal-trace-manifest.json'
  303. Assert-Equal 'formal-trace-manifest.formal_receipt_sha256' (Get-Value $traceManifest 'formal_receipt_sha256') ((Get-FileHash (Require-File 'evidence/formal-receipt.json') -Algorithm SHA256).Hash.ToLowerInvariant())
  304. $declaredTraces = @()
  305. foreach ($trace in @((Get-Value $formalReceipt 'trace_files'))) {
  306. if ($trace -and $declaredTraces -notcontains [string]$trace) { $declaredTraces += [string]$trace }
  307. }
  308. foreach ($target in @((Get-Value $formalReceipt 'targets'))) {
  309. foreach ($trace in @((Get-Value $target 'trace_files'))) {
  310. if ($trace -and $declaredTraces -notcontains [string]$trace) { $declaredTraces += [string]$trace }
  311. }
  312. foreach ($task in @((Get-Value $target 'task_results'))) {
  313. foreach ($trace in @((Get-Value $task 'trace_files'))) {
  314. if ($trace -and $declaredTraces -notcontains [string]$trace) { $declaredTraces += [string]$trace }
  315. }
  316. }
  317. }
  318. $traceEntries = @((Get-Value $traceManifest 'files'))
  319. if ($declaredTraces.Count -ne $traceEntries.Count) { throw 'formal trace count mismatch' }
  320. $traceHashes = [ordered]@{}
  321. foreach ($entry in $traceEntries) {
  322. $tracePath = [string](Get-Value $entry 'path')
  323. $traceHash = [string](Get-Value $entry 'sha256')
  324. if (-not $tracePath -or -not $traceHash) { throw 'formal trace manifest entry is incomplete' }
  325. $traceHashes[$tracePath] = (Get-FileHash (Require-File $tracePath) -Algorithm SHA256).Hash.ToLowerInvariant()
  326. Assert-Equal "formal-trace.$tracePath" $traceHashes[$tracePath] $traceHash
  327. }
  328. $traceHashObject = $traceHashes | ConvertTo-Json -Depth 100 | ConvertFrom-Json
  329. Assert-HashMap 'formal-trace-manifest.file_sha256' (Get-Value $traceManifest 'file_sha256') $traceHashObject
  330. "package provenance selftest passed"
  331. """.replace("\n", "\r\n")
  332. def new_run_id() -> str:
  333. return uuid.uuid4().hex
  334. def sha256_file(path: Path) -> str:
  335. digest = hashlib.sha256()
  336. with Path(path).open("rb") as stream:
  337. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  338. digest.update(chunk)
  339. return digest.hexdigest()
  340. def _canonical_sha256(value: Mapping[str, Any]) -> str:
  341. encoded = json.dumps(dict(value), sort_keys=True, separators=(",", ":"), ensure_ascii=True)
  342. return hashlib.sha256(encoded.encode("ascii")).hexdigest()
  343. def _repo_root(root: Path | None = None) -> Path:
  344. candidate = Path(root or Path(__file__).resolve().parents[1]).expanduser().resolve()
  345. if not candidate.is_dir():
  346. raise ValueError(f"repository root is not a directory: {candidate}")
  347. return candidate
  348. def _run_git(
  349. root: Path,
  350. args: Sequence[str],
  351. *,
  352. timeout_seconds: float = 10.0,
  353. check: bool = True,
  354. ) -> subprocess.CompletedProcess[bytes]:
  355. if timeout_seconds <= 0:
  356. raise ValueError("timeout_seconds must be positive")
  357. values = [str(value) for value in args]
  358. if not values or any(not value for value in values):
  359. raise ValueError("git args must be a non-empty sequence of non-empty strings")
  360. return subprocess.run(
  361. ["git", "-C", str(_repo_root(root)), *values],
  362. cwd=_repo_root(root),
  363. capture_output=True,
  364. check=check,
  365. shell=False,
  366. text=False,
  367. timeout=timeout_seconds,
  368. )
  369. def build_source_manifest(root: Path | None = None) -> dict[str, Any]:
  370. repo = _repo_root(root)
  371. project_path = repo / PROJECT_PATH
  372. generated_path = repo / SOURCE_MANIFEST_PATH
  373. try:
  374. generated = json.loads(generated_path.read_text(encoding="utf-8-sig"))
  375. except (OSError, UnicodeError, json.JSONDecodeError) as exc:
  376. raise ValueError(f"generated source manifest is not readable: {generated_path}") from exc
  377. if not isinstance(generated, Mapping) or not isinstance(generated.get("sources"), list):
  378. raise ValueError("generated source manifest has no sources list")
  379. source_paths = []
  380. for value in generated["sources"]:
  381. if not isinstance(value, str) or not value:
  382. raise ValueError("generated source manifest contains an invalid path")
  383. candidate = Path(value)
  384. if candidate.is_absolute() or ".." in candidate.parts:
  385. raise ValueError(f"generated source manifest contains unsafe path: {value}")
  386. source_paths.append(candidate.as_posix())
  387. if len(source_paths) != len(set(source_paths)):
  388. raise ValueError("generated source manifest contains duplicate paths")
  389. missing = [path for path in source_paths if not (repo / path).is_file()]
  390. if missing:
  391. raise FileNotFoundError(f"missing active source: {missing[0]}")
  392. source_hashes = {path: sha256_file(repo / path) for path in source_paths}
  393. payload = {
  394. "schema": "prod2u-simple-source-manifest-v1",
  395. "project_id": PROJECT_ID,
  396. "project": PROJECT_PATH.as_posix(),
  397. "project_sha256": sha256_file(project_path),
  398. "generated_source_manifest": SOURCE_MANIFEST_PATH.as_posix(),
  399. "generated_source_manifest_sha256": sha256_file(generated_path),
  400. "sources": source_paths,
  401. "source_sha256": source_hashes,
  402. }
  403. payload["manifest_sha256"] = _canonical_sha256(payload)
  404. return payload
  405. def _git_identity(root: Path) -> dict[str, str]:
  406. repo = _repo_root(root)
  407. top = _run_git(repo, ["rev-parse", "--show-toplevel"]).stdout.decode("utf-8", "strict").strip()
  408. branch = _run_git(repo, ["branch", "--show-current"]).stdout.decode("utf-8", "strict").strip()
  409. head = _run_git(repo, ["rev-parse", "HEAD"]).stdout.decode("ascii", "strict").strip().lower()
  410. actual_root = Path(top).expanduser().resolve()
  411. if actual_root != repo:
  412. raise ValueError(f"worktree root mismatch: expected {repo}, git reports {actual_root}")
  413. if not FULL_COMMIT_RE.fullmatch(head):
  414. raise ValueError("worktree HEAD is not a full commit")
  415. return {"root": str(actual_root), "branch": branch, "head": head}
  416. def validate_worktree_identity(
  417. root: Path,
  418. *,
  419. expected_branch: str | None = None,
  420. expected_head: str | None = None,
  421. assigned_base_commit: str | None = None,
  422. protected_root: Path | None = None,
  423. ) -> dict[str, str]:
  424. identity = _git_identity(root)
  425. protected_value = protected_root or os.environ.get("PROD2U_PROTECTED_REPO_ROOT")
  426. if protected_value and Path(protected_value).expanduser().resolve() == Path(identity["root"]):
  427. raise ValueError("protected_worktree_violation: writes are forbidden in protected repository")
  428. if expected_branch is not None and identity["branch"] != expected_branch:
  429. raise ValueError("worktree branch does not match expected branch")
  430. if expected_head is not None:
  431. _validate_full_commit(expected_head, "expected_head")
  432. if identity["head"] != expected_head:
  433. raise ValueError("worktree HEAD does not match expected HEAD")
  434. if assigned_base_commit is not None:
  435. _validate_full_commit(assigned_base_commit, "assigned_base_commit")
  436. ancestry = _run_git(Path(identity["root"]), ["merge-base", "--is-ancestor", assigned_base_commit, identity["head"]], check=False)
  437. if ancestry.returncode != 0:
  438. raise ValueError("assigned base is not an ancestor of worktree HEAD")
  439. return identity
  440. def current_commit8(root: Path | None = None) -> str:
  441. repo = _repo_root(root)
  442. result = _run_git(repo, ["rev-parse", "--short=8", "HEAD"])
  443. commit = result.stdout.decode("ascii").strip().lower()
  444. if not COMMIT_RE.fullmatch(commit):
  445. raise ValueError(f"unexpected commit: {commit}")
  446. return commit
  447. def _validate_full_commit(value: Any, field: str, *, allow_none: bool = False) -> str | None:
  448. if value is None and allow_none:
  449. return None
  450. if not isinstance(value, str) or not FULL_COMMIT_RE.fullmatch(value):
  451. raise ValueError(f"{field} must be a 40-character lowercase hexadecimal commit")
  452. return value
  453. def _validate_observation_fields(native_thread: Mapping[str, Any]) -> None:
  454. if native_thread.get("model_policy") != "unconstrained":
  455. raise ValueError("native_thread.model_policy must be unconstrained")
  456. if native_thread.get("reasoning_effort_policy") != "unconstrained":
  457. raise ValueError("native_thread.reasoning_effort_policy must be unconstrained")
  458. for field in ("model_selection_source", "effort_selection_source"):
  459. value = native_thread.get(field)
  460. if value is not None and value not in AGENT_SELECTION_SOURCES:
  461. raise ValueError(f"{field} has an unsupported selection source")
  462. observation_source = native_thread.get("observation_source")
  463. if observation_source is not None and not isinstance(observation_source, str):
  464. raise ValueError("observation_source must be a string or null")
  465. for field in ("observed_model", "observed_reasoning_effort", "observed_permission_mode"):
  466. value = native_thread.get(field)
  467. if value is not None and not isinstance(value, str):
  468. raise ValueError(f"{field} must be a string or null")
  469. def _normalise_repo_path(value: Any, *, owned: bool = False) -> str:
  470. if not isinstance(value, str) or not value:
  471. raise ValueError("path must be a non-empty string")
  472. raw = value.replace("\\", "/")
  473. if raw.startswith("/") or re.match(r"^[A-Za-z]:", raw):
  474. raise ValueError(f"path must be relative: {value}")
  475. if any(part == ".." for part in PurePosixPath(raw).parts):
  476. raise ValueError(f"path contains parent traversal: {value}")
  477. normalised = PurePosixPath(raw).as_posix()
  478. if normalised in {"", "."}:
  479. raise ValueError(f"path is not a file or directory: {value}")
  480. if owned and any(token in normalised for token in "*?["):
  481. raise ValueError("owned paths must not contain glob syntax")
  482. return normalised
  483. def _normalise_owned_path(value: Any) -> str:
  484. directory = isinstance(value, str) and value.replace("\\", "/").endswith("/")
  485. normalised = _normalise_repo_path(value, owned=True)
  486. return normalised.rstrip("/") + "/" if directory else normalised
  487. def parse_name_status_z(payload: bytes) -> list[tuple[str, tuple[str, ...]]]:
  488. tokens = payload.split(b"\0")
  489. if tokens and tokens[-1] == b"":
  490. tokens.pop()
  491. events: list[tuple[str, tuple[str, ...]]] = []
  492. index = 0
  493. while index < len(tokens):
  494. try:
  495. status = tokens[index].decode("utf-8", "surrogateescape")
  496. except UnicodeDecodeError as exc:
  497. raise ValueError("git status contains undecodable status") from exc
  498. index += 1
  499. if not status:
  500. raise ValueError("git status contains an empty status")
  501. path_count = 2 if status[0] in {"R", "C"} else 1
  502. if index + path_count > len(tokens):
  503. raise ValueError("git status has an incomplete path record")
  504. paths = tuple(token.decode("utf-8", "surrogateescape") for token in tokens[index : index + path_count])
  505. events.append((status, paths))
  506. index += path_count
  507. return events
  508. def validate_changed_paths(
  509. events: Iterable[tuple[str, Iterable[str]]],
  510. owned_paths: Iterable[str],
  511. ) -> list[str]:
  512. owned = [_normalise_owned_path(path) for path in owned_paths]
  513. changed: list[str] = []
  514. for _status, raw_paths in events:
  515. for raw_path in raw_paths:
  516. path = _normalise_repo_path(raw_path)
  517. changed.append(path)
  518. if not any(
  519. path == candidate
  520. or (candidate.endswith("/") and path.startswith(candidate))
  521. for candidate in owned
  522. ):
  523. raise ValueError(f"changed path is outside owned paths: {path}")
  524. return changed
  525. def changed_paths_for_result(
  526. root: Path,
  527. assigned_base_commit: str,
  528. result_commit: str,
  529. owned_paths: Iterable[str],
  530. ) -> list[str]:
  531. _validate_full_commit(assigned_base_commit, "assigned_base_commit")
  532. _validate_full_commit(result_commit, "result_commit")
  533. result = _run_git(
  534. root,
  535. ["diff", "--name-status", "-z", "--find-renames", assigned_base_commit, result_commit],
  536. )
  537. return validate_changed_paths(parse_name_status_z(result.stdout), owned_paths)
  538. def validate_agent_task_report(
  539. report: Mapping[str, Any],
  540. *,
  541. expected_run_id: str,
  542. expected_base_commit: str,
  543. root: Path | None = None,
  544. expected_dependencies: Mapping[str, Mapping[str, str | None]] | None = None,
  545. ) -> dict[str, Any]:
  546. if report.get("schema") != AGENT_TASK_REPORT_SCHEMA:
  547. raise ValueError("unexpected agent task report schema")
  548. if not RUN_ID_RE.fullmatch(expected_run_id) or report.get("run_id") != expected_run_id:
  549. raise ValueError("run_id mismatch")
  550. _validate_full_commit(expected_base_commit, "expected_base_commit")
  551. assigned_base = _validate_full_commit(report.get("assigned_base_commit"), "assigned_base_commit")
  552. if assigned_base != expected_base_commit:
  553. raise ValueError("stale assigned base mismatch")
  554. if not isinstance(report.get("task_id"), str) or not report["task_id"]:
  555. raise ValueError("task_id must be non-empty")
  556. feature_branch = report.get("feature_branch")
  557. if not isinstance(feature_branch, str) or not feature_branch.strip():
  558. raise ValueError("feature_branch must be non-empty")
  559. worktree = report.get("worktree")
  560. if not isinstance(worktree, str) or not worktree.strip():
  561. raise ValueError("worktree must be non-empty")
  562. report_worktree = Path(worktree).expanduser().resolve()
  563. identity = validate_worktree_identity(
  564. report_worktree,
  565. expected_branch=feature_branch,
  566. assigned_base_commit=assigned_base,
  567. )
  568. status = report.get("status")
  569. if status not in AGENT_TASK_STATUSES:
  570. raise ValueError("unsupported agent task status")
  571. dependencies = report.get("dependencies", [])
  572. if not isinstance(dependencies, list):
  573. raise ValueError("dependencies must be a list")
  574. dependency_map: dict[str, dict[str, str | None]] = {}
  575. for dependency in dependencies:
  576. if not isinstance(dependency, Mapping) or not isinstance(dependency.get("task_id"), str):
  577. raise ValueError("dependency entries must contain task_id")
  578. task_id = dependency["task_id"]
  579. if task_id in dependency_map:
  580. raise ValueError(f"duplicate dependency task_id: {task_id}")
  581. result_commit = _validate_full_commit(
  582. dependency.get("result_commit"), f"dependency {task_id} result_commit", allow_none=True
  583. )
  584. integration_commit = _validate_full_commit(
  585. dependency.get("integration_commit"),
  586. f"dependency {task_id} integration_commit",
  587. allow_none=True,
  588. )
  589. dependency_map[task_id] = {
  590. "result_commit": result_commit,
  591. "integration_commit": integration_commit,
  592. }
  593. if expected_dependencies is not None and dependency_map != dict(expected_dependencies):
  594. raise ValueError("stale dependency mismatch")
  595. native_thread = report.get("native_thread")
  596. if not isinstance(native_thread, Mapping):
  597. raise ValueError("native_thread must be an object")
  598. _validate_observation_fields(native_thread)
  599. owned_paths = report.get("owned_paths", [])
  600. if not isinstance(owned_paths, list):
  601. raise ValueError("owned_paths must be a list")
  602. [_normalise_owned_path(path) for path in owned_paths]
  603. result_commit = _validate_full_commit(report.get("result_commit"), "result_commit", allow_none=True)
  604. integration_commit = _validate_full_commit(
  605. report.get("integration_commit"), "integration_commit", allow_none=True
  606. )
  607. read_only_report = report.get("read_only_report")
  608. if result_commit is None and not (
  609. (isinstance(read_only_report, str) and read_only_report.strip())
  610. or isinstance(read_only_report, Mapping)
  611. ):
  612. raise ValueError("task report requires result_commit or read_only_report")
  613. if result_commit is not None:
  614. resolved = _run_git(report_worktree, ["rev-parse", "--verify", f"{result_commit}^{{commit}}"]).stdout
  615. if resolved.decode("ascii", "strict").strip().lower() != result_commit:
  616. raise ValueError("result commit does not resolve to the supplied full SHA")
  617. if identity["head"] != result_commit:
  618. raise ValueError("report result_commit does not match report worktree HEAD")
  619. ancestry = _run_git(
  620. report_worktree,
  621. ["merge-base", "--is-ancestor", assigned_base, result_commit],
  622. check=False,
  623. )
  624. if ancestry.returncode != 0:
  625. raise ValueError("stale result commit is not based on assigned base")
  626. changed_paths_for_result(report_worktree, assigned_base, result_commit, owned_paths)
  627. if root is not None and integration_commit is not None:
  628. _run_git(root, ["rev-parse", "--verify", f"{integration_commit}^{{commit}}"])
  629. if result_commit is not None:
  630. ancestry = _run_git(
  631. root,
  632. ["merge-base", "--is-ancestor", result_commit, integration_commit],
  633. check=False,
  634. )
  635. if ancestry.returncode != 0:
  636. raise ValueError("integration commit does not contain result commit")
  637. return dict(report)
  638. def aggregate_agent_receipt_bindings(
  639. receipts: Mapping[str, Mapping[str, Any]],
  640. *,
  641. expected_run_id: str,
  642. expected_commit: str,
  643. ) -> dict[str, Any]:
  644. if not RUN_ID_RE.fullmatch(expected_run_id):
  645. raise ValueError("expected_run_id must be 32 lowercase hexadecimal characters")
  646. aggregate: dict[str, Any] = {
  647. "schema": "prod2u-native-agent-receipt-aggregate-v1",
  648. "run_id": expected_run_id,
  649. "commit": expected_commit,
  650. "receipts": {},
  651. }
  652. for name, receipt in receipts.items():
  653. if not isinstance(receipt, Mapping):
  654. raise ValueError(f"receipt must be an object: {name}")
  655. observed_run_id = receipt.get("verification_run_id", receipt.get("run_id"))
  656. if observed_run_id != expected_run_id:
  657. raise ValueError(f"receipt run_id mismatch: {name}")
  658. if receipt.get("commit") != expected_commit:
  659. raise ValueError(f"receipt commit mismatch: {name}")
  660. hashes: dict[str, str] = {}
  661. for field, value in receipt.items():
  662. if field.endswith("_sha256"):
  663. if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):
  664. raise ValueError(f"receipt hash is invalid: {name}.{field}")
  665. hashes[field] = value
  666. aggregate["receipts"][name] = hashes
  667. return aggregate
  668. def _write_json(path: Path, value: Mapping[str, Any]) -> None:
  669. Path(path).parent.mkdir(parents=True, exist_ok=True)
  670. Path(path).write_text(json.dumps(dict(value), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
  671. def _copy_formal_traces(
  672. *,
  673. source_receipt: Path,
  674. formal_receipt: Mapping[str, Any],
  675. package: Path,
  676. repo: Path,
  677. ) -> dict[str, Any]:
  678. raw_trace_files: list[Any] = []
  679. top_level_traces = formal_receipt.get("trace_files", [])
  680. if isinstance(top_level_traces, list):
  681. raw_trace_files.extend(top_level_traces)
  682. elif isinstance(top_level_traces, str) and top_level_traces.strip():
  683. raw_trace_files.append(top_level_traces)
  684. targets = formal_receipt.get("targets", [])
  685. if isinstance(targets, list):
  686. for target in targets:
  687. if not isinstance(target, Mapping):
  688. continue
  689. traces = target.get("trace_files", [])
  690. if isinstance(traces, list):
  691. raw_trace_files.extend(traces)
  692. elif isinstance(traces, str) and traces.strip():
  693. raw_trace_files.append(traces)
  694. task_results = target.get("task_results", [])
  695. if isinstance(task_results, list):
  696. for task in task_results:
  697. if not isinstance(task, Mapping):
  698. continue
  699. task_traces = task.get("trace_files", [])
  700. if isinstance(task_traces, list):
  701. raw_trace_files.extend(task_traces)
  702. elif isinstance(task_traces, str) and task_traces.strip():
  703. raw_trace_files.append(task_traces)
  704. if raw_trace_files is None or raw_trace_files == "":
  705. trace_files: list[Any] = []
  706. elif isinstance(raw_trace_files, str):
  707. trace_files = [raw_trace_files]
  708. elif isinstance(raw_trace_files, list):
  709. trace_files = raw_trace_files
  710. else:
  711. raise ValueError("formal receipt trace_files must be a list")
  712. unique_trace_files: list[Any] = []
  713. seen_trace_files: set[str] = set()
  714. for raw_trace in trace_files:
  715. key = raw_trace if isinstance(raw_trace, str) else repr(raw_trace)
  716. if key not in seen_trace_files:
  717. seen_trace_files.add(key)
  718. unique_trace_files.append(raw_trace)
  719. trace_files = unique_trace_files
  720. trace_root = package / "evidence" / "formal-traces"
  721. trace_root.mkdir(parents=True, exist_ok=True)
  722. entries: list[dict[str, str]] = []
  723. file_sha256: dict[str, str] = {}
  724. used_names: set[str] = set()
  725. for index, raw_trace in enumerate(trace_files):
  726. if not isinstance(raw_trace, str) or not raw_trace.strip():
  727. raise ValueError("formal receipt contains an invalid trace path")
  728. trace_value = Path(raw_trace)
  729. candidates = (
  730. [trace_value]
  731. if trace_value.is_absolute()
  732. else [source_receipt.parent / trace_value, repo / trace_value, Path.cwd() / trace_value]
  733. )
  734. source_path = next((candidate.resolve() for candidate in candidates if candidate.is_file()), None)
  735. if source_path is None:
  736. raise FileNotFoundError(f"formal trace is missing: {raw_trace}")
  737. name = source_path.name
  738. if name in used_names:
  739. name = f"{index:02d}-{name}"
  740. while name in used_names:
  741. name = f"{index:02d}-{name}"
  742. used_names.add(name)
  743. destination = trace_root / name
  744. shutil.copy2(source_path, destination)
  745. relative = destination.relative_to(package).as_posix()
  746. digest = sha256_file(destination)
  747. file_sha256[relative] = digest
  748. entries.append(
  749. {
  750. "source": raw_trace,
  751. "path": relative,
  752. "sha256": digest,
  753. }
  754. )
  755. manifest = {
  756. "schema": "prod2u-p4-normal-v3-formal-trace-manifest-v1",
  757. "formal_receipt": "evidence/formal-receipt.json",
  758. "formal_receipt_sha256": sha256_file(package / "evidence" / "formal-receipt.json"),
  759. "files": entries,
  760. "file_sha256": file_sha256,
  761. }
  762. _write_json(package / "evidence" / "formal-trace-manifest.json", manifest)
  763. return manifest
  764. def init_run(run_id: str, root: Path | None = None) -> Path:
  765. if not RUN_ID_RE.fullmatch(run_id):
  766. raise ValueError("run_id must be 32 lowercase hexadecimal characters")
  767. repo = _repo_root(root)
  768. run_root = repo / "runs" / run_id
  769. run_root.mkdir(parents=True, exist_ok=True)
  770. _write_json(
  771. run_root / "plan.json",
  772. {
  773. "schema": "prod2u-simple-run-plan-v1",
  774. "run_id": run_id,
  775. "project_id": PROJECT_ID,
  776. "status": "DESIGN_FROZEN",
  777. "authority": [
  778. PROJECT_PATH.as_posix(),
  779. REQUIREMENTS_PATH.as_posix(),
  780. PROTOCOL_PATH.as_posix(),
  781. SOURCE_MANIFEST_PATH.as_posix(),
  782. ],
  783. "source_binding": build_source_manifest(repo),
  784. "hardware_access": {"com": False, "jtag": False, "programming": False, "drivers": False},
  785. },
  786. )
  787. _write_json(run_root / "source-manifest.json", build_source_manifest(repo))
  788. return run_root
  789. def create_unverified_package(
  790. *,
  791. bitstream: Path,
  792. project: Path,
  793. commit: str,
  794. run_id: str,
  795. output_root: Path,
  796. td_receipt: Path | None = None,
  797. verification_receipts: Mapping[str, Path] | None = None,
  798. production_integration_commit: str | None = None,
  799. source_manifest_sha256: str | None = None,
  800. td_receipt_sha256: str | None = None,
  801. offline_receipt: Path | None = None,
  802. package_class: str = "UNVERIFIED",
  803. ) -> Path:
  804. if not (COMMIT_RE.fullmatch(commit) or FULL_COMMIT_RE.fullmatch(commit)):
  805. raise ValueError("commit must be a full or 8-character lowercase hexadecimal SHA")
  806. if not RUN_ID_RE.fullmatch(run_id):
  807. raise ValueError("run_id must be 32 lowercase hexadecimal characters")
  808. if package_class not in {
  809. "UNVERIFIED",
  810. "UNVERIFIED_EARLY_BUILD",
  811. "UNVERIFIED_FINAL_CANDIDATE",
  812. }:
  813. raise ValueError("unsupported package class")
  814. early_fields = (
  815. production_integration_commit,
  816. source_manifest_sha256,
  817. td_receipt_sha256,
  818. )
  819. if package_class == "UNVERIFIED_EARLY_BUILD" and (
  820. any(value is None for value in early_fields) or td_receipt is None
  821. ):
  822. raise ValueError("early package requires production commit and input hashes")
  823. if production_integration_commit is not None and not FULL_COMMIT_RE.fullmatch(production_integration_commit):
  824. raise ValueError("production integration commit must be a 40-character lowercase SHA")
  825. for name, value in (
  826. ("source manifest", source_manifest_sha256),
  827. ("TD receipt", td_receipt_sha256),
  828. ):
  829. if value is not None and not SHA256_RE.fullmatch(value):
  830. raise ValueError(f"{name} hash must be 64 lowercase hexadecimal characters")
  831. bitstream = Path(bitstream)
  832. project = Path(project)
  833. if not bitstream.is_file() or bitstream.stat().st_size == 0:
  834. raise FileNotFoundError(f"bitstream is missing or empty: {bitstream}")
  835. if not project.is_file():
  836. raise FileNotFoundError(f"project is missing: {project}")
  837. repo = _repo_root()
  838. canonical_project = (repo / PROJECT_PATH).resolve()
  839. if project.resolve() != canonical_project:
  840. raise ValueError("package project must be the canonical project.json")
  841. if FULL_COMMIT_RE.fullmatch(commit):
  842. commit_full = commit
  843. else:
  844. resolved = _run_git(repo, ["rev-parse", "HEAD"]).stdout.decode("ascii", "strict").strip().lower()
  845. if not FULL_COMMIT_RE.fullmatch(resolved) or resolved[:8] != commit:
  846. raise ValueError("short commit does not match the current full HEAD")
  847. commit_full = resolved
  848. if package_class == "UNVERIFIED_FINAL_CANDIDATE" and offline_receipt is not None:
  849. identity = _git_identity(repo)
  850. if identity["head"] != commit_full:
  851. raise ValueError("final package commit does not match current HEAD")
  852. clean = _run_git(repo, ["status", "--porcelain"]).stdout.decode("utf-8", "replace")
  853. if clean:
  854. raise ValueError("final package requires a clean worktree")
  855. compatibility_commit = commit
  856. bitstream_sha256 = sha256_file(bitstream)
  857. package = Path(output_root) / PROJECT_ID / f"{compatibility_commit}-{bitstream_sha256[:16]}"
  858. package.mkdir(parents=True, exist_ok=True)
  859. package_bitstream = package / "fw.bit"
  860. package_project = package / "project.json"
  861. evidence = package / "evidence"
  862. evidence.mkdir(parents=True, exist_ok=True)
  863. shutil.copy2(bitstream, package_bitstream)
  864. shutil.copy2(project, package_project)
  865. artifacts = {
  866. "protocol.md": repo / PROTOCOL_PATH,
  867. "requirements.zh-CN.md": repo / REQUIREMENTS_PATH,
  868. "verification_targets.json": repo / VERIFICATION_TARGETS_PATH,
  869. }
  870. for name, source in artifacts.items():
  871. if not source.is_file():
  872. raise FileNotFoundError(f"package source is missing: {source}")
  873. shutil.copy2(source, package / name)
  874. (package / "selftest.ps1").write_text(
  875. _package_selftest_script(),
  876. encoding="ascii",
  877. newline="",
  878. )
  879. project_config_sha256 = sha256_file(package_project)
  880. source_manifest = build_source_manifest(repo)
  881. _write_json(package / "source_manifest.json", source_manifest)
  882. observed_source_manifest_sha256 = sha256_file(package / "source_manifest.json")
  883. td_source_manifest_sha256 = sha256_file(repo / SOURCE_MANIFEST_PATH)
  884. if source_manifest_sha256 is not None and source_manifest_sha256 != observed_source_manifest_sha256:
  885. raise ValueError("source manifest hash mismatch")
  886. offline_payload: dict[str, Any] | None = None
  887. if offline_receipt is not None:
  888. try:
  889. loaded = json.loads(Path(offline_receipt).read_text(encoding="utf-8-sig"))
  890. except (OSError, UnicodeError, json.JSONDecodeError) as exc:
  891. raise ValueError(f"offline receipt is not readable JSON: {offline_receipt}") from exc
  892. if not isinstance(loaded, dict):
  893. raise ValueError("offline receipt root must be an object")
  894. expected_bindings = {
  895. "verification_run_id": run_id,
  896. "commit_full": commit_full,
  897. "project_config_sha256": project_config_sha256,
  898. "td_source_manifest_sha256": td_source_manifest_sha256,
  899. }
  900. for field, expected in expected_bindings.items():
  901. if loaded.get(field) != expected:
  902. raise ValueError(f"offline receipt binding mismatch for {field}")
  903. if loaded.get("status") != "pass":
  904. raise ValueError("offline receipt must have status=pass")
  905. offline_payload = loaded
  906. shutil.copy2(Path(offline_receipt), evidence / "software-offline-receipt.json")
  907. receipt_sources = dict(verification_receipts or {})
  908. formal_receipt_source: Path | None = None
  909. formal_receipt_value: Mapping[str, Any] | None = None
  910. if td_receipt is not None:
  911. receipt = Path(td_receipt)
  912. if not receipt.is_file():
  913. raise FileNotFoundError(f"TD receipt is missing: {receipt}")
  914. if td_receipt_sha256 is not None and sha256_file(receipt) != td_receipt_sha256:
  915. raise ValueError("TD receipt hash mismatch")
  916. _copy_bound_receipt(
  917. receipt,
  918. evidence / "td-primary-receipt.json",
  919. run_id=run_id,
  920. commit=commit_full,
  921. bitstream_sha256=bitstream_sha256,
  922. project_config_sha256=project_config_sha256,
  923. td_source_manifest_sha256=td_source_manifest_sha256,
  924. receipt_role="td-primary",
  925. require_bitstream_sha256=True,
  926. )
  927. else:
  928. _write_json(
  929. evidence / "td-primary-receipt.json",
  930. _receipt_payload(
  931. name="td-primary",
  932. run_id=run_id,
  933. commit=commit_full,
  934. bitstream_sha256=bitstream_sha256,
  935. project_config_sha256=project_config_sha256,
  936. td_source_manifest_sha256=td_source_manifest_sha256,
  937. ),
  938. )
  939. receipt_specs = {
  940. "td-confirmation": "td-confirmation-receipt.json",
  941. "python-unit": "python-unit-receipt.json",
  942. "icarus": "icarus-receipt.json",
  943. "verilator": "verilator-receipt.json",
  944. "cocotb": "cocotb-receipt.json",
  945. "formal": "formal-receipt.json",
  946. }
  947. for name, filename in receipt_specs.items():
  948. source = receipt_sources.get(name)
  949. if source is not None:
  950. source_path = Path(source)
  951. if not source_path.is_file():
  952. raise FileNotFoundError(f"verification receipt is missing: {source_path}")
  953. copied_receipt = _copy_bound_receipt(
  954. source_path,
  955. evidence / filename,
  956. run_id=run_id,
  957. commit=commit_full,
  958. bitstream_sha256=bitstream_sha256,
  959. project_config_sha256=project_config_sha256,
  960. td_source_manifest_sha256=td_source_manifest_sha256,
  961. receipt_role=name,
  962. preserve_bitstream_sha256=name == "td-confirmation",
  963. require_bitstream_sha256=name == "td-primary",
  964. )
  965. if name == "formal":
  966. formal_receipt_source = source_path
  967. formal_receipt_value = copied_receipt
  968. else:
  969. placeholder = _receipt_payload(
  970. name=name,
  971. run_id=run_id,
  972. commit=commit_full,
  973. bitstream_sha256=bitstream_sha256,
  974. project_config_sha256=project_config_sha256,
  975. td_source_manifest_sha256=td_source_manifest_sha256,
  976. )
  977. _write_json(
  978. evidence / filename,
  979. placeholder,
  980. )
  981. if name == "formal":
  982. formal_receipt_source = repo
  983. formal_receipt_value = placeholder
  984. if formal_receipt_value is None:
  985. raise ValueError("formal receipt was not generated")
  986. _copy_formal_traces(
  987. source_receipt=formal_receipt_source or repo,
  988. formal_receipt=formal_receipt_value,
  989. package=package,
  990. repo=repo,
  991. )
  992. (package / "project_config_sha256.txt").write_text(
  993. project_config_sha256 + "\n", encoding="ascii", newline="\n"
  994. )
  995. (package / "bitstream_sha256.txt").write_text(
  996. bitstream_sha256 + "\n", encoding="ascii", newline="\n"
  997. )
  998. td_status = "not_run"
  999. td_synthesis_input_hash = None
  1000. confirmation_bitstream_sha256 = None
  1001. confirmation_synthesis_input_hash = None
  1002. try:
  1003. td_value = json.loads((evidence / "td-primary-receipt.json").read_text(encoding="utf-8-sig"))
  1004. if isinstance(td_value, Mapping) and td_value.get("status") in {"pass", "fail", "blocked", "not_run"}:
  1005. td_status = str(td_value["status"])
  1006. td_synthesis_input_hash = td_value.get("synthesis_input_hash")
  1007. except (OSError, UnicodeError, json.JSONDecodeError):
  1008. td_status = "fail"
  1009. try:
  1010. confirmation_value = json.loads((evidence / "td-confirmation-receipt.json").read_text(encoding="utf-8-sig"))
  1011. if isinstance(confirmation_value, Mapping) and confirmation_value.get("status") == "pass":
  1012. confirmation_bitstream_sha256 = confirmation_value.get("bitstream_sha256")
  1013. confirmation_synthesis_input_hash = confirmation_value.get("synthesis_input_hash")
  1014. except (OSError, UnicodeError, json.JSONDecodeError):
  1015. pass
  1016. def receipt_status(filename: str) -> str:
  1017. try:
  1018. value = json.loads((evidence / filename).read_text(encoding="utf-8-sig"))
  1019. except (OSError, UnicodeError, json.JSONDecodeError):
  1020. return "fail"
  1021. return str(value.get("status", "fail")) if isinstance(value, Mapping) else "fail"
  1022. validation_summary = {
  1023. "schema": "prod2u-p4-normal-v3-validation-summary-v1",
  1024. "status": "UNVERIFIED",
  1025. "delivery_mode": "normal_dual_td",
  1026. "verification_complete": False,
  1027. "confirmation_td_present": confirmation_bitstream_sha256 is not None,
  1028. "verification_run_id": run_id,
  1029. "commit": compatibility_commit,
  1030. "commit_full": commit_full,
  1031. "bitstream_sha256": bitstream_sha256,
  1032. "project_config_sha256": sha256_file(package_project),
  1033. "td_source_manifest_sha256": td_source_manifest_sha256,
  1034. "layers": {
  1035. "python_unit": {"status": receipt_status("python-unit-receipt.json")},
  1036. "icarus": {"status": receipt_status("icarus-receipt.json")},
  1037. "verilator": {"status": receipt_status("verilator-receipt.json")},
  1038. "cocotb": {"status": receipt_status("cocotb-receipt.json")},
  1039. "formal": {"status": receipt_status("formal-receipt.json")},
  1040. "td_primary": {"status": td_status},
  1041. "td_confirmation": {"status": receipt_status("td-confirmation-receipt.json")},
  1042. "td_confirmation_artifacts": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"},
  1043. "td_confirmation_bitstream": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"},
  1044. "td_confirmation_synthesis": {"status": "pass" if confirmation_synthesis_input_hash else "not_run"},
  1045. "td_confirmation_manifest": {"status": "pass" if confirmation_synthesis_input_hash else "not_run"},
  1046. "resource_confirmation": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"},
  1047. },
  1048. "hardware_validation": "not_run",
  1049. "verification_scope": "offline",
  1050. "board_validation": "not_run",
  1051. "programming_validation": "not_run",
  1052. "COM": False,
  1053. "JTAG": False,
  1054. }
  1055. _write_json(evidence / "validation-summary.json", validation_summary)
  1056. _write_json(package / "verification_summary.json", validation_summary)
  1057. _write_json(
  1058. evidence / "package-selftest-result.json",
  1059. {
  1060. "schema": "prod2u-p4-normal-v3-package-selftest-result-v1",
  1061. "status": "not_run",
  1062. "returncode": 0,
  1063. "verification_run_id": run_id,
  1064. "commit": commit_full,
  1065. "commit_full": commit_full,
  1066. "bitstream_sha256": bitstream_sha256,
  1067. "project_config_sha256": project_config_sha256,
  1068. "td_source_manifest_sha256": td_source_manifest_sha256,
  1069. "verification_scope": "offline",
  1070. "hardware_validation": "not_run",
  1071. "board_validation": "not_run",
  1072. "programming_validation": "not_run",
  1073. "COM": False,
  1074. "JTAG": False,
  1075. "hash_exclusions": sorted(PACKAGE_HASH_EXCLUSIONS),
  1076. "file_sha256": _package_file_hashes(package),
  1077. "package_file_sha256": _package_file_hashes(package),
  1078. },
  1079. )
  1080. receipt_paths = {
  1081. relative: sha256_file(package / relative)
  1082. for relative in PACKAGE_RECEIPT_PATHS
  1083. }
  1084. if offline_payload is not None:
  1085. receipt_paths["evidence/software-offline-receipt.json"] = sha256_file(
  1086. evidence / "software-offline-receipt.json"
  1087. )
  1088. formal_trace_manifest_path = evidence / "formal-trace-manifest.json"
  1089. package_info = {
  1090. "schema": PACKAGE_INFO_SCHEMA,
  1091. "profile": RUNTIME_PROFILE,
  1092. "project_id": PROJECT_ID,
  1093. "delivery_mode": "normal_dual_td",
  1094. "verification_complete": False,
  1095. "confirmation_td_present": confirmation_bitstream_sha256 is not None,
  1096. "verification_run_id": run_id,
  1097. "commit": compatibility_commit,
  1098. "commit_full": commit_full,
  1099. "bitstream": "fw.bit",
  1100. "bitstream_sha256": bitstream_sha256,
  1101. "project": "project.json",
  1102. "project_sha256": sha256_file(package_project),
  1103. "project_config_sha256": sha256_file(package_project),
  1104. "source_manifest_sha256": sha256_file(package / "source_manifest.json"),
  1105. "production_integration_commit": production_integration_commit,
  1106. "package_class": package_class,
  1107. "synthesis_input_hash": td_synthesis_input_hash,
  1108. "confirmation_bitstream_sha256": confirmation_bitstream_sha256,
  1109. "confirmation_synthesis_input_hash": confirmation_synthesis_input_hash,
  1110. "td_source_manifest_sha256": td_source_manifest_sha256,
  1111. "software_offline_receipt": "evidence/software-offline-receipt.json" if offline_payload is not None else None,
  1112. "receipt_sha256": receipt_paths,
  1113. "formal_trace_manifest": "evidence/formal-trace-manifest.json",
  1114. "formal_trace_manifest_sha256": sha256_file(formal_trace_manifest_path),
  1115. "hash_exclusions": sorted(PACKAGE_HASH_EXCLUSIONS),
  1116. "canonical_bitstream_build": "primary",
  1117. "bitstream_hash_equal": confirmation_bitstream_sha256 == bitstream_sha256 if confirmation_bitstream_sha256 else None,
  1118. "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
  1119. "td_source_receipt_sha256": td_receipt_sha256,
  1120. "confirmation_td_receipt_sha256": sha256_file(evidence / "td-confirmation-receipt.json"),
  1121. "validation_summary_sha256": sha256_file(evidence / "validation-summary.json"),
  1122. "package_selftest_result_sha256": sha256_file(evidence / "package-selftest-result.json"),
  1123. "file_sha256": _package_file_hashes(package),
  1124. "hardware_validation": "not_run",
  1125. "verification_scope": "offline",
  1126. "board_validation": "not_run",
  1127. "programming_validation": "not_run",
  1128. "COM": False,
  1129. "JTAG": False,
  1130. }
  1131. _write_json(package / "package-info.json", package_info)
  1132. manifest = {
  1133. "schema": PACKAGE_MANIFEST_SCHEMA,
  1134. "status": "UNVERIFIED",
  1135. "package_class": package_class,
  1136. "run_id": run_id,
  1137. "project_id": PROJECT_ID,
  1138. "commit": compatibility_commit,
  1139. "commit_full": commit_full,
  1140. "production_integration_commit": production_integration_commit,
  1141. "created_at": datetime.now(timezone.utc).isoformat(),
  1142. "bitstream": "fw.bit",
  1143. "bitstream_sha256": sha256_file(package_bitstream),
  1144. "project": "project.json",
  1145. "project_sha256": sha256_file(package_project),
  1146. "source_manifest_sha256": observed_source_manifest_sha256,
  1147. "package_info": "package-info.json",
  1148. "package_info_sha256": sha256_file(package / "package-info.json"),
  1149. "td_receipt": "evidence/td-primary-receipt.json",
  1150. "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
  1151. "td_source_receipt_sha256": td_receipt_sha256,
  1152. "td_source_manifest_sha256": td_source_manifest_sha256,
  1153. "software_offline_receipt": "evidence/software-offline-receipt.json" if offline_payload is not None else None,
  1154. "receipt_sha256": receipt_paths,
  1155. "validation_summary": "evidence/validation-summary.json",
  1156. "validation_summary_sha256": sha256_file(evidence / "validation-summary.json"),
  1157. "formal_trace_manifest": "evidence/formal-trace-manifest.json",
  1158. "formal_trace_manifest_sha256": sha256_file(formal_trace_manifest_path),
  1159. "package_selftest_result": "evidence/package-selftest-result.json",
  1160. "hash_exclusions": sorted(PACKAGE_HASH_EXCLUSIONS),
  1161. "canonical_bitstream_build": "primary",
  1162. "confirmation_bitstream_sha256": confirmation_bitstream_sha256,
  1163. "bitstream_hash_equal": confirmation_bitstream_sha256 == bitstream_sha256 if confirmation_bitstream_sha256 else None,
  1164. "file_sha256": _package_file_hashes(package),
  1165. "hardware_validation": "not_run",
  1166. "verification_scope": "offline",
  1167. "board_validation": "not_run",
  1168. "programming_validation": "not_run",
  1169. "COM": False,
  1170. "JTAG": False,
  1171. }
  1172. _write_json(package / "package_manifest.json", manifest)
  1173. return package
  1174. def main() -> int:
  1175. import argparse
  1176. parser = argparse.ArgumentParser(description=__doc__)
  1177. sub = parser.add_subparsers(dest="command", required=True)
  1178. sub.add_parser("run-id")
  1179. init = sub.add_parser("init")
  1180. init.add_argument("--run-id", required=True)
  1181. init.add_argument("--root", type=Path)
  1182. manifest = sub.add_parser("manifest")
  1183. manifest.add_argument("--root", type=Path)
  1184. package = sub.add_parser("package")
  1185. package.add_argument("--bitstream", type=Path, required=True)
  1186. package.add_argument("--project", type=Path, default=PROJECT_PATH)
  1187. package.add_argument("--commit", required=True)
  1188. package.add_argument("--run-id", required=True)
  1189. package.add_argument("--output-root", type=Path, default=Path("dist"))
  1190. package.add_argument("--td-receipt", type=Path)
  1191. package.add_argument("--production-integration-commit")
  1192. package.add_argument("--source-manifest-sha256")
  1193. package.add_argument("--td-receipt-sha256")
  1194. package.add_argument("--offline-receipt", type=Path)
  1195. package.add_argument(
  1196. "--package-class",
  1197. choices=("UNVERIFIED", "UNVERIFIED_EARLY_BUILD", "UNVERIFIED_FINAL_CANDIDATE"),
  1198. default="UNVERIFIED",
  1199. )
  1200. package.add_argument(
  1201. "--receipt",
  1202. action="append",
  1203. default=[],
  1204. metavar="NAME=PATH",
  1205. help="bind an additional receipt under evidence (NAME: python-unit, icarus, verilator, cocotb, formal, td-confirmation)",
  1206. )
  1207. args = parser.parse_args()
  1208. if args.command == "run-id":
  1209. print(new_run_id())
  1210. elif args.command == "init":
  1211. print(init_run(args.run_id, args.root))
  1212. elif args.command == "manifest":
  1213. print(json.dumps(build_source_manifest(args.root), indent=2, sort_keys=True))
  1214. else:
  1215. receipt_map: dict[str, Path] = {}
  1216. for item in args.receipt:
  1217. name, separator, raw_path = item.partition("=")
  1218. if not separator or not name or not raw_path:
  1219. raise SystemExit(f"invalid --receipt value: {item!r}; expected NAME=PATH")
  1220. receipt_map[name] = Path(raw_path)
  1221. print(create_unverified_package(
  1222. bitstream=args.bitstream,
  1223. project=args.project,
  1224. commit=args.commit,
  1225. run_id=args.run_id,
  1226. output_root=args.output_root,
  1227. td_receipt=args.td_receipt,
  1228. verification_receipts=receipt_map,
  1229. production_integration_commit=args.production_integration_commit,
  1230. source_manifest_sha256=args.source_manifest_sha256,
  1231. td_receipt_sha256=args.td_receipt_sha256,
  1232. offline_receipt=args.offline_receipt,
  1233. package_class=args.package_class,
  1234. ))
  1235. return 0
  1236. if __name__ == "__main__":
  1237. raise SystemExit(main())