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