codex_harness.py 61 KB

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